27048f9a10d358bdbf78e62187f6851c9483c299
[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
829     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
830     if (!Subtarget->hasV8Ops()) {
831       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
832       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
833     }
834
835     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
836     if (!Subtarget->hasFP16()) {
837       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
838       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
839     }
840   }
841
842   // Combine sin / cos into one node or libcall if possible.
843   if (Subtarget->hasSinCos()) {
844     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
845     setLibcallName(RTLIB::SINCOS_F64, "sincos");
846     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
847       // For iOS, we don't want to the normal expansion of a libcall to
848       // sincos. We want to issue a libcall to __sincos_stret.
849       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
850       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
851     }
852   }
853
854   // We have target-specific dag combine patterns for the following nodes:
855   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
856   setTargetDAGCombine(ISD::ADD);
857   setTargetDAGCombine(ISD::SUB);
858   setTargetDAGCombine(ISD::MUL);
859   setTargetDAGCombine(ISD::AND);
860   setTargetDAGCombine(ISD::OR);
861   setTargetDAGCombine(ISD::XOR);
862
863   if (Subtarget->hasV6Ops())
864     setTargetDAGCombine(ISD::SRL);
865
866   setStackPointerRegisterToSaveRestore(ARM::SP);
867
868   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
869       !Subtarget->hasVFP2())
870     setSchedulingPreference(Sched::RegPressure);
871   else
872     setSchedulingPreference(Sched::Hybrid);
873
874   //// temporary - rewrite interface to use type
875   MaxStoresPerMemset = 8;
876   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
877   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
878   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
879   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
880   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
881
882   // On ARM arguments smaller than 4 bytes are extended, so all arguments
883   // are at least 4 bytes aligned.
884   setMinStackArgumentAlignment(4);
885
886   // Prefer likely predicted branches to selects on out-of-order cores.
887   PredictableSelectIsExpensive = Subtarget->isLikeA9();
888
889   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
890 }
891
892 // FIXME: It might make sense to define the representative register class as the
893 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
894 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
895 // SPR's representative would be DPR_VFP2. This should work well if register
896 // pressure tracking were modified such that a register use would increment the
897 // pressure of the register class's representative and all of it's super
898 // classes' representatives transitively. We have not implemented this because
899 // of the difficulty prior to coalescing of modeling operand register classes
900 // due to the common occurrence of cross class copies and subregister insertions
901 // and extractions.
902 std::pair<const TargetRegisterClass*, uint8_t>
903 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
904   const TargetRegisterClass *RRC = nullptr;
905   uint8_t Cost = 1;
906   switch (VT.SimpleTy) {
907   default:
908     return TargetLowering::findRepresentativeClass(VT);
909   // Use DPR as representative register class for all floating point
910   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
911   // the cost is 1 for both f32 and f64.
912   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
913   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
914     RRC = &ARM::DPRRegClass;
915     // When NEON is used for SP, only half of the register file is available
916     // because operations that define both SP and DP results will be constrained
917     // to the VFP2 class (D0-D15). We currently model this constraint prior to
918     // coalescing by double-counting the SP regs. See the FIXME above.
919     if (Subtarget->useNEONForSinglePrecisionFP())
920       Cost = 2;
921     break;
922   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
923   case MVT::v4f32: case MVT::v2f64:
924     RRC = &ARM::DPRRegClass;
925     Cost = 2;
926     break;
927   case MVT::v4i64:
928     RRC = &ARM::DPRRegClass;
929     Cost = 4;
930     break;
931   case MVT::v8i64:
932     RRC = &ARM::DPRRegClass;
933     Cost = 8;
934     break;
935   }
936   return std::make_pair(RRC, Cost);
937 }
938
939 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
940   switch (Opcode) {
941   default: return nullptr;
942   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
943   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
944   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
945   case ARMISD::CALL:          return "ARMISD::CALL";
946   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
947   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
948   case ARMISD::tCALL:         return "ARMISD::tCALL";
949   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
950   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
951   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
952   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
953   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
954   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
955   case ARMISD::CMP:           return "ARMISD::CMP";
956   case ARMISD::CMN:           return "ARMISD::CMN";
957   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
958   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
959   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
960   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
961   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
962
963   case ARMISD::CMOV:          return "ARMISD::CMOV";
964
965   case ARMISD::RBIT:          return "ARMISD::RBIT";
966
967   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
968   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
969   case ARMISD::SITOF:         return "ARMISD::SITOF";
970   case ARMISD::UITOF:         return "ARMISD::UITOF";
971
972   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
973   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
974   case ARMISD::RRX:           return "ARMISD::RRX";
975
976   case ARMISD::ADDC:          return "ARMISD::ADDC";
977   case ARMISD::ADDE:          return "ARMISD::ADDE";
978   case ARMISD::SUBC:          return "ARMISD::SUBC";
979   case ARMISD::SUBE:          return "ARMISD::SUBE";
980
981   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
982   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
983
984   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
985   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
986
987   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
988
989   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
990
991   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
992
993   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
994
995   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
996
997   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
998
999   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1000   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1001   case ARMISD::VCGE:          return "ARMISD::VCGE";
1002   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1003   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1004   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1005   case ARMISD::VCGT:          return "ARMISD::VCGT";
1006   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1007   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1008   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1009   case ARMISD::VTST:          return "ARMISD::VTST";
1010
1011   case ARMISD::VSHL:          return "ARMISD::VSHL";
1012   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1013   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1014   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1015   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1016   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1017   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1018   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1019   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1020   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1021   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1022   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1023   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1024   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1025   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1026   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1027   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1028   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1029   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1030   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1031   case ARMISD::VDUP:          return "ARMISD::VDUP";
1032   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1033   case ARMISD::VEXT:          return "ARMISD::VEXT";
1034   case ARMISD::VREV64:        return "ARMISD::VREV64";
1035   case ARMISD::VREV32:        return "ARMISD::VREV32";
1036   case ARMISD::VREV16:        return "ARMISD::VREV16";
1037   case ARMISD::VZIP:          return "ARMISD::VZIP";
1038   case ARMISD::VUZP:          return "ARMISD::VUZP";
1039   case ARMISD::VTRN:          return "ARMISD::VTRN";
1040   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1041   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1042   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1043   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1044   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1045   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1046   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1047   case ARMISD::FMAX:          return "ARMISD::FMAX";
1048   case ARMISD::FMIN:          return "ARMISD::FMIN";
1049   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1050   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1051   case ARMISD::BFI:           return "ARMISD::BFI";
1052   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1053   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1054   case ARMISD::VBSL:          return "ARMISD::VBSL";
1055   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1056   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1057   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1058   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1059   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1060   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1061   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1062   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1063   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1064   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1065   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1066   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1067   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1068   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1069   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1070   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1071   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1072   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1073   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1074   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1075   }
1076 }
1077
1078 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1079   if (!VT.isVector()) return getPointerTy();
1080   return VT.changeVectorElementTypeToInteger();
1081 }
1082
1083 /// getRegClassFor - Return the register class that should be used for the
1084 /// specified value type.
1085 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1086   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1087   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1088   // load / store 4 to 8 consecutive D registers.
1089   if (Subtarget->hasNEON()) {
1090     if (VT == MVT::v4i64)
1091       return &ARM::QQPRRegClass;
1092     if (VT == MVT::v8i64)
1093       return &ARM::QQQQPRRegClass;
1094   }
1095   return TargetLowering::getRegClassFor(VT);
1096 }
1097
1098 // Create a fast isel object.
1099 FastISel *
1100 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1101                                   const TargetLibraryInfo *libInfo) const {
1102   return ARM::createFastISel(funcInfo, libInfo);
1103 }
1104
1105 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1106 /// be used for loads / stores from the global.
1107 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1108   return (Subtarget->isThumb1Only() ? 127 : 4095);
1109 }
1110
1111 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1112   unsigned NumVals = N->getNumValues();
1113   if (!NumVals)
1114     return Sched::RegPressure;
1115
1116   for (unsigned i = 0; i != NumVals; ++i) {
1117     EVT VT = N->getValueType(i);
1118     if (VT == MVT::Glue || VT == MVT::Other)
1119       continue;
1120     if (VT.isFloatingPoint() || VT.isVector())
1121       return Sched::ILP;
1122   }
1123
1124   if (!N->isMachineOpcode())
1125     return Sched::RegPressure;
1126
1127   // Load are scheduled for latency even if there instruction itinerary
1128   // is not available.
1129   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1130   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1131
1132   if (MCID.getNumDefs() == 0)
1133     return Sched::RegPressure;
1134   if (!Itins->isEmpty() &&
1135       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1136     return Sched::ILP;
1137
1138   return Sched::RegPressure;
1139 }
1140
1141 //===----------------------------------------------------------------------===//
1142 // Lowering Code
1143 //===----------------------------------------------------------------------===//
1144
1145 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1146 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1147   switch (CC) {
1148   default: llvm_unreachable("Unknown condition code!");
1149   case ISD::SETNE:  return ARMCC::NE;
1150   case ISD::SETEQ:  return ARMCC::EQ;
1151   case ISD::SETGT:  return ARMCC::GT;
1152   case ISD::SETGE:  return ARMCC::GE;
1153   case ISD::SETLT:  return ARMCC::LT;
1154   case ISD::SETLE:  return ARMCC::LE;
1155   case ISD::SETUGT: return ARMCC::HI;
1156   case ISD::SETUGE: return ARMCC::HS;
1157   case ISD::SETULT: return ARMCC::LO;
1158   case ISD::SETULE: return ARMCC::LS;
1159   }
1160 }
1161
1162 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1163 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1164                         ARMCC::CondCodes &CondCode2) {
1165   CondCode2 = ARMCC::AL;
1166   switch (CC) {
1167   default: llvm_unreachable("Unknown FP condition!");
1168   case ISD::SETEQ:
1169   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1170   case ISD::SETGT:
1171   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1172   case ISD::SETGE:
1173   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1174   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1175   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1176   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1177   case ISD::SETO:   CondCode = ARMCC::VC; break;
1178   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1179   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1180   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1181   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1182   case ISD::SETLT:
1183   case ISD::SETULT: CondCode = ARMCC::LT; break;
1184   case ISD::SETLE:
1185   case ISD::SETULE: CondCode = ARMCC::LE; break;
1186   case ISD::SETNE:
1187   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1188   }
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //                      Calling Convention Implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 #include "ARMGenCallingConv.inc"
1196
1197 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1198 /// account presence of floating point hardware and calling convention
1199 /// limitations, such as support for variadic functions.
1200 CallingConv::ID
1201 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1202                                            bool isVarArg) const {
1203   switch (CC) {
1204   default:
1205     llvm_unreachable("Unsupported calling convention");
1206   case CallingConv::ARM_AAPCS:
1207   case CallingConv::ARM_APCS:
1208   case CallingConv::GHC:
1209     return CC;
1210   case CallingConv::ARM_AAPCS_VFP:
1211     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1212   case CallingConv::C:
1213     if (!Subtarget->isAAPCS_ABI())
1214       return CallingConv::ARM_APCS;
1215     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1216              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1217              !isVarArg)
1218       return CallingConv::ARM_AAPCS_VFP;
1219     else
1220       return CallingConv::ARM_AAPCS;
1221   case CallingConv::Fast:
1222     if (!Subtarget->isAAPCS_ABI()) {
1223       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1224         return CallingConv::Fast;
1225       return CallingConv::ARM_APCS;
1226     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1227       return CallingConv::ARM_AAPCS_VFP;
1228     else
1229       return CallingConv::ARM_AAPCS;
1230   }
1231 }
1232
1233 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1234 /// CallingConvention.
1235 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1236                                                  bool Return,
1237                                                  bool isVarArg) const {
1238   switch (getEffectiveCallingConv(CC, isVarArg)) {
1239   default:
1240     llvm_unreachable("Unsupported calling convention");
1241   case CallingConv::ARM_APCS:
1242     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1243   case CallingConv::ARM_AAPCS:
1244     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1245   case CallingConv::ARM_AAPCS_VFP:
1246     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1247   case CallingConv::Fast:
1248     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1249   case CallingConv::GHC:
1250     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1251   }
1252 }
1253
1254 /// LowerCallResult - Lower the result values of a call into the
1255 /// appropriate copies out of appropriate physical registers.
1256 SDValue
1257 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1258                                    CallingConv::ID CallConv, bool isVarArg,
1259                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1260                                    SDLoc dl, SelectionDAG &DAG,
1261                                    SmallVectorImpl<SDValue> &InVals,
1262                                    bool isThisReturn, SDValue ThisVal) const {
1263
1264   // Assign locations to each value returned by this call.
1265   SmallVector<CCValAssign, 16> RVLocs;
1266   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1267                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1268   CCInfo.AnalyzeCallResult(Ins,
1269                            CCAssignFnForNode(CallConv, /* Return*/ true,
1270                                              isVarArg));
1271
1272   // Copy all of the result registers out of their specified physreg.
1273   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1274     CCValAssign VA = RVLocs[i];
1275
1276     // Pass 'this' value directly from the argument to return value, to avoid
1277     // reg unit interference
1278     if (i == 0 && isThisReturn) {
1279       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1280              "unexpected return calling convention register assignment");
1281       InVals.push_back(ThisVal);
1282       continue;
1283     }
1284
1285     SDValue Val;
1286     if (VA.needsCustom()) {
1287       // Handle f64 or half of a v2f64.
1288       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1289                                       InFlag);
1290       Chain = Lo.getValue(1);
1291       InFlag = Lo.getValue(2);
1292       VA = RVLocs[++i]; // skip ahead to next loc
1293       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1294                                       InFlag);
1295       Chain = Hi.getValue(1);
1296       InFlag = Hi.getValue(2);
1297       if (!Subtarget->isLittle())
1298         std::swap (Lo, Hi);
1299       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1300
1301       if (VA.getLocVT() == MVT::v2f64) {
1302         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1303         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1304                           DAG.getConstant(0, MVT::i32));
1305
1306         VA = RVLocs[++i]; // skip ahead to next loc
1307         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1308         Chain = Lo.getValue(1);
1309         InFlag = Lo.getValue(2);
1310         VA = RVLocs[++i]; // skip ahead to next loc
1311         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1312         Chain = Hi.getValue(1);
1313         InFlag = Hi.getValue(2);
1314         if (!Subtarget->isLittle())
1315           std::swap (Lo, Hi);
1316         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1317         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1318                           DAG.getConstant(1, MVT::i32));
1319       }
1320     } else {
1321       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1322                                InFlag);
1323       Chain = Val.getValue(1);
1324       InFlag = Val.getValue(2);
1325     }
1326
1327     switch (VA.getLocInfo()) {
1328     default: llvm_unreachable("Unknown loc info!");
1329     case CCValAssign::Full: break;
1330     case CCValAssign::BCvt:
1331       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1332       break;
1333     }
1334
1335     InVals.push_back(Val);
1336   }
1337
1338   return Chain;
1339 }
1340
1341 /// LowerMemOpCallTo - Store the argument to the stack.
1342 SDValue
1343 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1344                                     SDValue StackPtr, SDValue Arg,
1345                                     SDLoc dl, SelectionDAG &DAG,
1346                                     const CCValAssign &VA,
1347                                     ISD::ArgFlagsTy Flags) const {
1348   unsigned LocMemOffset = VA.getLocMemOffset();
1349   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1350   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1351   return DAG.getStore(Chain, dl, Arg, PtrOff,
1352                       MachinePointerInfo::getStack(LocMemOffset),
1353                       false, false, 0);
1354 }
1355
1356 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1357                                          SDValue Chain, SDValue &Arg,
1358                                          RegsToPassVector &RegsToPass,
1359                                          CCValAssign &VA, CCValAssign &NextVA,
1360                                          SDValue &StackPtr,
1361                                          SmallVectorImpl<SDValue> &MemOpChains,
1362                                          ISD::ArgFlagsTy Flags) const {
1363
1364   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1365                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1366   unsigned id = Subtarget->isLittle() ? 0 : 1;
1367   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1368
1369   if (NextVA.isRegLoc())
1370     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1371   else {
1372     assert(NextVA.isMemLoc());
1373     if (!StackPtr.getNode())
1374       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1375
1376     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1377                                            dl, DAG, NextVA,
1378                                            Flags));
1379   }
1380 }
1381
1382 /// LowerCall - Lowering a call into a callseq_start <-
1383 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1384 /// nodes.
1385 SDValue
1386 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1387                              SmallVectorImpl<SDValue> &InVals) const {
1388   SelectionDAG &DAG                     = CLI.DAG;
1389   SDLoc &dl                          = CLI.DL;
1390   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1391   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1392   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1393   SDValue Chain                         = CLI.Chain;
1394   SDValue Callee                        = CLI.Callee;
1395   bool &isTailCall                      = CLI.IsTailCall;
1396   CallingConv::ID CallConv              = CLI.CallConv;
1397   bool doesNotRet                       = CLI.DoesNotReturn;
1398   bool isVarArg                         = CLI.IsVarArg;
1399
1400   MachineFunction &MF = DAG.getMachineFunction();
1401   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1402   bool isThisReturn   = false;
1403   bool isSibCall      = false;
1404
1405   // Disable tail calls if they're not supported.
1406   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1407     isTailCall = false;
1408
1409   if (isTailCall) {
1410     // Check if it's really possible to do a tail call.
1411     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1412                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1413                                                    Outs, OutVals, Ins, DAG);
1414     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1415       report_fatal_error("failed to perform tail call elimination on a call "
1416                          "site marked musttail");
1417     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1418     // detected sibcalls.
1419     if (isTailCall) {
1420       ++NumTailCalls;
1421       isSibCall = true;
1422     }
1423   }
1424
1425   // Analyze operands of the call, assigning locations to each operand.
1426   SmallVector<CCValAssign, 16> ArgLocs;
1427   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1428                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1429   CCInfo.AnalyzeCallOperands(Outs,
1430                              CCAssignFnForNode(CallConv, /* Return*/ false,
1431                                                isVarArg));
1432
1433   // Get a count of how many bytes are to be pushed on the stack.
1434   unsigned NumBytes = CCInfo.getNextStackOffset();
1435
1436   // For tail calls, memory operands are available in our caller's stack.
1437   if (isSibCall)
1438     NumBytes = 0;
1439
1440   // Adjust the stack pointer for the new arguments...
1441   // These operations are automatically eliminated by the prolog/epilog pass
1442   if (!isSibCall)
1443     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1444                                  dl);
1445
1446   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1447
1448   RegsToPassVector RegsToPass;
1449   SmallVector<SDValue, 8> MemOpChains;
1450
1451   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1452   // of tail call optimization, arguments are handled later.
1453   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1454        i != e;
1455        ++i, ++realArgIdx) {
1456     CCValAssign &VA = ArgLocs[i];
1457     SDValue Arg = OutVals[realArgIdx];
1458     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1459     bool isByVal = Flags.isByVal();
1460
1461     // Promote the value if needed.
1462     switch (VA.getLocInfo()) {
1463     default: llvm_unreachable("Unknown loc info!");
1464     case CCValAssign::Full: break;
1465     case CCValAssign::SExt:
1466       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1467       break;
1468     case CCValAssign::ZExt:
1469       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1470       break;
1471     case CCValAssign::AExt:
1472       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1473       break;
1474     case CCValAssign::BCvt:
1475       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1476       break;
1477     }
1478
1479     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1480     if (VA.needsCustom()) {
1481       if (VA.getLocVT() == MVT::v2f64) {
1482         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1483                                   DAG.getConstant(0, MVT::i32));
1484         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1485                                   DAG.getConstant(1, MVT::i32));
1486
1487         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1488                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1489
1490         VA = ArgLocs[++i]; // skip ahead to next loc
1491         if (VA.isRegLoc()) {
1492           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1493                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1494         } else {
1495           assert(VA.isMemLoc());
1496
1497           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1498                                                  dl, DAG, VA, Flags));
1499         }
1500       } else {
1501         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1502                          StackPtr, MemOpChains, Flags);
1503       }
1504     } else if (VA.isRegLoc()) {
1505       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1506         assert(VA.getLocVT() == MVT::i32 &&
1507                "unexpected calling convention register assignment");
1508         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1509                "unexpected use of 'returned'");
1510         isThisReturn = true;
1511       }
1512       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1513     } else if (isByVal) {
1514       assert(VA.isMemLoc());
1515       unsigned offset = 0;
1516
1517       // True if this byval aggregate will be split between registers
1518       // and memory.
1519       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1520       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1521
1522       if (CurByValIdx < ByValArgsCount) {
1523
1524         unsigned RegBegin, RegEnd;
1525         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1526
1527         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1528         unsigned int i, j;
1529         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1530           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1531           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1532           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1533                                      MachinePointerInfo(),
1534                                      false, false, false,
1535                                      DAG.InferPtrAlignment(AddArg));
1536           MemOpChains.push_back(Load.getValue(1));
1537           RegsToPass.push_back(std::make_pair(j, Load));
1538         }
1539
1540         // If parameter size outsides register area, "offset" value
1541         // helps us to calculate stack slot for remained part properly.
1542         offset = RegEnd - RegBegin;
1543
1544         CCInfo.nextInRegsParam();
1545       }
1546
1547       if (Flags.getByValSize() > 4*offset) {
1548         unsigned LocMemOffset = VA.getLocMemOffset();
1549         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1550         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1551                                   StkPtrOff);
1552         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1553         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1554         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1555                                            MVT::i32);
1556         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1557
1558         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1559         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1560         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1561                                           Ops));
1562       }
1563     } else if (!isSibCall) {
1564       assert(VA.isMemLoc());
1565
1566       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1567                                              dl, DAG, VA, Flags));
1568     }
1569   }
1570
1571   if (!MemOpChains.empty())
1572     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1573
1574   // Build a sequence of copy-to-reg nodes chained together with token chain
1575   // and flag operands which copy the outgoing args into the appropriate regs.
1576   SDValue InFlag;
1577   // Tail call byval lowering might overwrite argument registers so in case of
1578   // tail call optimization the copies to registers are lowered later.
1579   if (!isTailCall)
1580     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1581       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1582                                RegsToPass[i].second, InFlag);
1583       InFlag = Chain.getValue(1);
1584     }
1585
1586   // For tail calls lower the arguments to the 'real' stack slot.
1587   if (isTailCall) {
1588     // Force all the incoming stack arguments to be loaded from the stack
1589     // before any new outgoing arguments are stored to the stack, because the
1590     // outgoing stack slots may alias the incoming argument stack slots, and
1591     // the alias isn't otherwise explicit. This is slightly more conservative
1592     // than necessary, because it means that each store effectively depends
1593     // on every argument instead of just those arguments it would clobber.
1594
1595     // Do not flag preceding copytoreg stuff together with the following stuff.
1596     InFlag = SDValue();
1597     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1598       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1599                                RegsToPass[i].second, InFlag);
1600       InFlag = Chain.getValue(1);
1601     }
1602     InFlag = SDValue();
1603   }
1604
1605   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1606   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1607   // node so that legalize doesn't hack it.
1608   bool isDirect = false;
1609   bool isARMFunc = false;
1610   bool isLocalARMFunc = false;
1611   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1612
1613   if (EnableARMLongCalls) {
1614     assert((Subtarget->isTargetWindows() ||
1615             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1616            "long-calls with non-static relocation model!");
1617     // Handle a global address or an external symbol. If it's not one of
1618     // those, the target's already in a register, so we don't need to do
1619     // anything extra.
1620     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1621       const GlobalValue *GV = G->getGlobal();
1622       // Create a constant pool entry for the callee address
1623       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1624       ARMConstantPoolValue *CPV =
1625         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1626
1627       // Get the address of the callee into a register
1628       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1629       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1630       Callee = DAG.getLoad(getPointerTy(), dl,
1631                            DAG.getEntryNode(), CPAddr,
1632                            MachinePointerInfo::getConstantPool(),
1633                            false, false, false, 0);
1634     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1635       const char *Sym = S->getSymbol();
1636
1637       // Create a constant pool entry for the callee address
1638       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1639       ARMConstantPoolValue *CPV =
1640         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1641                                       ARMPCLabelIndex, 0);
1642       // Get the address of the callee into a register
1643       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1644       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1645       Callee = DAG.getLoad(getPointerTy(), dl,
1646                            DAG.getEntryNode(), CPAddr,
1647                            MachinePointerInfo::getConstantPool(),
1648                            false, false, false, 0);
1649     }
1650   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1651     const GlobalValue *GV = G->getGlobal();
1652     isDirect = true;
1653     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1654     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1655                    getTargetMachine().getRelocationModel() != Reloc::Static;
1656     isARMFunc = !Subtarget->isThumb() || isStub;
1657     // ARM call to a local ARM function is predicable.
1658     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1659     // tBX takes a register source operand.
1660     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1661       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1662       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1663                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1664     } else if (Subtarget->isTargetCOFF()) {
1665       assert(Subtarget->isTargetWindows() &&
1666              "Windows is the only supported COFF target");
1667       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1668                                  ? ARMII::MO_DLLIMPORT
1669                                  : ARMII::MO_NO_FLAG;
1670       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1671                                           TargetFlags);
1672       if (GV->hasDLLImportStorageClass())
1673         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1674                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1675                                          Callee), MachinePointerInfo::getGOT(),
1676                              false, false, false, 0);
1677     } else {
1678       // On ELF targets for PIC code, direct calls should go through the PLT
1679       unsigned OpFlags = 0;
1680       if (Subtarget->isTargetELF() &&
1681           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1682         OpFlags = ARMII::MO_PLT;
1683       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1684     }
1685   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1686     isDirect = true;
1687     bool isStub = Subtarget->isTargetMachO() &&
1688                   getTargetMachine().getRelocationModel() != Reloc::Static;
1689     isARMFunc = !Subtarget->isThumb() || isStub;
1690     // tBX takes a register source operand.
1691     const char *Sym = S->getSymbol();
1692     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1693       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1694       ARMConstantPoolValue *CPV =
1695         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1696                                       ARMPCLabelIndex, 4);
1697       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1698       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1699       Callee = DAG.getLoad(getPointerTy(), dl,
1700                            DAG.getEntryNode(), CPAddr,
1701                            MachinePointerInfo::getConstantPool(),
1702                            false, false, false, 0);
1703       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1704       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1705                            getPointerTy(), Callee, PICLabel);
1706     } else {
1707       unsigned OpFlags = 0;
1708       // On ELF targets for PIC code, direct calls should go through the PLT
1709       if (Subtarget->isTargetELF() &&
1710                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1711         OpFlags = ARMII::MO_PLT;
1712       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1713     }
1714   }
1715
1716   // FIXME: handle tail calls differently.
1717   unsigned CallOpc;
1718   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1719       AttributeSet::FunctionIndex, Attribute::MinSize);
1720   if (Subtarget->isThumb()) {
1721     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1722       CallOpc = ARMISD::CALL_NOLINK;
1723     else
1724       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1725   } else {
1726     if (!isDirect && !Subtarget->hasV5TOps())
1727       CallOpc = ARMISD::CALL_NOLINK;
1728     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1729                // Emit regular call when code size is the priority
1730                !HasMinSizeAttr)
1731       // "mov lr, pc; b _foo" to avoid confusing the RSP
1732       CallOpc = ARMISD::CALL_NOLINK;
1733     else
1734       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1735   }
1736
1737   std::vector<SDValue> Ops;
1738   Ops.push_back(Chain);
1739   Ops.push_back(Callee);
1740
1741   // Add argument registers to the end of the list so that they are known live
1742   // into the call.
1743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1744     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1745                                   RegsToPass[i].second.getValueType()));
1746
1747   // Add a register mask operand representing the call-preserved registers.
1748   if (!isTailCall) {
1749     const uint32_t *Mask;
1750     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1751     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1752     if (isThisReturn) {
1753       // For 'this' returns, use the R0-preserving mask if applicable
1754       Mask = ARI->getThisReturnPreservedMask(CallConv);
1755       if (!Mask) {
1756         // Set isThisReturn to false if the calling convention is not one that
1757         // allows 'returned' to be modeled in this way, so LowerCallResult does
1758         // not try to pass 'this' straight through
1759         isThisReturn = false;
1760         Mask = ARI->getCallPreservedMask(CallConv);
1761       }
1762     } else
1763       Mask = ARI->getCallPreservedMask(CallConv);
1764
1765     assert(Mask && "Missing call preserved mask for calling convention");
1766     Ops.push_back(DAG.getRegisterMask(Mask));
1767   }
1768
1769   if (InFlag.getNode())
1770     Ops.push_back(InFlag);
1771
1772   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1773   if (isTailCall)
1774     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1775
1776   // Returns a chain and a flag for retval copy to use.
1777   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1778   InFlag = Chain.getValue(1);
1779
1780   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1781                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1782   if (!Ins.empty())
1783     InFlag = Chain.getValue(1);
1784
1785   // Handle result values, copying them out of physregs into vregs that we
1786   // return.
1787   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1788                          InVals, isThisReturn,
1789                          isThisReturn ? OutVals[0] : SDValue());
1790 }
1791
1792 /// HandleByVal - Every parameter *after* a byval parameter is passed
1793 /// on the stack.  Remember the next parameter register to allocate,
1794 /// and then confiscate the rest of the parameter registers to insure
1795 /// this.
1796 void
1797 ARMTargetLowering::HandleByVal(
1798     CCState *State, unsigned &size, unsigned Align) const {
1799   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1800   assert((State->getCallOrPrologue() == Prologue ||
1801           State->getCallOrPrologue() == Call) &&
1802          "unhandled ParmContext");
1803
1804   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1805     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1806       unsigned AlignInRegs = Align / 4;
1807       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1808       for (unsigned i = 0; i < Waste; ++i)
1809         reg = State->AllocateReg(GPRArgRegs, 4);
1810     }
1811     if (reg != 0) {
1812       unsigned excess = 4 * (ARM::R4 - reg);
1813
1814       // Special case when NSAA != SP and parameter size greater than size of
1815       // all remained GPR regs. In that case we can't split parameter, we must
1816       // send it to stack. We also must set NCRN to R4, so waste all
1817       // remained registers.
1818       const unsigned NSAAOffset = State->getNextStackOffset();
1819       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1820         while (State->AllocateReg(GPRArgRegs, 4))
1821           ;
1822         return;
1823       }
1824
1825       // First register for byval parameter is the first register that wasn't
1826       // allocated before this method call, so it would be "reg".
1827       // If parameter is small enough to be saved in range [reg, r4), then
1828       // the end (first after last) register would be reg + param-size-in-regs,
1829       // else parameter would be splitted between registers and stack,
1830       // end register would be r4 in this case.
1831       unsigned ByValRegBegin = reg;
1832       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1833       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1834       // Note, first register is allocated in the beginning of function already,
1835       // allocate remained amount of registers we need.
1836       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1837         State->AllocateReg(GPRArgRegs, 4);
1838       // A byval parameter that is split between registers and memory needs its
1839       // size truncated here.
1840       // In the case where the entire structure fits in registers, we set the
1841       // size in memory to zero.
1842       if (size < excess)
1843         size = 0;
1844       else
1845         size -= excess;
1846     }
1847   }
1848 }
1849
1850 /// MatchingStackOffset - Return true if the given stack call argument is
1851 /// already available in the same position (relatively) of the caller's
1852 /// incoming argument stack.
1853 static
1854 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1855                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1856                          const TargetInstrInfo *TII) {
1857   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1858   int FI = INT_MAX;
1859   if (Arg.getOpcode() == ISD::CopyFromReg) {
1860     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1861     if (!TargetRegisterInfo::isVirtualRegister(VR))
1862       return false;
1863     MachineInstr *Def = MRI->getVRegDef(VR);
1864     if (!Def)
1865       return false;
1866     if (!Flags.isByVal()) {
1867       if (!TII->isLoadFromStackSlot(Def, FI))
1868         return false;
1869     } else {
1870       return false;
1871     }
1872   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1873     if (Flags.isByVal())
1874       // ByVal argument is passed in as a pointer but it's now being
1875       // dereferenced. e.g.
1876       // define @foo(%struct.X* %A) {
1877       //   tail call @bar(%struct.X* byval %A)
1878       // }
1879       return false;
1880     SDValue Ptr = Ld->getBasePtr();
1881     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1882     if (!FINode)
1883       return false;
1884     FI = FINode->getIndex();
1885   } else
1886     return false;
1887
1888   assert(FI != INT_MAX);
1889   if (!MFI->isFixedObjectIndex(FI))
1890     return false;
1891   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1892 }
1893
1894 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1895 /// for tail call optimization. Targets which want to do tail call
1896 /// optimization should implement this function.
1897 bool
1898 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1899                                                      CallingConv::ID CalleeCC,
1900                                                      bool isVarArg,
1901                                                      bool isCalleeStructRet,
1902                                                      bool isCallerStructRet,
1903                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1904                                     const SmallVectorImpl<SDValue> &OutVals,
1905                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1906                                                      SelectionDAG& DAG) const {
1907   const Function *CallerF = DAG.getMachineFunction().getFunction();
1908   CallingConv::ID CallerCC = CallerF->getCallingConv();
1909   bool CCMatch = CallerCC == CalleeCC;
1910
1911   // Look for obvious safe cases to perform tail call optimization that do not
1912   // require ABI changes. This is what gcc calls sibcall.
1913
1914   // Do not sibcall optimize vararg calls unless the call site is not passing
1915   // any arguments.
1916   if (isVarArg && !Outs.empty())
1917     return false;
1918
1919   // Exception-handling functions need a special set of instructions to indicate
1920   // a return to the hardware. Tail-calling another function would probably
1921   // break this.
1922   if (CallerF->hasFnAttribute("interrupt"))
1923     return false;
1924
1925   // Also avoid sibcall optimization if either caller or callee uses struct
1926   // return semantics.
1927   if (isCalleeStructRet || isCallerStructRet)
1928     return false;
1929
1930   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1931   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1932   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1933   // support in the assembler and linker to be used. This would need to be
1934   // fixed to fully support tail calls in Thumb1.
1935   //
1936   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1937   // LR.  This means if we need to reload LR, it takes an extra instructions,
1938   // which outweighs the value of the tail call; but here we don't know yet
1939   // whether LR is going to be used.  Probably the right approach is to
1940   // generate the tail call here and turn it back into CALL/RET in
1941   // emitEpilogue if LR is used.
1942
1943   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1944   // but we need to make sure there are enough registers; the only valid
1945   // registers are the 4 used for parameters.  We don't currently do this
1946   // case.
1947   if (Subtarget->isThumb1Only())
1948     return false;
1949
1950   // If the calling conventions do not match, then we'd better make sure the
1951   // results are returned in the same way as what the caller expects.
1952   if (!CCMatch) {
1953     SmallVector<CCValAssign, 16> RVLocs1;
1954     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1955                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1956     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1957
1958     SmallVector<CCValAssign, 16> RVLocs2;
1959     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1960                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1961     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1962
1963     if (RVLocs1.size() != RVLocs2.size())
1964       return false;
1965     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1966       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1967         return false;
1968       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1969         return false;
1970       if (RVLocs1[i].isRegLoc()) {
1971         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1972           return false;
1973       } else {
1974         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1975           return false;
1976       }
1977     }
1978   }
1979
1980   // If Caller's vararg or byval argument has been split between registers and
1981   // stack, do not perform tail call, since part of the argument is in caller's
1982   // local frame.
1983   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1984                                       getInfo<ARMFunctionInfo>();
1985   if (AFI_Caller->getArgRegsSaveSize())
1986     return false;
1987
1988   // If the callee takes no arguments then go on to check the results of the
1989   // call.
1990   if (!Outs.empty()) {
1991     // Check if stack adjustment is needed. For now, do not do this if any
1992     // argument is passed on the stack.
1993     SmallVector<CCValAssign, 16> ArgLocs;
1994     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1995                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1996     CCInfo.AnalyzeCallOperands(Outs,
1997                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1998     if (CCInfo.getNextStackOffset()) {
1999       MachineFunction &MF = DAG.getMachineFunction();
2000
2001       // Check if the arguments are already laid out in the right way as
2002       // the caller's fixed stack objects.
2003       MachineFrameInfo *MFI = MF.getFrameInfo();
2004       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2005       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2006       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2007            i != e;
2008            ++i, ++realArgIdx) {
2009         CCValAssign &VA = ArgLocs[i];
2010         EVT RegVT = VA.getLocVT();
2011         SDValue Arg = OutVals[realArgIdx];
2012         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2013         if (VA.getLocInfo() == CCValAssign::Indirect)
2014           return false;
2015         if (VA.needsCustom()) {
2016           // f64 and vector types are split into multiple registers or
2017           // register/stack-slot combinations.  The types will not match
2018           // the registers; give up on memory f64 refs until we figure
2019           // out what to do about this.
2020           if (!VA.isRegLoc())
2021             return false;
2022           if (!ArgLocs[++i].isRegLoc())
2023             return false;
2024           if (RegVT == MVT::v2f64) {
2025             if (!ArgLocs[++i].isRegLoc())
2026               return false;
2027             if (!ArgLocs[++i].isRegLoc())
2028               return false;
2029           }
2030         } else if (!VA.isRegLoc()) {
2031           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2032                                    MFI, MRI, TII))
2033             return false;
2034         }
2035       }
2036     }
2037   }
2038
2039   return true;
2040 }
2041
2042 bool
2043 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2044                                   MachineFunction &MF, bool isVarArg,
2045                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2046                                   LLVMContext &Context) const {
2047   SmallVector<CCValAssign, 16> RVLocs;
2048   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2049   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2050                                                     isVarArg));
2051 }
2052
2053 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2054                                     SDLoc DL, SelectionDAG &DAG) {
2055   const MachineFunction &MF = DAG.getMachineFunction();
2056   const Function *F = MF.getFunction();
2057
2058   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2059
2060   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2061   // version of the "preferred return address". These offsets affect the return
2062   // instruction if this is a return from PL1 without hypervisor extensions.
2063   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2064   //    SWI:     0      "subs pc, lr, #0"
2065   //    ABORT:   +4     "subs pc, lr, #4"
2066   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2067   // UNDEF varies depending on where the exception came from ARM or Thumb
2068   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2069
2070   int64_t LROffset;
2071   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2072       IntKind == "ABORT")
2073     LROffset = 4;
2074   else if (IntKind == "SWI" || IntKind == "UNDEF")
2075     LROffset = 0;
2076   else
2077     report_fatal_error("Unsupported interrupt attribute. If present, value "
2078                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2079
2080   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2081
2082   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2083 }
2084
2085 SDValue
2086 ARMTargetLowering::LowerReturn(SDValue Chain,
2087                                CallingConv::ID CallConv, bool isVarArg,
2088                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2089                                const SmallVectorImpl<SDValue> &OutVals,
2090                                SDLoc dl, SelectionDAG &DAG) const {
2091
2092   // CCValAssign - represent the assignment of the return value to a location.
2093   SmallVector<CCValAssign, 16> RVLocs;
2094
2095   // CCState - Info about the registers and stack slots.
2096   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2097                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2098
2099   // Analyze outgoing return values.
2100   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2101                                                isVarArg));
2102
2103   SDValue Flag;
2104   SmallVector<SDValue, 4> RetOps;
2105   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2106   bool isLittleEndian = Subtarget->isLittle();
2107
2108   // Copy the result values into the output registers.
2109   for (unsigned i = 0, realRVLocIdx = 0;
2110        i != RVLocs.size();
2111        ++i, ++realRVLocIdx) {
2112     CCValAssign &VA = RVLocs[i];
2113     assert(VA.isRegLoc() && "Can only return in registers!");
2114
2115     SDValue Arg = OutVals[realRVLocIdx];
2116
2117     switch (VA.getLocInfo()) {
2118     default: llvm_unreachable("Unknown loc info!");
2119     case CCValAssign::Full: break;
2120     case CCValAssign::BCvt:
2121       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2122       break;
2123     }
2124
2125     if (VA.needsCustom()) {
2126       if (VA.getLocVT() == MVT::v2f64) {
2127         // Extract the first half and return it in two registers.
2128         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2129                                    DAG.getConstant(0, MVT::i32));
2130         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2131                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2132
2133         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2134                                  HalfGPRs.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                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2141                                  Flag);
2142         Flag = Chain.getValue(1);
2143         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2144         VA = RVLocs[++i]; // skip ahead to next loc
2145
2146         // Extract the 2nd half and fall through to handle it as an f64 value.
2147         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2148                           DAG.getConstant(1, MVT::i32));
2149       }
2150       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2151       // available.
2152       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2153                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2154       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2155                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2156                                Flag);
2157       Flag = Chain.getValue(1);
2158       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2159       VA = RVLocs[++i]; // skip ahead to next loc
2160       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2161                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2162                                Flag);
2163     } else
2164       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2165
2166     // Guarantee that all emitted copies are
2167     // stuck together, avoiding something bad.
2168     Flag = Chain.getValue(1);
2169     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2170   }
2171
2172   // Update chain and glue.
2173   RetOps[0] = Chain;
2174   if (Flag.getNode())
2175     RetOps.push_back(Flag);
2176
2177   // CPUs which aren't M-class use a special sequence to return from
2178   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2179   // though we use "subs pc, lr, #N").
2180   //
2181   // M-class CPUs actually use a normal return sequence with a special
2182   // (hardware-provided) value in LR, so the normal code path works.
2183   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2184       !Subtarget->isMClass()) {
2185     if (Subtarget->isThumb1Only())
2186       report_fatal_error("interrupt attribute is not supported in Thumb1");
2187     return LowerInterruptReturn(RetOps, dl, DAG);
2188   }
2189
2190   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2191 }
2192
2193 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2194   if (N->getNumValues() != 1)
2195     return false;
2196   if (!N->hasNUsesOfValue(1, 0))
2197     return false;
2198
2199   SDValue TCChain = Chain;
2200   SDNode *Copy = *N->use_begin();
2201   if (Copy->getOpcode() == ISD::CopyToReg) {
2202     // If the copy has a glue operand, we conservatively assume it isn't safe to
2203     // perform a tail call.
2204     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2205       return false;
2206     TCChain = Copy->getOperand(0);
2207   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2208     SDNode *VMov = Copy;
2209     // f64 returned in a pair of GPRs.
2210     SmallPtrSet<SDNode*, 2> Copies;
2211     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2212          UI != UE; ++UI) {
2213       if (UI->getOpcode() != ISD::CopyToReg)
2214         return false;
2215       Copies.insert(*UI);
2216     }
2217     if (Copies.size() > 2)
2218       return false;
2219
2220     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2221          UI != UE; ++UI) {
2222       SDValue UseChain = UI->getOperand(0);
2223       if (Copies.count(UseChain.getNode()))
2224         // Second CopyToReg
2225         Copy = *UI;
2226       else
2227         // First CopyToReg
2228         TCChain = UseChain;
2229     }
2230   } else if (Copy->getOpcode() == ISD::BITCAST) {
2231     // f32 returned in a single GPR.
2232     if (!Copy->hasOneUse())
2233       return false;
2234     Copy = *Copy->use_begin();
2235     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2236       return false;
2237     TCChain = Copy->getOperand(0);
2238   } else {
2239     return false;
2240   }
2241
2242   bool HasRet = false;
2243   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2244        UI != UE; ++UI) {
2245     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2246         UI->getOpcode() != ARMISD::INTRET_FLAG)
2247       return false;
2248     HasRet = true;
2249   }
2250
2251   if (!HasRet)
2252     return false;
2253
2254   Chain = TCChain;
2255   return true;
2256 }
2257
2258 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2259   if (!Subtarget->supportsTailCall())
2260     return false;
2261
2262   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2263     return false;
2264
2265   return !Subtarget->isThumb1Only();
2266 }
2267
2268 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2269 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2270 // one of the above mentioned nodes. It has to be wrapped because otherwise
2271 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2272 // be used to form addressing mode. These wrapped nodes will be selected
2273 // into MOVi.
2274 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2275   EVT PtrVT = Op.getValueType();
2276   // FIXME there is no actual debug info here
2277   SDLoc dl(Op);
2278   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2279   SDValue Res;
2280   if (CP->isMachineConstantPoolEntry())
2281     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2282                                     CP->getAlignment());
2283   else
2284     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2285                                     CP->getAlignment());
2286   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2287 }
2288
2289 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2290   return MachineJumpTableInfo::EK_Inline;
2291 }
2292
2293 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2294                                              SelectionDAG &DAG) const {
2295   MachineFunction &MF = DAG.getMachineFunction();
2296   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2297   unsigned ARMPCLabelIndex = 0;
2298   SDLoc DL(Op);
2299   EVT PtrVT = getPointerTy();
2300   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2301   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2302   SDValue CPAddr;
2303   if (RelocM == Reloc::Static) {
2304     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2305   } else {
2306     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2307     ARMPCLabelIndex = AFI->createPICLabelUId();
2308     ARMConstantPoolValue *CPV =
2309       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2310                                       ARMCP::CPBlockAddress, PCAdj);
2311     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2312   }
2313   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2314   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2315                                MachinePointerInfo::getConstantPool(),
2316                                false, false, false, 0);
2317   if (RelocM == Reloc::Static)
2318     return Result;
2319   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2320   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2321 }
2322
2323 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2324 SDValue
2325 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2326                                                  SelectionDAG &DAG) const {
2327   SDLoc dl(GA);
2328   EVT PtrVT = getPointerTy();
2329   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2330   MachineFunction &MF = DAG.getMachineFunction();
2331   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2332   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2333   ARMConstantPoolValue *CPV =
2334     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2335                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2336   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2337   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2338   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2339                          MachinePointerInfo::getConstantPool(),
2340                          false, false, false, 0);
2341   SDValue Chain = Argument.getValue(1);
2342
2343   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2344   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2345
2346   // call __tls_get_addr.
2347   ArgListTy Args;
2348   ArgListEntry Entry;
2349   Entry.Node = Argument;
2350   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2351   Args.push_back(Entry);
2352
2353   // FIXME: is there useful debug info available here?
2354   TargetLowering::CallLoweringInfo CLI(DAG);
2355   CLI.setDebugLoc(dl).setChain(Chain)
2356     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2357                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2358                0);
2359
2360   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2361   return CallResult.first;
2362 }
2363
2364 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2365 // "local exec" model.
2366 SDValue
2367 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2368                                         SelectionDAG &DAG,
2369                                         TLSModel::Model model) const {
2370   const GlobalValue *GV = GA->getGlobal();
2371   SDLoc dl(GA);
2372   SDValue Offset;
2373   SDValue Chain = DAG.getEntryNode();
2374   EVT PtrVT = getPointerTy();
2375   // Get the Thread Pointer
2376   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2377
2378   if (model == TLSModel::InitialExec) {
2379     MachineFunction &MF = DAG.getMachineFunction();
2380     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2381     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2382     // Initial exec model.
2383     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2384     ARMConstantPoolValue *CPV =
2385       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2386                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2387                                       true);
2388     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2389     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2390     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2391                          MachinePointerInfo::getConstantPool(),
2392                          false, false, false, 0);
2393     Chain = Offset.getValue(1);
2394
2395     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2396     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2397
2398     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2399                          MachinePointerInfo::getConstantPool(),
2400                          false, false, false, 0);
2401   } else {
2402     // local exec model
2403     assert(model == TLSModel::LocalExec);
2404     ARMConstantPoolValue *CPV =
2405       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2406     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2407     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2408     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2409                          MachinePointerInfo::getConstantPool(),
2410                          false, false, false, 0);
2411   }
2412
2413   // The address of the thread local variable is the add of the thread
2414   // pointer with the offset of the variable.
2415   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2416 }
2417
2418 SDValue
2419 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2420   // TODO: implement the "local dynamic" model
2421   assert(Subtarget->isTargetELF() &&
2422          "TLS not implemented for non-ELF targets");
2423   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2424
2425   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2426
2427   switch (model) {
2428     case TLSModel::GeneralDynamic:
2429     case TLSModel::LocalDynamic:
2430       return LowerToTLSGeneralDynamicModel(GA, DAG);
2431     case TLSModel::InitialExec:
2432     case TLSModel::LocalExec:
2433       return LowerToTLSExecModels(GA, DAG, model);
2434   }
2435   llvm_unreachable("bogus TLS model");
2436 }
2437
2438 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2439                                                  SelectionDAG &DAG) const {
2440   EVT PtrVT = getPointerTy();
2441   SDLoc dl(Op);
2442   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2443   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2444     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2445     ARMConstantPoolValue *CPV =
2446       ARMConstantPoolConstant::Create(GV,
2447                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2448     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2449     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2450     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2451                                  CPAddr,
2452                                  MachinePointerInfo::getConstantPool(),
2453                                  false, false, false, 0);
2454     SDValue Chain = Result.getValue(1);
2455     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2456     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2457     if (!UseGOTOFF)
2458       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2459                            MachinePointerInfo::getGOT(),
2460                            false, false, false, 0);
2461     return Result;
2462   }
2463
2464   // If we have T2 ops, we can materialize the address directly via movt/movw
2465   // pair. This is always cheaper.
2466   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2467     ++NumMovwMovt;
2468     // FIXME: Once remat is capable of dealing with instructions with register
2469     // operands, expand this into two nodes.
2470     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2471                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2472   } else {
2473     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2474     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2475     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2476                        MachinePointerInfo::getConstantPool(),
2477                        false, false, false, 0);
2478   }
2479 }
2480
2481 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2482                                                     SelectionDAG &DAG) const {
2483   EVT PtrVT = getPointerTy();
2484   SDLoc dl(Op);
2485   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2486   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2487
2488   if (Subtarget->useMovt(DAG.getMachineFunction()))
2489     ++NumMovwMovt;
2490
2491   // FIXME: Once remat is capable of dealing with instructions with register
2492   // operands, expand this into multiple nodes
2493   unsigned Wrapper =
2494       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2495
2496   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2497   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2498
2499   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2500     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2501                          MachinePointerInfo::getGOT(), false, false, false, 0);
2502   return Result;
2503 }
2504
2505 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2506                                                      SelectionDAG &DAG) const {
2507   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2508   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2509          "Windows on ARM expects to use movw/movt");
2510
2511   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2512   const ARMII::TOF TargetFlags =
2513     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2514   EVT PtrVT = getPointerTy();
2515   SDValue Result;
2516   SDLoc DL(Op);
2517
2518   ++NumMovwMovt;
2519
2520   // FIXME: Once remat is capable of dealing with instructions with register
2521   // operands, expand this into two nodes.
2522   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2523                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2524                                                   TargetFlags));
2525   if (GV->hasDLLImportStorageClass())
2526     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2527                          MachinePointerInfo::getGOT(), false, false, false, 0);
2528   return Result;
2529 }
2530
2531 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2532                                                     SelectionDAG &DAG) const {
2533   assert(Subtarget->isTargetELF() &&
2534          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2535   MachineFunction &MF = DAG.getMachineFunction();
2536   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2537   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2538   EVT PtrVT = getPointerTy();
2539   SDLoc dl(Op);
2540   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2541   ARMConstantPoolValue *CPV =
2542     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2543                                   ARMPCLabelIndex, PCAdj);
2544   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2545   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2546   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2547                                MachinePointerInfo::getConstantPool(),
2548                                false, false, false, 0);
2549   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2550   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2551 }
2552
2553 SDValue
2554 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2555   SDLoc dl(Op);
2556   SDValue Val = DAG.getConstant(0, MVT::i32);
2557   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2558                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2559                      Op.getOperand(1), Val);
2560 }
2561
2562 SDValue
2563 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2564   SDLoc dl(Op);
2565   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2566                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2567 }
2568
2569 SDValue
2570 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2571                                           const ARMSubtarget *Subtarget) const {
2572   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2573   SDLoc dl(Op);
2574   switch (IntNo) {
2575   default: return SDValue();    // Don't custom lower most intrinsics.
2576   case Intrinsic::arm_rbit: {
2577     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2578            "RBIT intrinsic must have i32 type!");
2579     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2580   }
2581   case Intrinsic::arm_thread_pointer: {
2582     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2583     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2584   }
2585   case Intrinsic::eh_sjlj_lsda: {
2586     MachineFunction &MF = DAG.getMachineFunction();
2587     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2588     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2589     EVT PtrVT = getPointerTy();
2590     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2591     SDValue CPAddr;
2592     unsigned PCAdj = (RelocM != Reloc::PIC_)
2593       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2594     ARMConstantPoolValue *CPV =
2595       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2596                                       ARMCP::CPLSDA, PCAdj);
2597     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2598     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2599     SDValue Result =
2600       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2601                   MachinePointerInfo::getConstantPool(),
2602                   false, false, false, 0);
2603
2604     if (RelocM == Reloc::PIC_) {
2605       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2606       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2607     }
2608     return Result;
2609   }
2610   case Intrinsic::arm_neon_vmulls:
2611   case Intrinsic::arm_neon_vmullu: {
2612     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2613       ? ARMISD::VMULLs : ARMISD::VMULLu;
2614     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2615                        Op.getOperand(1), Op.getOperand(2));
2616   }
2617   }
2618 }
2619
2620 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2621                                  const ARMSubtarget *Subtarget) {
2622   // FIXME: handle "fence singlethread" more efficiently.
2623   SDLoc dl(Op);
2624   if (!Subtarget->hasDataBarrier()) {
2625     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2626     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2627     // here.
2628     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2629            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2630     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2631                        DAG.getConstant(0, MVT::i32));
2632   }
2633
2634   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2635   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2636   unsigned Domain = ARM_MB::ISH;
2637   if (Subtarget->isMClass()) {
2638     // Only a full system barrier exists in the M-class architectures.
2639     Domain = ARM_MB::SY;
2640   } else if (Subtarget->isSwift() && Ord == Release) {
2641     // Swift happens to implement ISHST barriers in a way that's compatible with
2642     // Release semantics but weaker than ISH so we'd be fools not to use
2643     // it. Beware: other processors probably don't!
2644     Domain = ARM_MB::ISHST;
2645   }
2646
2647   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2648                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2649                      DAG.getConstant(Domain, MVT::i32));
2650 }
2651
2652 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2653                              const ARMSubtarget *Subtarget) {
2654   // ARM pre v5TE and Thumb1 does not have preload instructions.
2655   if (!(Subtarget->isThumb2() ||
2656         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2657     // Just preserve the chain.
2658     return Op.getOperand(0);
2659
2660   SDLoc dl(Op);
2661   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2662   if (!isRead &&
2663       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2664     // ARMv7 with MP extension has PLDW.
2665     return Op.getOperand(0);
2666
2667   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2668   if (Subtarget->isThumb()) {
2669     // Invert the bits.
2670     isRead = ~isRead & 1;
2671     isData = ~isData & 1;
2672   }
2673
2674   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2675                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2676                      DAG.getConstant(isData, MVT::i32));
2677 }
2678
2679 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2680   MachineFunction &MF = DAG.getMachineFunction();
2681   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2682
2683   // vastart just stores the address of the VarArgsFrameIndex slot into the
2684   // memory location argument.
2685   SDLoc dl(Op);
2686   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2687   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2688   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2689   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2690                       MachinePointerInfo(SV), false, false, 0);
2691 }
2692
2693 SDValue
2694 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2695                                         SDValue &Root, SelectionDAG &DAG,
2696                                         SDLoc dl) const {
2697   MachineFunction &MF = DAG.getMachineFunction();
2698   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2699
2700   const TargetRegisterClass *RC;
2701   if (AFI->isThumb1OnlyFunction())
2702     RC = &ARM::tGPRRegClass;
2703   else
2704     RC = &ARM::GPRRegClass;
2705
2706   // Transform the arguments stored in physical registers into virtual ones.
2707   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2708   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2709
2710   SDValue ArgValue2;
2711   if (NextVA.isMemLoc()) {
2712     MachineFrameInfo *MFI = MF.getFrameInfo();
2713     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2714
2715     // Create load node to retrieve arguments from the stack.
2716     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2717     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2718                             MachinePointerInfo::getFixedStack(FI),
2719                             false, false, false, 0);
2720   } else {
2721     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2722     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2723   }
2724   if (!Subtarget->isLittle())
2725     std::swap (ArgValue, ArgValue2);
2726   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2727 }
2728
2729 void
2730 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2731                                   unsigned InRegsParamRecordIdx,
2732                                   unsigned ArgSize,
2733                                   unsigned &ArgRegsSize,
2734                                   unsigned &ArgRegsSaveSize)
2735   const {
2736   unsigned NumGPRs;
2737   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2738     unsigned RBegin, REnd;
2739     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2740     NumGPRs = REnd - RBegin;
2741   } else {
2742     unsigned int firstUnalloced;
2743     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2744                                                 sizeof(GPRArgRegs) /
2745                                                 sizeof(GPRArgRegs[0]));
2746     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2747   }
2748
2749   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2750   ArgRegsSize = NumGPRs * 4;
2751
2752   // If parameter is split between stack and GPRs...
2753   if (NumGPRs && Align > 4 &&
2754       (ArgRegsSize < ArgSize ||
2755         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2756     // Add padding for part of param recovered from GPRs.  For example,
2757     // if Align == 8, its last byte must be at address K*8 - 1.
2758     // We need to do it, since remained (stack) part of parameter has
2759     // stack alignment, and we need to "attach" "GPRs head" without gaps
2760     // to it:
2761     // Stack:
2762     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2763     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2764     //
2765     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2766     unsigned Padding =
2767         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2768     ArgRegsSaveSize = ArgRegsSize + Padding;
2769   } else
2770     // We don't need to extend regs save size for byval parameters if they
2771     // are passed via GPRs only.
2772     ArgRegsSaveSize = ArgRegsSize;
2773 }
2774
2775 // The remaining GPRs hold either the beginning of variable-argument
2776 // data, or the beginning of an aggregate passed by value (usually
2777 // byval).  Either way, we allocate stack slots adjacent to the data
2778 // provided by our caller, and store the unallocated registers there.
2779 // If this is a variadic function, the va_list pointer will begin with
2780 // these values; otherwise, this reassembles a (byval) structure that
2781 // was split between registers and memory.
2782 // Return: The frame index registers were stored into.
2783 int
2784 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2785                                   SDLoc dl, SDValue &Chain,
2786                                   const Value *OrigArg,
2787                                   unsigned InRegsParamRecordIdx,
2788                                   unsigned OffsetFromOrigArg,
2789                                   unsigned ArgOffset,
2790                                   unsigned ArgSize,
2791                                   bool ForceMutable,
2792                                   unsigned ByValStoreOffset,
2793                                   unsigned TotalArgRegsSaveSize) const {
2794
2795   // Currently, two use-cases possible:
2796   // Case #1. Non-var-args function, and we meet first byval parameter.
2797   //          Setup first unallocated register as first byval register;
2798   //          eat all remained registers
2799   //          (these two actions are performed by HandleByVal method).
2800   //          Then, here, we initialize stack frame with
2801   //          "store-reg" instructions.
2802   // Case #2. Var-args function, that doesn't contain byval parameters.
2803   //          The same: eat all remained unallocated registers,
2804   //          initialize stack frame.
2805
2806   MachineFunction &MF = DAG.getMachineFunction();
2807   MachineFrameInfo *MFI = MF.getFrameInfo();
2808   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2809   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2810   unsigned RBegin, REnd;
2811   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2812     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2813     firstRegToSaveIndex = RBegin - ARM::R0;
2814     lastRegToSaveIndex = REnd - ARM::R0;
2815   } else {
2816     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2817       (GPRArgRegs, array_lengthof(GPRArgRegs));
2818     lastRegToSaveIndex = 4;
2819   }
2820
2821   unsigned ArgRegsSize, ArgRegsSaveSize;
2822   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2823                  ArgRegsSize, ArgRegsSaveSize);
2824
2825   // Store any by-val regs to their spots on the stack so that they may be
2826   // loaded by deferencing the result of formal parameter pointer or va_next.
2827   // Note: once stack area for byval/varargs registers
2828   // was initialized, it can't be initialized again.
2829   if (ArgRegsSaveSize) {
2830     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2831
2832     if (Padding) {
2833       assert(AFI->getStoredByValParamsPadding() == 0 &&
2834              "The only parameter may be padded.");
2835       AFI->setStoredByValParamsPadding(Padding);
2836     }
2837
2838     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2839                                             Padding +
2840                                               ByValStoreOffset -
2841                                               (int64_t)TotalArgRegsSaveSize,
2842                                             false);
2843     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2844     if (Padding) {
2845        MFI->CreateFixedObject(Padding,
2846                               ArgOffset + ByValStoreOffset -
2847                                 (int64_t)ArgRegsSaveSize,
2848                               false);
2849     }
2850
2851     SmallVector<SDValue, 4> MemOps;
2852     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2853          ++firstRegToSaveIndex, ++i) {
2854       const TargetRegisterClass *RC;
2855       if (AFI->isThumb1OnlyFunction())
2856         RC = &ARM::tGPRRegClass;
2857       else
2858         RC = &ARM::GPRRegClass;
2859
2860       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2861       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2862       SDValue Store =
2863         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2864                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2865                      false, false, 0);
2866       MemOps.push_back(Store);
2867       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2868                         DAG.getConstant(4, getPointerTy()));
2869     }
2870
2871     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2872
2873     if (!MemOps.empty())
2874       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2875     return FrameIndex;
2876   } else {
2877     if (ArgSize == 0) {
2878       // We cannot allocate a zero-byte object for the first variadic argument,
2879       // so just make up a size.
2880       ArgSize = 4;
2881     }
2882     // This will point to the next argument passed via stack.
2883     return MFI->CreateFixedObject(
2884       ArgSize, ArgOffset, !ForceMutable);
2885   }
2886 }
2887
2888 // Setup stack frame, the va_list pointer will start from.
2889 void
2890 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2891                                         SDLoc dl, SDValue &Chain,
2892                                         unsigned ArgOffset,
2893                                         unsigned TotalArgRegsSaveSize,
2894                                         bool ForceMutable) const {
2895   MachineFunction &MF = DAG.getMachineFunction();
2896   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2897
2898   // Try to store any remaining integer argument regs
2899   // to their spots on the stack so that they may be loaded by deferencing
2900   // the result of va_next.
2901   // If there is no regs to be stored, just point address after last
2902   // argument passed via stack.
2903   int FrameIndex =
2904     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2905                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2906                    0, TotalArgRegsSaveSize);
2907
2908   AFI->setVarArgsFrameIndex(FrameIndex);
2909 }
2910
2911 SDValue
2912 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2913                                         CallingConv::ID CallConv, bool isVarArg,
2914                                         const SmallVectorImpl<ISD::InputArg>
2915                                           &Ins,
2916                                         SDLoc dl, SelectionDAG &DAG,
2917                                         SmallVectorImpl<SDValue> &InVals)
2918                                           const {
2919   MachineFunction &MF = DAG.getMachineFunction();
2920   MachineFrameInfo *MFI = MF.getFrameInfo();
2921
2922   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2923
2924   // Assign locations to all of the incoming arguments.
2925   SmallVector<CCValAssign, 16> ArgLocs;
2926   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2927                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2928   CCInfo.AnalyzeFormalArguments(Ins,
2929                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2930                                                   isVarArg));
2931
2932   SmallVector<SDValue, 16> ArgValues;
2933   int lastInsIndex = -1;
2934   SDValue ArgValue;
2935   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2936   unsigned CurArgIdx = 0;
2937
2938   // Initially ArgRegsSaveSize is zero.
2939   // Then we increase this value each time we meet byval parameter.
2940   // We also increase this value in case of varargs function.
2941   AFI->setArgRegsSaveSize(0);
2942
2943   unsigned ByValStoreOffset = 0;
2944   unsigned TotalArgRegsSaveSize = 0;
2945   unsigned ArgRegsSaveSizeMaxAlign = 4;
2946
2947   // Calculate the amount of stack space that we need to allocate to store
2948   // byval and variadic arguments that are passed in registers.
2949   // We need to know this before we allocate the first byval or variadic
2950   // argument, as they will be allocated a stack slot below the CFA (Canonical
2951   // Frame Address, the stack pointer at entry to the function).
2952   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2953     CCValAssign &VA = ArgLocs[i];
2954     if (VA.isMemLoc()) {
2955       int index = VA.getValNo();
2956       if (index != lastInsIndex) {
2957         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2958         if (Flags.isByVal()) {
2959           unsigned ExtraArgRegsSize;
2960           unsigned ExtraArgRegsSaveSize;
2961           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2962                          Flags.getByValSize(),
2963                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2964
2965           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2966           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2967               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2968           CCInfo.nextInRegsParam();
2969         }
2970         lastInsIndex = index;
2971       }
2972     }
2973   }
2974   CCInfo.rewindByValRegsInfo();
2975   lastInsIndex = -1;
2976   if (isVarArg) {
2977     unsigned ExtraArgRegsSize;
2978     unsigned ExtraArgRegsSaveSize;
2979     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2980                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2981     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2982   }
2983   // If the arg regs save area contains N-byte aligned values, the
2984   // bottom of it must be at least N-byte aligned.
2985   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2986   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2987
2988   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989     CCValAssign &VA = ArgLocs[i];
2990     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2991     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2992     // Arguments stored in registers.
2993     if (VA.isRegLoc()) {
2994       EVT RegVT = VA.getLocVT();
2995
2996       if (VA.needsCustom()) {
2997         // f64 and vector types are split up into multiple registers or
2998         // combinations of registers and stack slots.
2999         if (VA.getLocVT() == MVT::v2f64) {
3000           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3001                                                    Chain, DAG, dl);
3002           VA = ArgLocs[++i]; // skip ahead to next loc
3003           SDValue ArgValue2;
3004           if (VA.isMemLoc()) {
3005             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3006             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3007             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3008                                     MachinePointerInfo::getFixedStack(FI),
3009                                     false, false, false, 0);
3010           } else {
3011             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3012                                              Chain, DAG, dl);
3013           }
3014           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3015           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3016                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3017           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3018                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3019         } else
3020           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3021
3022       } else {
3023         const TargetRegisterClass *RC;
3024
3025         if (RegVT == MVT::f32)
3026           RC = &ARM::SPRRegClass;
3027         else if (RegVT == MVT::f64)
3028           RC = &ARM::DPRRegClass;
3029         else if (RegVT == MVT::v2f64)
3030           RC = &ARM::QPRRegClass;
3031         else if (RegVT == MVT::i32)
3032           RC = AFI->isThumb1OnlyFunction() ?
3033             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3034             (const TargetRegisterClass*)&ARM::GPRRegClass;
3035         else
3036           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3037
3038         // Transform the arguments in physical registers into virtual ones.
3039         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3040         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3041       }
3042
3043       // If this is an 8 or 16-bit value, it is really passed promoted
3044       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3045       // truncate to the right size.
3046       switch (VA.getLocInfo()) {
3047       default: llvm_unreachable("Unknown loc info!");
3048       case CCValAssign::Full: break;
3049       case CCValAssign::BCvt:
3050         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3051         break;
3052       case CCValAssign::SExt:
3053         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3054                                DAG.getValueType(VA.getValVT()));
3055         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3056         break;
3057       case CCValAssign::ZExt:
3058         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3059                                DAG.getValueType(VA.getValVT()));
3060         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3061         break;
3062       }
3063
3064       InVals.push_back(ArgValue);
3065
3066     } else { // VA.isRegLoc()
3067
3068       // sanity check
3069       assert(VA.isMemLoc());
3070       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3071
3072       int index = ArgLocs[i].getValNo();
3073
3074       // Some Ins[] entries become multiple ArgLoc[] entries.
3075       // Process them only once.
3076       if (index != lastInsIndex)
3077         {
3078           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3079           // FIXME: For now, all byval parameter objects are marked mutable.
3080           // This can be changed with more analysis.
3081           // In case of tail call optimization mark all arguments mutable.
3082           // Since they could be overwritten by lowering of arguments in case of
3083           // a tail call.
3084           if (Flags.isByVal()) {
3085             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3086
3087             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3088             int FrameIndex = StoreByValRegs(
3089                 CCInfo, DAG, dl, Chain, CurOrigArg,
3090                 CurByValIndex,
3091                 Ins[VA.getValNo()].PartOffset,
3092                 VA.getLocMemOffset(),
3093                 Flags.getByValSize(),
3094                 true /*force mutable frames*/,
3095                 ByValStoreOffset,
3096                 TotalArgRegsSaveSize);
3097             ByValStoreOffset += Flags.getByValSize();
3098             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3099             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3100             CCInfo.nextInRegsParam();
3101           } else {
3102             unsigned FIOffset = VA.getLocMemOffset();
3103             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3104                                             FIOffset, true);
3105
3106             // Create load nodes to retrieve arguments from the stack.
3107             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3108             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3109                                          MachinePointerInfo::getFixedStack(FI),
3110                                          false, false, false, 0));
3111           }
3112           lastInsIndex = index;
3113         }
3114     }
3115   }
3116
3117   // varargs
3118   if (isVarArg)
3119     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3120                          CCInfo.getNextStackOffset(),
3121                          TotalArgRegsSaveSize);
3122
3123   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3124
3125   return Chain;
3126 }
3127
3128 /// isFloatingPointZero - Return true if this is +0.0.
3129 static bool isFloatingPointZero(SDValue Op) {
3130   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3131     return CFP->getValueAPF().isPosZero();
3132   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3133     // Maybe this has already been legalized into the constant pool?
3134     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3135       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3136       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3137         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3138           return CFP->getValueAPF().isPosZero();
3139     }
3140   }
3141   return false;
3142 }
3143
3144 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3145 /// the given operands.
3146 SDValue
3147 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3148                              SDValue &ARMcc, SelectionDAG &DAG,
3149                              SDLoc dl) const {
3150   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3151     unsigned C = RHSC->getZExtValue();
3152     if (!isLegalICmpImmediate(C)) {
3153       // Constant does not fit, try adjusting it by one?
3154       switch (CC) {
3155       default: break;
3156       case ISD::SETLT:
3157       case ISD::SETGE:
3158         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3159           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3160           RHS = DAG.getConstant(C-1, MVT::i32);
3161         }
3162         break;
3163       case ISD::SETULT:
3164       case ISD::SETUGE:
3165         if (C != 0 && isLegalICmpImmediate(C-1)) {
3166           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3167           RHS = DAG.getConstant(C-1, MVT::i32);
3168         }
3169         break;
3170       case ISD::SETLE:
3171       case ISD::SETGT:
3172         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3173           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3174           RHS = DAG.getConstant(C+1, MVT::i32);
3175         }
3176         break;
3177       case ISD::SETULE:
3178       case ISD::SETUGT:
3179         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3180           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3181           RHS = DAG.getConstant(C+1, MVT::i32);
3182         }
3183         break;
3184       }
3185     }
3186   }
3187
3188   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3189   ARMISD::NodeType CompareType;
3190   switch (CondCode) {
3191   default:
3192     CompareType = ARMISD::CMP;
3193     break;
3194   case ARMCC::EQ:
3195   case ARMCC::NE:
3196     // Uses only Z Flag
3197     CompareType = ARMISD::CMPZ;
3198     break;
3199   }
3200   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3201   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3202 }
3203
3204 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3205 SDValue
3206 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3207                              SDLoc dl) const {
3208   SDValue Cmp;
3209   if (!isFloatingPointZero(RHS))
3210     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3211   else
3212     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3213   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3214 }
3215
3216 /// duplicateCmp - Glue values can have only one use, so this function
3217 /// duplicates a comparison node.
3218 SDValue
3219 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3220   unsigned Opc = Cmp.getOpcode();
3221   SDLoc DL(Cmp);
3222   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3223     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3224
3225   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3226   Cmp = Cmp.getOperand(0);
3227   Opc = Cmp.getOpcode();
3228   if (Opc == ARMISD::CMPFP)
3229     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3230   else {
3231     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3232     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3233   }
3234   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3235 }
3236
3237 std::pair<SDValue, SDValue>
3238 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3239                                  SDValue &ARMcc) const {
3240   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3241
3242   SDValue Value, OverflowCmp;
3243   SDValue LHS = Op.getOperand(0);
3244   SDValue RHS = Op.getOperand(1);
3245
3246
3247   // FIXME: We are currently always generating CMPs because we don't support
3248   // generating CMN through the backend. This is not as good as the natural
3249   // CMP case because it causes a register dependency and cannot be folded
3250   // later.
3251
3252   switch (Op.getOpcode()) {
3253   default:
3254     llvm_unreachable("Unknown overflow instruction!");
3255   case ISD::SADDO:
3256     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3257     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3258     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3259     break;
3260   case ISD::UADDO:
3261     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3262     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3263     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3264     break;
3265   case ISD::SSUBO:
3266     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3267     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3268     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3269     break;
3270   case ISD::USUBO:
3271     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3272     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3273     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3274     break;
3275   } // switch (...)
3276
3277   return std::make_pair(Value, OverflowCmp);
3278 }
3279
3280
3281 SDValue
3282 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3283   // Let legalize expand this if it isn't a legal type yet.
3284   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3285     return SDValue();
3286
3287   SDValue Value, OverflowCmp;
3288   SDValue ARMcc;
3289   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3290   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3291   // We use 0 and 1 as false and true values.
3292   SDValue TVal = DAG.getConstant(1, MVT::i32);
3293   SDValue FVal = DAG.getConstant(0, MVT::i32);
3294   EVT VT = Op.getValueType();
3295
3296   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3297                                  ARMcc, CCR, OverflowCmp);
3298
3299   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3300   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3301 }
3302
3303
3304 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3305   SDValue Cond = Op.getOperand(0);
3306   SDValue SelectTrue = Op.getOperand(1);
3307   SDValue SelectFalse = Op.getOperand(2);
3308   SDLoc dl(Op);
3309   unsigned Opc = Cond.getOpcode();
3310
3311   if (Cond.getResNo() == 1 &&
3312       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3313        Opc == ISD::USUBO)) {
3314     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3315       return SDValue();
3316
3317     SDValue Value, OverflowCmp;
3318     SDValue ARMcc;
3319     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3320     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3321     EVT VT = Op.getValueType();
3322
3323     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3324                        ARMcc, CCR, OverflowCmp);
3325
3326   }
3327
3328   // Convert:
3329   //
3330   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3331   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3332   //
3333   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3334     const ConstantSDNode *CMOVTrue =
3335       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3336     const ConstantSDNode *CMOVFalse =
3337       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3338
3339     if (CMOVTrue && CMOVFalse) {
3340       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3341       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3342
3343       SDValue True;
3344       SDValue False;
3345       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3346         True = SelectTrue;
3347         False = SelectFalse;
3348       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3349         True = SelectFalse;
3350         False = SelectTrue;
3351       }
3352
3353       if (True.getNode() && False.getNode()) {
3354         EVT VT = Op.getValueType();
3355         SDValue ARMcc = Cond.getOperand(2);
3356         SDValue CCR = Cond.getOperand(3);
3357         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3358         assert(True.getValueType() == VT);
3359         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3360       }
3361     }
3362   }
3363
3364   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3365   // undefined bits before doing a full-word comparison with zero.
3366   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3367                      DAG.getConstant(1, Cond.getValueType()));
3368
3369   return DAG.getSelectCC(dl, Cond,
3370                          DAG.getConstant(0, Cond.getValueType()),
3371                          SelectTrue, SelectFalse, ISD::SETNE);
3372 }
3373
3374 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3375   if (CC == ISD::SETNE)
3376     return ISD::SETEQ;
3377   return ISD::getSetCCInverse(CC, true);
3378 }
3379
3380 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3381                                  bool &swpCmpOps, bool &swpVselOps) {
3382   // Start by selecting the GE condition code for opcodes that return true for
3383   // 'equality'
3384   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3385       CC == ISD::SETULE)
3386     CondCode = ARMCC::GE;
3387
3388   // and GT for opcodes that return false for 'equality'.
3389   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3390            CC == ISD::SETULT)
3391     CondCode = ARMCC::GT;
3392
3393   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3394   // to swap the compare operands.
3395   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3396       CC == ISD::SETULT)
3397     swpCmpOps = true;
3398
3399   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3400   // If we have an unordered opcode, we need to swap the operands to the VSEL
3401   // instruction (effectively negating the condition).
3402   //
3403   // This also has the effect of swapping which one of 'less' or 'greater'
3404   // returns true, so we also swap the compare operands. It also switches
3405   // whether we return true for 'equality', so we compensate by picking the
3406   // opposite condition code to our original choice.
3407   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3408       CC == ISD::SETUGT) {
3409     swpCmpOps = !swpCmpOps;
3410     swpVselOps = !swpVselOps;
3411     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3412   }
3413
3414   // 'ordered' is 'anything but unordered', so use the VS condition code and
3415   // swap the VSEL operands.
3416   if (CC == ISD::SETO) {
3417     CondCode = ARMCC::VS;
3418     swpVselOps = true;
3419   }
3420
3421   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3422   // code and swap the VSEL operands.
3423   if (CC == ISD::SETUNE) {
3424     CondCode = ARMCC::EQ;
3425     swpVselOps = true;
3426   }
3427 }
3428
3429 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3430   EVT VT = Op.getValueType();
3431   SDValue LHS = Op.getOperand(0);
3432   SDValue RHS = Op.getOperand(1);
3433   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3434   SDValue TrueVal = Op.getOperand(2);
3435   SDValue FalseVal = Op.getOperand(3);
3436   SDLoc dl(Op);
3437
3438   if (LHS.getValueType() == MVT::i32) {
3439     // Try to generate VSEL on ARMv8.
3440     // The VSEL instruction can't use all the usual ARM condition
3441     // codes: it only has two bits to select the condition code, so it's
3442     // constrained to use only GE, GT, VS and EQ.
3443     //
3444     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3445     // swap the operands of the previous compare instruction (effectively
3446     // inverting the compare condition, swapping 'less' and 'greater') and
3447     // sometimes need to swap the operands to the VSEL (which inverts the
3448     // condition in the sense of firing whenever the previous condition didn't)
3449     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3450                                       TrueVal.getValueType() == MVT::f64)) {
3451       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3452       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3453           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3454         CC = getInverseCCForVSEL(CC);
3455         std::swap(TrueVal, FalseVal);
3456       }
3457     }
3458
3459     SDValue ARMcc;
3460     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3461     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3462     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3463                        Cmp);
3464   }
3465
3466   ARMCC::CondCodes CondCode, CondCode2;
3467   FPCCToARMCC(CC, CondCode, CondCode2);
3468
3469   // Try to generate VSEL on ARMv8.
3470   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3471                                     TrueVal.getValueType() == MVT::f64)) {
3472     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3473     // same operands, as follows:
3474     //   c = fcmp [ogt, olt, ugt, ult] a, b
3475     //   select c, a, b
3476     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3477     // handled differently than the original code sequence.
3478     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3479         RHS == FalseVal) {
3480       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3481         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3482       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3483         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3484     }
3485
3486     bool swpCmpOps = false;
3487     bool swpVselOps = false;
3488     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3489
3490     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3491         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3492       if (swpCmpOps)
3493         std::swap(LHS, RHS);
3494       if (swpVselOps)
3495         std::swap(TrueVal, FalseVal);
3496     }
3497   }
3498
3499   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3500   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3501   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3502   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3503                                ARMcc, CCR, Cmp);
3504   if (CondCode2 != ARMCC::AL) {
3505     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3506     // FIXME: Needs another CMP because flag can have but one use.
3507     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3508     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3509                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3510   }
3511   return Result;
3512 }
3513
3514 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3515 /// to morph to an integer compare sequence.
3516 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3517                            const ARMSubtarget *Subtarget) {
3518   SDNode *N = Op.getNode();
3519   if (!N->hasOneUse())
3520     // Otherwise it requires moving the value from fp to integer registers.
3521     return false;
3522   if (!N->getNumValues())
3523     return false;
3524   EVT VT = Op.getValueType();
3525   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3526     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3527     // vmrs are very slow, e.g. cortex-a8.
3528     return false;
3529
3530   if (isFloatingPointZero(Op)) {
3531     SeenZero = true;
3532     return true;
3533   }
3534   return ISD::isNormalLoad(N);
3535 }
3536
3537 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3538   if (isFloatingPointZero(Op))
3539     return DAG.getConstant(0, MVT::i32);
3540
3541   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3542     return DAG.getLoad(MVT::i32, SDLoc(Op),
3543                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3544                        Ld->isVolatile(), Ld->isNonTemporal(),
3545                        Ld->isInvariant(), Ld->getAlignment());
3546
3547   llvm_unreachable("Unknown VFP cmp argument!");
3548 }
3549
3550 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3551                            SDValue &RetVal1, SDValue &RetVal2) {
3552   if (isFloatingPointZero(Op)) {
3553     RetVal1 = DAG.getConstant(0, MVT::i32);
3554     RetVal2 = DAG.getConstant(0, MVT::i32);
3555     return;
3556   }
3557
3558   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3559     SDValue Ptr = Ld->getBasePtr();
3560     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3561                           Ld->getChain(), Ptr,
3562                           Ld->getPointerInfo(),
3563                           Ld->isVolatile(), Ld->isNonTemporal(),
3564                           Ld->isInvariant(), Ld->getAlignment());
3565
3566     EVT PtrType = Ptr.getValueType();
3567     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3568     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3569                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3570     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3571                           Ld->getChain(), NewPtr,
3572                           Ld->getPointerInfo().getWithOffset(4),
3573                           Ld->isVolatile(), Ld->isNonTemporal(),
3574                           Ld->isInvariant(), NewAlign);
3575     return;
3576   }
3577
3578   llvm_unreachable("Unknown VFP cmp argument!");
3579 }
3580
3581 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3582 /// f32 and even f64 comparisons to integer ones.
3583 SDValue
3584 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3585   SDValue Chain = Op.getOperand(0);
3586   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3587   SDValue LHS = Op.getOperand(2);
3588   SDValue RHS = Op.getOperand(3);
3589   SDValue Dest = Op.getOperand(4);
3590   SDLoc dl(Op);
3591
3592   bool LHSSeenZero = false;
3593   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3594   bool RHSSeenZero = false;
3595   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3596   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3597     // If unsafe fp math optimization is enabled and there are no other uses of
3598     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3599     // to an integer comparison.
3600     if (CC == ISD::SETOEQ)
3601       CC = ISD::SETEQ;
3602     else if (CC == ISD::SETUNE)
3603       CC = ISD::SETNE;
3604
3605     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3606     SDValue ARMcc;
3607     if (LHS.getValueType() == MVT::f32) {
3608       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3609                         bitcastf32Toi32(LHS, DAG), Mask);
3610       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3611                         bitcastf32Toi32(RHS, DAG), Mask);
3612       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3613       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3614       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3615                          Chain, Dest, ARMcc, CCR, Cmp);
3616     }
3617
3618     SDValue LHS1, LHS2;
3619     SDValue RHS1, RHS2;
3620     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3621     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3622     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3623     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3624     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3625     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3626     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3627     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3628     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3629   }
3630
3631   return SDValue();
3632 }
3633
3634 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3635   SDValue Chain = Op.getOperand(0);
3636   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3637   SDValue LHS = Op.getOperand(2);
3638   SDValue RHS = Op.getOperand(3);
3639   SDValue Dest = Op.getOperand(4);
3640   SDLoc dl(Op);
3641
3642   if (LHS.getValueType() == MVT::i32) {
3643     SDValue ARMcc;
3644     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3645     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3646     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3647                        Chain, Dest, ARMcc, CCR, Cmp);
3648   }
3649
3650   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3651
3652   if (getTargetMachine().Options.UnsafeFPMath &&
3653       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3654        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3655     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3656     if (Result.getNode())
3657       return Result;
3658   }
3659
3660   ARMCC::CondCodes CondCode, CondCode2;
3661   FPCCToARMCC(CC, CondCode, CondCode2);
3662
3663   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3664   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3665   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3666   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3667   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3668   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3669   if (CondCode2 != ARMCC::AL) {
3670     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3671     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3672     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3673   }
3674   return Res;
3675 }
3676
3677 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3678   SDValue Chain = Op.getOperand(0);
3679   SDValue Table = Op.getOperand(1);
3680   SDValue Index = Op.getOperand(2);
3681   SDLoc dl(Op);
3682
3683   EVT PTy = getPointerTy();
3684   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3685   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3686   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3687   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3688   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3689   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3690   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3691   if (Subtarget->isThumb2()) {
3692     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3693     // which does another jump to the destination. This also makes it easier
3694     // to translate it to TBB / TBH later.
3695     // FIXME: This might not work if the function is extremely large.
3696     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3697                        Addr, Op.getOperand(2), JTI, UId);
3698   }
3699   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3700     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3701                        MachinePointerInfo::getJumpTable(),
3702                        false, false, false, 0);
3703     Chain = Addr.getValue(1);
3704     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3705     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3706   } else {
3707     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3708                        MachinePointerInfo::getJumpTable(),
3709                        false, false, false, 0);
3710     Chain = Addr.getValue(1);
3711     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3712   }
3713 }
3714
3715 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3716   EVT VT = Op.getValueType();
3717   SDLoc dl(Op);
3718
3719   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3720     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3721       return Op;
3722     return DAG.UnrollVectorOp(Op.getNode());
3723   }
3724
3725   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3726          "Invalid type for custom lowering!");
3727   if (VT != MVT::v4i16)
3728     return DAG.UnrollVectorOp(Op.getNode());
3729
3730   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3731   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3732 }
3733
3734 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3735   EVT VT = Op.getValueType();
3736   if (VT.isVector())
3737     return LowerVectorFP_TO_INT(Op, DAG);
3738
3739   SDLoc dl(Op);
3740   unsigned Opc;
3741
3742   switch (Op.getOpcode()) {
3743   default: llvm_unreachable("Invalid opcode!");
3744   case ISD::FP_TO_SINT:
3745     Opc = ARMISD::FTOSI;
3746     break;
3747   case ISD::FP_TO_UINT:
3748     Opc = ARMISD::FTOUI;
3749     break;
3750   }
3751   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3752   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3753 }
3754
3755 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3756   EVT VT = Op.getValueType();
3757   SDLoc dl(Op);
3758
3759   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3760     if (VT.getVectorElementType() == MVT::f32)
3761       return Op;
3762     return DAG.UnrollVectorOp(Op.getNode());
3763   }
3764
3765   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3766          "Invalid type for custom lowering!");
3767   if (VT != MVT::v4f32)
3768     return DAG.UnrollVectorOp(Op.getNode());
3769
3770   unsigned CastOpc;
3771   unsigned Opc;
3772   switch (Op.getOpcode()) {
3773   default: llvm_unreachable("Invalid opcode!");
3774   case ISD::SINT_TO_FP:
3775     CastOpc = ISD::SIGN_EXTEND;
3776     Opc = ISD::SINT_TO_FP;
3777     break;
3778   case ISD::UINT_TO_FP:
3779     CastOpc = ISD::ZERO_EXTEND;
3780     Opc = ISD::UINT_TO_FP;
3781     break;
3782   }
3783
3784   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3785   return DAG.getNode(Opc, dl, VT, Op);
3786 }
3787
3788 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3789   EVT VT = Op.getValueType();
3790   if (VT.isVector())
3791     return LowerVectorINT_TO_FP(Op, DAG);
3792
3793   SDLoc dl(Op);
3794   unsigned Opc;
3795
3796   switch (Op.getOpcode()) {
3797   default: llvm_unreachable("Invalid opcode!");
3798   case ISD::SINT_TO_FP:
3799     Opc = ARMISD::SITOF;
3800     break;
3801   case ISD::UINT_TO_FP:
3802     Opc = ARMISD::UITOF;
3803     break;
3804   }
3805
3806   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3807   return DAG.getNode(Opc, dl, VT, Op);
3808 }
3809
3810 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3811   // Implement fcopysign with a fabs and a conditional fneg.
3812   SDValue Tmp0 = Op.getOperand(0);
3813   SDValue Tmp1 = Op.getOperand(1);
3814   SDLoc dl(Op);
3815   EVT VT = Op.getValueType();
3816   EVT SrcVT = Tmp1.getValueType();
3817   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3818     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3819   bool UseNEON = !InGPR && Subtarget->hasNEON();
3820
3821   if (UseNEON) {
3822     // Use VBSL to copy the sign bit.
3823     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3824     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3825                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3826     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3827     if (VT == MVT::f64)
3828       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3829                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3830                          DAG.getConstant(32, MVT::i32));
3831     else /*if (VT == MVT::f32)*/
3832       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3833     if (SrcVT == MVT::f32) {
3834       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3835       if (VT == MVT::f64)
3836         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3837                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3838                            DAG.getConstant(32, MVT::i32));
3839     } else if (VT == MVT::f32)
3840       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3841                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3842                          DAG.getConstant(32, MVT::i32));
3843     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3844     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3845
3846     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3847                                             MVT::i32);
3848     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3849     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3850                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3851
3852     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3853                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3854                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3855     if (VT == MVT::f32) {
3856       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3857       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3858                         DAG.getConstant(0, MVT::i32));
3859     } else {
3860       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3861     }
3862
3863     return Res;
3864   }
3865
3866   // Bitcast operand 1 to i32.
3867   if (SrcVT == MVT::f64)
3868     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3869                        Tmp1).getValue(1);
3870   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3871
3872   // Or in the signbit with integer operations.
3873   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3874   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3875   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3876   if (VT == MVT::f32) {
3877     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3878                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3879     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3880                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3881   }
3882
3883   // f64: Or the high part with signbit and then combine two parts.
3884   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3885                      Tmp0);
3886   SDValue Lo = Tmp0.getValue(0);
3887   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3888   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3889   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3890 }
3891
3892 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3893   MachineFunction &MF = DAG.getMachineFunction();
3894   MachineFrameInfo *MFI = MF.getFrameInfo();
3895   MFI->setReturnAddressIsTaken(true);
3896
3897   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3898     return SDValue();
3899
3900   EVT VT = Op.getValueType();
3901   SDLoc dl(Op);
3902   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3903   if (Depth) {
3904     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3905     SDValue Offset = DAG.getConstant(4, MVT::i32);
3906     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3907                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3908                        MachinePointerInfo(), false, false, false, 0);
3909   }
3910
3911   // Return LR, which contains the return address. Mark it an implicit live-in.
3912   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3913   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3914 }
3915
3916 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3917   const ARMBaseRegisterInfo &ARI =
3918     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3919   MachineFunction &MF = DAG.getMachineFunction();
3920   MachineFrameInfo *MFI = MF.getFrameInfo();
3921   MFI->setFrameAddressIsTaken(true);
3922
3923   EVT VT = Op.getValueType();
3924   SDLoc dl(Op);  // FIXME probably not meaningful
3925   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3926   unsigned FrameReg = ARI.getFrameRegister(MF);
3927   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3928   while (Depth--)
3929     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3930                             MachinePointerInfo(),
3931                             false, false, false, 0);
3932   return FrameAddr;
3933 }
3934
3935 // FIXME? Maybe this could be a TableGen attribute on some registers and
3936 // this table could be generated automatically from RegInfo.
3937 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3938                                               EVT VT) const {
3939   unsigned Reg = StringSwitch<unsigned>(RegName)
3940                        .Case("sp", ARM::SP)
3941                        .Default(0);
3942   if (Reg)
3943     return Reg;
3944   report_fatal_error("Invalid register name global variable");
3945 }
3946
3947 /// ExpandBITCAST - If the target supports VFP, this function is called to
3948 /// expand a bit convert where either the source or destination type is i64 to
3949 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3950 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3951 /// vectors), since the legalizer won't know what to do with that.
3952 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3954   SDLoc dl(N);
3955   SDValue Op = N->getOperand(0);
3956
3957   // This function is only supposed to be called for i64 types, either as the
3958   // source or destination of the bit convert.
3959   EVT SrcVT = Op.getValueType();
3960   EVT DstVT = N->getValueType(0);
3961   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3962          "ExpandBITCAST called for non-i64 type");
3963
3964   // Turn i64->f64 into VMOVDRR.
3965   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3966     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3967                              DAG.getConstant(0, MVT::i32));
3968     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3969                              DAG.getConstant(1, MVT::i32));
3970     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3971                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3972   }
3973
3974   // Turn f64->i64 into VMOVRRD.
3975   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3976     SDValue Cvt;
3977     if (TLI.isBigEndian() && SrcVT.isVector() &&
3978         SrcVT.getVectorNumElements() > 1)
3979       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3980                         DAG.getVTList(MVT::i32, MVT::i32),
3981                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3982     else
3983       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3984                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3985     // Merge the pieces into a single i64 value.
3986     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3987   }
3988
3989   return SDValue();
3990 }
3991
3992 /// getZeroVector - Returns a vector of specified type with all zero elements.
3993 /// Zero vectors are used to represent vector negation and in those cases
3994 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3995 /// not support i64 elements, so sometimes the zero vectors will need to be
3996 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3997 /// zero vector.
3998 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3999   assert(VT.isVector() && "Expected a vector type");
4000   // The canonical modified immediate encoding of a zero vector is....0!
4001   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4002   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4003   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4004   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4005 }
4006
4007 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4008 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4009 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4010                                                 SelectionDAG &DAG) const {
4011   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4012   EVT VT = Op.getValueType();
4013   unsigned VTBits = VT.getSizeInBits();
4014   SDLoc dl(Op);
4015   SDValue ShOpLo = Op.getOperand(0);
4016   SDValue ShOpHi = Op.getOperand(1);
4017   SDValue ShAmt  = Op.getOperand(2);
4018   SDValue ARMcc;
4019   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4020
4021   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4022
4023   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4024                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4025   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4026   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4027                                    DAG.getConstant(VTBits, MVT::i32));
4028   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4029   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4030   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4031
4032   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4033   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4034                           ARMcc, DAG, dl);
4035   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4036   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4037                            CCR, Cmp);
4038
4039   SDValue Ops[2] = { Lo, Hi };
4040   return DAG.getMergeValues(Ops, dl);
4041 }
4042
4043 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4044 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4045 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4046                                                SelectionDAG &DAG) const {
4047   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4048   EVT VT = Op.getValueType();
4049   unsigned VTBits = VT.getSizeInBits();
4050   SDLoc dl(Op);
4051   SDValue ShOpLo = Op.getOperand(0);
4052   SDValue ShOpHi = Op.getOperand(1);
4053   SDValue ShAmt  = Op.getOperand(2);
4054   SDValue ARMcc;
4055
4056   assert(Op.getOpcode() == ISD::SHL_PARTS);
4057   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4058                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4059   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4060   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4061                                    DAG.getConstant(VTBits, MVT::i32));
4062   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4063   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4064
4065   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4066   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4067   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4068                           ARMcc, DAG, dl);
4069   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4070   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4071                            CCR, Cmp);
4072
4073   SDValue Ops[2] = { Lo, Hi };
4074   return DAG.getMergeValues(Ops, dl);
4075 }
4076
4077 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4078                                             SelectionDAG &DAG) const {
4079   // The rounding mode is in bits 23:22 of the FPSCR.
4080   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4081   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4082   // so that the shift + and get folded into a bitfield extract.
4083   SDLoc dl(Op);
4084   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4085                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4086                                               MVT::i32));
4087   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4088                                   DAG.getConstant(1U << 22, MVT::i32));
4089   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4090                               DAG.getConstant(22, MVT::i32));
4091   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4092                      DAG.getConstant(3, MVT::i32));
4093 }
4094
4095 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4096                          const ARMSubtarget *ST) {
4097   EVT VT = N->getValueType(0);
4098   SDLoc dl(N);
4099
4100   if (!ST->hasV6T2Ops())
4101     return SDValue();
4102
4103   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4104   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4105 }
4106
4107 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4108 /// for each 16-bit element from operand, repeated.  The basic idea is to
4109 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4110 ///
4111 /// Trace for v4i16:
4112 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4113 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4114 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4115 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4116 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4117 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4118 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4119 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4120 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4121   EVT VT = N->getValueType(0);
4122   SDLoc DL(N);
4123
4124   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4125   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4126   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4127   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4128   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4129   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4130 }
4131
4132 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4133 /// bit-count for each 16-bit element from the operand.  We need slightly
4134 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4135 /// 64/128-bit registers.
4136 ///
4137 /// Trace for v4i16:
4138 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4139 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4140 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4141 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4142 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4143   EVT VT = N->getValueType(0);
4144   SDLoc DL(N);
4145
4146   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4147   if (VT.is64BitVector()) {
4148     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4149     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4150                        DAG.getIntPtrConstant(0));
4151   } else {
4152     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4153                                     BitCounts, DAG.getIntPtrConstant(0));
4154     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4155   }
4156 }
4157
4158 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4159 /// bit-count for each 32-bit element from the operand.  The idea here is
4160 /// to split the vector into 16-bit elements, leverage the 16-bit count
4161 /// routine, and then combine the results.
4162 ///
4163 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4164 /// input    = [v0    v1    ] (vi: 32-bit elements)
4165 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4166 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4167 /// vrev: N0 = [k1 k0 k3 k2 ]
4168 ///            [k0 k1 k2 k3 ]
4169 ///       N1 =+[k1 k0 k3 k2 ]
4170 ///            [k0 k2 k1 k3 ]
4171 ///       N2 =+[k1 k3 k0 k2 ]
4172 ///            [k0    k2    k1    k3    ]
4173 /// Extended =+[k1    k3    k0    k2    ]
4174 ///            [k0    k2    ]
4175 /// Extracted=+[k1    k3    ]
4176 ///
4177 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4178   EVT VT = N->getValueType(0);
4179   SDLoc DL(N);
4180
4181   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4182
4183   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4184   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4185   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4186   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4187   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4188
4189   if (VT.is64BitVector()) {
4190     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4191     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4192                        DAG.getIntPtrConstant(0));
4193   } else {
4194     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4195                                     DAG.getIntPtrConstant(0));
4196     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4197   }
4198 }
4199
4200 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4201                           const ARMSubtarget *ST) {
4202   EVT VT = N->getValueType(0);
4203
4204   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4205   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4206           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4207          "Unexpected type for custom ctpop lowering");
4208
4209   if (VT.getVectorElementType() == MVT::i32)
4210     return lowerCTPOP32BitElements(N, DAG);
4211   else
4212     return lowerCTPOP16BitElements(N, DAG);
4213 }
4214
4215 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4216                           const ARMSubtarget *ST) {
4217   EVT VT = N->getValueType(0);
4218   SDLoc dl(N);
4219
4220   if (!VT.isVector())
4221     return SDValue();
4222
4223   // Lower vector shifts on NEON to use VSHL.
4224   assert(ST->hasNEON() && "unexpected vector shift");
4225
4226   // Left shifts translate directly to the vshiftu intrinsic.
4227   if (N->getOpcode() == ISD::SHL)
4228     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4229                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4230                        N->getOperand(0), N->getOperand(1));
4231
4232   assert((N->getOpcode() == ISD::SRA ||
4233           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4234
4235   // NEON uses the same intrinsics for both left and right shifts.  For
4236   // right shifts, the shift amounts are negative, so negate the vector of
4237   // shift amounts.
4238   EVT ShiftVT = N->getOperand(1).getValueType();
4239   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4240                                      getZeroVector(ShiftVT, DAG, dl),
4241                                      N->getOperand(1));
4242   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4243                              Intrinsic::arm_neon_vshifts :
4244                              Intrinsic::arm_neon_vshiftu);
4245   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4246                      DAG.getConstant(vshiftInt, MVT::i32),
4247                      N->getOperand(0), NegatedCount);
4248 }
4249
4250 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4251                                 const ARMSubtarget *ST) {
4252   EVT VT = N->getValueType(0);
4253   SDLoc dl(N);
4254
4255   // We can get here for a node like i32 = ISD::SHL i32, i64
4256   if (VT != MVT::i64)
4257     return SDValue();
4258
4259   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4260          "Unknown shift to lower!");
4261
4262   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4263   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4264       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4265     return SDValue();
4266
4267   // If we are in thumb mode, we don't have RRX.
4268   if (ST->isThumb1Only()) return SDValue();
4269
4270   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4271   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4272                            DAG.getConstant(0, MVT::i32));
4273   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4274                            DAG.getConstant(1, MVT::i32));
4275
4276   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4277   // captures the result into a carry flag.
4278   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4279   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4280
4281   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4282   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4283
4284   // Merge the pieces into a single i64 value.
4285  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4286 }
4287
4288 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4289   SDValue TmpOp0, TmpOp1;
4290   bool Invert = false;
4291   bool Swap = false;
4292   unsigned Opc = 0;
4293
4294   SDValue Op0 = Op.getOperand(0);
4295   SDValue Op1 = Op.getOperand(1);
4296   SDValue CC = Op.getOperand(2);
4297   EVT VT = Op.getValueType();
4298   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4299   SDLoc dl(Op);
4300
4301   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4302     switch (SetCCOpcode) {
4303     default: llvm_unreachable("Illegal FP comparison");
4304     case ISD::SETUNE:
4305     case ISD::SETNE:  Invert = true; // Fallthrough
4306     case ISD::SETOEQ:
4307     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4308     case ISD::SETOLT:
4309     case ISD::SETLT: Swap = true; // Fallthrough
4310     case ISD::SETOGT:
4311     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4312     case ISD::SETOLE:
4313     case ISD::SETLE:  Swap = true; // Fallthrough
4314     case ISD::SETOGE:
4315     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4316     case ISD::SETUGE: Swap = true; // Fallthrough
4317     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4318     case ISD::SETUGT: Swap = true; // Fallthrough
4319     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4320     case ISD::SETUEQ: Invert = true; // Fallthrough
4321     case ISD::SETONE:
4322       // Expand this to (OLT | OGT).
4323       TmpOp0 = Op0;
4324       TmpOp1 = Op1;
4325       Opc = ISD::OR;
4326       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4327       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4328       break;
4329     case ISD::SETUO: Invert = true; // Fallthrough
4330     case ISD::SETO:
4331       // Expand this to (OLT | OGE).
4332       TmpOp0 = Op0;
4333       TmpOp1 = Op1;
4334       Opc = ISD::OR;
4335       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4336       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4337       break;
4338     }
4339   } else {
4340     // Integer comparisons.
4341     switch (SetCCOpcode) {
4342     default: llvm_unreachable("Illegal integer comparison");
4343     case ISD::SETNE:  Invert = true;
4344     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4345     case ISD::SETLT:  Swap = true;
4346     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4347     case ISD::SETLE:  Swap = true;
4348     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4349     case ISD::SETULT: Swap = true;
4350     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4351     case ISD::SETULE: Swap = true;
4352     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4353     }
4354
4355     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4356     if (Opc == ARMISD::VCEQ) {
4357
4358       SDValue AndOp;
4359       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4360         AndOp = Op0;
4361       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4362         AndOp = Op1;
4363
4364       // Ignore bitconvert.
4365       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4366         AndOp = AndOp.getOperand(0);
4367
4368       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4369         Opc = ARMISD::VTST;
4370         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4371         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4372         Invert = !Invert;
4373       }
4374     }
4375   }
4376
4377   if (Swap)
4378     std::swap(Op0, Op1);
4379
4380   // If one of the operands is a constant vector zero, attempt to fold the
4381   // comparison to a specialized compare-against-zero form.
4382   SDValue SingleOp;
4383   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4384     SingleOp = Op0;
4385   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4386     if (Opc == ARMISD::VCGE)
4387       Opc = ARMISD::VCLEZ;
4388     else if (Opc == ARMISD::VCGT)
4389       Opc = ARMISD::VCLTZ;
4390     SingleOp = Op1;
4391   }
4392
4393   SDValue Result;
4394   if (SingleOp.getNode()) {
4395     switch (Opc) {
4396     case ARMISD::VCEQ:
4397       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4398     case ARMISD::VCGE:
4399       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4400     case ARMISD::VCLEZ:
4401       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4402     case ARMISD::VCGT:
4403       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4404     case ARMISD::VCLTZ:
4405       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4406     default:
4407       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4408     }
4409   } else {
4410      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4411   }
4412
4413   if (Invert)
4414     Result = DAG.getNOT(dl, Result, VT);
4415
4416   return Result;
4417 }
4418
4419 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4420 /// valid vector constant for a NEON instruction with a "modified immediate"
4421 /// operand (e.g., VMOV).  If so, return the encoded value.
4422 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4423                                  unsigned SplatBitSize, SelectionDAG &DAG,
4424                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4425   unsigned OpCmode, Imm;
4426
4427   // SplatBitSize is set to the smallest size that splats the vector, so a
4428   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4429   // immediate instructions others than VMOV do not support the 8-bit encoding
4430   // of a zero vector, and the default encoding of zero is supposed to be the
4431   // 32-bit version.
4432   if (SplatBits == 0)
4433     SplatBitSize = 32;
4434
4435   switch (SplatBitSize) {
4436   case 8:
4437     if (type != VMOVModImm)
4438       return SDValue();
4439     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4440     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4441     OpCmode = 0xe;
4442     Imm = SplatBits;
4443     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4444     break;
4445
4446   case 16:
4447     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4448     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4449     if ((SplatBits & ~0xff) == 0) {
4450       // Value = 0x00nn: Op=x, Cmode=100x.
4451       OpCmode = 0x8;
4452       Imm = SplatBits;
4453       break;
4454     }
4455     if ((SplatBits & ~0xff00) == 0) {
4456       // Value = 0xnn00: Op=x, Cmode=101x.
4457       OpCmode = 0xa;
4458       Imm = SplatBits >> 8;
4459       break;
4460     }
4461     return SDValue();
4462
4463   case 32:
4464     // NEON's 32-bit VMOV supports splat values where:
4465     // * only one byte is nonzero, or
4466     // * the least significant byte is 0xff and the second byte is nonzero, or
4467     // * the least significant 2 bytes are 0xff and the third is nonzero.
4468     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4469     if ((SplatBits & ~0xff) == 0) {
4470       // Value = 0x000000nn: Op=x, Cmode=000x.
4471       OpCmode = 0;
4472       Imm = SplatBits;
4473       break;
4474     }
4475     if ((SplatBits & ~0xff00) == 0) {
4476       // Value = 0x0000nn00: Op=x, Cmode=001x.
4477       OpCmode = 0x2;
4478       Imm = SplatBits >> 8;
4479       break;
4480     }
4481     if ((SplatBits & ~0xff0000) == 0) {
4482       // Value = 0x00nn0000: Op=x, Cmode=010x.
4483       OpCmode = 0x4;
4484       Imm = SplatBits >> 16;
4485       break;
4486     }
4487     if ((SplatBits & ~0xff000000) == 0) {
4488       // Value = 0xnn000000: Op=x, Cmode=011x.
4489       OpCmode = 0x6;
4490       Imm = SplatBits >> 24;
4491       break;
4492     }
4493
4494     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4495     if (type == OtherModImm) return SDValue();
4496
4497     if ((SplatBits & ~0xffff) == 0 &&
4498         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4499       // Value = 0x0000nnff: Op=x, Cmode=1100.
4500       OpCmode = 0xc;
4501       Imm = SplatBits >> 8;
4502       break;
4503     }
4504
4505     if ((SplatBits & ~0xffffff) == 0 &&
4506         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4507       // Value = 0x00nnffff: Op=x, Cmode=1101.
4508       OpCmode = 0xd;
4509       Imm = SplatBits >> 16;
4510       break;
4511     }
4512
4513     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4514     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4515     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4516     // and fall through here to test for a valid 64-bit splat.  But, then the
4517     // caller would also need to check and handle the change in size.
4518     return SDValue();
4519
4520   case 64: {
4521     if (type != VMOVModImm)
4522       return SDValue();
4523     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4524     uint64_t BitMask = 0xff;
4525     uint64_t Val = 0;
4526     unsigned ImmMask = 1;
4527     Imm = 0;
4528     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4529       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4530         Val |= BitMask;
4531         Imm |= ImmMask;
4532       } else if ((SplatBits & BitMask) != 0) {
4533         return SDValue();
4534       }
4535       BitMask <<= 8;
4536       ImmMask <<= 1;
4537     }
4538
4539     if (DAG.getTargetLoweringInfo().isBigEndian())
4540       // swap higher and lower 32 bit word
4541       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4542
4543     // Op=1, Cmode=1110.
4544     OpCmode = 0x1e;
4545     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4546     break;
4547   }
4548
4549   default:
4550     llvm_unreachable("unexpected size for isNEONModifiedImm");
4551   }
4552
4553   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4554   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4555 }
4556
4557 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4558                                            const ARMSubtarget *ST) const {
4559   if (!ST->hasVFP3())
4560     return SDValue();
4561
4562   bool IsDouble = Op.getValueType() == MVT::f64;
4563   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4564
4565   // Try splatting with a VMOV.f32...
4566   APFloat FPVal = CFP->getValueAPF();
4567   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4568
4569   if (ImmVal != -1) {
4570     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4571       // We have code in place to select a valid ConstantFP already, no need to
4572       // do any mangling.
4573       return Op;
4574     }
4575
4576     // It's a float and we are trying to use NEON operations where
4577     // possible. Lower it to a splat followed by an extract.
4578     SDLoc DL(Op);
4579     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4580     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4581                                       NewVal);
4582     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4583                        DAG.getConstant(0, MVT::i32));
4584   }
4585
4586   // The rest of our options are NEON only, make sure that's allowed before
4587   // proceeding..
4588   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4589     return SDValue();
4590
4591   EVT VMovVT;
4592   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4593
4594   // It wouldn't really be worth bothering for doubles except for one very
4595   // important value, which does happen to match: 0.0. So make sure we don't do
4596   // anything stupid.
4597   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4598     return SDValue();
4599
4600   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4601   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4602                                      false, VMOVModImm);
4603   if (NewVal != SDValue()) {
4604     SDLoc DL(Op);
4605     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4606                                       NewVal);
4607     if (IsDouble)
4608       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4609
4610     // It's a float: cast and extract a vector element.
4611     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4612                                        VecConstant);
4613     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4614                        DAG.getConstant(0, MVT::i32));
4615   }
4616
4617   // Finally, try a VMVN.i32
4618   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4619                              false, VMVNModImm);
4620   if (NewVal != SDValue()) {
4621     SDLoc DL(Op);
4622     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4623
4624     if (IsDouble)
4625       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4626
4627     // It's a float: cast and extract a vector element.
4628     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4629                                        VecConstant);
4630     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4631                        DAG.getConstant(0, MVT::i32));
4632   }
4633
4634   return SDValue();
4635 }
4636
4637 // check if an VEXT instruction can handle the shuffle mask when the
4638 // vector sources of the shuffle are the same.
4639 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4640   unsigned NumElts = VT.getVectorNumElements();
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, just follow it
4654     // back to index zero and keep going.
4655     ++ExpectedElt;
4656     if (ExpectedElt == NumElts)
4657       ExpectedElt = 0;
4658
4659     if (M[i] < 0) continue; // ignore UNDEF indices
4660     if (ExpectedElt != static_cast<unsigned>(M[i]))
4661       return false;
4662   }
4663
4664   return true;
4665 }
4666
4667
4668 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4669                        bool &ReverseVEXT, unsigned &Imm) {
4670   unsigned NumElts = VT.getVectorNumElements();
4671   ReverseVEXT = false;
4672
4673   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4674   if (M[0] < 0)
4675     return false;
4676
4677   Imm = M[0];
4678
4679   // If this is a VEXT shuffle, the immediate value is the index of the first
4680   // element.  The other shuffle indices must be the successive elements after
4681   // the first one.
4682   unsigned ExpectedElt = Imm;
4683   for (unsigned i = 1; i < NumElts; ++i) {
4684     // Increment the expected index.  If it wraps around, it may still be
4685     // a VEXT but the source vectors must be swapped.
4686     ExpectedElt += 1;
4687     if (ExpectedElt == NumElts * 2) {
4688       ExpectedElt = 0;
4689       ReverseVEXT = true;
4690     }
4691
4692     if (M[i] < 0) continue; // ignore UNDEF indices
4693     if (ExpectedElt != static_cast<unsigned>(M[i]))
4694       return false;
4695   }
4696
4697   // Adjust the index value if the source operands will be swapped.
4698   if (ReverseVEXT)
4699     Imm -= NumElts;
4700
4701   return true;
4702 }
4703
4704 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4705 /// instruction with the specified blocksize.  (The order of the elements
4706 /// within each block of the vector is reversed.)
4707 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4708   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4709          "Only possible block sizes for VREV are: 16, 32, 64");
4710
4711   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4712   if (EltSz == 64)
4713     return false;
4714
4715   unsigned NumElts = VT.getVectorNumElements();
4716   unsigned BlockElts = M[0] + 1;
4717   // If the first shuffle index is UNDEF, be optimistic.
4718   if (M[0] < 0)
4719     BlockElts = BlockSize / EltSz;
4720
4721   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4722     return false;
4723
4724   for (unsigned i = 0; i < NumElts; ++i) {
4725     if (M[i] < 0) continue; // ignore UNDEF indices
4726     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4727       return false;
4728   }
4729
4730   return true;
4731 }
4732
4733 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4734   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4735   // range, then 0 is placed into the resulting vector. So pretty much any mask
4736   // of 8 elements can work here.
4737   return VT == MVT::v8i8 && M.size() == 8;
4738 }
4739
4740 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4741   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4742   if (EltSz == 64)
4743     return false;
4744
4745   unsigned NumElts = VT.getVectorNumElements();
4746   WhichResult = (M[0] == 0 ? 0 : 1);
4747   for (unsigned i = 0; i < NumElts; i += 2) {
4748     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4749         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4750       return false;
4751   }
4752   return true;
4753 }
4754
4755 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4756 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4757 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4758 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4759   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4760   if (EltSz == 64)
4761     return false;
4762
4763   unsigned NumElts = VT.getVectorNumElements();
4764   WhichResult = (M[0] == 0 ? 0 : 1);
4765   for (unsigned i = 0; i < NumElts; i += 2) {
4766     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4767         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4768       return false;
4769   }
4770   return true;
4771 }
4772
4773 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4774   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4775   if (EltSz == 64)
4776     return false;
4777
4778   unsigned NumElts = VT.getVectorNumElements();
4779   WhichResult = (M[0] == 0 ? 0 : 1);
4780   for (unsigned i = 0; i != NumElts; ++i) {
4781     if (M[i] < 0) continue; // ignore UNDEF indices
4782     if ((unsigned) M[i] != 2 * i + WhichResult)
4783       return false;
4784   }
4785
4786   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4787   if (VT.is64BitVector() && EltSz == 32)
4788     return false;
4789
4790   return true;
4791 }
4792
4793 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4794 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4795 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4796 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4797   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4798   if (EltSz == 64)
4799     return false;
4800
4801   unsigned Half = VT.getVectorNumElements() / 2;
4802   WhichResult = (M[0] == 0 ? 0 : 1);
4803   for (unsigned j = 0; j != 2; ++j) {
4804     unsigned Idx = WhichResult;
4805     for (unsigned i = 0; i != Half; ++i) {
4806       int MIdx = M[i + j * Half];
4807       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4808         return false;
4809       Idx += 2;
4810     }
4811   }
4812
4813   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4814   if (VT.is64BitVector() && EltSz == 32)
4815     return false;
4816
4817   return true;
4818 }
4819
4820 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4821   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4822   if (EltSz == 64)
4823     return false;
4824
4825   unsigned NumElts = VT.getVectorNumElements();
4826   WhichResult = (M[0] == 0 ? 0 : 1);
4827   unsigned Idx = WhichResult * NumElts / 2;
4828   for (unsigned i = 0; i != NumElts; i += 2) {
4829     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4830         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4831       return false;
4832     Idx += 1;
4833   }
4834
4835   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4836   if (VT.is64BitVector() && EltSz == 32)
4837     return false;
4838
4839   return true;
4840 }
4841
4842 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4843 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4844 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4845 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4846   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4847   if (EltSz == 64)
4848     return false;
4849
4850   unsigned NumElts = VT.getVectorNumElements();
4851   WhichResult = (M[0] == 0 ? 0 : 1);
4852   unsigned Idx = WhichResult * NumElts / 2;
4853   for (unsigned i = 0; i != NumElts; i += 2) {
4854     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4855         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4856       return false;
4857     Idx += 1;
4858   }
4859
4860   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4861   if (VT.is64BitVector() && EltSz == 32)
4862     return false;
4863
4864   return true;
4865 }
4866
4867 /// \return true if this is a reverse operation on an vector.
4868 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4869   unsigned NumElts = VT.getVectorNumElements();
4870   // Make sure the mask has the right size.
4871   if (NumElts != M.size())
4872       return false;
4873
4874   // Look for <15, ..., 3, -1, 1, 0>.
4875   for (unsigned i = 0; i != NumElts; ++i)
4876     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4877       return false;
4878
4879   return true;
4880 }
4881
4882 // If N is an integer constant that can be moved into a register in one
4883 // instruction, return an SDValue of such a constant (will become a MOV
4884 // instruction).  Otherwise return null.
4885 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4886                                      const ARMSubtarget *ST, SDLoc dl) {
4887   uint64_t Val;
4888   if (!isa<ConstantSDNode>(N))
4889     return SDValue();
4890   Val = cast<ConstantSDNode>(N)->getZExtValue();
4891
4892   if (ST->isThumb1Only()) {
4893     if (Val <= 255 || ~Val <= 255)
4894       return DAG.getConstant(Val, MVT::i32);
4895   } else {
4896     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4897       return DAG.getConstant(Val, MVT::i32);
4898   }
4899   return SDValue();
4900 }
4901
4902 // If this is a case we can't handle, return null and let the default
4903 // expansion code take care of it.
4904 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4905                                              const ARMSubtarget *ST) const {
4906   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4907   SDLoc dl(Op);
4908   EVT VT = Op.getValueType();
4909
4910   APInt SplatBits, SplatUndef;
4911   unsigned SplatBitSize;
4912   bool HasAnyUndefs;
4913   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4914     if (SplatBitSize <= 64) {
4915       // Check if an immediate VMOV works.
4916       EVT VmovVT;
4917       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4918                                       SplatUndef.getZExtValue(), SplatBitSize,
4919                                       DAG, VmovVT, VT.is128BitVector(),
4920                                       VMOVModImm);
4921       if (Val.getNode()) {
4922         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4923         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4924       }
4925
4926       // Try an immediate VMVN.
4927       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4928       Val = isNEONModifiedImm(NegatedImm,
4929                                       SplatUndef.getZExtValue(), SplatBitSize,
4930                                       DAG, VmovVT, VT.is128BitVector(),
4931                                       VMVNModImm);
4932       if (Val.getNode()) {
4933         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4934         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4935       }
4936
4937       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4938       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4939         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4940         if (ImmVal != -1) {
4941           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4942           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4943         }
4944       }
4945     }
4946   }
4947
4948   // Scan through the operands to see if only one value is used.
4949   //
4950   // As an optimisation, even if more than one value is used it may be more
4951   // profitable to splat with one value then change some lanes.
4952   //
4953   // Heuristically we decide to do this if the vector has a "dominant" value,
4954   // defined as splatted to more than half of the lanes.
4955   unsigned NumElts = VT.getVectorNumElements();
4956   bool isOnlyLowElement = true;
4957   bool usesOnlyOneValue = true;
4958   bool hasDominantValue = false;
4959   bool isConstant = true;
4960
4961   // Map of the number of times a particular SDValue appears in the
4962   // element list.
4963   DenseMap<SDValue, unsigned> ValueCounts;
4964   SDValue Value;
4965   for (unsigned i = 0; i < NumElts; ++i) {
4966     SDValue V = Op.getOperand(i);
4967     if (V.getOpcode() == ISD::UNDEF)
4968       continue;
4969     if (i > 0)
4970       isOnlyLowElement = false;
4971     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4972       isConstant = false;
4973
4974     ValueCounts.insert(std::make_pair(V, 0));
4975     unsigned &Count = ValueCounts[V];
4976
4977     // Is this value dominant? (takes up more than half of the lanes)
4978     if (++Count > (NumElts / 2)) {
4979       hasDominantValue = true;
4980       Value = V;
4981     }
4982   }
4983   if (ValueCounts.size() != 1)
4984     usesOnlyOneValue = false;
4985   if (!Value.getNode() && ValueCounts.size() > 0)
4986     Value = ValueCounts.begin()->first;
4987
4988   if (ValueCounts.size() == 0)
4989     return DAG.getUNDEF(VT);
4990
4991   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4992   // Keep going if we are hitting this case.
4993   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4994     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4995
4996   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4997
4998   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4999   // i32 and try again.
5000   if (hasDominantValue && EltSize <= 32) {
5001     if (!isConstant) {
5002       SDValue N;
5003
5004       // If we are VDUPing a value that comes directly from a vector, that will
5005       // cause an unnecessary move to and from a GPR, where instead we could
5006       // just use VDUPLANE. We can only do this if the lane being extracted
5007       // is at a constant index, as the VDUP from lane instructions only have
5008       // constant-index forms.
5009       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5010           isa<ConstantSDNode>(Value->getOperand(1))) {
5011         // We need to create a new undef vector to use for the VDUPLANE if the
5012         // size of the vector from which we get the value is different than the
5013         // size of the vector that we need to create. We will insert the element
5014         // such that the register coalescer will remove unnecessary copies.
5015         if (VT != Value->getOperand(0).getValueType()) {
5016           ConstantSDNode *constIndex;
5017           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5018           assert(constIndex && "The index is not a constant!");
5019           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5020                              VT.getVectorNumElements();
5021           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5022                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5023                         Value, DAG.getConstant(index, MVT::i32)),
5024                            DAG.getConstant(index, MVT::i32));
5025         } else
5026           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5027                         Value->getOperand(0), Value->getOperand(1));
5028       } else
5029         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5030
5031       if (!usesOnlyOneValue) {
5032         // The dominant value was splatted as 'N', but we now have to insert
5033         // all differing elements.
5034         for (unsigned I = 0; I < NumElts; ++I) {
5035           if (Op.getOperand(I) == Value)
5036             continue;
5037           SmallVector<SDValue, 3> Ops;
5038           Ops.push_back(N);
5039           Ops.push_back(Op.getOperand(I));
5040           Ops.push_back(DAG.getConstant(I, MVT::i32));
5041           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5042         }
5043       }
5044       return N;
5045     }
5046     if (VT.getVectorElementType().isFloatingPoint()) {
5047       SmallVector<SDValue, 8> Ops;
5048       for (unsigned i = 0; i < NumElts; ++i)
5049         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5050                                   Op.getOperand(i)));
5051       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5052       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5053       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5054       if (Val.getNode())
5055         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5056     }
5057     if (usesOnlyOneValue) {
5058       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5059       if (isConstant && Val.getNode())
5060         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5061     }
5062   }
5063
5064   // If all elements are constants and the case above didn't get hit, fall back
5065   // to the default expansion, which will generate a load from the constant
5066   // pool.
5067   if (isConstant)
5068     return SDValue();
5069
5070   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5071   if (NumElts >= 4) {
5072     SDValue shuffle = ReconstructShuffle(Op, DAG);
5073     if (shuffle != SDValue())
5074       return shuffle;
5075   }
5076
5077   // Vectors with 32- or 64-bit elements can be built by directly assigning
5078   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5079   // will be legalized.
5080   if (EltSize >= 32) {
5081     // Do the expansion with floating-point types, since that is what the VFP
5082     // registers are defined to use, and since i64 is not legal.
5083     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5084     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5085     SmallVector<SDValue, 8> Ops;
5086     for (unsigned i = 0; i < NumElts; ++i)
5087       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5088     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5089     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5090   }
5091
5092   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5093   // know the default expansion would otherwise fall back on something even
5094   // worse. For a vector with one or two non-undef values, that's
5095   // scalar_to_vector for the elements followed by a shuffle (provided the
5096   // shuffle is valid for the target) and materialization element by element
5097   // on the stack followed by a load for everything else.
5098   if (!isConstant && !usesOnlyOneValue) {
5099     SDValue Vec = DAG.getUNDEF(VT);
5100     for (unsigned i = 0 ; i < NumElts; ++i) {
5101       SDValue V = Op.getOperand(i);
5102       if (V.getOpcode() == ISD::UNDEF)
5103         continue;
5104       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5105       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5106     }
5107     return Vec;
5108   }
5109
5110   return SDValue();
5111 }
5112
5113 // Gather data to see if the operation can be modelled as a
5114 // shuffle in combination with VEXTs.
5115 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5116                                               SelectionDAG &DAG) const {
5117   SDLoc dl(Op);
5118   EVT VT = Op.getValueType();
5119   unsigned NumElts = VT.getVectorNumElements();
5120
5121   SmallVector<SDValue, 2> SourceVecs;
5122   SmallVector<unsigned, 2> MinElts;
5123   SmallVector<unsigned, 2> MaxElts;
5124
5125   for (unsigned i = 0; i < NumElts; ++i) {
5126     SDValue V = Op.getOperand(i);
5127     if (V.getOpcode() == ISD::UNDEF)
5128       continue;
5129     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5130       // A shuffle can only come from building a vector from various
5131       // elements of other vectors.
5132       return SDValue();
5133     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5134                VT.getVectorElementType()) {
5135       // This code doesn't know how to handle shuffles where the vector
5136       // element types do not match (this happens because type legalization
5137       // promotes the return type of EXTRACT_VECTOR_ELT).
5138       // FIXME: It might be appropriate to extend this code to handle
5139       // mismatched types.
5140       return SDValue();
5141     }
5142
5143     // Record this extraction against the appropriate vector if possible...
5144     SDValue SourceVec = V.getOperand(0);
5145     // If the element number isn't a constant, we can't effectively
5146     // analyze what's going on.
5147     if (!isa<ConstantSDNode>(V.getOperand(1)))
5148       return SDValue();
5149     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5150     bool FoundSource = false;
5151     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5152       if (SourceVecs[j] == SourceVec) {
5153         if (MinElts[j] > EltNo)
5154           MinElts[j] = EltNo;
5155         if (MaxElts[j] < EltNo)
5156           MaxElts[j] = EltNo;
5157         FoundSource = true;
5158         break;
5159       }
5160     }
5161
5162     // Or record a new source if not...
5163     if (!FoundSource) {
5164       SourceVecs.push_back(SourceVec);
5165       MinElts.push_back(EltNo);
5166       MaxElts.push_back(EltNo);
5167     }
5168   }
5169
5170   // Currently only do something sane when at most two source vectors
5171   // involved.
5172   if (SourceVecs.size() > 2)
5173     return SDValue();
5174
5175   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5176   int VEXTOffsets[2] = {0, 0};
5177
5178   // This loop extracts the usage patterns of the source vectors
5179   // and prepares appropriate SDValues for a shuffle if possible.
5180   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5181     if (SourceVecs[i].getValueType() == VT) {
5182       // No VEXT necessary
5183       ShuffleSrcs[i] = SourceVecs[i];
5184       VEXTOffsets[i] = 0;
5185       continue;
5186     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5187       // It probably isn't worth padding out a smaller vector just to
5188       // break it down again in a shuffle.
5189       return SDValue();
5190     }
5191
5192     // Since only 64-bit and 128-bit vectors are legal on ARM and
5193     // we've eliminated the other cases...
5194     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5195            "unexpected vector sizes in ReconstructShuffle");
5196
5197     if (MaxElts[i] - MinElts[i] >= NumElts) {
5198       // Span too large for a VEXT to cope
5199       return SDValue();
5200     }
5201
5202     if (MinElts[i] >= NumElts) {
5203       // The extraction can just take the second half
5204       VEXTOffsets[i] = NumElts;
5205       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5206                                    SourceVecs[i],
5207                                    DAG.getIntPtrConstant(NumElts));
5208     } else if (MaxElts[i] < NumElts) {
5209       // The extraction can just take the first half
5210       VEXTOffsets[i] = 0;
5211       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5212                                    SourceVecs[i],
5213                                    DAG.getIntPtrConstant(0));
5214     } else {
5215       // An actual VEXT is needed
5216       VEXTOffsets[i] = MinElts[i];
5217       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5218                                      SourceVecs[i],
5219                                      DAG.getIntPtrConstant(0));
5220       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5221                                      SourceVecs[i],
5222                                      DAG.getIntPtrConstant(NumElts));
5223       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5224                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5225     }
5226   }
5227
5228   SmallVector<int, 8> Mask;
5229
5230   for (unsigned i = 0; i < NumElts; ++i) {
5231     SDValue Entry = Op.getOperand(i);
5232     if (Entry.getOpcode() == ISD::UNDEF) {
5233       Mask.push_back(-1);
5234       continue;
5235     }
5236
5237     SDValue ExtractVec = Entry.getOperand(0);
5238     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5239                                           .getOperand(1))->getSExtValue();
5240     if (ExtractVec == SourceVecs[0]) {
5241       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5242     } else {
5243       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5244     }
5245   }
5246
5247   // Final check before we try to produce nonsense...
5248   if (isShuffleMaskLegal(Mask, VT))
5249     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5250                                 &Mask[0]);
5251
5252   return SDValue();
5253 }
5254
5255 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5256 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5257 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5258 /// are assumed to be legal.
5259 bool
5260 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5261                                       EVT VT) const {
5262   if (VT.getVectorNumElements() == 4 &&
5263       (VT.is128BitVector() || VT.is64BitVector())) {
5264     unsigned PFIndexes[4];
5265     for (unsigned i = 0; i != 4; ++i) {
5266       if (M[i] < 0)
5267         PFIndexes[i] = 8;
5268       else
5269         PFIndexes[i] = M[i];
5270     }
5271
5272     // Compute the index in the perfect shuffle table.
5273     unsigned PFTableIndex =
5274       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5275     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5276     unsigned Cost = (PFEntry >> 30);
5277
5278     if (Cost <= 4)
5279       return true;
5280   }
5281
5282   bool ReverseVEXT;
5283   unsigned Imm, WhichResult;
5284
5285   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5286   return (EltSize >= 32 ||
5287           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5288           isVREVMask(M, VT, 64) ||
5289           isVREVMask(M, VT, 32) ||
5290           isVREVMask(M, VT, 16) ||
5291           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5292           isVTBLMask(M, VT) ||
5293           isVTRNMask(M, VT, WhichResult) ||
5294           isVUZPMask(M, VT, WhichResult) ||
5295           isVZIPMask(M, VT, WhichResult) ||
5296           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5297           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5298           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5299           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5300 }
5301
5302 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5303 /// the specified operations to build the shuffle.
5304 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5305                                       SDValue RHS, SelectionDAG &DAG,
5306                                       SDLoc dl) {
5307   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5308   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5309   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5310
5311   enum {
5312     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5313     OP_VREV,
5314     OP_VDUP0,
5315     OP_VDUP1,
5316     OP_VDUP2,
5317     OP_VDUP3,
5318     OP_VEXT1,
5319     OP_VEXT2,
5320     OP_VEXT3,
5321     OP_VUZPL, // VUZP, left result
5322     OP_VUZPR, // VUZP, right result
5323     OP_VZIPL, // VZIP, left result
5324     OP_VZIPR, // VZIP, right result
5325     OP_VTRNL, // VTRN, left result
5326     OP_VTRNR  // VTRN, right result
5327   };
5328
5329   if (OpNum == OP_COPY) {
5330     if (LHSID == (1*9+2)*9+3) return LHS;
5331     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5332     return RHS;
5333   }
5334
5335   SDValue OpLHS, OpRHS;
5336   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5337   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5338   EVT VT = OpLHS.getValueType();
5339
5340   switch (OpNum) {
5341   default: llvm_unreachable("Unknown shuffle opcode!");
5342   case OP_VREV:
5343     // VREV divides the vector in half and swaps within the half.
5344     if (VT.getVectorElementType() == MVT::i32 ||
5345         VT.getVectorElementType() == MVT::f32)
5346       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5347     // vrev <4 x i16> -> VREV32
5348     if (VT.getVectorElementType() == MVT::i16)
5349       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5350     // vrev <4 x i8> -> VREV16
5351     assert(VT.getVectorElementType() == MVT::i8);
5352     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5353   case OP_VDUP0:
5354   case OP_VDUP1:
5355   case OP_VDUP2:
5356   case OP_VDUP3:
5357     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5358                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5359   case OP_VEXT1:
5360   case OP_VEXT2:
5361   case OP_VEXT3:
5362     return DAG.getNode(ARMISD::VEXT, dl, VT,
5363                        OpLHS, OpRHS,
5364                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5365   case OP_VUZPL:
5366   case OP_VUZPR:
5367     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5368                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5369   case OP_VZIPL:
5370   case OP_VZIPR:
5371     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5372                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5373   case OP_VTRNL:
5374   case OP_VTRNR:
5375     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5376                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5377   }
5378 }
5379
5380 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5381                                        ArrayRef<int> ShuffleMask,
5382                                        SelectionDAG &DAG) {
5383   // Check to see if we can use the VTBL instruction.
5384   SDValue V1 = Op.getOperand(0);
5385   SDValue V2 = Op.getOperand(1);
5386   SDLoc DL(Op);
5387
5388   SmallVector<SDValue, 8> VTBLMask;
5389   for (ArrayRef<int>::iterator
5390          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5391     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5392
5393   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5394     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5395                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5396
5397   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5398                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5399 }
5400
5401 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5402                                                       SelectionDAG &DAG) {
5403   SDLoc DL(Op);
5404   SDValue OpLHS = Op.getOperand(0);
5405   EVT VT = OpLHS.getValueType();
5406
5407   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5408          "Expect an v8i16/v16i8 type");
5409   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5410   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5411   // extract the first 8 bytes into the top double word and the last 8 bytes
5412   // into the bottom double word. The v8i16 case is similar.
5413   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5414   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5415                      DAG.getConstant(ExtractNum, MVT::i32));
5416 }
5417
5418 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5419   SDValue V1 = Op.getOperand(0);
5420   SDValue V2 = Op.getOperand(1);
5421   SDLoc dl(Op);
5422   EVT VT = Op.getValueType();
5423   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5424
5425   // Convert shuffles that are directly supported on NEON to target-specific
5426   // DAG nodes, instead of keeping them as shuffles and matching them again
5427   // during code selection.  This is more efficient and avoids the possibility
5428   // of inconsistencies between legalization and selection.
5429   // FIXME: floating-point vectors should be canonicalized to integer vectors
5430   // of the same time so that they get CSEd properly.
5431   ArrayRef<int> ShuffleMask = SVN->getMask();
5432
5433   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5434   if (EltSize <= 32) {
5435     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5436       int Lane = SVN->getSplatIndex();
5437       // If this is undef splat, generate it via "just" vdup, if possible.
5438       if (Lane == -1) Lane = 0;
5439
5440       // Test if V1 is a SCALAR_TO_VECTOR.
5441       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5442         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5443       }
5444       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5445       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5446       // reaches it).
5447       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5448           !isa<ConstantSDNode>(V1.getOperand(0))) {
5449         bool IsScalarToVector = true;
5450         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5451           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5452             IsScalarToVector = false;
5453             break;
5454           }
5455         if (IsScalarToVector)
5456           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5457       }
5458       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5459                          DAG.getConstant(Lane, MVT::i32));
5460     }
5461
5462     bool ReverseVEXT;
5463     unsigned Imm;
5464     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5465       if (ReverseVEXT)
5466         std::swap(V1, V2);
5467       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5468                          DAG.getConstant(Imm, MVT::i32));
5469     }
5470
5471     if (isVREVMask(ShuffleMask, VT, 64))
5472       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5473     if (isVREVMask(ShuffleMask, VT, 32))
5474       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5475     if (isVREVMask(ShuffleMask, VT, 16))
5476       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5477
5478     if (V2->getOpcode() == ISD::UNDEF &&
5479         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5480       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5481                          DAG.getConstant(Imm, MVT::i32));
5482     }
5483
5484     // Check for Neon shuffles that modify both input vectors in place.
5485     // If both results are used, i.e., if there are two shuffles with the same
5486     // source operands and with masks corresponding to both results of one of
5487     // these operations, DAG memoization will ensure that a single node is
5488     // used for both shuffles.
5489     unsigned WhichResult;
5490     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5491       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5492                          V1, V2).getValue(WhichResult);
5493     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5494       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5495                          V1, V2).getValue(WhichResult);
5496     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5497       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5498                          V1, V2).getValue(WhichResult);
5499
5500     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5501       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5502                          V1, V1).getValue(WhichResult);
5503     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5504       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5505                          V1, V1).getValue(WhichResult);
5506     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5507       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5508                          V1, V1).getValue(WhichResult);
5509   }
5510
5511   // If the shuffle is not directly supported and it has 4 elements, use
5512   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5513   unsigned NumElts = VT.getVectorNumElements();
5514   if (NumElts == 4) {
5515     unsigned PFIndexes[4];
5516     for (unsigned i = 0; i != 4; ++i) {
5517       if (ShuffleMask[i] < 0)
5518         PFIndexes[i] = 8;
5519       else
5520         PFIndexes[i] = ShuffleMask[i];
5521     }
5522
5523     // Compute the index in the perfect shuffle table.
5524     unsigned PFTableIndex =
5525       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5526     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5527     unsigned Cost = (PFEntry >> 30);
5528
5529     if (Cost <= 4)
5530       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5531   }
5532
5533   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5534   if (EltSize >= 32) {
5535     // Do the expansion with floating-point types, since that is what the VFP
5536     // registers are defined to use, and since i64 is not legal.
5537     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5538     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5539     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5540     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5541     SmallVector<SDValue, 8> Ops;
5542     for (unsigned i = 0; i < NumElts; ++i) {
5543       if (ShuffleMask[i] < 0)
5544         Ops.push_back(DAG.getUNDEF(EltVT));
5545       else
5546         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5547                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5548                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5549                                                   MVT::i32)));
5550     }
5551     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5552     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5553   }
5554
5555   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5556     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5557
5558   if (VT == MVT::v8i8) {
5559     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5560     if (NewOp.getNode())
5561       return NewOp;
5562   }
5563
5564   return SDValue();
5565 }
5566
5567 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5568   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5569   SDValue Lane = Op.getOperand(2);
5570   if (!isa<ConstantSDNode>(Lane))
5571     return SDValue();
5572
5573   return Op;
5574 }
5575
5576 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5577   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5578   SDValue Lane = Op.getOperand(1);
5579   if (!isa<ConstantSDNode>(Lane))
5580     return SDValue();
5581
5582   SDValue Vec = Op.getOperand(0);
5583   if (Op.getValueType() == MVT::i32 &&
5584       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5585     SDLoc dl(Op);
5586     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5587   }
5588
5589   return Op;
5590 }
5591
5592 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5593   // The only time a CONCAT_VECTORS operation can have legal types is when
5594   // two 64-bit vectors are concatenated to a 128-bit vector.
5595   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5596          "unexpected CONCAT_VECTORS");
5597   SDLoc dl(Op);
5598   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5599   SDValue Op0 = Op.getOperand(0);
5600   SDValue Op1 = Op.getOperand(1);
5601   if (Op0.getOpcode() != ISD::UNDEF)
5602     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5603                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5604                       DAG.getIntPtrConstant(0));
5605   if (Op1.getOpcode() != ISD::UNDEF)
5606     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5607                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5608                       DAG.getIntPtrConstant(1));
5609   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5610 }
5611
5612 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5613 /// element has been zero/sign-extended, depending on the isSigned parameter,
5614 /// from an integer type half its size.
5615 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5616                                    bool isSigned) {
5617   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5618   EVT VT = N->getValueType(0);
5619   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5620     SDNode *BVN = N->getOperand(0).getNode();
5621     if (BVN->getValueType(0) != MVT::v4i32 ||
5622         BVN->getOpcode() != ISD::BUILD_VECTOR)
5623       return false;
5624     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5625     unsigned HiElt = 1 - LoElt;
5626     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5627     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5628     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5629     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5630     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5631       return false;
5632     if (isSigned) {
5633       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5634           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5635         return true;
5636     } else {
5637       if (Hi0->isNullValue() && Hi1->isNullValue())
5638         return true;
5639     }
5640     return false;
5641   }
5642
5643   if (N->getOpcode() != ISD::BUILD_VECTOR)
5644     return false;
5645
5646   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5647     SDNode *Elt = N->getOperand(i).getNode();
5648     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5649       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5650       unsigned HalfSize = EltSize / 2;
5651       if (isSigned) {
5652         if (!isIntN(HalfSize, C->getSExtValue()))
5653           return false;
5654       } else {
5655         if (!isUIntN(HalfSize, C->getZExtValue()))
5656           return false;
5657       }
5658       continue;
5659     }
5660     return false;
5661   }
5662
5663   return true;
5664 }
5665
5666 /// isSignExtended - Check if a node is a vector value that is sign-extended
5667 /// or a constant BUILD_VECTOR with sign-extended elements.
5668 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5669   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5670     return true;
5671   if (isExtendedBUILD_VECTOR(N, DAG, true))
5672     return true;
5673   return false;
5674 }
5675
5676 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5677 /// or a constant BUILD_VECTOR with zero-extended elements.
5678 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5679   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5680     return true;
5681   if (isExtendedBUILD_VECTOR(N, DAG, false))
5682     return true;
5683   return false;
5684 }
5685
5686 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5687   if (OrigVT.getSizeInBits() >= 64)
5688     return OrigVT;
5689
5690   assert(OrigVT.isSimple() && "Expecting a simple value type");
5691
5692   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5693   switch (OrigSimpleTy) {
5694   default: llvm_unreachable("Unexpected Vector Type");
5695   case MVT::v2i8:
5696   case MVT::v2i16:
5697      return MVT::v2i32;
5698   case MVT::v4i8:
5699     return  MVT::v4i16;
5700   }
5701 }
5702
5703 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5704 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5705 /// We insert the required extension here to get the vector to fill a D register.
5706 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5707                                             const EVT &OrigTy,
5708                                             const EVT &ExtTy,
5709                                             unsigned ExtOpcode) {
5710   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5711   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5712   // 64-bits we need to insert a new extension so that it will be 64-bits.
5713   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5714   if (OrigTy.getSizeInBits() >= 64)
5715     return N;
5716
5717   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5718   EVT NewVT = getExtensionTo64Bits(OrigTy);
5719
5720   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5721 }
5722
5723 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5724 /// does not do any sign/zero extension. If the original vector is less
5725 /// than 64 bits, an appropriate extension will be added after the load to
5726 /// reach a total size of 64 bits. We have to add the extension separately
5727 /// because ARM does not have a sign/zero extending load for vectors.
5728 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5729   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5730
5731   // The load already has the right type.
5732   if (ExtendedTy == LD->getMemoryVT())
5733     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5734                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5735                 LD->isNonTemporal(), LD->isInvariant(),
5736                 LD->getAlignment());
5737
5738   // We need to create a zextload/sextload. We cannot just create a load
5739   // followed by a zext/zext node because LowerMUL is also run during normal
5740   // operation legalization where we can't create illegal types.
5741   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5742                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5743                         LD->getMemoryVT(), LD->isVolatile(),
5744                         LD->isNonTemporal(), LD->getAlignment());
5745 }
5746
5747 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5748 /// extending load, or BUILD_VECTOR with extended elements, return the
5749 /// unextended value. The unextended vector should be 64 bits so that it can
5750 /// be used as an operand to a VMULL instruction. If the original vector size
5751 /// before extension is less than 64 bits we add a an extension to resize
5752 /// the vector to 64 bits.
5753 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5754   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5755     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5756                                         N->getOperand(0)->getValueType(0),
5757                                         N->getValueType(0),
5758                                         N->getOpcode());
5759
5760   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5761     return SkipLoadExtensionForVMULL(LD, DAG);
5762
5763   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5764   // have been legalized as a BITCAST from v4i32.
5765   if (N->getOpcode() == ISD::BITCAST) {
5766     SDNode *BVN = N->getOperand(0).getNode();
5767     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5768            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5769     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5770     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5771                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5772   }
5773   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5774   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5775   EVT VT = N->getValueType(0);
5776   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5777   unsigned NumElts = VT.getVectorNumElements();
5778   MVT TruncVT = MVT::getIntegerVT(EltSize);
5779   SmallVector<SDValue, 8> Ops;
5780   for (unsigned i = 0; i != NumElts; ++i) {
5781     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5782     const APInt &CInt = C->getAPIntValue();
5783     // Element types smaller than 32 bits are not legal, so use i32 elements.
5784     // The values are implicitly truncated so sext vs. zext doesn't matter.
5785     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5786   }
5787   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5788                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5789 }
5790
5791 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5792   unsigned Opcode = N->getOpcode();
5793   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5794     SDNode *N0 = N->getOperand(0).getNode();
5795     SDNode *N1 = N->getOperand(1).getNode();
5796     return N0->hasOneUse() && N1->hasOneUse() &&
5797       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5798   }
5799   return false;
5800 }
5801
5802 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5803   unsigned Opcode = N->getOpcode();
5804   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5805     SDNode *N0 = N->getOperand(0).getNode();
5806     SDNode *N1 = N->getOperand(1).getNode();
5807     return N0->hasOneUse() && N1->hasOneUse() &&
5808       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5809   }
5810   return false;
5811 }
5812
5813 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5814   // Multiplications are only custom-lowered for 128-bit vectors so that
5815   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5816   EVT VT = Op.getValueType();
5817   assert(VT.is128BitVector() && VT.isInteger() &&
5818          "unexpected type for custom-lowering ISD::MUL");
5819   SDNode *N0 = Op.getOperand(0).getNode();
5820   SDNode *N1 = Op.getOperand(1).getNode();
5821   unsigned NewOpc = 0;
5822   bool isMLA = false;
5823   bool isN0SExt = isSignExtended(N0, DAG);
5824   bool isN1SExt = isSignExtended(N1, DAG);
5825   if (isN0SExt && isN1SExt)
5826     NewOpc = ARMISD::VMULLs;
5827   else {
5828     bool isN0ZExt = isZeroExtended(N0, DAG);
5829     bool isN1ZExt = isZeroExtended(N1, DAG);
5830     if (isN0ZExt && isN1ZExt)
5831       NewOpc = ARMISD::VMULLu;
5832     else if (isN1SExt || isN1ZExt) {
5833       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5834       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5835       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5836         NewOpc = ARMISD::VMULLs;
5837         isMLA = true;
5838       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5839         NewOpc = ARMISD::VMULLu;
5840         isMLA = true;
5841       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5842         std::swap(N0, N1);
5843         NewOpc = ARMISD::VMULLu;
5844         isMLA = true;
5845       }
5846     }
5847
5848     if (!NewOpc) {
5849       if (VT == MVT::v2i64)
5850         // Fall through to expand this.  It is not legal.
5851         return SDValue();
5852       else
5853         // Other vector multiplications are legal.
5854         return Op;
5855     }
5856   }
5857
5858   // Legalize to a VMULL instruction.
5859   SDLoc DL(Op);
5860   SDValue Op0;
5861   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5862   if (!isMLA) {
5863     Op0 = SkipExtensionForVMULL(N0, DAG);
5864     assert(Op0.getValueType().is64BitVector() &&
5865            Op1.getValueType().is64BitVector() &&
5866            "unexpected types for extended operands to VMULL");
5867     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5868   }
5869
5870   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5871   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5872   //   vmull q0, d4, d6
5873   //   vmlal q0, d5, d6
5874   // is faster than
5875   //   vaddl q0, d4, d5
5876   //   vmovl q1, d6
5877   //   vmul  q0, q0, q1
5878   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5879   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5880   EVT Op1VT = Op1.getValueType();
5881   return DAG.getNode(N0->getOpcode(), DL, VT,
5882                      DAG.getNode(NewOpc, DL, VT,
5883                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5884                      DAG.getNode(NewOpc, DL, VT,
5885                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5886 }
5887
5888 static SDValue
5889 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5890   // Convert to float
5891   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5892   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5893   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5894   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5895   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5896   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5897   // Get reciprocal estimate.
5898   // float4 recip = vrecpeq_f32(yf);
5899   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5900                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5901   // Because char has a smaller range than uchar, we can actually get away
5902   // without any newton steps.  This requires that we use a weird bias
5903   // of 0xb000, however (again, this has been exhaustively tested).
5904   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5905   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5906   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5907   Y = DAG.getConstant(0xb000, MVT::i32);
5908   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5909   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5910   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5911   // Convert back to short.
5912   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5913   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5914   return X;
5915 }
5916
5917 static SDValue
5918 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5919   SDValue N2;
5920   // Convert to float.
5921   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5922   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5923   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5924   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5925   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5926   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5927
5928   // Use reciprocal estimate and one refinement step.
5929   // float4 recip = vrecpeq_f32(yf);
5930   // recip *= vrecpsq_f32(yf, recip);
5931   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5932                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5933   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5934                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5935                    N1, N2);
5936   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5937   // Because short has a smaller range than ushort, we can actually get away
5938   // with only a single newton step.  This requires that we use a weird bias
5939   // of 89, however (again, this has been exhaustively tested).
5940   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5941   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5942   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5943   N1 = DAG.getConstant(0x89, MVT::i32);
5944   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5945   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5946   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5947   // Convert back to integer and return.
5948   // return vmovn_s32(vcvt_s32_f32(result));
5949   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5950   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5951   return N0;
5952 }
5953
5954 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5955   EVT VT = Op.getValueType();
5956   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5957          "unexpected type for custom-lowering ISD::SDIV");
5958
5959   SDLoc dl(Op);
5960   SDValue N0 = Op.getOperand(0);
5961   SDValue N1 = Op.getOperand(1);
5962   SDValue N2, N3;
5963
5964   if (VT == MVT::v8i8) {
5965     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5966     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5967
5968     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5969                      DAG.getIntPtrConstant(4));
5970     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5971                      DAG.getIntPtrConstant(4));
5972     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5973                      DAG.getIntPtrConstant(0));
5974     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5975                      DAG.getIntPtrConstant(0));
5976
5977     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5978     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5979
5980     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5981     N0 = LowerCONCAT_VECTORS(N0, DAG);
5982
5983     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5984     return N0;
5985   }
5986   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5987 }
5988
5989 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5990   EVT VT = Op.getValueType();
5991   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5992          "unexpected type for custom-lowering ISD::UDIV");
5993
5994   SDLoc dl(Op);
5995   SDValue N0 = Op.getOperand(0);
5996   SDValue N1 = Op.getOperand(1);
5997   SDValue N2, N3;
5998
5999   if (VT == MVT::v8i8) {
6000     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6001     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6002
6003     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6004                      DAG.getIntPtrConstant(4));
6005     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6006                      DAG.getIntPtrConstant(4));
6007     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6008                      DAG.getIntPtrConstant(0));
6009     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6010                      DAG.getIntPtrConstant(0));
6011
6012     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6013     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6014
6015     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6016     N0 = LowerCONCAT_VECTORS(N0, DAG);
6017
6018     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6019                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6020                      N0);
6021     return N0;
6022   }
6023
6024   // v4i16 sdiv ... Convert to float.
6025   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6026   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6027   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6028   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6029   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6030   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6031
6032   // Use reciprocal estimate and two refinement steps.
6033   // float4 recip = vrecpeq_f32(yf);
6034   // recip *= vrecpsq_f32(yf, recip);
6035   // recip *= vrecpsq_f32(yf, recip);
6036   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6037                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6038   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6039                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6040                    BN1, N2);
6041   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6042   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6043                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6044                    BN1, N2);
6045   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6046   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6047   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6048   // and that it will never cause us to return an answer too large).
6049   // float4 result = as_float4(as_int4(xf*recip) + 2);
6050   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6051   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6052   N1 = DAG.getConstant(2, MVT::i32);
6053   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6054   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6055   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6056   // Convert back to integer and return.
6057   // return vmovn_u32(vcvt_s32_f32(result));
6058   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6059   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6060   return N0;
6061 }
6062
6063 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6064   EVT VT = Op.getNode()->getValueType(0);
6065   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6066
6067   unsigned Opc;
6068   bool ExtraOp = false;
6069   switch (Op.getOpcode()) {
6070   default: llvm_unreachable("Invalid code");
6071   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6072   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6073   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6074   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6075   }
6076
6077   if (!ExtraOp)
6078     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6079                        Op.getOperand(1));
6080   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6081                      Op.getOperand(1), Op.getOperand(2));
6082 }
6083
6084 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6085   assert(Subtarget->isTargetDarwin());
6086
6087   // For iOS, we want to call an alternative entry point: __sincos_stret,
6088   // return values are passed via sret.
6089   SDLoc dl(Op);
6090   SDValue Arg = Op.getOperand(0);
6091   EVT ArgVT = Arg.getValueType();
6092   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6093
6094   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6095   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6096
6097   // Pair of floats / doubles used to pass the result.
6098   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6099
6100   // Create stack object for sret.
6101   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6102   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6103   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6104   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6105
6106   ArgListTy Args;
6107   ArgListEntry Entry;
6108
6109   Entry.Node = SRet;
6110   Entry.Ty = RetTy->getPointerTo();
6111   Entry.isSExt = false;
6112   Entry.isZExt = false;
6113   Entry.isSRet = true;
6114   Args.push_back(Entry);
6115
6116   Entry.Node = Arg;
6117   Entry.Ty = ArgTy;
6118   Entry.isSExt = false;
6119   Entry.isZExt = false;
6120   Args.push_back(Entry);
6121
6122   const char *LibcallName  = (ArgVT == MVT::f64)
6123   ? "__sincos_stret" : "__sincosf_stret";
6124   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6125
6126   TargetLowering::CallLoweringInfo CLI(DAG);
6127   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6128     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6129                std::move(Args), 0)
6130     .setDiscardResult();
6131
6132   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6133
6134   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6135                                 MachinePointerInfo(), false, false, false, 0);
6136
6137   // Address of cos field.
6138   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6139                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6140   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6141                                 MachinePointerInfo(), false, false, false, 0);
6142
6143   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6144   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6145                      LoadSin.getValue(0), LoadCos.getValue(0));
6146 }
6147
6148 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6149   // Monotonic load/store is legal for all targets
6150   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6151     return Op;
6152
6153   // Acquire/Release load/store is not legal for targets without a
6154   // dmb or equivalent available.
6155   return SDValue();
6156 }
6157
6158 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6159                                     SmallVectorImpl<SDValue> &Results,
6160                                     SelectionDAG &DAG,
6161                                     const ARMSubtarget *Subtarget) {
6162   SDLoc DL(N);
6163   SDValue Cycles32, OutChain;
6164
6165   if (Subtarget->hasPerfMon()) {
6166     // Under Power Management extensions, the cycle-count is:
6167     //    mrc p15, #0, <Rt>, c9, c13, #0
6168     SDValue Ops[] = { N->getOperand(0), // Chain
6169                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6170                       DAG.getConstant(15, MVT::i32),
6171                       DAG.getConstant(0, MVT::i32),
6172                       DAG.getConstant(9, MVT::i32),
6173                       DAG.getConstant(13, MVT::i32),
6174                       DAG.getConstant(0, MVT::i32)
6175     };
6176
6177     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6178                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6179     OutChain = Cycles32.getValue(1);
6180   } else {
6181     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6182     // there are older ARM CPUs that have implementation-specific ways of
6183     // obtaining this information (FIXME!).
6184     Cycles32 = DAG.getConstant(0, MVT::i32);
6185     OutChain = DAG.getEntryNode();
6186   }
6187
6188
6189   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6190                                  Cycles32, DAG.getConstant(0, MVT::i32));
6191   Results.push_back(Cycles64);
6192   Results.push_back(OutChain);
6193 }
6194
6195 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6196   switch (Op.getOpcode()) {
6197   default: llvm_unreachable("Don't know how to custom lower this!");
6198   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6199   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6200   case ISD::GlobalAddress:
6201     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6202     default: llvm_unreachable("unknown object format");
6203     case Triple::COFF:
6204       return LowerGlobalAddressWindows(Op, DAG);
6205     case Triple::ELF:
6206       return LowerGlobalAddressELF(Op, DAG);
6207     case Triple::MachO:
6208       return LowerGlobalAddressDarwin(Op, DAG);
6209     }
6210   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6211   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6212   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6213   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6214   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6215   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6216   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6217   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6218   case ISD::SINT_TO_FP:
6219   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6220   case ISD::FP_TO_SINT:
6221   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6222   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6223   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6224   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6225   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6226   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6227   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6228   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6229                                                                Subtarget);
6230   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6231   case ISD::SHL:
6232   case ISD::SRL:
6233   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6234   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6235   case ISD::SRL_PARTS:
6236   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6237   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6238   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6239   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6240   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6241   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6242   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6243   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6244   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6245   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6246   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6247   case ISD::MUL:           return LowerMUL(Op, DAG);
6248   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6249   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6250   case ISD::ADDC:
6251   case ISD::ADDE:
6252   case ISD::SUBC:
6253   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6254   case ISD::SADDO:
6255   case ISD::UADDO:
6256   case ISD::SSUBO:
6257   case ISD::USUBO:
6258     return LowerXALUO(Op, DAG);
6259   case ISD::ATOMIC_LOAD:
6260   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6261   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6262   case ISD::SDIVREM:
6263   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6264   case ISD::DYNAMIC_STACKALLOC:
6265     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6266       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6267     llvm_unreachable("Don't know how to custom lower this!");
6268   }
6269 }
6270
6271 /// ReplaceNodeResults - Replace the results of node with an illegal result
6272 /// type with new values built out of custom code.
6273 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6274                                            SmallVectorImpl<SDValue>&Results,
6275                                            SelectionDAG &DAG) const {
6276   SDValue Res;
6277   switch (N->getOpcode()) {
6278   default:
6279     llvm_unreachable("Don't know how to custom expand this!");
6280   case ISD::BITCAST:
6281     Res = ExpandBITCAST(N, DAG);
6282     break;
6283   case ISD::SRL:
6284   case ISD::SRA:
6285     Res = Expand64BitShift(N, DAG, Subtarget);
6286     break;
6287   case ISD::READCYCLECOUNTER:
6288     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6289     return;
6290   }
6291   if (Res.getNode())
6292     Results.push_back(Res);
6293 }
6294
6295 //===----------------------------------------------------------------------===//
6296 //                           ARM Scheduler Hooks
6297 //===----------------------------------------------------------------------===//
6298
6299 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6300 /// registers the function context.
6301 void ARMTargetLowering::
6302 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6303                        MachineBasicBlock *DispatchBB, int FI) const {
6304   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6305   DebugLoc dl = MI->getDebugLoc();
6306   MachineFunction *MF = MBB->getParent();
6307   MachineRegisterInfo *MRI = &MF->getRegInfo();
6308   MachineConstantPool *MCP = MF->getConstantPool();
6309   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6310   const Function *F = MF->getFunction();
6311
6312   bool isThumb = Subtarget->isThumb();
6313   bool isThumb2 = Subtarget->isThumb2();
6314
6315   unsigned PCLabelId = AFI->createPICLabelUId();
6316   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6317   ARMConstantPoolValue *CPV =
6318     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6319   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6320
6321   const TargetRegisterClass *TRC = isThumb ?
6322     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6323     (const TargetRegisterClass*)&ARM::GPRRegClass;
6324
6325   // Grab constant pool and fixed stack memory operands.
6326   MachineMemOperand *CPMMO =
6327     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6328                              MachineMemOperand::MOLoad, 4, 4);
6329
6330   MachineMemOperand *FIMMOSt =
6331     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6332                              MachineMemOperand::MOStore, 4, 4);
6333
6334   // Load the address of the dispatch MBB into the jump buffer.
6335   if (isThumb2) {
6336     // Incoming value: jbuf
6337     //   ldr.n  r5, LCPI1_1
6338     //   orr    r5, r5, #1
6339     //   add    r5, pc
6340     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6341     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6342     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6343                    .addConstantPoolIndex(CPI)
6344                    .addMemOperand(CPMMO));
6345     // Set the low bit because of thumb mode.
6346     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6347     AddDefaultCC(
6348       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6349                      .addReg(NewVReg1, RegState::Kill)
6350                      .addImm(0x01)));
6351     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6352     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6353       .addReg(NewVReg2, RegState::Kill)
6354       .addImm(PCLabelId);
6355     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6356                    .addReg(NewVReg3, RegState::Kill)
6357                    .addFrameIndex(FI)
6358                    .addImm(36)  // &jbuf[1] :: pc
6359                    .addMemOperand(FIMMOSt));
6360   } else if (isThumb) {
6361     // Incoming value: jbuf
6362     //   ldr.n  r1, LCPI1_4
6363     //   add    r1, pc
6364     //   mov    r2, #1
6365     //   orrs   r1, r2
6366     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6367     //   str    r1, [r2]
6368     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6369     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6370                    .addConstantPoolIndex(CPI)
6371                    .addMemOperand(CPMMO));
6372     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6373     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6374       .addReg(NewVReg1, RegState::Kill)
6375       .addImm(PCLabelId);
6376     // Set the low bit because of thumb mode.
6377     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6378     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6379                    .addReg(ARM::CPSR, RegState::Define)
6380                    .addImm(1));
6381     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6382     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6383                    .addReg(ARM::CPSR, RegState::Define)
6384                    .addReg(NewVReg2, RegState::Kill)
6385                    .addReg(NewVReg3, RegState::Kill));
6386     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6387     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6388                    .addFrameIndex(FI)
6389                    .addImm(36)); // &jbuf[1] :: pc
6390     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6391                    .addReg(NewVReg4, RegState::Kill)
6392                    .addReg(NewVReg5, RegState::Kill)
6393                    .addImm(0)
6394                    .addMemOperand(FIMMOSt));
6395   } else {
6396     // Incoming value: jbuf
6397     //   ldr  r1, LCPI1_1
6398     //   add  r1, pc, r1
6399     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6400     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6401     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6402                    .addConstantPoolIndex(CPI)
6403                    .addImm(0)
6404                    .addMemOperand(CPMMO));
6405     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6406     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6407                    .addReg(NewVReg1, RegState::Kill)
6408                    .addImm(PCLabelId));
6409     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6410                    .addReg(NewVReg2, RegState::Kill)
6411                    .addFrameIndex(FI)
6412                    .addImm(36)  // &jbuf[1] :: pc
6413                    .addMemOperand(FIMMOSt));
6414   }
6415 }
6416
6417 MachineBasicBlock *ARMTargetLowering::
6418 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6419   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6420   DebugLoc dl = MI->getDebugLoc();
6421   MachineFunction *MF = MBB->getParent();
6422   MachineRegisterInfo *MRI = &MF->getRegInfo();
6423   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6424   MachineFrameInfo *MFI = MF->getFrameInfo();
6425   int FI = MFI->getFunctionContextIndex();
6426
6427   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6428     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6429     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6430
6431   // Get a mapping of the call site numbers to all of the landing pads they're
6432   // associated with.
6433   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6434   unsigned MaxCSNum = 0;
6435   MachineModuleInfo &MMI = MF->getMMI();
6436   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6437        ++BB) {
6438     if (!BB->isLandingPad()) continue;
6439
6440     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6441     // pad.
6442     for (MachineBasicBlock::iterator
6443            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6444       if (!II->isEHLabel()) continue;
6445
6446       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6447       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6448
6449       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6450       for (SmallVectorImpl<unsigned>::iterator
6451              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6452            CSI != CSE; ++CSI) {
6453         CallSiteNumToLPad[*CSI].push_back(BB);
6454         MaxCSNum = std::max(MaxCSNum, *CSI);
6455       }
6456       break;
6457     }
6458   }
6459
6460   // Get an ordered list of the machine basic blocks for the jump table.
6461   std::vector<MachineBasicBlock*> LPadList;
6462   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6463   LPadList.reserve(CallSiteNumToLPad.size());
6464   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6465     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6466     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6467            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6468       LPadList.push_back(*II);
6469       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6470     }
6471   }
6472
6473   assert(!LPadList.empty() &&
6474          "No landing pad destinations for the dispatch jump table!");
6475
6476   // Create the jump table and associated information.
6477   MachineJumpTableInfo *JTI =
6478     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6479   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6480   unsigned UId = AFI->createJumpTableUId();
6481   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6482
6483   // Create the MBBs for the dispatch code.
6484
6485   // Shove the dispatch's address into the return slot in the function context.
6486   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6487   DispatchBB->setIsLandingPad();
6488
6489   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6490   unsigned trap_opcode;
6491   if (Subtarget->isThumb())
6492     trap_opcode = ARM::tTRAP;
6493   else
6494     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6495
6496   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6497   DispatchBB->addSuccessor(TrapBB);
6498
6499   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6500   DispatchBB->addSuccessor(DispContBB);
6501
6502   // Insert and MBBs.
6503   MF->insert(MF->end(), DispatchBB);
6504   MF->insert(MF->end(), DispContBB);
6505   MF->insert(MF->end(), TrapBB);
6506
6507   // Insert code into the entry block that creates and registers the function
6508   // context.
6509   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6510
6511   MachineMemOperand *FIMMOLd =
6512     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6513                              MachineMemOperand::MOLoad |
6514                              MachineMemOperand::MOVolatile, 4, 4);
6515
6516   MachineInstrBuilder MIB;
6517   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6518
6519   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6520   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6521
6522   // Add a register mask with no preserved registers.  This results in all
6523   // registers being marked as clobbered.
6524   MIB.addRegMask(RI.getNoPreservedMask());
6525
6526   unsigned NumLPads = LPadList.size();
6527   if (Subtarget->isThumb2()) {
6528     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6529     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6530                    .addFrameIndex(FI)
6531                    .addImm(4)
6532                    .addMemOperand(FIMMOLd));
6533
6534     if (NumLPads < 256) {
6535       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6536                      .addReg(NewVReg1)
6537                      .addImm(LPadList.size()));
6538     } else {
6539       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6540       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6541                      .addImm(NumLPads & 0xFFFF));
6542
6543       unsigned VReg2 = VReg1;
6544       if ((NumLPads & 0xFFFF0000) != 0) {
6545         VReg2 = MRI->createVirtualRegister(TRC);
6546         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6547                        .addReg(VReg1)
6548                        .addImm(NumLPads >> 16));
6549       }
6550
6551       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6552                      .addReg(NewVReg1)
6553                      .addReg(VReg2));
6554     }
6555
6556     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6557       .addMBB(TrapBB)
6558       .addImm(ARMCC::HI)
6559       .addReg(ARM::CPSR);
6560
6561     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6562     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6563                    .addJumpTableIndex(MJTI)
6564                    .addImm(UId));
6565
6566     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6567     AddDefaultCC(
6568       AddDefaultPred(
6569         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6570         .addReg(NewVReg3, RegState::Kill)
6571         .addReg(NewVReg1)
6572         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6573
6574     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6575       .addReg(NewVReg4, RegState::Kill)
6576       .addReg(NewVReg1)
6577       .addJumpTableIndex(MJTI)
6578       .addImm(UId);
6579   } else if (Subtarget->isThumb()) {
6580     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6581     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6582                    .addFrameIndex(FI)
6583                    .addImm(1)
6584                    .addMemOperand(FIMMOLd));
6585
6586     if (NumLPads < 256) {
6587       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6588                      .addReg(NewVReg1)
6589                      .addImm(NumLPads));
6590     } else {
6591       MachineConstantPool *ConstantPool = MF->getConstantPool();
6592       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6593       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6594
6595       // MachineConstantPool wants an explicit alignment.
6596       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6597       if (Align == 0)
6598         Align = getDataLayout()->getTypeAllocSize(C->getType());
6599       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6600
6601       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6602       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6603                      .addReg(VReg1, RegState::Define)
6604                      .addConstantPoolIndex(Idx));
6605       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6606                      .addReg(NewVReg1)
6607                      .addReg(VReg1));
6608     }
6609
6610     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6611       .addMBB(TrapBB)
6612       .addImm(ARMCC::HI)
6613       .addReg(ARM::CPSR);
6614
6615     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6616     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6617                    .addReg(ARM::CPSR, RegState::Define)
6618                    .addReg(NewVReg1)
6619                    .addImm(2));
6620
6621     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6622     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6623                    .addJumpTableIndex(MJTI)
6624                    .addImm(UId));
6625
6626     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6627     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6628                    .addReg(ARM::CPSR, RegState::Define)
6629                    .addReg(NewVReg2, RegState::Kill)
6630                    .addReg(NewVReg3));
6631
6632     MachineMemOperand *JTMMOLd =
6633       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6634                                MachineMemOperand::MOLoad, 4, 4);
6635
6636     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6637     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6638                    .addReg(NewVReg4, RegState::Kill)
6639                    .addImm(0)
6640                    .addMemOperand(JTMMOLd));
6641
6642     unsigned NewVReg6 = NewVReg5;
6643     if (RelocM == Reloc::PIC_) {
6644       NewVReg6 = MRI->createVirtualRegister(TRC);
6645       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6646                      .addReg(ARM::CPSR, RegState::Define)
6647                      .addReg(NewVReg5, RegState::Kill)
6648                      .addReg(NewVReg3));
6649     }
6650
6651     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6652       .addReg(NewVReg6, RegState::Kill)
6653       .addJumpTableIndex(MJTI)
6654       .addImm(UId);
6655   } else {
6656     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6657     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6658                    .addFrameIndex(FI)
6659                    .addImm(4)
6660                    .addMemOperand(FIMMOLd));
6661
6662     if (NumLPads < 256) {
6663       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6664                      .addReg(NewVReg1)
6665                      .addImm(NumLPads));
6666     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6667       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6668       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6669                      .addImm(NumLPads & 0xFFFF));
6670
6671       unsigned VReg2 = VReg1;
6672       if ((NumLPads & 0xFFFF0000) != 0) {
6673         VReg2 = MRI->createVirtualRegister(TRC);
6674         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6675                        .addReg(VReg1)
6676                        .addImm(NumLPads >> 16));
6677       }
6678
6679       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6680                      .addReg(NewVReg1)
6681                      .addReg(VReg2));
6682     } else {
6683       MachineConstantPool *ConstantPool = MF->getConstantPool();
6684       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6685       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6686
6687       // MachineConstantPool wants an explicit alignment.
6688       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6689       if (Align == 0)
6690         Align = getDataLayout()->getTypeAllocSize(C->getType());
6691       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6692
6693       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6694       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6695                      .addReg(VReg1, RegState::Define)
6696                      .addConstantPoolIndex(Idx)
6697                      .addImm(0));
6698       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6699                      .addReg(NewVReg1)
6700                      .addReg(VReg1, RegState::Kill));
6701     }
6702
6703     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6704       .addMBB(TrapBB)
6705       .addImm(ARMCC::HI)
6706       .addReg(ARM::CPSR);
6707
6708     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6709     AddDefaultCC(
6710       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6711                      .addReg(NewVReg1)
6712                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6713     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6714     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6715                    .addJumpTableIndex(MJTI)
6716                    .addImm(UId));
6717
6718     MachineMemOperand *JTMMOLd =
6719       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6720                                MachineMemOperand::MOLoad, 4, 4);
6721     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6722     AddDefaultPred(
6723       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6724       .addReg(NewVReg3, RegState::Kill)
6725       .addReg(NewVReg4)
6726       .addImm(0)
6727       .addMemOperand(JTMMOLd));
6728
6729     if (RelocM == Reloc::PIC_) {
6730       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6731         .addReg(NewVReg5, RegState::Kill)
6732         .addReg(NewVReg4)
6733         .addJumpTableIndex(MJTI)
6734         .addImm(UId);
6735     } else {
6736       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6737         .addReg(NewVReg5, RegState::Kill)
6738         .addJumpTableIndex(MJTI)
6739         .addImm(UId);
6740     }
6741   }
6742
6743   // Add the jump table entries as successors to the MBB.
6744   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6745   for (std::vector<MachineBasicBlock*>::iterator
6746          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6747     MachineBasicBlock *CurMBB = *I;
6748     if (SeenMBBs.insert(CurMBB))
6749       DispContBB->addSuccessor(CurMBB);
6750   }
6751
6752   // N.B. the order the invoke BBs are processed in doesn't matter here.
6753   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6754   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6755   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6756          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6757     MachineBasicBlock *BB = *I;
6758
6759     // Remove the landing pad successor from the invoke block and replace it
6760     // with the new dispatch block.
6761     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6762                                                   BB->succ_end());
6763     while (!Successors.empty()) {
6764       MachineBasicBlock *SMBB = Successors.pop_back_val();
6765       if (SMBB->isLandingPad()) {
6766         BB->removeSuccessor(SMBB);
6767         MBBLPads.push_back(SMBB);
6768       }
6769     }
6770
6771     BB->addSuccessor(DispatchBB);
6772
6773     // Find the invoke call and mark all of the callee-saved registers as
6774     // 'implicit defined' so that they're spilled. This prevents code from
6775     // moving instructions to before the EH block, where they will never be
6776     // executed.
6777     for (MachineBasicBlock::reverse_iterator
6778            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6779       if (!II->isCall()) continue;
6780
6781       DenseMap<unsigned, bool> DefRegs;
6782       for (MachineInstr::mop_iterator
6783              OI = II->operands_begin(), OE = II->operands_end();
6784            OI != OE; ++OI) {
6785         if (!OI->isReg()) continue;
6786         DefRegs[OI->getReg()] = true;
6787       }
6788
6789       MachineInstrBuilder MIB(*MF, &*II);
6790
6791       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6792         unsigned Reg = SavedRegs[i];
6793         if (Subtarget->isThumb2() &&
6794             !ARM::tGPRRegClass.contains(Reg) &&
6795             !ARM::hGPRRegClass.contains(Reg))
6796           continue;
6797         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6798           continue;
6799         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6800           continue;
6801         if (!DefRegs[Reg])
6802           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6803       }
6804
6805       break;
6806     }
6807   }
6808
6809   // Mark all former landing pads as non-landing pads. The dispatch is the only
6810   // landing pad now.
6811   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6812          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6813     (*I)->setIsLandingPad(false);
6814
6815   // The instruction is gone now.
6816   MI->eraseFromParent();
6817
6818   return MBB;
6819 }
6820
6821 static
6822 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6823   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6824        E = MBB->succ_end(); I != E; ++I)
6825     if (*I != Succ)
6826       return *I;
6827   llvm_unreachable("Expecting a BB with two successors!");
6828 }
6829
6830 /// Return the load opcode for a given load size. If load size >= 8,
6831 /// neon opcode will be returned.
6832 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6833   if (LdSize >= 8)
6834     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6835                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6836   if (IsThumb1)
6837     return LdSize == 4 ? ARM::tLDRi
6838                        : LdSize == 2 ? ARM::tLDRHi
6839                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6840   if (IsThumb2)
6841     return LdSize == 4 ? ARM::t2LDR_POST
6842                        : LdSize == 2 ? ARM::t2LDRH_POST
6843                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6844   return LdSize == 4 ? ARM::LDR_POST_IMM
6845                      : LdSize == 2 ? ARM::LDRH_POST
6846                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6847 }
6848
6849 /// Return the store opcode for a given store size. If store size >= 8,
6850 /// neon opcode will be returned.
6851 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6852   if (StSize >= 8)
6853     return StSize == 16 ? ARM::VST1q32wb_fixed
6854                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6855   if (IsThumb1)
6856     return StSize == 4 ? ARM::tSTRi
6857                        : StSize == 2 ? ARM::tSTRHi
6858                                      : StSize == 1 ? ARM::tSTRBi : 0;
6859   if (IsThumb2)
6860     return StSize == 4 ? ARM::t2STR_POST
6861                        : StSize == 2 ? ARM::t2STRH_POST
6862                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6863   return StSize == 4 ? ARM::STR_POST_IMM
6864                      : StSize == 2 ? ARM::STRH_POST
6865                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6866 }
6867
6868 /// Emit a post-increment load operation with given size. The instructions
6869 /// will be added to BB at Pos.
6870 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6871                        const TargetInstrInfo *TII, DebugLoc dl,
6872                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6873                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6874   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6875   assert(LdOpc != 0 && "Should have a load opcode");
6876   if (LdSize >= 8) {
6877     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6878                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6879                        .addImm(0));
6880   } else if (IsThumb1) {
6881     // load + update AddrIn
6882     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), 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(LdSize);
6888     AddDefaultPred(MIB);
6889   } else if (IsThumb2) {
6890     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6891                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6892                        .addImm(LdSize));
6893   } else { // arm
6894     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6895                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6896                        .addReg(0).addImm(LdSize));
6897   }
6898 }
6899
6900 /// Emit a post-increment store operation with given size. The instructions
6901 /// will be added to BB at Pos.
6902 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6903                        const TargetInstrInfo *TII, DebugLoc dl,
6904                        unsigned StSize, unsigned Data, unsigned AddrIn,
6905                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6906   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6907   assert(StOpc != 0 && "Should have a store opcode");
6908   if (StSize >= 8) {
6909     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6910                        .addReg(AddrIn).addImm(0).addReg(Data));
6911   } else if (IsThumb1) {
6912     // store + update AddrIn
6913     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6914                        .addReg(AddrIn).addImm(0));
6915     MachineInstrBuilder MIB =
6916         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6917     MIB = AddDefaultT1CC(MIB);
6918     MIB.addReg(AddrIn).addImm(StSize);
6919     AddDefaultPred(MIB);
6920   } else if (IsThumb2) {
6921     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6922                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6923   } else { // arm
6924     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6925                        .addReg(Data).addReg(AddrIn).addReg(0)
6926                        .addImm(StSize));
6927   }
6928 }
6929
6930 MachineBasicBlock *
6931 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6932                                    MachineBasicBlock *BB) const {
6933   // This pseudo instruction has 3 operands: dst, src, size
6934   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6935   // Otherwise, we will generate unrolled scalar copies.
6936   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6937   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6938   MachineFunction::iterator It = BB;
6939   ++It;
6940
6941   unsigned dest = MI->getOperand(0).getReg();
6942   unsigned src = MI->getOperand(1).getReg();
6943   unsigned SizeVal = MI->getOperand(2).getImm();
6944   unsigned Align = MI->getOperand(3).getImm();
6945   DebugLoc dl = MI->getDebugLoc();
6946
6947   MachineFunction *MF = BB->getParent();
6948   MachineRegisterInfo &MRI = MF->getRegInfo();
6949   unsigned UnitSize = 0;
6950   const TargetRegisterClass *TRC = nullptr;
6951   const TargetRegisterClass *VecTRC = nullptr;
6952
6953   bool IsThumb1 = Subtarget->isThumb1Only();
6954   bool IsThumb2 = Subtarget->isThumb2();
6955
6956   if (Align & 1) {
6957     UnitSize = 1;
6958   } else if (Align & 2) {
6959     UnitSize = 2;
6960   } else {
6961     // Check whether we can use NEON instructions.
6962     if (!MF->getFunction()->getAttributes().
6963           hasAttribute(AttributeSet::FunctionIndex,
6964                        Attribute::NoImplicitFloat) &&
6965         Subtarget->hasNEON()) {
6966       if ((Align % 16 == 0) && SizeVal >= 16)
6967         UnitSize = 16;
6968       else if ((Align % 8 == 0) && SizeVal >= 8)
6969         UnitSize = 8;
6970     }
6971     // Can't use NEON instructions.
6972     if (UnitSize == 0)
6973       UnitSize = 4;
6974   }
6975
6976   // Select the correct opcode and register class for unit size load/store
6977   bool IsNeon = UnitSize >= 8;
6978   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6979                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6980   if (IsNeon)
6981     VecTRC = UnitSize == 16
6982                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6983                  : UnitSize == 8
6984                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6985                        : nullptr;
6986
6987   unsigned BytesLeft = SizeVal % UnitSize;
6988   unsigned LoopSize = SizeVal - BytesLeft;
6989
6990   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6991     // Use LDR and STR to copy.
6992     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6993     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6994     unsigned srcIn = src;
6995     unsigned destIn = dest;
6996     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6997       unsigned srcOut = MRI.createVirtualRegister(TRC);
6998       unsigned destOut = MRI.createVirtualRegister(TRC);
6999       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7000       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7001                  IsThumb1, IsThumb2);
7002       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7003                  IsThumb1, IsThumb2);
7004       srcIn = srcOut;
7005       destIn = destOut;
7006     }
7007
7008     // Handle the leftover bytes with LDRB and STRB.
7009     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7010     // [destOut] = STRB_POST(scratch, destIn, 1)
7011     for (unsigned i = 0; i < BytesLeft; i++) {
7012       unsigned srcOut = MRI.createVirtualRegister(TRC);
7013       unsigned destOut = MRI.createVirtualRegister(TRC);
7014       unsigned scratch = MRI.createVirtualRegister(TRC);
7015       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7016                  IsThumb1, IsThumb2);
7017       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7018                  IsThumb1, IsThumb2);
7019       srcIn = srcOut;
7020       destIn = destOut;
7021     }
7022     MI->eraseFromParent();   // The instruction is gone now.
7023     return BB;
7024   }
7025
7026   // Expand the pseudo op to a loop.
7027   // thisMBB:
7028   //   ...
7029   //   movw varEnd, # --> with thumb2
7030   //   movt varEnd, #
7031   //   ldrcp varEnd, idx --> without thumb2
7032   //   fallthrough --> loopMBB
7033   // loopMBB:
7034   //   PHI varPhi, varEnd, varLoop
7035   //   PHI srcPhi, src, srcLoop
7036   //   PHI destPhi, dst, destLoop
7037   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7038   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7039   //   subs varLoop, varPhi, #UnitSize
7040   //   bne loopMBB
7041   //   fallthrough --> exitMBB
7042   // exitMBB:
7043   //   epilogue to handle left-over bytes
7044   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7045   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7046   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7047   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7048   MF->insert(It, loopMBB);
7049   MF->insert(It, exitMBB);
7050
7051   // Transfer the remainder of BB and its successor edges to exitMBB.
7052   exitMBB->splice(exitMBB->begin(), BB,
7053                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7054   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7055
7056   // Load an immediate to varEnd.
7057   unsigned varEnd = MRI.createVirtualRegister(TRC);
7058   if (IsThumb2) {
7059     unsigned Vtmp = varEnd;
7060     if ((LoopSize & 0xFFFF0000) != 0)
7061       Vtmp = MRI.createVirtualRegister(TRC);
7062     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7063                        .addImm(LoopSize & 0xFFFF));
7064
7065     if ((LoopSize & 0xFFFF0000) != 0)
7066       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7067                          .addReg(Vtmp).addImm(LoopSize >> 16));
7068   } else {
7069     MachineConstantPool *ConstantPool = MF->getConstantPool();
7070     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7071     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7072
7073     // MachineConstantPool wants an explicit alignment.
7074     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7075     if (Align == 0)
7076       Align = getDataLayout()->getTypeAllocSize(C->getType());
7077     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7078
7079     if (IsThumb1)
7080       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7081           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7082     else
7083       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7084           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7085   }
7086   BB->addSuccessor(loopMBB);
7087
7088   // Generate the loop body:
7089   //   varPhi = PHI(varLoop, varEnd)
7090   //   srcPhi = PHI(srcLoop, src)
7091   //   destPhi = PHI(destLoop, dst)
7092   MachineBasicBlock *entryBB = BB;
7093   BB = loopMBB;
7094   unsigned varLoop = MRI.createVirtualRegister(TRC);
7095   unsigned varPhi = MRI.createVirtualRegister(TRC);
7096   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7097   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7098   unsigned destLoop = MRI.createVirtualRegister(TRC);
7099   unsigned destPhi = MRI.createVirtualRegister(TRC);
7100
7101   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7102     .addReg(varLoop).addMBB(loopMBB)
7103     .addReg(varEnd).addMBB(entryBB);
7104   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7105     .addReg(srcLoop).addMBB(loopMBB)
7106     .addReg(src).addMBB(entryBB);
7107   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7108     .addReg(destLoop).addMBB(loopMBB)
7109     .addReg(dest).addMBB(entryBB);
7110
7111   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7112   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7113   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7114   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7115              IsThumb1, IsThumb2);
7116   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7117              IsThumb1, IsThumb2);
7118
7119   // Decrement loop variable by UnitSize.
7120   if (IsThumb1) {
7121     MachineInstrBuilder MIB =
7122         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7123     MIB = AddDefaultT1CC(MIB);
7124     MIB.addReg(varPhi).addImm(UnitSize);
7125     AddDefaultPred(MIB);
7126   } else {
7127     MachineInstrBuilder MIB =
7128         BuildMI(*BB, BB->end(), dl,
7129                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7130     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7131     MIB->getOperand(5).setReg(ARM::CPSR);
7132     MIB->getOperand(5).setIsDef(true);
7133   }
7134   BuildMI(*BB, BB->end(), dl,
7135           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7136       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7137
7138   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7139   BB->addSuccessor(loopMBB);
7140   BB->addSuccessor(exitMBB);
7141
7142   // Add epilogue to handle BytesLeft.
7143   BB = exitMBB;
7144   MachineInstr *StartOfExit = exitMBB->begin();
7145
7146   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7147   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7148   unsigned srcIn = srcLoop;
7149   unsigned destIn = destLoop;
7150   for (unsigned i = 0; i < BytesLeft; i++) {
7151     unsigned srcOut = MRI.createVirtualRegister(TRC);
7152     unsigned destOut = MRI.createVirtualRegister(TRC);
7153     unsigned scratch = MRI.createVirtualRegister(TRC);
7154     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7155                IsThumb1, IsThumb2);
7156     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7157                IsThumb1, IsThumb2);
7158     srcIn = srcOut;
7159     destIn = destOut;
7160   }
7161
7162   MI->eraseFromParent();   // The instruction is gone now.
7163   return BB;
7164 }
7165
7166 MachineBasicBlock *
7167 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7168                                        MachineBasicBlock *MBB) const {
7169   const TargetMachine &TM = getTargetMachine();
7170   const TargetInstrInfo &TII = *TM.getInstrInfo();
7171   DebugLoc DL = MI->getDebugLoc();
7172
7173   assert(Subtarget->isTargetWindows() &&
7174          "__chkstk is only supported on Windows");
7175   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7176
7177   // __chkstk takes the number of words to allocate on the stack in R4, and
7178   // returns the stack adjustment in number of bytes in R4.  This will not
7179   // clober any other registers (other than the obvious lr).
7180   //
7181   // Although, technically, IP should be considered a register which may be
7182   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7183   // thumb-2 environment, so there is no interworking required.  As a result, we
7184   // do not expect a veneer to be emitted by the linker, clobbering IP.
7185   //
7186   // Each module receives its own copy of __chkstk, so no import thunk is
7187   // required, again, ensuring that IP is not clobbered.
7188   //
7189   // Finally, although some linkers may theoretically provide a trampoline for
7190   // out of range calls (which is quite common due to a 32M range limitation of
7191   // branches for Thumb), we can generate the long-call version via
7192   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7193   // IP.
7194
7195   switch (TM.getCodeModel()) {
7196   case CodeModel::Small:
7197   case CodeModel::Medium:
7198   case CodeModel::Default:
7199   case CodeModel::Kernel:
7200     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7201       .addImm((unsigned)ARMCC::AL).addReg(0)
7202       .addExternalSymbol("__chkstk")
7203       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7204       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7205       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7206     break;
7207   case CodeModel::Large:
7208   case CodeModel::JITDefault: {
7209     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7210     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7211
7212     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7213       .addExternalSymbol("__chkstk");
7214     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7215       .addImm((unsigned)ARMCC::AL).addReg(0)
7216       .addReg(Reg, RegState::Kill)
7217       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7218       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7219       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7220     break;
7221   }
7222   }
7223
7224   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7225                                       ARM::SP)
7226                               .addReg(ARM::SP, RegState::Define)
7227                               .addReg(ARM::R4, RegState::Kill)));
7228
7229   MI->eraseFromParent();
7230   return MBB;
7231 }
7232
7233 MachineBasicBlock *
7234 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7235                                                MachineBasicBlock *BB) const {
7236   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7237   DebugLoc dl = MI->getDebugLoc();
7238   bool isThumb2 = Subtarget->isThumb2();
7239   switch (MI->getOpcode()) {
7240   default: {
7241     MI->dump();
7242     llvm_unreachable("Unexpected instr type to insert");
7243   }
7244   // The Thumb2 pre-indexed stores have the same MI operands, they just
7245   // define them differently in the .td files from the isel patterns, so
7246   // they need pseudos.
7247   case ARM::t2STR_preidx:
7248     MI->setDesc(TII->get(ARM::t2STR_PRE));
7249     return BB;
7250   case ARM::t2STRB_preidx:
7251     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7252     return BB;
7253   case ARM::t2STRH_preidx:
7254     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7255     return BB;
7256
7257   case ARM::STRi_preidx:
7258   case ARM::STRBi_preidx: {
7259     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7260       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7261     // Decode the offset.
7262     unsigned Offset = MI->getOperand(4).getImm();
7263     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7264     Offset = ARM_AM::getAM2Offset(Offset);
7265     if (isSub)
7266       Offset = -Offset;
7267
7268     MachineMemOperand *MMO = *MI->memoperands_begin();
7269     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7270       .addOperand(MI->getOperand(0))  // Rn_wb
7271       .addOperand(MI->getOperand(1))  // Rt
7272       .addOperand(MI->getOperand(2))  // Rn
7273       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7274       .addOperand(MI->getOperand(5))  // pred
7275       .addOperand(MI->getOperand(6))
7276       .addMemOperand(MMO);
7277     MI->eraseFromParent();
7278     return BB;
7279   }
7280   case ARM::STRr_preidx:
7281   case ARM::STRBr_preidx:
7282   case ARM::STRH_preidx: {
7283     unsigned NewOpc;
7284     switch (MI->getOpcode()) {
7285     default: llvm_unreachable("unexpected opcode!");
7286     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7287     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7288     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7289     }
7290     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7291     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7292       MIB.addOperand(MI->getOperand(i));
7293     MI->eraseFromParent();
7294     return BB;
7295   }
7296
7297   case ARM::tMOVCCr_pseudo: {
7298     // To "insert" a SELECT_CC instruction, we actually have to insert the
7299     // diamond control-flow pattern.  The incoming instruction knows the
7300     // destination vreg to set, the condition code register to branch on, the
7301     // true/false values to select between, and a branch opcode to use.
7302     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7303     MachineFunction::iterator It = BB;
7304     ++It;
7305
7306     //  thisMBB:
7307     //  ...
7308     //   TrueVal = ...
7309     //   cmpTY ccX, r1, r2
7310     //   bCC copy1MBB
7311     //   fallthrough --> copy0MBB
7312     MachineBasicBlock *thisMBB  = BB;
7313     MachineFunction *F = BB->getParent();
7314     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7315     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7316     F->insert(It, copy0MBB);
7317     F->insert(It, sinkMBB);
7318
7319     // Transfer the remainder of BB and its successor edges to sinkMBB.
7320     sinkMBB->splice(sinkMBB->begin(), BB,
7321                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7322     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7323
7324     BB->addSuccessor(copy0MBB);
7325     BB->addSuccessor(sinkMBB);
7326
7327     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7328       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7329
7330     //  copy0MBB:
7331     //   %FalseValue = ...
7332     //   # fallthrough to sinkMBB
7333     BB = copy0MBB;
7334
7335     // Update machine-CFG edges
7336     BB->addSuccessor(sinkMBB);
7337
7338     //  sinkMBB:
7339     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7340     //  ...
7341     BB = sinkMBB;
7342     BuildMI(*BB, BB->begin(), dl,
7343             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7344       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7345       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7346
7347     MI->eraseFromParent();   // The pseudo instruction is gone now.
7348     return BB;
7349   }
7350
7351   case ARM::BCCi64:
7352   case ARM::BCCZi64: {
7353     // If there is an unconditional branch to the other successor, remove it.
7354     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7355
7356     // Compare both parts that make up the double comparison separately for
7357     // equality.
7358     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7359
7360     unsigned LHS1 = MI->getOperand(1).getReg();
7361     unsigned LHS2 = MI->getOperand(2).getReg();
7362     if (RHSisZero) {
7363       AddDefaultPred(BuildMI(BB, dl,
7364                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7365                      .addReg(LHS1).addImm(0));
7366       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7367         .addReg(LHS2).addImm(0)
7368         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7369     } else {
7370       unsigned RHS1 = MI->getOperand(3).getReg();
7371       unsigned RHS2 = MI->getOperand(4).getReg();
7372       AddDefaultPred(BuildMI(BB, dl,
7373                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7374                      .addReg(LHS1).addReg(RHS1));
7375       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7376         .addReg(LHS2).addReg(RHS2)
7377         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7378     }
7379
7380     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7381     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7382     if (MI->getOperand(0).getImm() == ARMCC::NE)
7383       std::swap(destMBB, exitMBB);
7384
7385     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7386       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7387     if (isThumb2)
7388       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7389     else
7390       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7391
7392     MI->eraseFromParent();   // The pseudo instruction is gone now.
7393     return BB;
7394   }
7395
7396   case ARM::Int_eh_sjlj_setjmp:
7397   case ARM::Int_eh_sjlj_setjmp_nofp:
7398   case ARM::tInt_eh_sjlj_setjmp:
7399   case ARM::t2Int_eh_sjlj_setjmp:
7400   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7401     EmitSjLjDispatchBlock(MI, BB);
7402     return BB;
7403
7404   case ARM::ABS:
7405   case ARM::t2ABS: {
7406     // To insert an ABS instruction, we have to insert the
7407     // diamond control-flow pattern.  The incoming instruction knows the
7408     // source vreg to test against 0, the destination vreg to set,
7409     // the condition code register to branch on, the
7410     // true/false values to select between, and a branch opcode to use.
7411     // It transforms
7412     //     V1 = ABS V0
7413     // into
7414     //     V2 = MOVS V0
7415     //     BCC                      (branch to SinkBB if V0 >= 0)
7416     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7417     //     SinkBB: V1 = PHI(V2, V3)
7418     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7419     MachineFunction::iterator BBI = BB;
7420     ++BBI;
7421     MachineFunction *Fn = BB->getParent();
7422     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7423     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7424     Fn->insert(BBI, RSBBB);
7425     Fn->insert(BBI, SinkBB);
7426
7427     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7428     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7429     bool isThumb2 = Subtarget->isThumb2();
7430     MachineRegisterInfo &MRI = Fn->getRegInfo();
7431     // In Thumb mode S must not be specified if source register is the SP or
7432     // PC and if destination register is the SP, so restrict register class
7433     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7434       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7435       (const TargetRegisterClass*)&ARM::GPRRegClass);
7436
7437     // Transfer the remainder of BB and its successor edges to sinkMBB.
7438     SinkBB->splice(SinkBB->begin(), BB,
7439                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7440     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7441
7442     BB->addSuccessor(RSBBB);
7443     BB->addSuccessor(SinkBB);
7444
7445     // fall through to SinkMBB
7446     RSBBB->addSuccessor(SinkBB);
7447
7448     // insert a cmp at the end of BB
7449     AddDefaultPred(BuildMI(BB, dl,
7450                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7451                    .addReg(ABSSrcReg).addImm(0));
7452
7453     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7454     BuildMI(BB, dl,
7455       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7456       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7457
7458     // insert rsbri in RSBBB
7459     // Note: BCC and rsbri will be converted into predicated rsbmi
7460     // by if-conversion pass
7461     BuildMI(*RSBBB, RSBBB->begin(), dl,
7462       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7463       .addReg(ABSSrcReg, RegState::Kill)
7464       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7465
7466     // insert PHI in SinkBB,
7467     // reuse ABSDstReg to not change uses of ABS instruction
7468     BuildMI(*SinkBB, SinkBB->begin(), dl,
7469       TII->get(ARM::PHI), ABSDstReg)
7470       .addReg(NewRsbDstReg).addMBB(RSBBB)
7471       .addReg(ABSSrcReg).addMBB(BB);
7472
7473     // remove ABS instruction
7474     MI->eraseFromParent();
7475
7476     // return last added BB
7477     return SinkBB;
7478   }
7479   case ARM::COPY_STRUCT_BYVAL_I32:
7480     ++NumLoopByVals;
7481     return EmitStructByval(MI, BB);
7482   case ARM::WIN__CHKSTK:
7483     return EmitLowered__chkstk(MI, BB);
7484   }
7485 }
7486
7487 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7488                                                       SDNode *Node) const {
7489   if (!MI->hasPostISelHook()) {
7490     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7491            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7492     return;
7493   }
7494
7495   const MCInstrDesc *MCID = &MI->getDesc();
7496   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7497   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7498   // operand is still set to noreg. If needed, set the optional operand's
7499   // register to CPSR, and remove the redundant implicit def.
7500   //
7501   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7502
7503   // Rename pseudo opcodes.
7504   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7505   if (NewOpc) {
7506     const ARMBaseInstrInfo *TII =
7507       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7508     MCID = &TII->get(NewOpc);
7509
7510     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7511            "converted opcode should be the same except for cc_out");
7512
7513     MI->setDesc(*MCID);
7514
7515     // Add the optional cc_out operand
7516     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7517   }
7518   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7519
7520   // Any ARM instruction that sets the 's' bit should specify an optional
7521   // "cc_out" operand in the last operand position.
7522   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7523     assert(!NewOpc && "Optional cc_out operand required");
7524     return;
7525   }
7526   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7527   // since we already have an optional CPSR def.
7528   bool definesCPSR = false;
7529   bool deadCPSR = false;
7530   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7531        i != e; ++i) {
7532     const MachineOperand &MO = MI->getOperand(i);
7533     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7534       definesCPSR = true;
7535       if (MO.isDead())
7536         deadCPSR = true;
7537       MI->RemoveOperand(i);
7538       break;
7539     }
7540   }
7541   if (!definesCPSR) {
7542     assert(!NewOpc && "Optional cc_out operand required");
7543     return;
7544   }
7545   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7546   if (deadCPSR) {
7547     assert(!MI->getOperand(ccOutIdx).getReg() &&
7548            "expect uninitialized optional cc_out operand");
7549     return;
7550   }
7551
7552   // If this instruction was defined with an optional CPSR def and its dag node
7553   // had a live implicit CPSR def, then activate the optional CPSR def.
7554   MachineOperand &MO = MI->getOperand(ccOutIdx);
7555   MO.setReg(ARM::CPSR);
7556   MO.setIsDef(true);
7557 }
7558
7559 //===----------------------------------------------------------------------===//
7560 //                           ARM Optimization Hooks
7561 //===----------------------------------------------------------------------===//
7562
7563 // Helper function that checks if N is a null or all ones constant.
7564 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7565   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7566   if (!C)
7567     return false;
7568   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7569 }
7570
7571 // Return true if N is conditionally 0 or all ones.
7572 // Detects these expressions where cc is an i1 value:
7573 //
7574 //   (select cc 0, y)   [AllOnes=0]
7575 //   (select cc y, 0)   [AllOnes=0]
7576 //   (zext cc)          [AllOnes=0]
7577 //   (sext cc)          [AllOnes=0/1]
7578 //   (select cc -1, y)  [AllOnes=1]
7579 //   (select cc y, -1)  [AllOnes=1]
7580 //
7581 // Invert is set when N is the null/all ones constant when CC is false.
7582 // OtherOp is set to the alternative value of N.
7583 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7584                                        SDValue &CC, bool &Invert,
7585                                        SDValue &OtherOp,
7586                                        SelectionDAG &DAG) {
7587   switch (N->getOpcode()) {
7588   default: return false;
7589   case ISD::SELECT: {
7590     CC = N->getOperand(0);
7591     SDValue N1 = N->getOperand(1);
7592     SDValue N2 = N->getOperand(2);
7593     if (isZeroOrAllOnes(N1, AllOnes)) {
7594       Invert = false;
7595       OtherOp = N2;
7596       return true;
7597     }
7598     if (isZeroOrAllOnes(N2, AllOnes)) {
7599       Invert = true;
7600       OtherOp = N1;
7601       return true;
7602     }
7603     return false;
7604   }
7605   case ISD::ZERO_EXTEND:
7606     // (zext cc) can never be the all ones value.
7607     if (AllOnes)
7608       return false;
7609     // Fall through.
7610   case ISD::SIGN_EXTEND: {
7611     EVT VT = N->getValueType(0);
7612     CC = N->getOperand(0);
7613     if (CC.getValueType() != MVT::i1)
7614       return false;
7615     Invert = !AllOnes;
7616     if (AllOnes)
7617       // When looking for an AllOnes constant, N is an sext, and the 'other'
7618       // value is 0.
7619       OtherOp = DAG.getConstant(0, VT);
7620     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7621       // When looking for a 0 constant, N can be zext or sext.
7622       OtherOp = DAG.getConstant(1, VT);
7623     else
7624       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7625     return true;
7626   }
7627   }
7628 }
7629
7630 // Combine a constant select operand into its use:
7631 //
7632 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7633 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7634 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7635 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7636 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7637 //
7638 // The transform is rejected if the select doesn't have a constant operand that
7639 // is null, or all ones when AllOnes is set.
7640 //
7641 // Also recognize sext/zext from i1:
7642 //
7643 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7644 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7645 //
7646 // These transformations eventually create predicated instructions.
7647 //
7648 // @param N       The node to transform.
7649 // @param Slct    The N operand that is a select.
7650 // @param OtherOp The other N operand (x above).
7651 // @param DCI     Context.
7652 // @param AllOnes Require the select constant to be all ones instead of null.
7653 // @returns The new node, or SDValue() on failure.
7654 static
7655 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7656                             TargetLowering::DAGCombinerInfo &DCI,
7657                             bool AllOnes = false) {
7658   SelectionDAG &DAG = DCI.DAG;
7659   EVT VT = N->getValueType(0);
7660   SDValue NonConstantVal;
7661   SDValue CCOp;
7662   bool SwapSelectOps;
7663   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7664                                   NonConstantVal, DAG))
7665     return SDValue();
7666
7667   // Slct is now know to be the desired identity constant when CC is true.
7668   SDValue TrueVal = OtherOp;
7669   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7670                                  OtherOp, NonConstantVal);
7671   // Unless SwapSelectOps says CC should be false.
7672   if (SwapSelectOps)
7673     std::swap(TrueVal, FalseVal);
7674
7675   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7676                      CCOp, TrueVal, FalseVal);
7677 }
7678
7679 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7680 static
7681 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7682                                        TargetLowering::DAGCombinerInfo &DCI) {
7683   SDValue N0 = N->getOperand(0);
7684   SDValue N1 = N->getOperand(1);
7685   if (N0.getNode()->hasOneUse()) {
7686     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7687     if (Result.getNode())
7688       return Result;
7689   }
7690   if (N1.getNode()->hasOneUse()) {
7691     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7692     if (Result.getNode())
7693       return Result;
7694   }
7695   return SDValue();
7696 }
7697
7698 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7699 // (only after legalization).
7700 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7701                                  TargetLowering::DAGCombinerInfo &DCI,
7702                                  const ARMSubtarget *Subtarget) {
7703
7704   // Only perform optimization if after legalize, and if NEON is available. We
7705   // also expected both operands to be BUILD_VECTORs.
7706   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7707       || N0.getOpcode() != ISD::BUILD_VECTOR
7708       || N1.getOpcode() != ISD::BUILD_VECTOR)
7709     return SDValue();
7710
7711   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7712   EVT VT = N->getValueType(0);
7713   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7714     return SDValue();
7715
7716   // Check that the vector operands are of the right form.
7717   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7718   // operands, where N is the size of the formed vector.
7719   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7720   // index such that we have a pair wise add pattern.
7721
7722   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7723   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7724     return SDValue();
7725   SDValue Vec = N0->getOperand(0)->getOperand(0);
7726   SDNode *V = Vec.getNode();
7727   unsigned nextIndex = 0;
7728
7729   // For each operands to the ADD which are BUILD_VECTORs,
7730   // check to see if each of their operands are an EXTRACT_VECTOR with
7731   // the same vector and appropriate index.
7732   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7733     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7734         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7735
7736       SDValue ExtVec0 = N0->getOperand(i);
7737       SDValue ExtVec1 = N1->getOperand(i);
7738
7739       // First operand is the vector, verify its the same.
7740       if (V != ExtVec0->getOperand(0).getNode() ||
7741           V != ExtVec1->getOperand(0).getNode())
7742         return SDValue();
7743
7744       // Second is the constant, verify its correct.
7745       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7746       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7747
7748       // For the constant, we want to see all the even or all the odd.
7749       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7750           || C1->getZExtValue() != nextIndex+1)
7751         return SDValue();
7752
7753       // Increment index.
7754       nextIndex+=2;
7755     } else
7756       return SDValue();
7757   }
7758
7759   // Create VPADDL node.
7760   SelectionDAG &DAG = DCI.DAG;
7761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7762
7763   // Build operand list.
7764   SmallVector<SDValue, 8> Ops;
7765   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7766                                 TLI.getPointerTy()));
7767
7768   // Input is the vector.
7769   Ops.push_back(Vec);
7770
7771   // Get widened type and narrowed type.
7772   MVT widenType;
7773   unsigned numElem = VT.getVectorNumElements();
7774   
7775   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7776   switch (inputLaneType.getSimpleVT().SimpleTy) {
7777     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7778     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7779     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7780     default:
7781       llvm_unreachable("Invalid vector element type for padd optimization.");
7782   }
7783
7784   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7785   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7786   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7787 }
7788
7789 static SDValue findMUL_LOHI(SDValue V) {
7790   if (V->getOpcode() == ISD::UMUL_LOHI ||
7791       V->getOpcode() == ISD::SMUL_LOHI)
7792     return V;
7793   return SDValue();
7794 }
7795
7796 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7797                                      TargetLowering::DAGCombinerInfo &DCI,
7798                                      const ARMSubtarget *Subtarget) {
7799
7800   if (Subtarget->isThumb1Only()) return SDValue();
7801
7802   // Only perform the checks after legalize when the pattern is available.
7803   if (DCI.isBeforeLegalize()) return SDValue();
7804
7805   // Look for multiply add opportunities.
7806   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7807   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7808   // a glue link from the first add to the second add.
7809   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7810   // a S/UMLAL instruction.
7811   //          loAdd   UMUL_LOHI
7812   //            \    / :lo    \ :hi
7813   //             \  /          \          [no multiline comment]
7814   //              ADDC         |  hiAdd
7815   //                 \ :glue  /  /
7816   //                  \      /  /
7817   //                    ADDE
7818   //
7819   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7820   SDValue AddcOp0 = AddcNode->getOperand(0);
7821   SDValue AddcOp1 = AddcNode->getOperand(1);
7822
7823   // Check if the two operands are from the same mul_lohi node.
7824   if (AddcOp0.getNode() == AddcOp1.getNode())
7825     return SDValue();
7826
7827   assert(AddcNode->getNumValues() == 2 &&
7828          AddcNode->getValueType(0) == MVT::i32 &&
7829          "Expect ADDC with two result values. First: i32");
7830
7831   // Check that we have a glued ADDC node.
7832   if (AddcNode->getValueType(1) != MVT::Glue)
7833     return SDValue();
7834
7835   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7836   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7837       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7838       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7839       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7840     return SDValue();
7841
7842   // Look for the glued ADDE.
7843   SDNode* AddeNode = AddcNode->getGluedUser();
7844   if (!AddeNode)
7845     return SDValue();
7846
7847   // Make sure it is really an ADDE.
7848   if (AddeNode->getOpcode() != ISD::ADDE)
7849     return SDValue();
7850
7851   assert(AddeNode->getNumOperands() == 3 &&
7852          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7853          "ADDE node has the wrong inputs");
7854
7855   // Check for the triangle shape.
7856   SDValue AddeOp0 = AddeNode->getOperand(0);
7857   SDValue AddeOp1 = AddeNode->getOperand(1);
7858
7859   // Make sure that the ADDE operands are not coming from the same node.
7860   if (AddeOp0.getNode() == AddeOp1.getNode())
7861     return SDValue();
7862
7863   // Find the MUL_LOHI node walking up ADDE's operands.
7864   bool IsLeftOperandMUL = false;
7865   SDValue MULOp = findMUL_LOHI(AddeOp0);
7866   if (MULOp == SDValue())
7867    MULOp = findMUL_LOHI(AddeOp1);
7868   else
7869     IsLeftOperandMUL = true;
7870   if (MULOp == SDValue())
7871      return SDValue();
7872
7873   // Figure out the right opcode.
7874   unsigned Opc = MULOp->getOpcode();
7875   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7876
7877   // Figure out the high and low input values to the MLAL node.
7878   SDValue* HiMul = &MULOp;
7879   SDValue* HiAdd = nullptr;
7880   SDValue* LoMul = nullptr;
7881   SDValue* LowAdd = nullptr;
7882
7883   if (IsLeftOperandMUL)
7884     HiAdd = &AddeOp1;
7885   else
7886     HiAdd = &AddeOp0;
7887
7888
7889   if (AddcOp0->getOpcode() == Opc) {
7890     LoMul = &AddcOp0;
7891     LowAdd = &AddcOp1;
7892   }
7893   if (AddcOp1->getOpcode() == Opc) {
7894     LoMul = &AddcOp1;
7895     LowAdd = &AddcOp0;
7896   }
7897
7898   if (!LoMul)
7899     return SDValue();
7900
7901   if (LoMul->getNode() != HiMul->getNode())
7902     return SDValue();
7903
7904   // Create the merged node.
7905   SelectionDAG &DAG = DCI.DAG;
7906
7907   // Build operand list.
7908   SmallVector<SDValue, 8> Ops;
7909   Ops.push_back(LoMul->getOperand(0));
7910   Ops.push_back(LoMul->getOperand(1));
7911   Ops.push_back(*LowAdd);
7912   Ops.push_back(*HiAdd);
7913
7914   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7915                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7916
7917   // Replace the ADDs' nodes uses by the MLA node's values.
7918   SDValue HiMLALResult(MLALNode.getNode(), 1);
7919   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7920
7921   SDValue LoMLALResult(MLALNode.getNode(), 0);
7922   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7923
7924   // Return original node to notify the driver to stop replacing.
7925   SDValue resNode(AddcNode, 0);
7926   return resNode;
7927 }
7928
7929 /// PerformADDCCombine - Target-specific dag combine transform from
7930 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7931 static SDValue PerformADDCCombine(SDNode *N,
7932                                  TargetLowering::DAGCombinerInfo &DCI,
7933                                  const ARMSubtarget *Subtarget) {
7934
7935   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7936
7937 }
7938
7939 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7940 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7941 /// called with the default operands, and if that fails, with commuted
7942 /// operands.
7943 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7944                                           TargetLowering::DAGCombinerInfo &DCI,
7945                                           const ARMSubtarget *Subtarget){
7946
7947   // Attempt to create vpaddl for this add.
7948   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7949   if (Result.getNode())
7950     return Result;
7951
7952   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7953   if (N0.getNode()->hasOneUse()) {
7954     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7955     if (Result.getNode()) return Result;
7956   }
7957   return SDValue();
7958 }
7959
7960 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7961 ///
7962 static SDValue PerformADDCombine(SDNode *N,
7963                                  TargetLowering::DAGCombinerInfo &DCI,
7964                                  const ARMSubtarget *Subtarget) {
7965   SDValue N0 = N->getOperand(0);
7966   SDValue N1 = N->getOperand(1);
7967
7968   // First try with the default operand order.
7969   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7970   if (Result.getNode())
7971     return Result;
7972
7973   // If that didn't work, try again with the operands commuted.
7974   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7975 }
7976
7977 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7978 ///
7979 static SDValue PerformSUBCombine(SDNode *N,
7980                                  TargetLowering::DAGCombinerInfo &DCI) {
7981   SDValue N0 = N->getOperand(0);
7982   SDValue N1 = N->getOperand(1);
7983
7984   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7985   if (N1.getNode()->hasOneUse()) {
7986     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7987     if (Result.getNode()) return Result;
7988   }
7989
7990   return SDValue();
7991 }
7992
7993 /// PerformVMULCombine
7994 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7995 /// special multiplier accumulator forwarding.
7996 ///   vmul d3, d0, d2
7997 ///   vmla d3, d1, d2
7998 /// is faster than
7999 ///   vadd d3, d0, d1
8000 ///   vmul d3, d3, d2
8001 //  However, for (A + B) * (A + B),
8002 //    vadd d2, d0, d1
8003 //    vmul d3, d0, d2
8004 //    vmla d3, d1, d2
8005 //  is slower than
8006 //    vadd d2, d0, d1
8007 //    vmul d3, d2, d2
8008 static SDValue PerformVMULCombine(SDNode *N,
8009                                   TargetLowering::DAGCombinerInfo &DCI,
8010                                   const ARMSubtarget *Subtarget) {
8011   if (!Subtarget->hasVMLxForwarding())
8012     return SDValue();
8013
8014   SelectionDAG &DAG = DCI.DAG;
8015   SDValue N0 = N->getOperand(0);
8016   SDValue N1 = N->getOperand(1);
8017   unsigned Opcode = N0.getOpcode();
8018   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8019       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8020     Opcode = N1.getOpcode();
8021     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8022         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8023       return SDValue();
8024     std::swap(N0, N1);
8025   }
8026
8027   if (N0 == N1)
8028     return SDValue();
8029
8030   EVT VT = N->getValueType(0);
8031   SDLoc DL(N);
8032   SDValue N00 = N0->getOperand(0);
8033   SDValue N01 = N0->getOperand(1);
8034   return DAG.getNode(Opcode, DL, VT,
8035                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8036                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8037 }
8038
8039 static SDValue PerformMULCombine(SDNode *N,
8040                                  TargetLowering::DAGCombinerInfo &DCI,
8041                                  const ARMSubtarget *Subtarget) {
8042   SelectionDAG &DAG = DCI.DAG;
8043
8044   if (Subtarget->isThumb1Only())
8045     return SDValue();
8046
8047   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8048     return SDValue();
8049
8050   EVT VT = N->getValueType(0);
8051   if (VT.is64BitVector() || VT.is128BitVector())
8052     return PerformVMULCombine(N, DCI, Subtarget);
8053   if (VT != MVT::i32)
8054     return SDValue();
8055
8056   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8057   if (!C)
8058     return SDValue();
8059
8060   int64_t MulAmt = C->getSExtValue();
8061   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8062
8063   ShiftAmt = ShiftAmt & (32 - 1);
8064   SDValue V = N->getOperand(0);
8065   SDLoc DL(N);
8066
8067   SDValue Res;
8068   MulAmt >>= ShiftAmt;
8069
8070   if (MulAmt >= 0) {
8071     if (isPowerOf2_32(MulAmt - 1)) {
8072       // (mul x, 2^N + 1) => (add (shl x, N), x)
8073       Res = DAG.getNode(ISD::ADD, DL, VT,
8074                         V,
8075                         DAG.getNode(ISD::SHL, DL, VT,
8076                                     V,
8077                                     DAG.getConstant(Log2_32(MulAmt - 1),
8078                                                     MVT::i32)));
8079     } else if (isPowerOf2_32(MulAmt + 1)) {
8080       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8081       Res = DAG.getNode(ISD::SUB, DL, VT,
8082                         DAG.getNode(ISD::SHL, DL, VT,
8083                                     V,
8084                                     DAG.getConstant(Log2_32(MulAmt + 1),
8085                                                     MVT::i32)),
8086                         V);
8087     } else
8088       return SDValue();
8089   } else {
8090     uint64_t MulAmtAbs = -MulAmt;
8091     if (isPowerOf2_32(MulAmtAbs + 1)) {
8092       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8093       Res = DAG.getNode(ISD::SUB, DL, VT,
8094                         V,
8095                         DAG.getNode(ISD::SHL, DL, VT,
8096                                     V,
8097                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8098                                                     MVT::i32)));
8099     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8100       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8101       Res = DAG.getNode(ISD::ADD, DL, VT,
8102                         V,
8103                         DAG.getNode(ISD::SHL, DL, VT,
8104                                     V,
8105                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8106                                                     MVT::i32)));
8107       Res = DAG.getNode(ISD::SUB, DL, VT,
8108                         DAG.getConstant(0, MVT::i32),Res);
8109
8110     } else
8111       return SDValue();
8112   }
8113
8114   if (ShiftAmt != 0)
8115     Res = DAG.getNode(ISD::SHL, DL, VT,
8116                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8117
8118   // Do not add new nodes to DAG combiner worklist.
8119   DCI.CombineTo(N, Res, false);
8120   return SDValue();
8121 }
8122
8123 static SDValue PerformANDCombine(SDNode *N,
8124                                  TargetLowering::DAGCombinerInfo &DCI,
8125                                  const ARMSubtarget *Subtarget) {
8126
8127   // Attempt to use immediate-form VBIC
8128   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8129   SDLoc dl(N);
8130   EVT VT = N->getValueType(0);
8131   SelectionDAG &DAG = DCI.DAG;
8132
8133   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8134     return SDValue();
8135
8136   APInt SplatBits, SplatUndef;
8137   unsigned SplatBitSize;
8138   bool HasAnyUndefs;
8139   if (BVN &&
8140       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8141     if (SplatBitSize <= 64) {
8142       EVT VbicVT;
8143       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8144                                       SplatUndef.getZExtValue(), SplatBitSize,
8145                                       DAG, VbicVT, VT.is128BitVector(),
8146                                       OtherModImm);
8147       if (Val.getNode()) {
8148         SDValue Input =
8149           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8150         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8151         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8152       }
8153     }
8154   }
8155
8156   if (!Subtarget->isThumb1Only()) {
8157     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8158     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8159     if (Result.getNode())
8160       return Result;
8161   }
8162
8163   return SDValue();
8164 }
8165
8166 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8167 static SDValue PerformORCombine(SDNode *N,
8168                                 TargetLowering::DAGCombinerInfo &DCI,
8169                                 const ARMSubtarget *Subtarget) {
8170   // Attempt to use immediate-form VORR
8171   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8172   SDLoc dl(N);
8173   EVT VT = N->getValueType(0);
8174   SelectionDAG &DAG = DCI.DAG;
8175
8176   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8177     return SDValue();
8178
8179   APInt SplatBits, SplatUndef;
8180   unsigned SplatBitSize;
8181   bool HasAnyUndefs;
8182   if (BVN && Subtarget->hasNEON() &&
8183       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8184     if (SplatBitSize <= 64) {
8185       EVT VorrVT;
8186       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8187                                       SplatUndef.getZExtValue(), SplatBitSize,
8188                                       DAG, VorrVT, VT.is128BitVector(),
8189                                       OtherModImm);
8190       if (Val.getNode()) {
8191         SDValue Input =
8192           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8193         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8194         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8195       }
8196     }
8197   }
8198
8199   if (!Subtarget->isThumb1Only()) {
8200     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8201     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8202     if (Result.getNode())
8203       return Result;
8204   }
8205
8206   // The code below optimizes (or (and X, Y), Z).
8207   // The AND operand needs to have a single user to make these optimizations
8208   // profitable.
8209   SDValue N0 = N->getOperand(0);
8210   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8211     return SDValue();
8212   SDValue N1 = N->getOperand(1);
8213
8214   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8215   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8216       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8217     APInt SplatUndef;
8218     unsigned SplatBitSize;
8219     bool HasAnyUndefs;
8220
8221     APInt SplatBits0, SplatBits1;
8222     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8223     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8224     // Ensure that the second operand of both ands are constants
8225     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8226                                       HasAnyUndefs) && !HasAnyUndefs) {
8227         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8228                                           HasAnyUndefs) && !HasAnyUndefs) {
8229             // Ensure that the bit width of the constants are the same and that
8230             // the splat arguments are logical inverses as per the pattern we
8231             // are trying to simplify.
8232             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8233                 SplatBits0 == ~SplatBits1) {
8234                 // Canonicalize the vector type to make instruction selection
8235                 // simpler.
8236                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8237                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8238                                              N0->getOperand(1),
8239                                              N0->getOperand(0),
8240                                              N1->getOperand(0));
8241                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8242             }
8243         }
8244     }
8245   }
8246
8247   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8248   // reasonable.
8249
8250   // BFI is only available on V6T2+
8251   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8252     return SDValue();
8253
8254   SDLoc DL(N);
8255   // 1) or (and A, mask), val => ARMbfi A, val, mask
8256   //      iff (val & mask) == val
8257   //
8258   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8259   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8260   //          && mask == ~mask2
8261   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8262   //          && ~mask == mask2
8263   //  (i.e., copy a bitfield value into another bitfield of the same width)
8264
8265   if (VT != MVT::i32)
8266     return SDValue();
8267
8268   SDValue N00 = N0.getOperand(0);
8269
8270   // The value and the mask need to be constants so we can verify this is
8271   // actually a bitfield set. If the mask is 0xffff, we can do better
8272   // via a movt instruction, so don't use BFI in that case.
8273   SDValue MaskOp = N0.getOperand(1);
8274   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8275   if (!MaskC)
8276     return SDValue();
8277   unsigned Mask = MaskC->getZExtValue();
8278   if (Mask == 0xffff)
8279     return SDValue();
8280   SDValue Res;
8281   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8282   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8283   if (N1C) {
8284     unsigned Val = N1C->getZExtValue();
8285     if ((Val & ~Mask) != Val)
8286       return SDValue();
8287
8288     if (ARM::isBitFieldInvertedMask(Mask)) {
8289       Val >>= countTrailingZeros(~Mask);
8290
8291       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8292                         DAG.getConstant(Val, MVT::i32),
8293                         DAG.getConstant(Mask, MVT::i32));
8294
8295       // Do not add new nodes to DAG combiner worklist.
8296       DCI.CombineTo(N, Res, false);
8297       return SDValue();
8298     }
8299   } else if (N1.getOpcode() == ISD::AND) {
8300     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8301     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8302     if (!N11C)
8303       return SDValue();
8304     unsigned Mask2 = N11C->getZExtValue();
8305
8306     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8307     // as is to match.
8308     if (ARM::isBitFieldInvertedMask(Mask) &&
8309         (Mask == ~Mask2)) {
8310       // The pack halfword instruction works better for masks that fit it,
8311       // so use that when it's available.
8312       if (Subtarget->hasT2ExtractPack() &&
8313           (Mask == 0xffff || Mask == 0xffff0000))
8314         return SDValue();
8315       // 2a
8316       unsigned amt = countTrailingZeros(Mask2);
8317       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8318                         DAG.getConstant(amt, MVT::i32));
8319       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8320                         DAG.getConstant(Mask, MVT::i32));
8321       // Do not add new nodes to DAG combiner worklist.
8322       DCI.CombineTo(N, Res, false);
8323       return SDValue();
8324     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8325                (~Mask == Mask2)) {
8326       // The pack halfword instruction works better for masks that fit it,
8327       // so use that when it's available.
8328       if (Subtarget->hasT2ExtractPack() &&
8329           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8330         return SDValue();
8331       // 2b
8332       unsigned lsb = countTrailingZeros(Mask);
8333       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8334                         DAG.getConstant(lsb, MVT::i32));
8335       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8336                         DAG.getConstant(Mask2, MVT::i32));
8337       // Do not add new nodes to DAG combiner worklist.
8338       DCI.CombineTo(N, Res, false);
8339       return SDValue();
8340     }
8341   }
8342
8343   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8344       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8345       ARM::isBitFieldInvertedMask(~Mask)) {
8346     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8347     // where lsb(mask) == #shamt and masked bits of B are known zero.
8348     SDValue ShAmt = N00.getOperand(1);
8349     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8350     unsigned LSB = countTrailingZeros(Mask);
8351     if (ShAmtC != LSB)
8352       return SDValue();
8353
8354     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8355                       DAG.getConstant(~Mask, MVT::i32));
8356
8357     // Do not add new nodes to DAG combiner worklist.
8358     DCI.CombineTo(N, Res, false);
8359   }
8360
8361   return SDValue();
8362 }
8363
8364 static SDValue PerformXORCombine(SDNode *N,
8365                                  TargetLowering::DAGCombinerInfo &DCI,
8366                                  const ARMSubtarget *Subtarget) {
8367   EVT VT = N->getValueType(0);
8368   SelectionDAG &DAG = DCI.DAG;
8369
8370   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8371     return SDValue();
8372
8373   if (!Subtarget->isThumb1Only()) {
8374     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8375     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8376     if (Result.getNode())
8377       return Result;
8378   }
8379
8380   return SDValue();
8381 }
8382
8383 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8384 /// the bits being cleared by the AND are not demanded by the BFI.
8385 static SDValue PerformBFICombine(SDNode *N,
8386                                  TargetLowering::DAGCombinerInfo &DCI) {
8387   SDValue N1 = N->getOperand(1);
8388   if (N1.getOpcode() == ISD::AND) {
8389     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8390     if (!N11C)
8391       return SDValue();
8392     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8393     unsigned LSB = countTrailingZeros(~InvMask);
8394     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8395     unsigned Mask = (1 << Width)-1;
8396     unsigned Mask2 = N11C->getZExtValue();
8397     if ((Mask & (~Mask2)) == 0)
8398       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8399                              N->getOperand(0), N1.getOperand(0),
8400                              N->getOperand(2));
8401   }
8402   return SDValue();
8403 }
8404
8405 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8406 /// ARMISD::VMOVRRD.
8407 static SDValue PerformVMOVRRDCombine(SDNode *N,
8408                                      TargetLowering::DAGCombinerInfo &DCI) {
8409   // vmovrrd(vmovdrr x, y) -> x,y
8410   SDValue InDouble = N->getOperand(0);
8411   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8412     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8413
8414   // vmovrrd(load f64) -> (load i32), (load i32)
8415   SDNode *InNode = InDouble.getNode();
8416   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8417       InNode->getValueType(0) == MVT::f64 &&
8418       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8419       !cast<LoadSDNode>(InNode)->isVolatile()) {
8420     // TODO: Should this be done for non-FrameIndex operands?
8421     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8422
8423     SelectionDAG &DAG = DCI.DAG;
8424     SDLoc DL(LD);
8425     SDValue BasePtr = LD->getBasePtr();
8426     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8427                                  LD->getPointerInfo(), LD->isVolatile(),
8428                                  LD->isNonTemporal(), LD->isInvariant(),
8429                                  LD->getAlignment());
8430
8431     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8432                                     DAG.getConstant(4, MVT::i32));
8433     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8434                                  LD->getPointerInfo(), LD->isVolatile(),
8435                                  LD->isNonTemporal(), LD->isInvariant(),
8436                                  std::min(4U, LD->getAlignment() / 2));
8437
8438     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8439     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8440       std::swap (NewLD1, NewLD2);
8441     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8442     DCI.RemoveFromWorklist(LD);
8443     DAG.DeleteNode(LD);
8444     return Result;
8445   }
8446
8447   return SDValue();
8448 }
8449
8450 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8451 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8452 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8453   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8454   SDValue Op0 = N->getOperand(0);
8455   SDValue Op1 = N->getOperand(1);
8456   if (Op0.getOpcode() == ISD::BITCAST)
8457     Op0 = Op0.getOperand(0);
8458   if (Op1.getOpcode() == ISD::BITCAST)
8459     Op1 = Op1.getOperand(0);
8460   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8461       Op0.getNode() == Op1.getNode() &&
8462       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8463     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8464                        N->getValueType(0), Op0.getOperand(0));
8465   return SDValue();
8466 }
8467
8468 /// PerformSTORECombine - Target-specific dag combine xforms for
8469 /// ISD::STORE.
8470 static SDValue PerformSTORECombine(SDNode *N,
8471                                    TargetLowering::DAGCombinerInfo &DCI) {
8472   StoreSDNode *St = cast<StoreSDNode>(N);
8473   if (St->isVolatile())
8474     return SDValue();
8475
8476   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8477   // pack all of the elements in one place.  Next, store to memory in fewer
8478   // chunks.
8479   SDValue StVal = St->getValue();
8480   EVT VT = StVal.getValueType();
8481   if (St->isTruncatingStore() && VT.isVector()) {
8482     SelectionDAG &DAG = DCI.DAG;
8483     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8484     EVT StVT = St->getMemoryVT();
8485     unsigned NumElems = VT.getVectorNumElements();
8486     assert(StVT != VT && "Cannot truncate to the same type");
8487     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8488     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8489
8490     // From, To sizes and ElemCount must be pow of two
8491     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8492
8493     // We are going to use the original vector elt for storing.
8494     // Accumulated smaller vector elements must be a multiple of the store size.
8495     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8496
8497     unsigned SizeRatio  = FromEltSz / ToEltSz;
8498     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8499
8500     // Create a type on which we perform the shuffle.
8501     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8502                                      NumElems*SizeRatio);
8503     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8504
8505     SDLoc DL(St);
8506     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8507     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8508     for (unsigned i = 0; i < NumElems; ++i)
8509       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8510
8511     // Can't shuffle using an illegal type.
8512     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8513
8514     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8515                                 DAG.getUNDEF(WideVec.getValueType()),
8516                                 ShuffleVec.data());
8517     // At this point all of the data is stored at the bottom of the
8518     // register. We now need to save it to mem.
8519
8520     // Find the largest store unit
8521     MVT StoreType = MVT::i8;
8522     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8523          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8524       MVT Tp = (MVT::SimpleValueType)tp;
8525       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8526         StoreType = Tp;
8527     }
8528     // Didn't find a legal store type.
8529     if (!TLI.isTypeLegal(StoreType))
8530       return SDValue();
8531
8532     // Bitcast the original vector into a vector of store-size units
8533     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8534             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8535     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8536     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8537     SmallVector<SDValue, 8> Chains;
8538     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8539                                         TLI.getPointerTy());
8540     SDValue BasePtr = St->getBasePtr();
8541
8542     // Perform one or more big stores into memory.
8543     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8544     for (unsigned I = 0; I < E; I++) {
8545       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8546                                    StoreType, ShuffWide,
8547                                    DAG.getIntPtrConstant(I));
8548       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8549                                 St->getPointerInfo(), St->isVolatile(),
8550                                 St->isNonTemporal(), St->getAlignment());
8551       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8552                             Increment);
8553       Chains.push_back(Ch);
8554     }
8555     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8556   }
8557
8558   if (!ISD::isNormalStore(St))
8559     return SDValue();
8560
8561   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8562   // ARM stores of arguments in the same cache line.
8563   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8564       StVal.getNode()->hasOneUse()) {
8565     SelectionDAG  &DAG = DCI.DAG;
8566     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8567     SDLoc DL(St);
8568     SDValue BasePtr = St->getBasePtr();
8569     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8570                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8571                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8572                                   St->isNonTemporal(), St->getAlignment());
8573
8574     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8575                                     DAG.getConstant(4, MVT::i32));
8576     return DAG.getStore(NewST1.getValue(0), DL,
8577                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8578                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8579                         St->isNonTemporal(),
8580                         std::min(4U, St->getAlignment() / 2));
8581   }
8582
8583   if (StVal.getValueType() != MVT::i64 ||
8584       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8585     return SDValue();
8586
8587   // Bitcast an i64 store extracted from a vector to f64.
8588   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8589   SelectionDAG &DAG = DCI.DAG;
8590   SDLoc dl(StVal);
8591   SDValue IntVec = StVal.getOperand(0);
8592   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8593                                  IntVec.getValueType().getVectorNumElements());
8594   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8595   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8596                                Vec, StVal.getOperand(1));
8597   dl = SDLoc(N);
8598   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8599   // Make the DAGCombiner fold the bitcasts.
8600   DCI.AddToWorklist(Vec.getNode());
8601   DCI.AddToWorklist(ExtElt.getNode());
8602   DCI.AddToWorklist(V.getNode());
8603   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8604                       St->getPointerInfo(), St->isVolatile(),
8605                       St->isNonTemporal(), St->getAlignment(),
8606                       St->getTBAAInfo());
8607 }
8608
8609 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8610 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8611 /// i64 vector to have f64 elements, since the value can then be loaded
8612 /// directly into a VFP register.
8613 static bool hasNormalLoadOperand(SDNode *N) {
8614   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8615   for (unsigned i = 0; i < NumElts; ++i) {
8616     SDNode *Elt = N->getOperand(i).getNode();
8617     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8618       return true;
8619   }
8620   return false;
8621 }
8622
8623 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8624 /// ISD::BUILD_VECTOR.
8625 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8626                                           TargetLowering::DAGCombinerInfo &DCI){
8627   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8628   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8629   // into a pair of GPRs, which is fine when the value is used as a scalar,
8630   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8631   SelectionDAG &DAG = DCI.DAG;
8632   if (N->getNumOperands() == 2) {
8633     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8634     if (RV.getNode())
8635       return RV;
8636   }
8637
8638   // Load i64 elements as f64 values so that type legalization does not split
8639   // them up into i32 values.
8640   EVT VT = N->getValueType(0);
8641   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8642     return SDValue();
8643   SDLoc dl(N);
8644   SmallVector<SDValue, 8> Ops;
8645   unsigned NumElts = VT.getVectorNumElements();
8646   for (unsigned i = 0; i < NumElts; ++i) {
8647     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8648     Ops.push_back(V);
8649     // Make the DAGCombiner fold the bitcast.
8650     DCI.AddToWorklist(V.getNode());
8651   }
8652   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8653   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8654   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8655 }
8656
8657 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8658 static SDValue
8659 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8660   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8661   // At that time, we may have inserted bitcasts from integer to float.
8662   // If these bitcasts have survived DAGCombine, change the lowering of this
8663   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8664   // force to use floating point types.
8665
8666   // Make sure we can change the type of the vector.
8667   // This is possible iff:
8668   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8669   //    1.1. Vector is used only once.
8670   //    1.2. Use is a bit convert to an integer type.
8671   // 2. The size of its operands are 32-bits (64-bits are not legal).
8672   EVT VT = N->getValueType(0);
8673   EVT EltVT = VT.getVectorElementType();
8674
8675   // Check 1.1. and 2.
8676   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8677     return SDValue();
8678
8679   // By construction, the input type must be float.
8680   assert(EltVT == MVT::f32 && "Unexpected type!");
8681
8682   // Check 1.2.
8683   SDNode *Use = *N->use_begin();
8684   if (Use->getOpcode() != ISD::BITCAST ||
8685       Use->getValueType(0).isFloatingPoint())
8686     return SDValue();
8687
8688   // Check profitability.
8689   // Model is, if more than half of the relevant operands are bitcast from
8690   // i32, turn the build_vector into a sequence of insert_vector_elt.
8691   // Relevant operands are everything that is not statically
8692   // (i.e., at compile time) bitcasted.
8693   unsigned NumOfBitCastedElts = 0;
8694   unsigned NumElts = VT.getVectorNumElements();
8695   unsigned NumOfRelevantElts = NumElts;
8696   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8697     SDValue Elt = N->getOperand(Idx);
8698     if (Elt->getOpcode() == ISD::BITCAST) {
8699       // Assume only bit cast to i32 will go away.
8700       if (Elt->getOperand(0).getValueType() == MVT::i32)
8701         ++NumOfBitCastedElts;
8702     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8703       // Constants are statically casted, thus do not count them as
8704       // relevant operands.
8705       --NumOfRelevantElts;
8706   }
8707
8708   // Check if more than half of the elements require a non-free bitcast.
8709   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8710     return SDValue();
8711
8712   SelectionDAG &DAG = DCI.DAG;
8713   // Create the new vector type.
8714   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8715   // Check if the type is legal.
8716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8717   if (!TLI.isTypeLegal(VecVT))
8718     return SDValue();
8719
8720   // Combine:
8721   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8722   // => BITCAST INSERT_VECTOR_ELT
8723   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8724   //                      (BITCAST EN), N.
8725   SDValue Vec = DAG.getUNDEF(VecVT);
8726   SDLoc dl(N);
8727   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8728     SDValue V = N->getOperand(Idx);
8729     if (V.getOpcode() == ISD::UNDEF)
8730       continue;
8731     if (V.getOpcode() == ISD::BITCAST &&
8732         V->getOperand(0).getValueType() == MVT::i32)
8733       // Fold obvious case.
8734       V = V.getOperand(0);
8735     else {
8736       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8737       // Make the DAGCombiner fold the bitcasts.
8738       DCI.AddToWorklist(V.getNode());
8739     }
8740     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8741     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8742   }
8743   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8744   // Make the DAGCombiner fold the bitcasts.
8745   DCI.AddToWorklist(Vec.getNode());
8746   return Vec;
8747 }
8748
8749 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8750 /// ISD::INSERT_VECTOR_ELT.
8751 static SDValue PerformInsertEltCombine(SDNode *N,
8752                                        TargetLowering::DAGCombinerInfo &DCI) {
8753   // Bitcast an i64 load inserted into a vector to f64.
8754   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8755   EVT VT = N->getValueType(0);
8756   SDNode *Elt = N->getOperand(1).getNode();
8757   if (VT.getVectorElementType() != MVT::i64 ||
8758       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8759     return SDValue();
8760
8761   SelectionDAG &DAG = DCI.DAG;
8762   SDLoc dl(N);
8763   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8764                                  VT.getVectorNumElements());
8765   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8766   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8767   // Make the DAGCombiner fold the bitcasts.
8768   DCI.AddToWorklist(Vec.getNode());
8769   DCI.AddToWorklist(V.getNode());
8770   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8771                                Vec, V, N->getOperand(2));
8772   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8773 }
8774
8775 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8776 /// ISD::VECTOR_SHUFFLE.
8777 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8778   // The LLVM shufflevector instruction does not require the shuffle mask
8779   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8780   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8781   // operands do not match the mask length, they are extended by concatenating
8782   // them with undef vectors.  That is probably the right thing for other
8783   // targets, but for NEON it is better to concatenate two double-register
8784   // size vector operands into a single quad-register size vector.  Do that
8785   // transformation here:
8786   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8787   //   shuffle(concat(v1, v2), undef)
8788   SDValue Op0 = N->getOperand(0);
8789   SDValue Op1 = N->getOperand(1);
8790   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8791       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8792       Op0.getNumOperands() != 2 ||
8793       Op1.getNumOperands() != 2)
8794     return SDValue();
8795   SDValue Concat0Op1 = Op0.getOperand(1);
8796   SDValue Concat1Op1 = Op1.getOperand(1);
8797   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8798       Concat1Op1.getOpcode() != ISD::UNDEF)
8799     return SDValue();
8800   // Skip the transformation if any of the types are illegal.
8801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8802   EVT VT = N->getValueType(0);
8803   if (!TLI.isTypeLegal(VT) ||
8804       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8805       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8806     return SDValue();
8807
8808   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8809                                   Op0.getOperand(0), Op1.getOperand(0));
8810   // Translate the shuffle mask.
8811   SmallVector<int, 16> NewMask;
8812   unsigned NumElts = VT.getVectorNumElements();
8813   unsigned HalfElts = NumElts/2;
8814   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8815   for (unsigned n = 0; n < NumElts; ++n) {
8816     int MaskElt = SVN->getMaskElt(n);
8817     int NewElt = -1;
8818     if (MaskElt < (int)HalfElts)
8819       NewElt = MaskElt;
8820     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8821       NewElt = HalfElts + MaskElt - NumElts;
8822     NewMask.push_back(NewElt);
8823   }
8824   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8825                               DAG.getUNDEF(VT), NewMask.data());
8826 }
8827
8828 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8829 /// NEON load/store intrinsics to merge base address updates.
8830 static SDValue CombineBaseUpdate(SDNode *N,
8831                                  TargetLowering::DAGCombinerInfo &DCI) {
8832   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8833     return SDValue();
8834
8835   SelectionDAG &DAG = DCI.DAG;
8836   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8837                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8838   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8839   SDValue Addr = N->getOperand(AddrOpIdx);
8840
8841   // Search for a use of the address operand that is an increment.
8842   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8843          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8844     SDNode *User = *UI;
8845     if (User->getOpcode() != ISD::ADD ||
8846         UI.getUse().getResNo() != Addr.getResNo())
8847       continue;
8848
8849     // Check that the add is independent of the load/store.  Otherwise, folding
8850     // it would create a cycle.
8851     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8852       continue;
8853
8854     // Find the new opcode for the updating load/store.
8855     bool isLoad = true;
8856     bool isLaneOp = false;
8857     unsigned NewOpc = 0;
8858     unsigned NumVecs = 0;
8859     if (isIntrinsic) {
8860       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8861       switch (IntNo) {
8862       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8863       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8864         NumVecs = 1; break;
8865       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8866         NumVecs = 2; break;
8867       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8868         NumVecs = 3; break;
8869       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8870         NumVecs = 4; break;
8871       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8872         NumVecs = 2; isLaneOp = true; break;
8873       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8874         NumVecs = 3; isLaneOp = true; break;
8875       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8876         NumVecs = 4; isLaneOp = true; break;
8877       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8878         NumVecs = 1; isLoad = false; break;
8879       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8880         NumVecs = 2; isLoad = false; break;
8881       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8882         NumVecs = 3; isLoad = false; break;
8883       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8884         NumVecs = 4; isLoad = false; break;
8885       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8886         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8887       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8888         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8889       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8890         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8891       }
8892     } else {
8893       isLaneOp = true;
8894       switch (N->getOpcode()) {
8895       default: llvm_unreachable("unexpected opcode for Neon base update");
8896       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8897       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8898       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8899       }
8900     }
8901
8902     // Find the size of memory referenced by the load/store.
8903     EVT VecTy;
8904     if (isLoad)
8905       VecTy = N->getValueType(0);
8906     else
8907       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8908     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8909     if (isLaneOp)
8910       NumBytes /= VecTy.getVectorNumElements();
8911
8912     // If the increment is a constant, it must match the memory ref size.
8913     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8914     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8915       uint64_t IncVal = CInc->getZExtValue();
8916       if (IncVal != NumBytes)
8917         continue;
8918     } else if (NumBytes >= 3 * 16) {
8919       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8920       // separate instructions that make it harder to use a non-constant update.
8921       continue;
8922     }
8923
8924     // Create the new updating load/store node.
8925     EVT Tys[6];
8926     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8927     unsigned n;
8928     for (n = 0; n < NumResultVecs; ++n)
8929       Tys[n] = VecTy;
8930     Tys[n++] = MVT::i32;
8931     Tys[n] = MVT::Other;
8932     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8933     SmallVector<SDValue, 8> Ops;
8934     Ops.push_back(N->getOperand(0)); // incoming chain
8935     Ops.push_back(N->getOperand(AddrOpIdx));
8936     Ops.push_back(Inc);
8937     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8938       Ops.push_back(N->getOperand(i));
8939     }
8940     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8941     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8942                                            Ops, MemInt->getMemoryVT(),
8943                                            MemInt->getMemOperand());
8944
8945     // Update the uses.
8946     std::vector<SDValue> NewResults;
8947     for (unsigned i = 0; i < NumResultVecs; ++i) {
8948       NewResults.push_back(SDValue(UpdN.getNode(), i));
8949     }
8950     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8951     DCI.CombineTo(N, NewResults);
8952     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8953
8954     break;
8955   }
8956   return SDValue();
8957 }
8958
8959 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8960 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8961 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8962 /// return true.
8963 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8964   SelectionDAG &DAG = DCI.DAG;
8965   EVT VT = N->getValueType(0);
8966   // vldN-dup instructions only support 64-bit vectors for N > 1.
8967   if (!VT.is64BitVector())
8968     return false;
8969
8970   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8971   SDNode *VLD = N->getOperand(0).getNode();
8972   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8973     return false;
8974   unsigned NumVecs = 0;
8975   unsigned NewOpc = 0;
8976   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8977   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8978     NumVecs = 2;
8979     NewOpc = ARMISD::VLD2DUP;
8980   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8981     NumVecs = 3;
8982     NewOpc = ARMISD::VLD3DUP;
8983   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8984     NumVecs = 4;
8985     NewOpc = ARMISD::VLD4DUP;
8986   } else {
8987     return false;
8988   }
8989
8990   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8991   // numbers match the load.
8992   unsigned VLDLaneNo =
8993     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8994   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8995        UI != UE; ++UI) {
8996     // Ignore uses of the chain result.
8997     if (UI.getUse().getResNo() == NumVecs)
8998       continue;
8999     SDNode *User = *UI;
9000     if (User->getOpcode() != ARMISD::VDUPLANE ||
9001         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9002       return false;
9003   }
9004
9005   // Create the vldN-dup node.
9006   EVT Tys[5];
9007   unsigned n;
9008   for (n = 0; n < NumVecs; ++n)
9009     Tys[n] = VT;
9010   Tys[n] = MVT::Other;
9011   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9012   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9013   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9014   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9015                                            Ops, VLDMemInt->getMemoryVT(),
9016                                            VLDMemInt->getMemOperand());
9017
9018   // Update the uses.
9019   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9020        UI != UE; ++UI) {
9021     unsigned ResNo = UI.getUse().getResNo();
9022     // Ignore uses of the chain result.
9023     if (ResNo == NumVecs)
9024       continue;
9025     SDNode *User = *UI;
9026     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9027   }
9028
9029   // Now the vldN-lane intrinsic is dead except for its chain result.
9030   // Update uses of the chain.
9031   std::vector<SDValue> VLDDupResults;
9032   for (unsigned n = 0; n < NumVecs; ++n)
9033     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9034   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9035   DCI.CombineTo(VLD, VLDDupResults);
9036
9037   return true;
9038 }
9039
9040 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9041 /// ARMISD::VDUPLANE.
9042 static SDValue PerformVDUPLANECombine(SDNode *N,
9043                                       TargetLowering::DAGCombinerInfo &DCI) {
9044   SDValue Op = N->getOperand(0);
9045
9046   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9047   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9048   if (CombineVLDDUP(N, DCI))
9049     return SDValue(N, 0);
9050
9051   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9052   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9053   while (Op.getOpcode() == ISD::BITCAST)
9054     Op = Op.getOperand(0);
9055   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9056     return SDValue();
9057
9058   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9059   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9060   // The canonical VMOV for a zero vector uses a 32-bit element size.
9061   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9062   unsigned EltBits;
9063   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9064     EltSize = 8;
9065   EVT VT = N->getValueType(0);
9066   if (EltSize > VT.getVectorElementType().getSizeInBits())
9067     return SDValue();
9068
9069   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9070 }
9071
9072 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9073 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9074 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9075 {
9076   integerPart cN;
9077   integerPart c0 = 0;
9078   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9079        I != E; I++) {
9080     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9081     if (!C)
9082       return false;
9083
9084     bool isExact;
9085     APFloat APF = C->getValueAPF();
9086     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9087         != APFloat::opOK || !isExact)
9088       return false;
9089
9090     c0 = (I == 0) ? cN : c0;
9091     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9092       return false;
9093   }
9094   C = c0;
9095   return true;
9096 }
9097
9098 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9099 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9100 /// when the VMUL has a constant operand that is a power of 2.
9101 ///
9102 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9103 ///  vmul.f32        d16, d17, d16
9104 ///  vcvt.s32.f32    d16, d16
9105 /// becomes:
9106 ///  vcvt.s32.f32    d16, d16, #3
9107 static SDValue PerformVCVTCombine(SDNode *N,
9108                                   TargetLowering::DAGCombinerInfo &DCI,
9109                                   const ARMSubtarget *Subtarget) {
9110   SelectionDAG &DAG = DCI.DAG;
9111   SDValue Op = N->getOperand(0);
9112
9113   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9114       Op.getOpcode() != ISD::FMUL)
9115     return SDValue();
9116
9117   uint64_t C;
9118   SDValue N0 = Op->getOperand(0);
9119   SDValue ConstVec = Op->getOperand(1);
9120   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9121
9122   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9123       !isConstVecPow2(ConstVec, isSigned, C))
9124     return SDValue();
9125
9126   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9127   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9128   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9129     // These instructions only exist converting from f32 to i32. We can handle
9130     // smaller integers by generating an extra truncate, but larger ones would
9131     // be lossy.
9132     return SDValue();
9133   }
9134
9135   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9136     Intrinsic::arm_neon_vcvtfp2fxu;
9137   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9138   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9139                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9140                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9141                                  DAG.getConstant(Log2_64(C), MVT::i32));
9142
9143   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9144     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9145
9146   return FixConv;
9147 }
9148
9149 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9150 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9151 /// when the VDIV has a constant operand that is a power of 2.
9152 ///
9153 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9154 ///  vcvt.f32.s32    d16, d16
9155 ///  vdiv.f32        d16, d17, d16
9156 /// becomes:
9157 ///  vcvt.f32.s32    d16, d16, #3
9158 static SDValue PerformVDIVCombine(SDNode *N,
9159                                   TargetLowering::DAGCombinerInfo &DCI,
9160                                   const ARMSubtarget *Subtarget) {
9161   SelectionDAG &DAG = DCI.DAG;
9162   SDValue Op = N->getOperand(0);
9163   unsigned OpOpcode = Op.getNode()->getOpcode();
9164
9165   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9166       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9167     return SDValue();
9168
9169   uint64_t C;
9170   SDValue ConstVec = N->getOperand(1);
9171   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9172
9173   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9174       !isConstVecPow2(ConstVec, isSigned, C))
9175     return SDValue();
9176
9177   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9178   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9179   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9180     // These instructions only exist converting from i32 to f32. We can handle
9181     // smaller integers by generating an extra extend, but larger ones would
9182     // be lossy.
9183     return SDValue();
9184   }
9185
9186   SDValue ConvInput = Op.getOperand(0);
9187   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9188   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9189     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9190                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9191                             ConvInput);
9192
9193   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9194     Intrinsic::arm_neon_vcvtfxu2fp;
9195   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9196                      Op.getValueType(),
9197                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9198                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9199 }
9200
9201 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9202 /// operand of a vector shift operation, where all the elements of the
9203 /// build_vector must have the same constant integer value.
9204 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9205   // Ignore bit_converts.
9206   while (Op.getOpcode() == ISD::BITCAST)
9207     Op = Op.getOperand(0);
9208   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9209   APInt SplatBits, SplatUndef;
9210   unsigned SplatBitSize;
9211   bool HasAnyUndefs;
9212   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9213                                       HasAnyUndefs, ElementBits) ||
9214       SplatBitSize > ElementBits)
9215     return false;
9216   Cnt = SplatBits.getSExtValue();
9217   return true;
9218 }
9219
9220 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9221 /// operand of a vector shift left operation.  That value must be in the range:
9222 ///   0 <= Value < ElementBits for a left shift; or
9223 ///   0 <= Value <= ElementBits for a long left shift.
9224 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9225   assert(VT.isVector() && "vector shift count is not a vector type");
9226   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9227   if (! getVShiftImm(Op, ElementBits, Cnt))
9228     return false;
9229   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9230 }
9231
9232 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9233 /// operand of a vector shift right operation.  For a shift opcode, the value
9234 /// is positive, but for an intrinsic the value count must be negative. The
9235 /// absolute value must be in the range:
9236 ///   1 <= |Value| <= ElementBits for a right shift; or
9237 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9238 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9239                          int64_t &Cnt) {
9240   assert(VT.isVector() && "vector shift count is not a vector type");
9241   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9242   if (! getVShiftImm(Op, ElementBits, Cnt))
9243     return false;
9244   if (isIntrinsic)
9245     Cnt = -Cnt;
9246   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9247 }
9248
9249 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9250 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9251   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9252   switch (IntNo) {
9253   default:
9254     // Don't do anything for most intrinsics.
9255     break;
9256
9257   // Vector shifts: check for immediate versions and lower them.
9258   // Note: This is done during DAG combining instead of DAG legalizing because
9259   // the build_vectors for 64-bit vector element shift counts are generally
9260   // not legal, and it is hard to see their values after they get legalized to
9261   // loads from a constant pool.
9262   case Intrinsic::arm_neon_vshifts:
9263   case Intrinsic::arm_neon_vshiftu:
9264   case Intrinsic::arm_neon_vrshifts:
9265   case Intrinsic::arm_neon_vrshiftu:
9266   case Intrinsic::arm_neon_vrshiftn:
9267   case Intrinsic::arm_neon_vqshifts:
9268   case Intrinsic::arm_neon_vqshiftu:
9269   case Intrinsic::arm_neon_vqshiftsu:
9270   case Intrinsic::arm_neon_vqshiftns:
9271   case Intrinsic::arm_neon_vqshiftnu:
9272   case Intrinsic::arm_neon_vqshiftnsu:
9273   case Intrinsic::arm_neon_vqrshiftns:
9274   case Intrinsic::arm_neon_vqrshiftnu:
9275   case Intrinsic::arm_neon_vqrshiftnsu: {
9276     EVT VT = N->getOperand(1).getValueType();
9277     int64_t Cnt;
9278     unsigned VShiftOpc = 0;
9279
9280     switch (IntNo) {
9281     case Intrinsic::arm_neon_vshifts:
9282     case Intrinsic::arm_neon_vshiftu:
9283       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9284         VShiftOpc = ARMISD::VSHL;
9285         break;
9286       }
9287       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9288         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9289                      ARMISD::VSHRs : ARMISD::VSHRu);
9290         break;
9291       }
9292       return SDValue();
9293
9294     case Intrinsic::arm_neon_vrshifts:
9295     case Intrinsic::arm_neon_vrshiftu:
9296       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9297         break;
9298       return SDValue();
9299
9300     case Intrinsic::arm_neon_vqshifts:
9301     case Intrinsic::arm_neon_vqshiftu:
9302       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9303         break;
9304       return SDValue();
9305
9306     case Intrinsic::arm_neon_vqshiftsu:
9307       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9308         break;
9309       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9310
9311     case Intrinsic::arm_neon_vrshiftn:
9312     case Intrinsic::arm_neon_vqshiftns:
9313     case Intrinsic::arm_neon_vqshiftnu:
9314     case Intrinsic::arm_neon_vqshiftnsu:
9315     case Intrinsic::arm_neon_vqrshiftns:
9316     case Intrinsic::arm_neon_vqrshiftnu:
9317     case Intrinsic::arm_neon_vqrshiftnsu:
9318       // Narrowing shifts require an immediate right shift.
9319       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9320         break;
9321       llvm_unreachable("invalid shift count for narrowing vector shift "
9322                        "intrinsic");
9323
9324     default:
9325       llvm_unreachable("unhandled vector shift");
9326     }
9327
9328     switch (IntNo) {
9329     case Intrinsic::arm_neon_vshifts:
9330     case Intrinsic::arm_neon_vshiftu:
9331       // Opcode already set above.
9332       break;
9333     case Intrinsic::arm_neon_vrshifts:
9334       VShiftOpc = ARMISD::VRSHRs; break;
9335     case Intrinsic::arm_neon_vrshiftu:
9336       VShiftOpc = ARMISD::VRSHRu; break;
9337     case Intrinsic::arm_neon_vrshiftn:
9338       VShiftOpc = ARMISD::VRSHRN; break;
9339     case Intrinsic::arm_neon_vqshifts:
9340       VShiftOpc = ARMISD::VQSHLs; break;
9341     case Intrinsic::arm_neon_vqshiftu:
9342       VShiftOpc = ARMISD::VQSHLu; break;
9343     case Intrinsic::arm_neon_vqshiftsu:
9344       VShiftOpc = ARMISD::VQSHLsu; break;
9345     case Intrinsic::arm_neon_vqshiftns:
9346       VShiftOpc = ARMISD::VQSHRNs; break;
9347     case Intrinsic::arm_neon_vqshiftnu:
9348       VShiftOpc = ARMISD::VQSHRNu; break;
9349     case Intrinsic::arm_neon_vqshiftnsu:
9350       VShiftOpc = ARMISD::VQSHRNsu; break;
9351     case Intrinsic::arm_neon_vqrshiftns:
9352       VShiftOpc = ARMISD::VQRSHRNs; break;
9353     case Intrinsic::arm_neon_vqrshiftnu:
9354       VShiftOpc = ARMISD::VQRSHRNu; break;
9355     case Intrinsic::arm_neon_vqrshiftnsu:
9356       VShiftOpc = ARMISD::VQRSHRNsu; break;
9357     }
9358
9359     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9360                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9361   }
9362
9363   case Intrinsic::arm_neon_vshiftins: {
9364     EVT VT = N->getOperand(1).getValueType();
9365     int64_t Cnt;
9366     unsigned VShiftOpc = 0;
9367
9368     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9369       VShiftOpc = ARMISD::VSLI;
9370     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9371       VShiftOpc = ARMISD::VSRI;
9372     else {
9373       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9374     }
9375
9376     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9377                        N->getOperand(1), N->getOperand(2),
9378                        DAG.getConstant(Cnt, MVT::i32));
9379   }
9380
9381   case Intrinsic::arm_neon_vqrshifts:
9382   case Intrinsic::arm_neon_vqrshiftu:
9383     // No immediate versions of these to check for.
9384     break;
9385   }
9386
9387   return SDValue();
9388 }
9389
9390 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9391 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9392 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9393 /// vector element shift counts are generally not legal, and it is hard to see
9394 /// their values after they get legalized to loads from a constant pool.
9395 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9396                                    const ARMSubtarget *ST) {
9397   EVT VT = N->getValueType(0);
9398   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9399     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9400     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9401     SDValue N1 = N->getOperand(1);
9402     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9403       SDValue N0 = N->getOperand(0);
9404       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9405           DAG.MaskedValueIsZero(N0.getOperand(0),
9406                                 APInt::getHighBitsSet(32, 16)))
9407         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9408     }
9409   }
9410
9411   // Nothing to be done for scalar shifts.
9412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9413   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9414     return SDValue();
9415
9416   assert(ST->hasNEON() && "unexpected vector shift");
9417   int64_t Cnt;
9418
9419   switch (N->getOpcode()) {
9420   default: llvm_unreachable("unexpected shift opcode");
9421
9422   case ISD::SHL:
9423     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9424       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9425                          DAG.getConstant(Cnt, MVT::i32));
9426     break;
9427
9428   case ISD::SRA:
9429   case ISD::SRL:
9430     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9431       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9432                             ARMISD::VSHRs : ARMISD::VSHRu);
9433       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9434                          DAG.getConstant(Cnt, MVT::i32));
9435     }
9436   }
9437   return SDValue();
9438 }
9439
9440 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9441 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9442 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9443                                     const ARMSubtarget *ST) {
9444   SDValue N0 = N->getOperand(0);
9445
9446   // Check for sign- and zero-extensions of vector extract operations of 8-
9447   // and 16-bit vector elements.  NEON supports these directly.  They are
9448   // handled during DAG combining because type legalization will promote them
9449   // to 32-bit types and it is messy to recognize the operations after that.
9450   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9451     SDValue Vec = N0.getOperand(0);
9452     SDValue Lane = N0.getOperand(1);
9453     EVT VT = N->getValueType(0);
9454     EVT EltVT = N0.getValueType();
9455     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9456
9457     if (VT == MVT::i32 &&
9458         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9459         TLI.isTypeLegal(Vec.getValueType()) &&
9460         isa<ConstantSDNode>(Lane)) {
9461
9462       unsigned Opc = 0;
9463       switch (N->getOpcode()) {
9464       default: llvm_unreachable("unexpected opcode");
9465       case ISD::SIGN_EXTEND:
9466         Opc = ARMISD::VGETLANEs;
9467         break;
9468       case ISD::ZERO_EXTEND:
9469       case ISD::ANY_EXTEND:
9470         Opc = ARMISD::VGETLANEu;
9471         break;
9472       }
9473       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9474     }
9475   }
9476
9477   return SDValue();
9478 }
9479
9480 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9481 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9482 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9483                                        const ARMSubtarget *ST) {
9484   // If the target supports NEON, try to use vmax/vmin instructions for f32
9485   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9486   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9487   // a NaN; only do the transformation when it matches that behavior.
9488
9489   // For now only do this when using NEON for FP operations; if using VFP, it
9490   // is not obvious that the benefit outweighs the cost of switching to the
9491   // NEON pipeline.
9492   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9493       N->getValueType(0) != MVT::f32)
9494     return SDValue();
9495
9496   SDValue CondLHS = N->getOperand(0);
9497   SDValue CondRHS = N->getOperand(1);
9498   SDValue LHS = N->getOperand(2);
9499   SDValue RHS = N->getOperand(3);
9500   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9501
9502   unsigned Opcode = 0;
9503   bool IsReversed;
9504   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9505     IsReversed = false; // x CC y ? x : y
9506   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9507     IsReversed = true ; // x CC y ? y : x
9508   } else {
9509     return SDValue();
9510   }
9511
9512   bool IsUnordered;
9513   switch (CC) {
9514   default: break;
9515   case ISD::SETOLT:
9516   case ISD::SETOLE:
9517   case ISD::SETLT:
9518   case ISD::SETLE:
9519   case ISD::SETULT:
9520   case ISD::SETULE:
9521     // If LHS is NaN, an ordered comparison will be false and the result will
9522     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9523     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9524     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9525     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9526       break;
9527     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9528     // will return -0, so vmin can only be used for unsafe math or if one of
9529     // the operands is known to be nonzero.
9530     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9531         !DAG.getTarget().Options.UnsafeFPMath &&
9532         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9533       break;
9534     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9535     break;
9536
9537   case ISD::SETOGT:
9538   case ISD::SETOGE:
9539   case ISD::SETGT:
9540   case ISD::SETGE:
9541   case ISD::SETUGT:
9542   case ISD::SETUGE:
9543     // If LHS is NaN, an ordered comparison will be false and the result will
9544     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9545     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9546     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9547     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9548       break;
9549     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9550     // will return +0, so vmax can only be used for unsafe math or if one of
9551     // the operands is known to be nonzero.
9552     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9553         !DAG.getTarget().Options.UnsafeFPMath &&
9554         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9555       break;
9556     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9557     break;
9558   }
9559
9560   if (!Opcode)
9561     return SDValue();
9562   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9563 }
9564
9565 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9566 SDValue
9567 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9568   SDValue Cmp = N->getOperand(4);
9569   if (Cmp.getOpcode() != ARMISD::CMPZ)
9570     // Only looking at EQ and NE cases.
9571     return SDValue();
9572
9573   EVT VT = N->getValueType(0);
9574   SDLoc dl(N);
9575   SDValue LHS = Cmp.getOperand(0);
9576   SDValue RHS = Cmp.getOperand(1);
9577   SDValue FalseVal = N->getOperand(0);
9578   SDValue TrueVal = N->getOperand(1);
9579   SDValue ARMcc = N->getOperand(2);
9580   ARMCC::CondCodes CC =
9581     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9582
9583   // Simplify
9584   //   mov     r1, r0
9585   //   cmp     r1, x
9586   //   mov     r0, y
9587   //   moveq   r0, x
9588   // to
9589   //   cmp     r0, x
9590   //   movne   r0, y
9591   //
9592   //   mov     r1, r0
9593   //   cmp     r1, x
9594   //   mov     r0, x
9595   //   movne   r0, y
9596   // to
9597   //   cmp     r0, x
9598   //   movne   r0, y
9599   /// FIXME: Turn this into a target neutral optimization?
9600   SDValue Res;
9601   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9602     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9603                       N->getOperand(3), Cmp);
9604   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9605     SDValue ARMcc;
9606     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9607     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9608                       N->getOperand(3), NewCmp);
9609   }
9610
9611   if (Res.getNode()) {
9612     APInt KnownZero, KnownOne;
9613     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9614     // Capture demanded bits information that would be otherwise lost.
9615     if (KnownZero == 0xfffffffe)
9616       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9617                         DAG.getValueType(MVT::i1));
9618     else if (KnownZero == 0xffffff00)
9619       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9620                         DAG.getValueType(MVT::i8));
9621     else if (KnownZero == 0xffff0000)
9622       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9623                         DAG.getValueType(MVT::i16));
9624   }
9625
9626   return Res;
9627 }
9628
9629 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9630                                              DAGCombinerInfo &DCI) const {
9631   switch (N->getOpcode()) {
9632   default: break;
9633   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9634   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9635   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9636   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9637   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9638   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9639   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9640   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9641   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9642   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9643   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9644   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9645   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9646   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9647   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9648   case ISD::FP_TO_SINT:
9649   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9650   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9651   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9652   case ISD::SHL:
9653   case ISD::SRA:
9654   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9655   case ISD::SIGN_EXTEND:
9656   case ISD::ZERO_EXTEND:
9657   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9658   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9659   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9660   case ARMISD::VLD2DUP:
9661   case ARMISD::VLD3DUP:
9662   case ARMISD::VLD4DUP:
9663     return CombineBaseUpdate(N, DCI);
9664   case ARMISD::BUILD_VECTOR:
9665     return PerformARMBUILD_VECTORCombine(N, DCI);
9666   case ISD::INTRINSIC_VOID:
9667   case ISD::INTRINSIC_W_CHAIN:
9668     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9669     case Intrinsic::arm_neon_vld1:
9670     case Intrinsic::arm_neon_vld2:
9671     case Intrinsic::arm_neon_vld3:
9672     case Intrinsic::arm_neon_vld4:
9673     case Intrinsic::arm_neon_vld2lane:
9674     case Intrinsic::arm_neon_vld3lane:
9675     case Intrinsic::arm_neon_vld4lane:
9676     case Intrinsic::arm_neon_vst1:
9677     case Intrinsic::arm_neon_vst2:
9678     case Intrinsic::arm_neon_vst3:
9679     case Intrinsic::arm_neon_vst4:
9680     case Intrinsic::arm_neon_vst2lane:
9681     case Intrinsic::arm_neon_vst3lane:
9682     case Intrinsic::arm_neon_vst4lane:
9683       return CombineBaseUpdate(N, DCI);
9684     default: break;
9685     }
9686     break;
9687   }
9688   return SDValue();
9689 }
9690
9691 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9692                                                           EVT VT) const {
9693   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9694 }
9695
9696 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9697                                                       bool *Fast) const {
9698   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9699   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9700
9701   switch (VT.getSimpleVT().SimpleTy) {
9702   default:
9703     return false;
9704   case MVT::i8:
9705   case MVT::i16:
9706   case MVT::i32: {
9707     // Unaligned access can use (for example) LRDB, LRDH, LDR
9708     if (AllowsUnaligned) {
9709       if (Fast)
9710         *Fast = Subtarget->hasV7Ops();
9711       return true;
9712     }
9713     return false;
9714   }
9715   case MVT::f64:
9716   case MVT::v2f64: {
9717     // For any little-endian targets with neon, we can support unaligned ld/st
9718     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9719     // A big-endian target may also explicitly support unaligned accesses
9720     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9721       if (Fast)
9722         *Fast = true;
9723       return true;
9724     }
9725     return false;
9726   }
9727   }
9728 }
9729
9730 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9731                        unsigned AlignCheck) {
9732   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9733           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9734 }
9735
9736 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9737                                            unsigned DstAlign, unsigned SrcAlign,
9738                                            bool IsMemset, bool ZeroMemset,
9739                                            bool MemcpyStrSrc,
9740                                            MachineFunction &MF) const {
9741   const Function *F = MF.getFunction();
9742
9743   // See if we can use NEON instructions for this...
9744   if ((!IsMemset || ZeroMemset) &&
9745       Subtarget->hasNEON() &&
9746       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9747                                        Attribute::NoImplicitFloat)) {
9748     bool Fast;
9749     if (Size >= 16 &&
9750         (memOpAlign(SrcAlign, DstAlign, 16) ||
9751          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9752       return MVT::v2f64;
9753     } else if (Size >= 8 &&
9754                (memOpAlign(SrcAlign, DstAlign, 8) ||
9755                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9756       return MVT::f64;
9757     }
9758   }
9759
9760   // Lowering to i32/i16 if the size permits.
9761   if (Size >= 4)
9762     return MVT::i32;
9763   else if (Size >= 2)
9764     return MVT::i16;
9765
9766   // Let the target-independent logic figure it out.
9767   return MVT::Other;
9768 }
9769
9770 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9771   if (Val.getOpcode() != ISD::LOAD)
9772     return false;
9773
9774   EVT VT1 = Val.getValueType();
9775   if (!VT1.isSimple() || !VT1.isInteger() ||
9776       !VT2.isSimple() || !VT2.isInteger())
9777     return false;
9778
9779   switch (VT1.getSimpleVT().SimpleTy) {
9780   default: break;
9781   case MVT::i1:
9782   case MVT::i8:
9783   case MVT::i16:
9784     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9785     return true;
9786   }
9787
9788   return false;
9789 }
9790
9791 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9792   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9793     return false;
9794
9795   if (!isTypeLegal(EVT::getEVT(Ty1)))
9796     return false;
9797
9798   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9799
9800   // Assuming the caller doesn't have a zeroext or signext return parameter,
9801   // truncation all the way down to i1 is valid.
9802   return true;
9803 }
9804
9805
9806 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9807   if (V < 0)
9808     return false;
9809
9810   unsigned Scale = 1;
9811   switch (VT.getSimpleVT().SimpleTy) {
9812   default: return false;
9813   case MVT::i1:
9814   case MVT::i8:
9815     // Scale == 1;
9816     break;
9817   case MVT::i16:
9818     // Scale == 2;
9819     Scale = 2;
9820     break;
9821   case MVT::i32:
9822     // Scale == 4;
9823     Scale = 4;
9824     break;
9825   }
9826
9827   if ((V & (Scale - 1)) != 0)
9828     return false;
9829   V /= Scale;
9830   return V == (V & ((1LL << 5) - 1));
9831 }
9832
9833 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9834                                       const ARMSubtarget *Subtarget) {
9835   bool isNeg = false;
9836   if (V < 0) {
9837     isNeg = true;
9838     V = - V;
9839   }
9840
9841   switch (VT.getSimpleVT().SimpleTy) {
9842   default: return false;
9843   case MVT::i1:
9844   case MVT::i8:
9845   case MVT::i16:
9846   case MVT::i32:
9847     // + imm12 or - imm8
9848     if (isNeg)
9849       return V == (V & ((1LL << 8) - 1));
9850     return V == (V & ((1LL << 12) - 1));
9851   case MVT::f32:
9852   case MVT::f64:
9853     // Same as ARM mode. FIXME: NEON?
9854     if (!Subtarget->hasVFP2())
9855       return false;
9856     if ((V & 3) != 0)
9857       return false;
9858     V >>= 2;
9859     return V == (V & ((1LL << 8) - 1));
9860   }
9861 }
9862
9863 /// isLegalAddressImmediate - Return true if the integer value can be used
9864 /// as the offset of the target addressing mode for load / store of the
9865 /// given type.
9866 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9867                                     const ARMSubtarget *Subtarget) {
9868   if (V == 0)
9869     return true;
9870
9871   if (!VT.isSimple())
9872     return false;
9873
9874   if (Subtarget->isThumb1Only())
9875     return isLegalT1AddressImmediate(V, VT);
9876   else if (Subtarget->isThumb2())
9877     return isLegalT2AddressImmediate(V, VT, Subtarget);
9878
9879   // ARM mode.
9880   if (V < 0)
9881     V = - V;
9882   switch (VT.getSimpleVT().SimpleTy) {
9883   default: return false;
9884   case MVT::i1:
9885   case MVT::i8:
9886   case MVT::i32:
9887     // +- imm12
9888     return V == (V & ((1LL << 12) - 1));
9889   case MVT::i16:
9890     // +- imm8
9891     return V == (V & ((1LL << 8) - 1));
9892   case MVT::f32:
9893   case MVT::f64:
9894     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9895       return false;
9896     if ((V & 3) != 0)
9897       return false;
9898     V >>= 2;
9899     return V == (V & ((1LL << 8) - 1));
9900   }
9901 }
9902
9903 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9904                                                       EVT VT) const {
9905   int Scale = AM.Scale;
9906   if (Scale < 0)
9907     return false;
9908
9909   switch (VT.getSimpleVT().SimpleTy) {
9910   default: return false;
9911   case MVT::i1:
9912   case MVT::i8:
9913   case MVT::i16:
9914   case MVT::i32:
9915     if (Scale == 1)
9916       return true;
9917     // r + r << imm
9918     Scale = Scale & ~1;
9919     return Scale == 2 || Scale == 4 || Scale == 8;
9920   case MVT::i64:
9921     // r + r
9922     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9923       return true;
9924     return false;
9925   case MVT::isVoid:
9926     // Note, we allow "void" uses (basically, uses that aren't loads or
9927     // stores), because arm allows folding a scale into many arithmetic
9928     // operations.  This should be made more precise and revisited later.
9929
9930     // Allow r << imm, but the imm has to be a multiple of two.
9931     if (Scale & 1) return false;
9932     return isPowerOf2_32(Scale);
9933   }
9934 }
9935
9936 /// isLegalAddressingMode - Return true if the addressing mode represented
9937 /// by AM is legal for this target, for a load/store of the specified type.
9938 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9939                                               Type *Ty) const {
9940   EVT VT = getValueType(Ty, true);
9941   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9942     return false;
9943
9944   // Can never fold addr of global into load/store.
9945   if (AM.BaseGV)
9946     return false;
9947
9948   switch (AM.Scale) {
9949   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9950     break;
9951   case 1:
9952     if (Subtarget->isThumb1Only())
9953       return false;
9954     // FALL THROUGH.
9955   default:
9956     // ARM doesn't support any R+R*scale+imm addr modes.
9957     if (AM.BaseOffs)
9958       return false;
9959
9960     if (!VT.isSimple())
9961       return false;
9962
9963     if (Subtarget->isThumb2())
9964       return isLegalT2ScaledAddressingMode(AM, VT);
9965
9966     int Scale = AM.Scale;
9967     switch (VT.getSimpleVT().SimpleTy) {
9968     default: return false;
9969     case MVT::i1:
9970     case MVT::i8:
9971     case MVT::i32:
9972       if (Scale < 0) Scale = -Scale;
9973       if (Scale == 1)
9974         return true;
9975       // r + r << imm
9976       return isPowerOf2_32(Scale & ~1);
9977     case MVT::i16:
9978     case MVT::i64:
9979       // r + r
9980       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9981         return true;
9982       return false;
9983
9984     case MVT::isVoid:
9985       // Note, we allow "void" uses (basically, uses that aren't loads or
9986       // stores), because arm allows folding a scale into many arithmetic
9987       // operations.  This should be made more precise and revisited later.
9988
9989       // Allow r << imm, but the imm has to be a multiple of two.
9990       if (Scale & 1) return false;
9991       return isPowerOf2_32(Scale);
9992     }
9993   }
9994   return true;
9995 }
9996
9997 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9998 /// icmp immediate, that is the target has icmp instructions which can compare
9999 /// a register against the immediate without having to materialize the
10000 /// immediate into a register.
10001 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10002   // Thumb2 and ARM modes can use cmn for negative immediates.
10003   if (!Subtarget->isThumb())
10004     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10005   if (Subtarget->isThumb2())
10006     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10007   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10008   return Imm >= 0 && Imm <= 255;
10009 }
10010
10011 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10012 /// *or sub* immediate, that is the target has add or sub instructions which can
10013 /// add a register with the immediate without having to materialize the
10014 /// immediate into a register.
10015 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10016   // Same encoding for add/sub, just flip the sign.
10017   int64_t AbsImm = llvm::abs64(Imm);
10018   if (!Subtarget->isThumb())
10019     return ARM_AM::getSOImmVal(AbsImm) != -1;
10020   if (Subtarget->isThumb2())
10021     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10022   // Thumb1 only has 8-bit unsigned immediate.
10023   return AbsImm >= 0 && AbsImm <= 255;
10024 }
10025
10026 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10027                                       bool isSEXTLoad, SDValue &Base,
10028                                       SDValue &Offset, bool &isInc,
10029                                       SelectionDAG &DAG) {
10030   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10031     return false;
10032
10033   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10034     // AddressingMode 3
10035     Base = Ptr->getOperand(0);
10036     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10037       int RHSC = (int)RHS->getZExtValue();
10038       if (RHSC < 0 && RHSC > -256) {
10039         assert(Ptr->getOpcode() == ISD::ADD);
10040         isInc = false;
10041         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10042         return true;
10043       }
10044     }
10045     isInc = (Ptr->getOpcode() == ISD::ADD);
10046     Offset = Ptr->getOperand(1);
10047     return true;
10048   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10049     // AddressingMode 2
10050     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10051       int RHSC = (int)RHS->getZExtValue();
10052       if (RHSC < 0 && RHSC > -0x1000) {
10053         assert(Ptr->getOpcode() == ISD::ADD);
10054         isInc = false;
10055         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10056         Base = Ptr->getOperand(0);
10057         return true;
10058       }
10059     }
10060
10061     if (Ptr->getOpcode() == ISD::ADD) {
10062       isInc = true;
10063       ARM_AM::ShiftOpc ShOpcVal=
10064         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10065       if (ShOpcVal != ARM_AM::no_shift) {
10066         Base = Ptr->getOperand(1);
10067         Offset = Ptr->getOperand(0);
10068       } else {
10069         Base = Ptr->getOperand(0);
10070         Offset = Ptr->getOperand(1);
10071       }
10072       return true;
10073     }
10074
10075     isInc = (Ptr->getOpcode() == ISD::ADD);
10076     Base = Ptr->getOperand(0);
10077     Offset = Ptr->getOperand(1);
10078     return true;
10079   }
10080
10081   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10082   return false;
10083 }
10084
10085 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10086                                      bool isSEXTLoad, SDValue &Base,
10087                                      SDValue &Offset, bool &isInc,
10088                                      SelectionDAG &DAG) {
10089   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10090     return false;
10091
10092   Base = Ptr->getOperand(0);
10093   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10094     int RHSC = (int)RHS->getZExtValue();
10095     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10096       assert(Ptr->getOpcode() == ISD::ADD);
10097       isInc = false;
10098       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10099       return true;
10100     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10101       isInc = Ptr->getOpcode() == ISD::ADD;
10102       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10103       return true;
10104     }
10105   }
10106
10107   return false;
10108 }
10109
10110 /// getPreIndexedAddressParts - returns true by value, base pointer and
10111 /// offset pointer and addressing mode by reference if the node's address
10112 /// can be legally represented as pre-indexed load / store address.
10113 bool
10114 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10115                                              SDValue &Offset,
10116                                              ISD::MemIndexedMode &AM,
10117                                              SelectionDAG &DAG) const {
10118   if (Subtarget->isThumb1Only())
10119     return false;
10120
10121   EVT VT;
10122   SDValue Ptr;
10123   bool isSEXTLoad = false;
10124   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10125     Ptr = LD->getBasePtr();
10126     VT  = LD->getMemoryVT();
10127     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10128   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10129     Ptr = ST->getBasePtr();
10130     VT  = ST->getMemoryVT();
10131   } else
10132     return false;
10133
10134   bool isInc;
10135   bool isLegal = false;
10136   if (Subtarget->isThumb2())
10137     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10138                                        Offset, isInc, DAG);
10139   else
10140     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10141                                         Offset, isInc, DAG);
10142   if (!isLegal)
10143     return false;
10144
10145   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10146   return true;
10147 }
10148
10149 /// getPostIndexedAddressParts - returns true by value, base pointer and
10150 /// offset pointer and addressing mode by reference if this node can be
10151 /// combined with a load / store to form a post-indexed load / store.
10152 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10153                                                    SDValue &Base,
10154                                                    SDValue &Offset,
10155                                                    ISD::MemIndexedMode &AM,
10156                                                    SelectionDAG &DAG) const {
10157   if (Subtarget->isThumb1Only())
10158     return false;
10159
10160   EVT VT;
10161   SDValue Ptr;
10162   bool isSEXTLoad = false;
10163   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10164     VT  = LD->getMemoryVT();
10165     Ptr = LD->getBasePtr();
10166     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10167   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10168     VT  = ST->getMemoryVT();
10169     Ptr = ST->getBasePtr();
10170   } else
10171     return false;
10172
10173   bool isInc;
10174   bool isLegal = false;
10175   if (Subtarget->isThumb2())
10176     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10177                                        isInc, DAG);
10178   else
10179     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10180                                         isInc, DAG);
10181   if (!isLegal)
10182     return false;
10183
10184   if (Ptr != Base) {
10185     // Swap base ptr and offset to catch more post-index load / store when
10186     // it's legal. In Thumb2 mode, offset must be an immediate.
10187     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10188         !Subtarget->isThumb2())
10189       std::swap(Base, Offset);
10190
10191     // Post-indexed load / store update the base pointer.
10192     if (Ptr != Base)
10193       return false;
10194   }
10195
10196   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10197   return true;
10198 }
10199
10200 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10201                                                       APInt &KnownZero,
10202                                                       APInt &KnownOne,
10203                                                       const SelectionDAG &DAG,
10204                                                       unsigned Depth) const {
10205   unsigned BitWidth = KnownOne.getBitWidth();
10206   KnownZero = KnownOne = APInt(BitWidth, 0);
10207   switch (Op.getOpcode()) {
10208   default: break;
10209   case ARMISD::ADDC:
10210   case ARMISD::ADDE:
10211   case ARMISD::SUBC:
10212   case ARMISD::SUBE:
10213     // These nodes' second result is a boolean
10214     if (Op.getResNo() == 0)
10215       break;
10216     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10217     break;
10218   case ARMISD::CMOV: {
10219     // Bits are known zero/one if known on the LHS and RHS.
10220     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10221     if (KnownZero == 0 && KnownOne == 0) return;
10222
10223     APInt KnownZeroRHS, KnownOneRHS;
10224     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10225     KnownZero &= KnownZeroRHS;
10226     KnownOne  &= KnownOneRHS;
10227     return;
10228   }
10229   case ISD::INTRINSIC_W_CHAIN: {
10230     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10231     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10232     switch (IntID) {
10233     default: return;
10234     case Intrinsic::arm_ldaex:
10235     case Intrinsic::arm_ldrex: {
10236       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10237       unsigned MemBits = VT.getScalarType().getSizeInBits();
10238       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10239       return;
10240     }
10241     }
10242   }
10243   }
10244 }
10245
10246 //===----------------------------------------------------------------------===//
10247 //                           ARM Inline Assembly Support
10248 //===----------------------------------------------------------------------===//
10249
10250 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10251   // Looking for "rev" which is V6+.
10252   if (!Subtarget->hasV6Ops())
10253     return false;
10254
10255   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10256   std::string AsmStr = IA->getAsmString();
10257   SmallVector<StringRef, 4> AsmPieces;
10258   SplitString(AsmStr, AsmPieces, ";\n");
10259
10260   switch (AsmPieces.size()) {
10261   default: return false;
10262   case 1:
10263     AsmStr = AsmPieces[0];
10264     AsmPieces.clear();
10265     SplitString(AsmStr, AsmPieces, " \t,");
10266
10267     // rev $0, $1
10268     if (AsmPieces.size() == 3 &&
10269         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10270         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10271       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10272       if (Ty && Ty->getBitWidth() == 32)
10273         return IntrinsicLowering::LowerToByteSwap(CI);
10274     }
10275     break;
10276   }
10277
10278   return false;
10279 }
10280
10281 /// getConstraintType - Given a constraint letter, return the type of
10282 /// constraint it is for this target.
10283 ARMTargetLowering::ConstraintType
10284 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10285   if (Constraint.size() == 1) {
10286     switch (Constraint[0]) {
10287     default:  break;
10288     case 'l': return C_RegisterClass;
10289     case 'w': return C_RegisterClass;
10290     case 'h': return C_RegisterClass;
10291     case 'x': return C_RegisterClass;
10292     case 't': return C_RegisterClass;
10293     case 'j': return C_Other; // Constant for movw.
10294       // An address with a single base register. Due to the way we
10295       // currently handle addresses it is the same as an 'r' memory constraint.
10296     case 'Q': return C_Memory;
10297     }
10298   } else if (Constraint.size() == 2) {
10299     switch (Constraint[0]) {
10300     default: break;
10301     // All 'U+' constraints are addresses.
10302     case 'U': return C_Memory;
10303     }
10304   }
10305   return TargetLowering::getConstraintType(Constraint);
10306 }
10307
10308 /// Examine constraint type and operand type and determine a weight value.
10309 /// This object must already have been set up with the operand type
10310 /// and the current alternative constraint selected.
10311 TargetLowering::ConstraintWeight
10312 ARMTargetLowering::getSingleConstraintMatchWeight(
10313     AsmOperandInfo &info, const char *constraint) const {
10314   ConstraintWeight weight = CW_Invalid;
10315   Value *CallOperandVal = info.CallOperandVal;
10316     // If we don't have a value, we can't do a match,
10317     // but allow it at the lowest weight.
10318   if (!CallOperandVal)
10319     return CW_Default;
10320   Type *type = CallOperandVal->getType();
10321   // Look at the constraint type.
10322   switch (*constraint) {
10323   default:
10324     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10325     break;
10326   case 'l':
10327     if (type->isIntegerTy()) {
10328       if (Subtarget->isThumb())
10329         weight = CW_SpecificReg;
10330       else
10331         weight = CW_Register;
10332     }
10333     break;
10334   case 'w':
10335     if (type->isFloatingPointTy())
10336       weight = CW_Register;
10337     break;
10338   }
10339   return weight;
10340 }
10341
10342 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10343 RCPair
10344 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10345                                                 MVT VT) const {
10346   if (Constraint.size() == 1) {
10347     // GCC ARM Constraint Letters
10348     switch (Constraint[0]) {
10349     case 'l': // Low regs or general regs.
10350       if (Subtarget->isThumb())
10351         return RCPair(0U, &ARM::tGPRRegClass);
10352       return RCPair(0U, &ARM::GPRRegClass);
10353     case 'h': // High regs or no regs.
10354       if (Subtarget->isThumb())
10355         return RCPair(0U, &ARM::hGPRRegClass);
10356       break;
10357     case 'r':
10358       return RCPair(0U, &ARM::GPRRegClass);
10359     case 'w':
10360       if (VT == MVT::Other)
10361         break;
10362       if (VT == MVT::f32)
10363         return RCPair(0U, &ARM::SPRRegClass);
10364       if (VT.getSizeInBits() == 64)
10365         return RCPair(0U, &ARM::DPRRegClass);
10366       if (VT.getSizeInBits() == 128)
10367         return RCPair(0U, &ARM::QPRRegClass);
10368       break;
10369     case 'x':
10370       if (VT == MVT::Other)
10371         break;
10372       if (VT == MVT::f32)
10373         return RCPair(0U, &ARM::SPR_8RegClass);
10374       if (VT.getSizeInBits() == 64)
10375         return RCPair(0U, &ARM::DPR_8RegClass);
10376       if (VT.getSizeInBits() == 128)
10377         return RCPair(0U, &ARM::QPR_8RegClass);
10378       break;
10379     case 't':
10380       if (VT == MVT::f32)
10381         return RCPair(0U, &ARM::SPRRegClass);
10382       break;
10383     }
10384   }
10385   if (StringRef("{cc}").equals_lower(Constraint))
10386     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10387
10388   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10389 }
10390
10391 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10392 /// vector.  If it is invalid, don't add anything to Ops.
10393 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10394                                                      std::string &Constraint,
10395                                                      std::vector<SDValue>&Ops,
10396                                                      SelectionDAG &DAG) const {
10397   SDValue Result;
10398
10399   // Currently only support length 1 constraints.
10400   if (Constraint.length() != 1) return;
10401
10402   char ConstraintLetter = Constraint[0];
10403   switch (ConstraintLetter) {
10404   default: break;
10405   case 'j':
10406   case 'I': case 'J': case 'K': case 'L':
10407   case 'M': case 'N': case 'O':
10408     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10409     if (!C)
10410       return;
10411
10412     int64_t CVal64 = C->getSExtValue();
10413     int CVal = (int) CVal64;
10414     // None of these constraints allow values larger than 32 bits.  Check
10415     // that the value fits in an int.
10416     if (CVal != CVal64)
10417       return;
10418
10419     switch (ConstraintLetter) {
10420       case 'j':
10421         // Constant suitable for movw, must be between 0 and
10422         // 65535.
10423         if (Subtarget->hasV6T2Ops())
10424           if (CVal >= 0 && CVal <= 65535)
10425             break;
10426         return;
10427       case 'I':
10428         if (Subtarget->isThumb1Only()) {
10429           // This must be a constant between 0 and 255, for ADD
10430           // immediates.
10431           if (CVal >= 0 && CVal <= 255)
10432             break;
10433         } else if (Subtarget->isThumb2()) {
10434           // A constant that can be used as an immediate value in a
10435           // data-processing instruction.
10436           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10437             break;
10438         } else {
10439           // A constant that can be used as an immediate value in a
10440           // data-processing instruction.
10441           if (ARM_AM::getSOImmVal(CVal) != -1)
10442             break;
10443         }
10444         return;
10445
10446       case 'J':
10447         if (Subtarget->isThumb()) {  // FIXME thumb2
10448           // This must be a constant between -255 and -1, for negated ADD
10449           // immediates. This can be used in GCC with an "n" modifier that
10450           // prints the negated value, for use with SUB instructions. It is
10451           // not useful otherwise but is implemented for compatibility.
10452           if (CVal >= -255 && CVal <= -1)
10453             break;
10454         } else {
10455           // This must be a constant between -4095 and 4095. It is not clear
10456           // what this constraint is intended for. Implemented for
10457           // compatibility with GCC.
10458           if (CVal >= -4095 && CVal <= 4095)
10459             break;
10460         }
10461         return;
10462
10463       case 'K':
10464         if (Subtarget->isThumb1Only()) {
10465           // A 32-bit value where only one byte has a nonzero value. Exclude
10466           // zero to match GCC. This constraint is used by GCC internally for
10467           // constants that can be loaded with a move/shift combination.
10468           // It is not useful otherwise but is implemented for compatibility.
10469           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10470             break;
10471         } else if (Subtarget->isThumb2()) {
10472           // A constant whose bitwise inverse can be used as an immediate
10473           // value in a data-processing instruction. This can be used in GCC
10474           // with a "B" modifier that prints the inverted value, for use with
10475           // BIC and MVN instructions. It is not useful otherwise but is
10476           // implemented for compatibility.
10477           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10478             break;
10479         } else {
10480           // A constant whose bitwise inverse can be used as an immediate
10481           // value in a data-processing instruction. This can be used in GCC
10482           // with a "B" modifier that prints the inverted value, for use with
10483           // BIC and MVN instructions. It is not useful otherwise but is
10484           // implemented for compatibility.
10485           if (ARM_AM::getSOImmVal(~CVal) != -1)
10486             break;
10487         }
10488         return;
10489
10490       case 'L':
10491         if (Subtarget->isThumb1Only()) {
10492           // This must be a constant between -7 and 7,
10493           // for 3-operand ADD/SUB immediate instructions.
10494           if (CVal >= -7 && CVal < 7)
10495             break;
10496         } else if (Subtarget->isThumb2()) {
10497           // A constant whose negation can be used as an immediate value in a
10498           // data-processing instruction. This can be used in GCC with an "n"
10499           // modifier that prints the negated value, for use with SUB
10500           // instructions. It is not useful otherwise but is implemented for
10501           // compatibility.
10502           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10503             break;
10504         } else {
10505           // A constant whose negation can be used as an immediate value in a
10506           // data-processing instruction. This can be used in GCC with an "n"
10507           // modifier that prints the negated value, for use with SUB
10508           // instructions. It is not useful otherwise but is implemented for
10509           // compatibility.
10510           if (ARM_AM::getSOImmVal(-CVal) != -1)
10511             break;
10512         }
10513         return;
10514
10515       case 'M':
10516         if (Subtarget->isThumb()) { // FIXME thumb2
10517           // This must be a multiple of 4 between 0 and 1020, for
10518           // ADD sp + immediate.
10519           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10520             break;
10521         } else {
10522           // A power of two or a constant between 0 and 32.  This is used in
10523           // GCC for the shift amount on shifted register operands, but it is
10524           // useful in general for any shift amounts.
10525           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10526             break;
10527         }
10528         return;
10529
10530       case 'N':
10531         if (Subtarget->isThumb()) {  // FIXME thumb2
10532           // This must be a constant between 0 and 31, for shift amounts.
10533           if (CVal >= 0 && CVal <= 31)
10534             break;
10535         }
10536         return;
10537
10538       case 'O':
10539         if (Subtarget->isThumb()) {  // FIXME thumb2
10540           // This must be a multiple of 4 between -508 and 508, for
10541           // ADD/SUB sp = sp + immediate.
10542           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10543             break;
10544         }
10545         return;
10546     }
10547     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10548     break;
10549   }
10550
10551   if (Result.getNode()) {
10552     Ops.push_back(Result);
10553     return;
10554   }
10555   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10556 }
10557
10558 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10559   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10560   unsigned Opcode = Op->getOpcode();
10561   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10562       "Invalid opcode for Div/Rem lowering");
10563   bool isSigned = (Opcode == ISD::SDIVREM);
10564   EVT VT = Op->getValueType(0);
10565   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10566
10567   RTLIB::Libcall LC;
10568   switch (VT.getSimpleVT().SimpleTy) {
10569   default: llvm_unreachable("Unexpected request for libcall!");
10570   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10571   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10572   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10573   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10574   }
10575
10576   SDValue InChain = DAG.getEntryNode();
10577
10578   TargetLowering::ArgListTy Args;
10579   TargetLowering::ArgListEntry Entry;
10580   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10581     EVT ArgVT = Op->getOperand(i).getValueType();
10582     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10583     Entry.Node = Op->getOperand(i);
10584     Entry.Ty = ArgTy;
10585     Entry.isSExt = isSigned;
10586     Entry.isZExt = !isSigned;
10587     Args.push_back(Entry);
10588   }
10589
10590   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10591                                          getPointerTy());
10592
10593   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10594
10595   SDLoc dl(Op);
10596   TargetLowering::CallLoweringInfo CLI(DAG);
10597   CLI.setDebugLoc(dl).setChain(InChain)
10598     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10599     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10600
10601   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10602   return CallInfo.first;
10603 }
10604
10605 SDValue
10606 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10607   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10608   SDLoc DL(Op);
10609
10610   // Get the inputs.
10611   SDValue Chain = Op.getOperand(0);
10612   SDValue Size  = Op.getOperand(1);
10613
10614   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10615                               DAG.getConstant(2, MVT::i32));
10616
10617   SDValue Flag;
10618   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10619   Flag = Chain.getValue(1);
10620
10621   SDVTList NodeTys = DAG.getVTList(MVT::i32, MVT::Glue);
10622   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10623
10624   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10625   Chain = NewSP.getValue(1);
10626
10627   SDValue Ops[2] = { NewSP, Chain };
10628   return DAG.getMergeValues(Ops, DL);
10629 }
10630
10631 bool
10632 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10633   // The ARM target isn't yet aware of offsets.
10634   return false;
10635 }
10636
10637 bool ARM::isBitFieldInvertedMask(unsigned v) {
10638   if (v == 0xffffffff)
10639     return false;
10640
10641   // there can be 1's on either or both "outsides", all the "inside"
10642   // bits must be 0's
10643   unsigned TO = CountTrailingOnes_32(v);
10644   unsigned LO = CountLeadingOnes_32(v);
10645   v = (v >> TO) << TO;
10646   v = (v << LO) >> LO;
10647   return v == 0;
10648 }
10649
10650 /// isFPImmLegal - Returns true if the target can instruction select the
10651 /// specified FP immediate natively. If false, the legalizer will
10652 /// materialize the FP immediate as a load from a constant pool.
10653 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10654   if (!Subtarget->hasVFP3())
10655     return false;
10656   if (VT == MVT::f32)
10657     return ARM_AM::getFP32Imm(Imm) != -1;
10658   if (VT == MVT::f64)
10659     return ARM_AM::getFP64Imm(Imm) != -1;
10660   return false;
10661 }
10662
10663 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10664 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10665 /// specified in the intrinsic calls.
10666 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10667                                            const CallInst &I,
10668                                            unsigned Intrinsic) const {
10669   switch (Intrinsic) {
10670   case Intrinsic::arm_neon_vld1:
10671   case Intrinsic::arm_neon_vld2:
10672   case Intrinsic::arm_neon_vld3:
10673   case Intrinsic::arm_neon_vld4:
10674   case Intrinsic::arm_neon_vld2lane:
10675   case Intrinsic::arm_neon_vld3lane:
10676   case Intrinsic::arm_neon_vld4lane: {
10677     Info.opc = ISD::INTRINSIC_W_CHAIN;
10678     // Conservatively set memVT to the entire set of vectors loaded.
10679     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10680     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10681     Info.ptrVal = I.getArgOperand(0);
10682     Info.offset = 0;
10683     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10684     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10685     Info.vol = false; // volatile loads with NEON intrinsics not supported
10686     Info.readMem = true;
10687     Info.writeMem = false;
10688     return true;
10689   }
10690   case Intrinsic::arm_neon_vst1:
10691   case Intrinsic::arm_neon_vst2:
10692   case Intrinsic::arm_neon_vst3:
10693   case Intrinsic::arm_neon_vst4:
10694   case Intrinsic::arm_neon_vst2lane:
10695   case Intrinsic::arm_neon_vst3lane:
10696   case Intrinsic::arm_neon_vst4lane: {
10697     Info.opc = ISD::INTRINSIC_VOID;
10698     // Conservatively set memVT to the entire set of vectors stored.
10699     unsigned NumElts = 0;
10700     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10701       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10702       if (!ArgTy->isVectorTy())
10703         break;
10704       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10705     }
10706     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10707     Info.ptrVal = I.getArgOperand(0);
10708     Info.offset = 0;
10709     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10710     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10711     Info.vol = false; // volatile stores with NEON intrinsics not supported
10712     Info.readMem = false;
10713     Info.writeMem = true;
10714     return true;
10715   }
10716   case Intrinsic::arm_ldaex:
10717   case Intrinsic::arm_ldrex: {
10718     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10719     Info.opc = ISD::INTRINSIC_W_CHAIN;
10720     Info.memVT = MVT::getVT(PtrTy->getElementType());
10721     Info.ptrVal = I.getArgOperand(0);
10722     Info.offset = 0;
10723     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10724     Info.vol = true;
10725     Info.readMem = true;
10726     Info.writeMem = false;
10727     return true;
10728   }
10729   case Intrinsic::arm_stlex:
10730   case Intrinsic::arm_strex: {
10731     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10732     Info.opc = ISD::INTRINSIC_W_CHAIN;
10733     Info.memVT = MVT::getVT(PtrTy->getElementType());
10734     Info.ptrVal = I.getArgOperand(1);
10735     Info.offset = 0;
10736     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10737     Info.vol = true;
10738     Info.readMem = false;
10739     Info.writeMem = true;
10740     return true;
10741   }
10742   case Intrinsic::arm_stlexd:
10743   case Intrinsic::arm_strexd: {
10744     Info.opc = ISD::INTRINSIC_W_CHAIN;
10745     Info.memVT = MVT::i64;
10746     Info.ptrVal = I.getArgOperand(2);
10747     Info.offset = 0;
10748     Info.align = 8;
10749     Info.vol = true;
10750     Info.readMem = false;
10751     Info.writeMem = true;
10752     return true;
10753   }
10754   case Intrinsic::arm_ldaexd:
10755   case Intrinsic::arm_ldrexd: {
10756     Info.opc = ISD::INTRINSIC_W_CHAIN;
10757     Info.memVT = MVT::i64;
10758     Info.ptrVal = I.getArgOperand(0);
10759     Info.offset = 0;
10760     Info.align = 8;
10761     Info.vol = true;
10762     Info.readMem = true;
10763     Info.writeMem = false;
10764     return true;
10765   }
10766   default:
10767     break;
10768   }
10769
10770   return false;
10771 }
10772
10773 /// \brief Returns true if it is beneficial to convert a load of a constant
10774 /// to just the constant itself.
10775 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10776                                                           Type *Ty) const {
10777   assert(Ty->isIntegerTy());
10778
10779   unsigned Bits = Ty->getPrimitiveSizeInBits();
10780   if (Bits == 0 || Bits > 32)
10781     return false;
10782   return true;
10783 }
10784
10785 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10786   // Loads and stores less than 64-bits are already atomic; ones above that
10787   // are doomed anyway, so defer to the default libcall and blame the OS when
10788   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10789   // anything for those.
10790   bool IsMClass = Subtarget->isMClass();
10791   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10792     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10793     return Size == 64 && !IsMClass;
10794   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10795     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10796   }
10797
10798   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10799   // and up to 64 bits on the non-M profiles
10800   unsigned AtomicLimit = IsMClass ? 32 : 64;
10801   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10802 }
10803
10804 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10805                                          AtomicOrdering Ord) const {
10806   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10807   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10808   bool IsAcquire =
10809       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10810
10811   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10812   // intrinsic must return {i32, i32} and we have to recombine them into a
10813   // single i64 here.
10814   if (ValTy->getPrimitiveSizeInBits() == 64) {
10815     Intrinsic::ID Int =
10816         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10817     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10818
10819     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10820     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10821
10822     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10823     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10824     if (!Subtarget->isLittle())
10825       std::swap (Lo, Hi);
10826     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10827     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10828     return Builder.CreateOr(
10829         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10830   }
10831
10832   Type *Tys[] = { Addr->getType() };
10833   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10834   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10835
10836   return Builder.CreateTruncOrBitCast(
10837       Builder.CreateCall(Ldrex, Addr),
10838       cast<PointerType>(Addr->getType())->getElementType());
10839 }
10840
10841 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10842                                                Value *Addr,
10843                                                AtomicOrdering Ord) const {
10844   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10845   bool IsRelease =
10846       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10847
10848   // Since the intrinsics must have legal type, the i64 intrinsics take two
10849   // parameters: "i32, i32". We must marshal Val into the appropriate form
10850   // before the call.
10851   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10852     Intrinsic::ID Int =
10853         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10854     Function *Strex = Intrinsic::getDeclaration(M, Int);
10855     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10856
10857     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10858     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10859     if (!Subtarget->isLittle())
10860       std::swap (Lo, Hi);
10861     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10862     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10863   }
10864
10865   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10866   Type *Tys[] = { Addr->getType() };
10867   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10868
10869   return Builder.CreateCall2(
10870       Strex, Builder.CreateZExtOrBitCast(
10871                  Val, Strex->getFunctionType()->getParamType(0)),
10872       Addr);
10873 }
10874
10875 enum HABaseType {
10876   HA_UNKNOWN = 0,
10877   HA_FLOAT,
10878   HA_DOUBLE,
10879   HA_VECT64,
10880   HA_VECT128
10881 };
10882
10883 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10884                                    uint64_t &Members) {
10885   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10886     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10887       uint64_t SubMembers = 0;
10888       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10889         return false;
10890       Members += SubMembers;
10891     }
10892   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10893     uint64_t SubMembers = 0;
10894     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10895       return false;
10896     Members += SubMembers * AT->getNumElements();
10897   } else if (Ty->isFloatTy()) {
10898     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10899       return false;
10900     Members = 1;
10901     Base = HA_FLOAT;
10902   } else if (Ty->isDoubleTy()) {
10903     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10904       return false;
10905     Members = 1;
10906     Base = HA_DOUBLE;
10907   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10908     Members = 1;
10909     switch (Base) {
10910     case HA_FLOAT:
10911     case HA_DOUBLE:
10912       return false;
10913     case HA_VECT64:
10914       return VT->getBitWidth() == 64;
10915     case HA_VECT128:
10916       return VT->getBitWidth() == 128;
10917     case HA_UNKNOWN:
10918       switch (VT->getBitWidth()) {
10919       case 64:
10920         Base = HA_VECT64;
10921         return true;
10922       case 128:
10923         Base = HA_VECT128;
10924         return true;
10925       default:
10926         return false;
10927       }
10928     }
10929   }
10930
10931   return (Members > 0 && Members <= 4);
10932 }
10933
10934 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10935 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10936     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10937   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10938       CallingConv::ARM_AAPCS_VFP)
10939     return false;
10940
10941   HABaseType Base = HA_UNKNOWN;
10942   uint64_t Members = 0;
10943   bool result = isHomogeneousAggregate(Ty, Base, Members);
10944   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10945   return result;
10946 }