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 "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/MachineValueType.h"
56 #include "llvm/CodeGen/RuntimeLibcalls.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGNodes.h"
59 #include "llvm/CodeGen/ValueTypes.h"
60 #include "llvm/IR/Attributes.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugLoc.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalValue.h"
71 #include "llvm/IR/GlobalVariable.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/Instruction.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/User.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/MC/MCInstrDesc.h"
83 #include "llvm/MC/MCInstrItineraries.h"
84 #include "llvm/MC/MCRegisterInfo.h"
85 #include "llvm/MC/MCSchedule.h"
86 #include "llvm/Support/AtomicOrdering.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CodeGen.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetInstrInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include <algorithm>
100 #include <cassert>
101 #include <cstdint>
102 #include <cstdlib>
103 #include <iterator>
104 #include <limits>
105 #include <tuple>
106 #include <string>
107 #include <utility>
108 #include <vector>
109 
110 using namespace llvm;
111 
112 #define DEBUG_TYPE "arm-isel"
113 
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
117 STATISTIC(NumConstpoolPromoted,
118   "Number of constants with their storage promoted into constant pools");
119 
120 static cl::opt<bool>
121 ARMInterworking("arm-interworking", cl::Hidden,
122   cl::desc("Enable / disable ARM interworking (for debugging only)"),
123   cl::init(true));
124 
125 static cl::opt<bool> EnableConstpoolPromotion(
126     "arm-promote-constant", cl::Hidden,
127     cl::desc("Enable / disable promotion of unnamed_addr constants into "
128              "constant pools"),
129     cl::init(true));
130 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
131     "arm-promote-constant-max-size", cl::Hidden,
132     cl::desc("Maximum size of constant to promote into a constant pool"),
133     cl::init(64));
134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
135     "arm-promote-constant-max-total", cl::Hidden,
136     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
137     cl::init(128));
138 
139 // The APCS parameter registers.
140 static const MCPhysReg GPRArgRegs[] = {
141   ARM::R0, ARM::R1, ARM::R2, ARM::R3
142 };
143 
144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
145                                        MVT PromotedBitwiseVT) {
146   if (VT != PromotedLdStVT) {
147     setOperationAction(ISD::LOAD, VT, Promote);
148     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
149 
150     setOperationAction(ISD::STORE, VT, Promote);
151     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
152   }
153 
154   MVT ElemTy = VT.getVectorElementType();
155   if (ElemTy != MVT::f64)
156     setOperationAction(ISD::SETCC, VT, Custom);
157   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
158   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
159   if (ElemTy == MVT::i32) {
160     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
161     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
162     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
163     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
164   } else {
165     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
166     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
167     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
168     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
169   }
170   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
171   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
172   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
173   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
174   setOperationAction(ISD::SELECT,            VT, Expand);
175   setOperationAction(ISD::SELECT_CC,         VT, Expand);
176   setOperationAction(ISD::VSELECT,           VT, Expand);
177   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
178   if (VT.isInteger()) {
179     setOperationAction(ISD::SHL, VT, Custom);
180     setOperationAction(ISD::SRA, VT, Custom);
181     setOperationAction(ISD::SRL, VT, Custom);
182   }
183 
184   // Promote all bit-wise operations.
185   if (VT.isInteger() && VT != PromotedBitwiseVT) {
186     setOperationAction(ISD::AND, VT, Promote);
187     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
188     setOperationAction(ISD::OR,  VT, Promote);
189     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
190     setOperationAction(ISD::XOR, VT, Promote);
191     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
192   }
193 
194   // Neon does not support vector divide/remainder operations.
195   setOperationAction(ISD::SDIV, VT, Expand);
196   setOperationAction(ISD::UDIV, VT, Expand);
197   setOperationAction(ISD::FDIV, VT, Expand);
198   setOperationAction(ISD::SREM, VT, Expand);
199   setOperationAction(ISD::UREM, VT, Expand);
200   setOperationAction(ISD::FREM, VT, Expand);
201 
202   if (!VT.isFloatingPoint() &&
203       VT != MVT::v2i64 && VT != MVT::v1i64)
204     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
205       setOperationAction(Opcode, VT, Legal);
206 }
207 
208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
209   addRegisterClass(VT, &ARM::DPRRegClass);
210   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
211 }
212 
213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
214   addRegisterClass(VT, &ARM::DPairRegClass);
215   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
216 }
217 
218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
219                                      const ARMSubtarget &STI)
220     : TargetLowering(TM), Subtarget(&STI) {
221   RegInfo = Subtarget->getRegisterInfo();
222   Itins = Subtarget->getInstrItineraryData();
223 
224   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
225 
226   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
227       !Subtarget->isTargetWatchOS()) {
228     const auto &E = Subtarget->getTargetTriple().getEnvironment();
229 
230     bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
231                       E == Triple::MuslEABIHF;
232     // Windows is a special case.  Technically, we will replace all of the "GNU"
233     // calls with calls to MSVCRT if appropriate and adjust the calling
234     // convention then.
235     IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
236 
237     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
238       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
239                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
240                                        : CallingConv::ARM_AAPCS);
241   }
242 
243   if (Subtarget->isTargetMachO()) {
244     // Uses VFP for Thumb libfuncs if available.
245     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
246         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
247       static const struct {
248         const RTLIB::Libcall Op;
249         const char * const Name;
250         const ISD::CondCode Cond;
251       } LibraryCalls[] = {
252         // Single-precision floating-point arithmetic.
253         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
254         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
255         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
256         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
257 
258         // Double-precision floating-point arithmetic.
259         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
262         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
263 
264         // Single-precision comparisons.
265         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
266         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
267         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
268         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
269         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
270         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
271         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
272         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
273 
274         // Double-precision comparisons.
275         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
276         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
277         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
278         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
279         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
280         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
281         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
282         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
283 
284         // Floating-point to integer conversions.
285         // i64 conversions are done via library routines even when generating VFP
286         // instructions, so use the same ones.
287         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
288         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
289         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
290         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
291 
292         // Conversions between floating types.
293         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
294         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
295 
296         // Integer to floating-point conversions.
297         // i64 conversions are done via library routines even when generating VFP
298         // instructions, so use the same ones.
299         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
300         // e.g., __floatunsidf vs. __floatunssidfvfp.
301         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
302         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
303         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
304         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
305       };
306 
307       for (const auto &LC : LibraryCalls) {
308         setLibcallName(LC.Op, LC.Name);
309         if (LC.Cond != ISD::SETCC_INVALID)
310           setCmpLibcallCC(LC.Op, LC.Cond);
311       }
312     }
313 
314     // Set the correct calling convention for ARMv7k WatchOS. It's just
315     // AAPCS_VFP for functions as simple as libcalls.
316     if (Subtarget->isTargetWatchABI()) {
317       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
318         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
319     }
320   }
321 
322   // These libcalls are not available in 32-bit.
323   setLibcallName(RTLIB::SHL_I128, nullptr);
324   setLibcallName(RTLIB::SRL_I128, nullptr);
325   setLibcallName(RTLIB::SRA_I128, nullptr);
326 
327   // RTLIB
328   if (Subtarget->isAAPCS_ABI() &&
329       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
330        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
331     static const struct {
332       const RTLIB::Libcall Op;
333       const char * const Name;
334       const CallingConv::ID CC;
335       const ISD::CondCode Cond;
336     } LibraryCalls[] = {
337       // Double-precision floating-point arithmetic helper functions
338       // RTABI chapter 4.1.2, Table 2
339       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 
344       // Double-precision floating-point comparison helper functions
345       // RTABI chapter 4.1.2, Table 3
346       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
347       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
348       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
349       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
352       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
353       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
354 
355       // Single-precision floating-point arithmetic helper functions
356       // RTABI chapter 4.1.2, Table 4
357       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
361 
362       // Single-precision floating-point comparison helper functions
363       // RTABI chapter 4.1.2, Table 5
364       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
365       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
366       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
367       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
370       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
371       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
372 
373       // Floating-point to integer conversions.
374       // RTABI chapter 4.1.2, Table 6
375       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383 
384       // Conversions between floating types.
385       // RTABI chapter 4.1.2, Table 7
386       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389 
390       // Integer to floating-point conversions.
391       // RTABI chapter 4.1.2, Table 8
392       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400 
401       // Long long helper functions
402       // RTABI chapter 4.2, Table 9
403       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407 
408       // Integer division functions
409       // RTABI chapter 4.3.1
410       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418     };
419 
420     for (const auto &LC : LibraryCalls) {
421       setLibcallName(LC.Op, LC.Name);
422       setLibcallCallingConv(LC.Op, LC.CC);
423       if (LC.Cond != ISD::SETCC_INVALID)
424         setCmpLibcallCC(LC.Op, LC.Cond);
425     }
426 
427     // EABI dependent RTLIB
428     if (TM.Options.EABIVersion == EABI::EABI4 ||
429         TM.Options.EABIVersion == EABI::EABI5) {
430       static const struct {
431         const RTLIB::Libcall Op;
432         const char *const Name;
433         const CallingConv::ID CC;
434         const ISD::CondCode Cond;
435       } MemOpsLibraryCalls[] = {
436         // Memory operations
437         // RTABI chapter 4.3.4
438         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
441       };
442 
443       for (const auto &LC : MemOpsLibraryCalls) {
444         setLibcallName(LC.Op, LC.Name);
445         setLibcallCallingConv(LC.Op, LC.CC);
446         if (LC.Cond != ISD::SETCC_INVALID)
447           setCmpLibcallCC(LC.Op, LC.Cond);
448       }
449     }
450   }
451 
452   if (Subtarget->isTargetWindows()) {
453     static const struct {
454       const RTLIB::Libcall Op;
455       const char * const Name;
456       const CallingConv::ID CC;
457     } LibraryCalls[] = {
458       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
459       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
464       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
465       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
466     };
467 
468     for (const auto &LC : LibraryCalls) {
469       setLibcallName(LC.Op, LC.Name);
470       setLibcallCallingConv(LC.Op, LC.CC);
471     }
472   }
473 
474   // Use divmod compiler-rt calls for iOS 5.0 and later.
475   if (Subtarget->isTargetWatchOS() ||
476       (Subtarget->isTargetIOS() &&
477        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
478     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
479     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
480   }
481 
482   // The half <-> float conversion functions are always soft-float on
483   // non-watchos platforms, but are needed for some targets which use a
484   // hard-float calling convention by default.
485   if (!Subtarget->isTargetWatchABI()) {
486     if (Subtarget->isAAPCS_ABI()) {
487       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
488       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
489       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
490     } else {
491       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
492       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
493       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
494     }
495   }
496 
497   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
498   // a __gnu_ prefix (which is the default).
499   if (Subtarget->isTargetAEABI()) {
500     static const struct {
501       const RTLIB::Libcall Op;
502       const char * const Name;
503       const CallingConv::ID CC;
504     } LibraryCalls[] = {
505       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
506       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
507       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
508     };
509 
510     for (const auto &LC : LibraryCalls) {
511       setLibcallName(LC.Op, LC.Name);
512       setLibcallCallingConv(LC.Op, LC.CC);
513     }
514   }
515 
516   if (Subtarget->isThumb1Only())
517     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
518   else
519     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
520 
521   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
522       !Subtarget->isThumb1Only()) {
523     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
524     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
525   }
526 
527   for (MVT VT : MVT::vector_valuetypes()) {
528     for (MVT InnerVT : MVT::vector_valuetypes()) {
529       setTruncStoreAction(VT, InnerVT, Expand);
530       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
531       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
532       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
533     }
534 
535     setOperationAction(ISD::MULHS, VT, Expand);
536     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
537     setOperationAction(ISD::MULHU, VT, Expand);
538     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
539 
540     setOperationAction(ISD::BSWAP, VT, Expand);
541   }
542 
543   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
544   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
545 
546   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
547   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
548 
549   if (Subtarget->hasNEON()) {
550     addDRTypeForNEON(MVT::v2f32);
551     addDRTypeForNEON(MVT::v8i8);
552     addDRTypeForNEON(MVT::v4i16);
553     addDRTypeForNEON(MVT::v2i32);
554     addDRTypeForNEON(MVT::v1i64);
555 
556     addQRTypeForNEON(MVT::v4f32);
557     addQRTypeForNEON(MVT::v2f64);
558     addQRTypeForNEON(MVT::v16i8);
559     addQRTypeForNEON(MVT::v8i16);
560     addQRTypeForNEON(MVT::v4i32);
561     addQRTypeForNEON(MVT::v2i64);
562 
563     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
564     // neither Neon nor VFP support any arithmetic operations on it.
565     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
566     // supported for v4f32.
567     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
568     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
569     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
570     // FIXME: Code duplication: FDIV and FREM are expanded always, see
571     // ARMTargetLowering::addTypeForNEON method for details.
572     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
573     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
574     // FIXME: Create unittest.
575     // In another words, find a way when "copysign" appears in DAG with vector
576     // operands.
577     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
578     // FIXME: Code duplication: SETCC has custom operation action, see
579     // ARMTargetLowering::addTypeForNEON method for details.
580     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
581     // FIXME: Create unittest for FNEG and for FABS.
582     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
583     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
584     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
585     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
586     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
587     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
588     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
589     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
590     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
591     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
592     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
593     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
594     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
595     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
596     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
597     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
598     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
599     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
600     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
601 
602     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
603     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
604     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
605     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
606     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
607     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
608     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
609     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
610     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
611     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
612     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
613     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
614     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
615     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
616     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
617 
618     // Mark v2f32 intrinsics.
619     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
620     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
621     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
622     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
623     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
624     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
625     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
626     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
627     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
628     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
629     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
630     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
631     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
632     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
633     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
634 
635     // Neon does not support some operations on v1i64 and v2i64 types.
636     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
637     // Custom handling for some quad-vector types to detect VMULL.
638     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
639     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
640     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
641     // Custom handling for some vector types to avoid expensive expansions
642     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
643     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
644     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
645     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
646     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
647     // a destination type that is wider than the source, and nor does
648     // it have a FP_TO_[SU]INT instruction with a narrower destination than
649     // source.
650     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
651     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
652     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
653     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
654 
655     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
656     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
657 
658     // NEON does not have single instruction CTPOP for vectors with element
659     // types wider than 8-bits.  However, custom lowering can leverage the
660     // v8i8/v16i8 vcnt instruction.
661     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
662     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
663     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
664     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
665     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
666     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
667 
668     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
669     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
670 
671     // NEON does not have single instruction CTTZ for vectors.
672     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
673     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
674     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
675     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
676 
677     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
678     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
679     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
680     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
681 
682     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
683     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
684     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
686 
687     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
689     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
691 
692     // NEON only has FMA instructions as of VFP4.
693     if (!Subtarget->hasVFP4()) {
694       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
695       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
696     }
697 
698     setTargetDAGCombine(ISD::INTRINSIC_VOID);
699     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
700     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
701     setTargetDAGCombine(ISD::SHL);
702     setTargetDAGCombine(ISD::SRL);
703     setTargetDAGCombine(ISD::SRA);
704     setTargetDAGCombine(ISD::SIGN_EXTEND);
705     setTargetDAGCombine(ISD::ZERO_EXTEND);
706     setTargetDAGCombine(ISD::ANY_EXTEND);
707     setTargetDAGCombine(ISD::BUILD_VECTOR);
708     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
709     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
710     setTargetDAGCombine(ISD::STORE);
711     setTargetDAGCombine(ISD::FP_TO_SINT);
712     setTargetDAGCombine(ISD::FP_TO_UINT);
713     setTargetDAGCombine(ISD::FDIV);
714     setTargetDAGCombine(ISD::LOAD);
715 
716     // It is legal to extload from v4i8 to v4i16 or v4i32.
717     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
718                    MVT::v2i32}) {
719       for (MVT VT : MVT::integer_vector_valuetypes()) {
720         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
721         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
722         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
723       }
724     }
725   }
726 
727   // ARM and Thumb2 support UMLAL/SMLAL.
728   if (!Subtarget->isThumb1Only())
729     setTargetDAGCombine(ISD::ADDC);
730 
731   if (Subtarget->isFPOnlySP()) {
732     // When targeting a floating-point unit with only single-precision
733     // operations, f64 is legal for the few double-precision instructions which
734     // are present However, no double-precision operations other than moves,
735     // loads and stores are provided by the hardware.
736     setOperationAction(ISD::FADD,       MVT::f64, Expand);
737     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
738     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
739     setOperationAction(ISD::FMA,        MVT::f64, Expand);
740     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
741     setOperationAction(ISD::FREM,       MVT::f64, Expand);
742     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
743     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
744     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
745     setOperationAction(ISD::FABS,       MVT::f64, Expand);
746     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
747     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
748     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
749     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
750     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
751     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
752     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
753     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
754     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
755     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
756     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
757     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
758     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
759     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
760     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
761     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
762     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
763     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
764     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
765     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
766     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
767     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
768     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
769   }
770 
771   computeRegisterProperties(Subtarget->getRegisterInfo());
772 
773   // ARM does not have floating-point extending loads.
774   for (MVT VT : MVT::fp_valuetypes()) {
775     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
776     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
777   }
778 
779   // ... or truncating stores
780   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
781   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
782   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
783 
784   // ARM does not have i1 sign extending load.
785   for (MVT VT : MVT::integer_valuetypes())
786     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
787 
788   // ARM supports all 4 flavors of integer indexed load / store.
789   if (!Subtarget->isThumb1Only()) {
790     for (unsigned im = (unsigned)ISD::PRE_INC;
791          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
792       setIndexedLoadAction(im,  MVT::i1,  Legal);
793       setIndexedLoadAction(im,  MVT::i8,  Legal);
794       setIndexedLoadAction(im,  MVT::i16, Legal);
795       setIndexedLoadAction(im,  MVT::i32, Legal);
796       setIndexedStoreAction(im, MVT::i1,  Legal);
797       setIndexedStoreAction(im, MVT::i8,  Legal);
798       setIndexedStoreAction(im, MVT::i16, Legal);
799       setIndexedStoreAction(im, MVT::i32, Legal);
800     }
801   } else {
802     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
803     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
804     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
805   }
806 
807   setOperationAction(ISD::SADDO, MVT::i32, Custom);
808   setOperationAction(ISD::UADDO, MVT::i32, Custom);
809   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
810   setOperationAction(ISD::USUBO, MVT::i32, Custom);
811 
812   // i64 operation support.
813   setOperationAction(ISD::MUL,     MVT::i64, Expand);
814   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
815   if (Subtarget->isThumb1Only()) {
816     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
817     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
818   }
819   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
820       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
821     setOperationAction(ISD::MULHS, MVT::i32, Expand);
822 
823   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
824   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
825   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
826   setOperationAction(ISD::SRL,       MVT::i64, Custom);
827   setOperationAction(ISD::SRA,       MVT::i64, Custom);
828 
829   if (!Subtarget->isThumb1Only()) {
830     // FIXME: We should do this for Thumb1 as well.
831     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
832     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
833     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
834     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
835   }
836 
837   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
838     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
839 
840   // ARM does not have ROTL.
841   setOperationAction(ISD::ROTL, MVT::i32, Expand);
842   for (MVT VT : MVT::vector_valuetypes()) {
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845   }
846   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
847   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
848   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
849     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
850 
851   // @llvm.readcyclecounter requires the Performance Monitors extension.
852   // Default to the 0 expansion on unsupported platforms.
853   // FIXME: Technically there are older ARM CPUs that have
854   // implementation-specific ways of obtaining this information.
855   if (Subtarget->hasPerfMon())
856     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
857 
858   // Only ARMv6 has BSWAP.
859   if (!Subtarget->hasV6Ops())
860     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
861 
862   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
863                                         : Subtarget->hasDivideInARMMode();
864   if (!hasDivide) {
865     // These are expanded into libcalls if the cpu doesn't have HW divider.
866     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
867     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
868   }
869 
870   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
871     setOperationAction(ISD::SDIV, MVT::i32, Custom);
872     setOperationAction(ISD::UDIV, MVT::i32, Custom);
873 
874     setOperationAction(ISD::SDIV, MVT::i64, Custom);
875     setOperationAction(ISD::UDIV, MVT::i64, Custom);
876   }
877 
878   setOperationAction(ISD::SREM,  MVT::i32, Expand);
879   setOperationAction(ISD::UREM,  MVT::i32, Expand);
880 
881   // Register based DivRem for AEABI (RTABI 4.2)
882   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
883       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
884       Subtarget->isTargetWindows()) {
885     setOperationAction(ISD::SREM, MVT::i64, Custom);
886     setOperationAction(ISD::UREM, MVT::i64, Custom);
887     HasStandaloneRem = false;
888 
889     if (Subtarget->isTargetWindows()) {
890       const struct {
891         const RTLIB::Libcall Op;
892         const char * const Name;
893         const CallingConv::ID CC;
894       } LibraryCalls[] = {
895         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
896         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
897         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
898         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
899 
900         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
901         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
902         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
903         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
904       };
905 
906       for (const auto &LC : LibraryCalls) {
907         setLibcallName(LC.Op, LC.Name);
908         setLibcallCallingConv(LC.Op, LC.CC);
909       }
910     } else {
911       const struct {
912         const RTLIB::Libcall Op;
913         const char * const Name;
914         const CallingConv::ID CC;
915       } LibraryCalls[] = {
916         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
918         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
919         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
920 
921         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
922         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
923         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
924         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
925       };
926 
927       for (const auto &LC : LibraryCalls) {
928         setLibcallName(LC.Op, LC.Name);
929         setLibcallCallingConv(LC.Op, LC.CC);
930       }
931     }
932 
933     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
934     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
935     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
936     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
937   } else {
938     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
939     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
940   }
941 
942   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
943     for (auto &VT : {MVT::f32, MVT::f64})
944       setOperationAction(ISD::FPOWI, VT, Custom);
945 
946   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
947   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
948   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
949   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
950 
951   setOperationAction(ISD::TRAP, MVT::Other, Legal);
952 
953   // Use the default implementation.
954   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
955   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
956   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
957   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
958   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
959   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
960 
961   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
962     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
963   else
964     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
965 
966   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
967   // the default expansion.
968   InsertFencesForAtomic = false;
969   if (Subtarget->hasAnyDataBarrier() &&
970       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
971     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
972     // to ldrex/strex loops already.
973     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
974     if (!Subtarget->isThumb() || !Subtarget->isMClass())
975       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
976 
977     // On v8, we have particularly efficient implementations of atomic fences
978     // if they can be combined with nearby atomic loads and stores.
979     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
980       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
981       InsertFencesForAtomic = true;
982     }
983   } else {
984     // If there's anything we can use as a barrier, go through custom lowering
985     // for ATOMIC_FENCE.
986     // If target has DMB in thumb, Fences can be inserted.
987     if (Subtarget->hasDataBarrier())
988       InsertFencesForAtomic = true;
989 
990     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
991                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
992 
993     // Set them all for expansion, which will force libcalls.
994     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1001     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1002     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1003     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1004     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1005     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1006     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1007     // Unordered/Monotonic case.
1008     if (!InsertFencesForAtomic) {
1009       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1010       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1011     }
1012   }
1013 
1014   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1015 
1016   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1017   if (!Subtarget->hasV6Ops()) {
1018     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1019     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1020   }
1021   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1022 
1023   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1024       !Subtarget->isThumb1Only()) {
1025     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1026     // iff target supports vfp2.
1027     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1028     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1029   }
1030 
1031   // We want to custom lower some of our intrinsics.
1032   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1033   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1034   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1035   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1036   if (Subtarget->useSjLjEH())
1037     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1038 
1039   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1040   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1041   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1042   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1043   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1044   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1045   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1046   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1047   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1048 
1049   // Thumb-1 cannot currently select ARMISD::SUBE.
1050   if (!Subtarget->isThumb1Only())
1051     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1052 
1053   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1054   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1055   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1056   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1057   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1058 
1059   // We don't support sin/cos/fmod/copysign/pow
1060   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1061   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1062   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1063   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1064   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1065   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1066   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1067   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1068   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1069       !Subtarget->isThumb1Only()) {
1070     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1071     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1072   }
1073   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1074   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1075 
1076   if (!Subtarget->hasVFP4()) {
1077     setOperationAction(ISD::FMA, MVT::f64, Expand);
1078     setOperationAction(ISD::FMA, MVT::f32, Expand);
1079   }
1080 
1081   // Various VFP goodness
1082   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1083     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1084     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1085       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1086       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1087     }
1088 
1089     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1090     if (!Subtarget->hasFP16()) {
1091       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1092       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1093     }
1094   }
1095 
1096   // Combine sin / cos into one node or libcall if possible.
1097   if (Subtarget->hasSinCos()) {
1098     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1099     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1100     if (Subtarget->isTargetWatchABI()) {
1101       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1102       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1103     }
1104     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1105       // For iOS, we don't want to the normal expansion of a libcall to
1106       // sincos. We want to issue a libcall to __sincos_stret.
1107       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1108       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1109     }
1110   }
1111 
1112   // FP-ARMv8 implements a lot of rounding-like FP operations.
1113   if (Subtarget->hasFPARMv8()) {
1114     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1115     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1116     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1117     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1118     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1119     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1120     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1121     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1122     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1123     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1124     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1125     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1126 
1127     if (!Subtarget->isFPOnlySP()) {
1128       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1129       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1130       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1131       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1132       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1133       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1134       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1135       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1136     }
1137   }
1138 
1139   if (Subtarget->hasNEON()) {
1140     // vmin and vmax aren't available in a scalar form, so we use
1141     // a NEON instruction with an undef lane instead.
1142     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1143     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1144     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1145     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1146     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1147     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1148   }
1149 
1150   // We have target-specific dag combine patterns for the following nodes:
1151   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1152   setTargetDAGCombine(ISD::ADD);
1153   setTargetDAGCombine(ISD::SUB);
1154   setTargetDAGCombine(ISD::MUL);
1155   setTargetDAGCombine(ISD::AND);
1156   setTargetDAGCombine(ISD::OR);
1157   setTargetDAGCombine(ISD::XOR);
1158 
1159   if (Subtarget->hasV6Ops())
1160     setTargetDAGCombine(ISD::SRL);
1161 
1162   setStackPointerRegisterToSaveRestore(ARM::SP);
1163 
1164   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1165       !Subtarget->hasVFP2())
1166     setSchedulingPreference(Sched::RegPressure);
1167   else
1168     setSchedulingPreference(Sched::Hybrid);
1169 
1170   //// temporary - rewrite interface to use type
1171   MaxStoresPerMemset = 8;
1172   MaxStoresPerMemsetOptSize = 4;
1173   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1174   MaxStoresPerMemcpyOptSize = 2;
1175   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1176   MaxStoresPerMemmoveOptSize = 2;
1177 
1178   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1179   // are at least 4 bytes aligned.
1180   setMinStackArgumentAlignment(4);
1181 
1182   // Prefer likely predicted branches to selects on out-of-order cores.
1183   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1184 
1185   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1186 }
1187 
1188 bool ARMTargetLowering::useSoftFloat() const {
1189   return Subtarget->useSoftFloat();
1190 }
1191 
1192 // FIXME: It might make sense to define the representative register class as the
1193 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1194 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1195 // SPR's representative would be DPR_VFP2. This should work well if register
1196 // pressure tracking were modified such that a register use would increment the
1197 // pressure of the register class's representative and all of it's super
1198 // classes' representatives transitively. We have not implemented this because
1199 // of the difficulty prior to coalescing of modeling operand register classes
1200 // due to the common occurrence of cross class copies and subregister insertions
1201 // and extractions.
1202 std::pair<const TargetRegisterClass *, uint8_t>
1203 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1204                                            MVT VT) const {
1205   const TargetRegisterClass *RRC = nullptr;
1206   uint8_t Cost = 1;
1207   switch (VT.SimpleTy) {
1208   default:
1209     return TargetLowering::findRepresentativeClass(TRI, VT);
1210   // Use DPR as representative register class for all floating point
1211   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1212   // the cost is 1 for both f32 and f64.
1213   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1214   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1215     RRC = &ARM::DPRRegClass;
1216     // When NEON is used for SP, only half of the register file is available
1217     // because operations that define both SP and DP results will be constrained
1218     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1219     // coalescing by double-counting the SP regs. See the FIXME above.
1220     if (Subtarget->useNEONForSinglePrecisionFP())
1221       Cost = 2;
1222     break;
1223   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1224   case MVT::v4f32: case MVT::v2f64:
1225     RRC = &ARM::DPRRegClass;
1226     Cost = 2;
1227     break;
1228   case MVT::v4i64:
1229     RRC = &ARM::DPRRegClass;
1230     Cost = 4;
1231     break;
1232   case MVT::v8i64:
1233     RRC = &ARM::DPRRegClass;
1234     Cost = 8;
1235     break;
1236   }
1237   return std::make_pair(RRC, Cost);
1238 }
1239 
1240 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1241   switch ((ARMISD::NodeType)Opcode) {
1242   case ARMISD::FIRST_NUMBER:  break;
1243   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1244   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1245   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1246   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1247   case ARMISD::CALL:          return "ARMISD::CALL";
1248   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1249   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1250   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1251   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1252   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1253   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1254   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1255   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1256   case ARMISD::CMP:           return "ARMISD::CMP";
1257   case ARMISD::CMN:           return "ARMISD::CMN";
1258   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1259   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1260   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1261   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1262   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1263 
1264   case ARMISD::CMOV:          return "ARMISD::CMOV";
1265 
1266   case ARMISD::SSAT:          return "ARMISD::SSAT";
1267 
1268   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1269   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1270   case ARMISD::RRX:           return "ARMISD::RRX";
1271 
1272   case ARMISD::ADDC:          return "ARMISD::ADDC";
1273   case ARMISD::ADDE:          return "ARMISD::ADDE";
1274   case ARMISD::SUBC:          return "ARMISD::SUBC";
1275   case ARMISD::SUBE:          return "ARMISD::SUBE";
1276 
1277   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1278   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1279 
1280   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1281   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1282   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1283 
1284   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1285 
1286   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1287 
1288   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1289 
1290   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1291 
1292   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1293 
1294   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1295   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1296 
1297   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1298   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1299   case ARMISD::VCGE:          return "ARMISD::VCGE";
1300   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1301   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1302   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1303   case ARMISD::VCGT:          return "ARMISD::VCGT";
1304   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1305   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1306   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1307   case ARMISD::VTST:          return "ARMISD::VTST";
1308 
1309   case ARMISD::VSHL:          return "ARMISD::VSHL";
1310   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1311   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1312   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1313   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1314   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1315   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1316   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1317   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1318   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1319   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1320   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1321   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1322   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1323   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1324   case ARMISD::VSLI:          return "ARMISD::VSLI";
1325   case ARMISD::VSRI:          return "ARMISD::VSRI";
1326   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1327   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1328   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1329   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1330   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1331   case ARMISD::VDUP:          return "ARMISD::VDUP";
1332   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1333   case ARMISD::VEXT:          return "ARMISD::VEXT";
1334   case ARMISD::VREV64:        return "ARMISD::VREV64";
1335   case ARMISD::VREV32:        return "ARMISD::VREV32";
1336   case ARMISD::VREV16:        return "ARMISD::VREV16";
1337   case ARMISD::VZIP:          return "ARMISD::VZIP";
1338   case ARMISD::VUZP:          return "ARMISD::VUZP";
1339   case ARMISD::VTRN:          return "ARMISD::VTRN";
1340   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1341   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1342   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1343   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1344   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1345   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1346   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1347   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1348   case ARMISD::BFI:           return "ARMISD::BFI";
1349   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1350   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1351   case ARMISD::VBSL:          return "ARMISD::VBSL";
1352   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1353   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1354   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1355   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1356   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1357   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1358   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1359   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1360   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1361   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1362   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1363   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1364   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1365   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1366   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1367   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1368   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1369   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1370   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1371   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1372   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1373   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1374   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1375   }
1376   return nullptr;
1377 }
1378 
1379 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1380                                           EVT VT) const {
1381   if (!VT.isVector())
1382     return getPointerTy(DL);
1383   return VT.changeVectorElementTypeToInteger();
1384 }
1385 
1386 /// getRegClassFor - Return the register class that should be used for the
1387 /// specified value type.
1388 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1389   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1390   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1391   // load / store 4 to 8 consecutive D registers.
1392   if (Subtarget->hasNEON()) {
1393     if (VT == MVT::v4i64)
1394       return &ARM::QQPRRegClass;
1395     if (VT == MVT::v8i64)
1396       return &ARM::QQQQPRRegClass;
1397   }
1398   return TargetLowering::getRegClassFor(VT);
1399 }
1400 
1401 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1402 // source/dest is aligned and the copy size is large enough. We therefore want
1403 // to align such objects passed to memory intrinsics.
1404 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1405                                                unsigned &PrefAlign) const {
1406   if (!isa<MemIntrinsic>(CI))
1407     return false;
1408   MinSize = 8;
1409   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1410   // cycle faster than 4-byte aligned LDM.
1411   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1412   return true;
1413 }
1414 
1415 // Create a fast isel object.
1416 FastISel *
1417 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1418                                   const TargetLibraryInfo *libInfo) const {
1419   return ARM::createFastISel(funcInfo, libInfo);
1420 }
1421 
1422 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1423   unsigned NumVals = N->getNumValues();
1424   if (!NumVals)
1425     return Sched::RegPressure;
1426 
1427   for (unsigned i = 0; i != NumVals; ++i) {
1428     EVT VT = N->getValueType(i);
1429     if (VT == MVT::Glue || VT == MVT::Other)
1430       continue;
1431     if (VT.isFloatingPoint() || VT.isVector())
1432       return Sched::ILP;
1433   }
1434 
1435   if (!N->isMachineOpcode())
1436     return Sched::RegPressure;
1437 
1438   // Load are scheduled for latency even if there instruction itinerary
1439   // is not available.
1440   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1441   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1442 
1443   if (MCID.getNumDefs() == 0)
1444     return Sched::RegPressure;
1445   if (!Itins->isEmpty() &&
1446       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1447     return Sched::ILP;
1448 
1449   return Sched::RegPressure;
1450 }
1451 
1452 //===----------------------------------------------------------------------===//
1453 // Lowering Code
1454 //===----------------------------------------------------------------------===//
1455 
1456 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1457 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1458   switch (CC) {
1459   default: llvm_unreachable("Unknown condition code!");
1460   case ISD::SETNE:  return ARMCC::NE;
1461   case ISD::SETEQ:  return ARMCC::EQ;
1462   case ISD::SETGT:  return ARMCC::GT;
1463   case ISD::SETGE:  return ARMCC::GE;
1464   case ISD::SETLT:  return ARMCC::LT;
1465   case ISD::SETLE:  return ARMCC::LE;
1466   case ISD::SETUGT: return ARMCC::HI;
1467   case ISD::SETUGE: return ARMCC::HS;
1468   case ISD::SETULT: return ARMCC::LO;
1469   case ISD::SETULE: return ARMCC::LS;
1470   }
1471 }
1472 
1473 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1474 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1475                         ARMCC::CondCodes &CondCode2) {
1476   CondCode2 = ARMCC::AL;
1477   switch (CC) {
1478   default: llvm_unreachable("Unknown FP condition!");
1479   case ISD::SETEQ:
1480   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1481   case ISD::SETGT:
1482   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1483   case ISD::SETGE:
1484   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1485   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1486   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1487   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1488   case ISD::SETO:   CondCode = ARMCC::VC; break;
1489   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1490   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1491   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1492   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1493   case ISD::SETLT:
1494   case ISD::SETULT: CondCode = ARMCC::LT; break;
1495   case ISD::SETLE:
1496   case ISD::SETULE: CondCode = ARMCC::LE; break;
1497   case ISD::SETNE:
1498   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1499   }
1500 }
1501 
1502 //===----------------------------------------------------------------------===//
1503 //                      Calling Convention Implementation
1504 //===----------------------------------------------------------------------===//
1505 
1506 #include "ARMGenCallingConv.inc"
1507 
1508 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1509 /// account presence of floating point hardware and calling convention
1510 /// limitations, such as support for variadic functions.
1511 CallingConv::ID
1512 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1513                                            bool isVarArg) const {
1514   switch (CC) {
1515   default:
1516     llvm_unreachable("Unsupported calling convention");
1517   case CallingConv::ARM_AAPCS:
1518   case CallingConv::ARM_APCS:
1519   case CallingConv::GHC:
1520     return CC;
1521   case CallingConv::PreserveMost:
1522     return CallingConv::PreserveMost;
1523   case CallingConv::ARM_AAPCS_VFP:
1524   case CallingConv::Swift:
1525     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1526   case CallingConv::C:
1527     if (!Subtarget->isAAPCS_ABI())
1528       return CallingConv::ARM_APCS;
1529     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1530              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1531              !isVarArg)
1532       return CallingConv::ARM_AAPCS_VFP;
1533     else
1534       return CallingConv::ARM_AAPCS;
1535   case CallingConv::Fast:
1536   case CallingConv::CXX_FAST_TLS:
1537     if (!Subtarget->isAAPCS_ABI()) {
1538       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1539         return CallingConv::Fast;
1540       return CallingConv::ARM_APCS;
1541     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1542       return CallingConv::ARM_AAPCS_VFP;
1543     else
1544       return CallingConv::ARM_AAPCS;
1545   }
1546 }
1547 
1548 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1549                                                  bool isVarArg) const {
1550   return CCAssignFnForNode(CC, false, isVarArg);
1551 }
1552 
1553 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1554                                                    bool isVarArg) const {
1555   return CCAssignFnForNode(CC, true, isVarArg);
1556 }
1557 
1558 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1559 /// CallingConvention.
1560 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1561                                                  bool Return,
1562                                                  bool isVarArg) const {
1563   switch (getEffectiveCallingConv(CC, isVarArg)) {
1564   default:
1565     llvm_unreachable("Unsupported calling convention");
1566   case CallingConv::ARM_APCS:
1567     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1568   case CallingConv::ARM_AAPCS:
1569     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1570   case CallingConv::ARM_AAPCS_VFP:
1571     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1572   case CallingConv::Fast:
1573     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1574   case CallingConv::GHC:
1575     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1576   case CallingConv::PreserveMost:
1577     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1578   }
1579 }
1580 
1581 /// LowerCallResult - Lower the result values of a call into the
1582 /// appropriate copies out of appropriate physical registers.
1583 SDValue ARMTargetLowering::LowerCallResult(
1584     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1585     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1586     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1587     SDValue ThisVal) const {
1588 
1589   // Assign locations to each value returned by this call.
1590   SmallVector<CCValAssign, 16> RVLocs;
1591   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1592                  *DAG.getContext());
1593   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1594 
1595   // Copy all of the result registers out of their specified physreg.
1596   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1597     CCValAssign VA = RVLocs[i];
1598 
1599     // Pass 'this' value directly from the argument to return value, to avoid
1600     // reg unit interference
1601     if (i == 0 && isThisReturn) {
1602       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1603              "unexpected return calling convention register assignment");
1604       InVals.push_back(ThisVal);
1605       continue;
1606     }
1607 
1608     SDValue Val;
1609     if (VA.needsCustom()) {
1610       // Handle f64 or half of a v2f64.
1611       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1612                                       InFlag);
1613       Chain = Lo.getValue(1);
1614       InFlag = Lo.getValue(2);
1615       VA = RVLocs[++i]; // skip ahead to next loc
1616       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1617                                       InFlag);
1618       Chain = Hi.getValue(1);
1619       InFlag = Hi.getValue(2);
1620       if (!Subtarget->isLittle())
1621         std::swap (Lo, Hi);
1622       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1623 
1624       if (VA.getLocVT() == MVT::v2f64) {
1625         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1626         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1627                           DAG.getConstant(0, dl, MVT::i32));
1628 
1629         VA = RVLocs[++i]; // skip ahead to next loc
1630         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1631         Chain = Lo.getValue(1);
1632         InFlag = Lo.getValue(2);
1633         VA = RVLocs[++i]; // skip ahead to next loc
1634         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1635         Chain = Hi.getValue(1);
1636         InFlag = Hi.getValue(2);
1637         if (!Subtarget->isLittle())
1638           std::swap (Lo, Hi);
1639         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1640         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1641                           DAG.getConstant(1, dl, MVT::i32));
1642       }
1643     } else {
1644       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1645                                InFlag);
1646       Chain = Val.getValue(1);
1647       InFlag = Val.getValue(2);
1648     }
1649 
1650     switch (VA.getLocInfo()) {
1651     default: llvm_unreachable("Unknown loc info!");
1652     case CCValAssign::Full: break;
1653     case CCValAssign::BCvt:
1654       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1655       break;
1656     }
1657 
1658     InVals.push_back(Val);
1659   }
1660 
1661   return Chain;
1662 }
1663 
1664 /// LowerMemOpCallTo - Store the argument to the stack.
1665 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1666                                             SDValue Arg, const SDLoc &dl,
1667                                             SelectionDAG &DAG,
1668                                             const CCValAssign &VA,
1669                                             ISD::ArgFlagsTy Flags) const {
1670   unsigned LocMemOffset = VA.getLocMemOffset();
1671   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1672   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1673                        StackPtr, PtrOff);
1674   return DAG.getStore(
1675       Chain, dl, Arg, PtrOff,
1676       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1677 }
1678 
1679 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1680                                          SDValue Chain, SDValue &Arg,
1681                                          RegsToPassVector &RegsToPass,
1682                                          CCValAssign &VA, CCValAssign &NextVA,
1683                                          SDValue &StackPtr,
1684                                          SmallVectorImpl<SDValue> &MemOpChains,
1685                                          ISD::ArgFlagsTy Flags) const {
1686 
1687   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1688                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1689   unsigned id = Subtarget->isLittle() ? 0 : 1;
1690   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1691 
1692   if (NextVA.isRegLoc())
1693     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1694   else {
1695     assert(NextVA.isMemLoc());
1696     if (!StackPtr.getNode())
1697       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1698                                     getPointerTy(DAG.getDataLayout()));
1699 
1700     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1701                                            dl, DAG, NextVA,
1702                                            Flags));
1703   }
1704 }
1705 
1706 /// LowerCall - Lowering a call into a callseq_start <-
1707 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1708 /// nodes.
1709 SDValue
1710 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1711                              SmallVectorImpl<SDValue> &InVals) const {
1712   SelectionDAG &DAG                     = CLI.DAG;
1713   SDLoc &dl                             = CLI.DL;
1714   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1715   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1716   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1717   SDValue Chain                         = CLI.Chain;
1718   SDValue Callee                        = CLI.Callee;
1719   bool &isTailCall                      = CLI.IsTailCall;
1720   CallingConv::ID CallConv              = CLI.CallConv;
1721   bool doesNotRet                       = CLI.DoesNotReturn;
1722   bool isVarArg                         = CLI.IsVarArg;
1723 
1724   MachineFunction &MF = DAG.getMachineFunction();
1725   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1726   bool isThisReturn   = false;
1727   bool isSibCall      = false;
1728   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1729 
1730   // Disable tail calls if they're not supported.
1731   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1732     isTailCall = false;
1733 
1734   if (isTailCall) {
1735     // Check if it's really possible to do a tail call.
1736     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1737                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1738                                                    Outs, OutVals, Ins, DAG);
1739     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1740       report_fatal_error("failed to perform tail call elimination on a call "
1741                          "site marked musttail");
1742     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1743     // detected sibcalls.
1744     if (isTailCall) {
1745       ++NumTailCalls;
1746       isSibCall = true;
1747     }
1748   }
1749 
1750   // Analyze operands of the call, assigning locations to each operand.
1751   SmallVector<CCValAssign, 16> ArgLocs;
1752   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1753                  *DAG.getContext());
1754   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1755 
1756   // Get a count of how many bytes are to be pushed on the stack.
1757   unsigned NumBytes = CCInfo.getNextStackOffset();
1758 
1759   // For tail calls, memory operands are available in our caller's stack.
1760   if (isSibCall)
1761     NumBytes = 0;
1762 
1763   // Adjust the stack pointer for the new arguments...
1764   // These operations are automatically eliminated by the prolog/epilog pass
1765   if (!isSibCall)
1766     Chain = DAG.getCALLSEQ_START(Chain,
1767                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1768 
1769   SDValue StackPtr =
1770       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1771 
1772   RegsToPassVector RegsToPass;
1773   SmallVector<SDValue, 8> MemOpChains;
1774 
1775   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1776   // of tail call optimization, arguments are handled later.
1777   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1778        i != e;
1779        ++i, ++realArgIdx) {
1780     CCValAssign &VA = ArgLocs[i];
1781     SDValue Arg = OutVals[realArgIdx];
1782     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1783     bool isByVal = Flags.isByVal();
1784 
1785     // Promote the value if needed.
1786     switch (VA.getLocInfo()) {
1787     default: llvm_unreachable("Unknown loc info!");
1788     case CCValAssign::Full: break;
1789     case CCValAssign::SExt:
1790       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1791       break;
1792     case CCValAssign::ZExt:
1793       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1794       break;
1795     case CCValAssign::AExt:
1796       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1797       break;
1798     case CCValAssign::BCvt:
1799       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1800       break;
1801     }
1802 
1803     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1804     if (VA.needsCustom()) {
1805       if (VA.getLocVT() == MVT::v2f64) {
1806         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1807                                   DAG.getConstant(0, dl, MVT::i32));
1808         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1809                                   DAG.getConstant(1, dl, MVT::i32));
1810 
1811         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1812                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1813 
1814         VA = ArgLocs[++i]; // skip ahead to next loc
1815         if (VA.isRegLoc()) {
1816           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1817                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1818         } else {
1819           assert(VA.isMemLoc());
1820 
1821           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1822                                                  dl, DAG, VA, Flags));
1823         }
1824       } else {
1825         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1826                          StackPtr, MemOpChains, Flags);
1827       }
1828     } else if (VA.isRegLoc()) {
1829       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1830           Outs[0].VT == MVT::i32) {
1831         assert(VA.getLocVT() == MVT::i32 &&
1832                "unexpected calling convention register assignment");
1833         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1834                "unexpected use of 'returned'");
1835         isThisReturn = true;
1836       }
1837       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1838     } else if (isByVal) {
1839       assert(VA.isMemLoc());
1840       unsigned offset = 0;
1841 
1842       // True if this byval aggregate will be split between registers
1843       // and memory.
1844       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1845       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1846 
1847       if (CurByValIdx < ByValArgsCount) {
1848 
1849         unsigned RegBegin, RegEnd;
1850         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1851 
1852         EVT PtrVT =
1853             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1854         unsigned int i, j;
1855         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1856           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1857           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1858           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1859                                      MachinePointerInfo(),
1860                                      DAG.InferPtrAlignment(AddArg));
1861           MemOpChains.push_back(Load.getValue(1));
1862           RegsToPass.push_back(std::make_pair(j, Load));
1863         }
1864 
1865         // If parameter size outsides register area, "offset" value
1866         // helps us to calculate stack slot for remained part properly.
1867         offset = RegEnd - RegBegin;
1868 
1869         CCInfo.nextInRegsParam();
1870       }
1871 
1872       if (Flags.getByValSize() > 4*offset) {
1873         auto PtrVT = getPointerTy(DAG.getDataLayout());
1874         unsigned LocMemOffset = VA.getLocMemOffset();
1875         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1876         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1877         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1878         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1879         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1880                                            MVT::i32);
1881         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1882                                             MVT::i32);
1883 
1884         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1885         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1886         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1887                                           Ops));
1888       }
1889     } else if (!isSibCall) {
1890       assert(VA.isMemLoc());
1891 
1892       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1893                                              dl, DAG, VA, Flags));
1894     }
1895   }
1896 
1897   if (!MemOpChains.empty())
1898     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1899 
1900   // Build a sequence of copy-to-reg nodes chained together with token chain
1901   // and flag operands which copy the outgoing args into the appropriate regs.
1902   SDValue InFlag;
1903   // Tail call byval lowering might overwrite argument registers so in case of
1904   // tail call optimization the copies to registers are lowered later.
1905   if (!isTailCall)
1906     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1907       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1908                                RegsToPass[i].second, InFlag);
1909       InFlag = Chain.getValue(1);
1910     }
1911 
1912   // For tail calls lower the arguments to the 'real' stack slot.
1913   if (isTailCall) {
1914     // Force all the incoming stack arguments to be loaded from the stack
1915     // before any new outgoing arguments are stored to the stack, because the
1916     // outgoing stack slots may alias the incoming argument stack slots, and
1917     // the alias isn't otherwise explicit. This is slightly more conservative
1918     // than necessary, because it means that each store effectively depends
1919     // on every argument instead of just those arguments it would clobber.
1920 
1921     // Do not flag preceding copytoreg stuff together with the following stuff.
1922     InFlag = SDValue();
1923     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1924       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1925                                RegsToPass[i].second, InFlag);
1926       InFlag = Chain.getValue(1);
1927     }
1928     InFlag = SDValue();
1929   }
1930 
1931   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1932   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1933   // node so that legalize doesn't hack it.
1934   bool isDirect = false;
1935 
1936   const TargetMachine &TM = getTargetMachine();
1937   const Module *Mod = MF.getFunction()->getParent();
1938   const GlobalValue *GV = nullptr;
1939   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1940     GV = G->getGlobal();
1941   bool isStub =
1942       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1943 
1944   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1945   bool isLocalARMFunc = false;
1946   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1947   auto PtrVt = getPointerTy(DAG.getDataLayout());
1948 
1949   if (Subtarget->genLongCalls()) {
1950     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1951            "long-calls codegen is not position independent!");
1952     // Handle a global address or an external symbol. If it's not one of
1953     // those, the target's already in a register, so we don't need to do
1954     // anything extra.
1955     if (isa<GlobalAddressSDNode>(Callee)) {
1956       // Create a constant pool entry for the callee address
1957       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1958       ARMConstantPoolValue *CPV =
1959         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1960 
1961       // Get the address of the callee into a register
1962       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1963       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1964       Callee = DAG.getLoad(
1965           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1966           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1967     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1968       const char *Sym = S->getSymbol();
1969 
1970       // Create a constant pool entry for the callee address
1971       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1972       ARMConstantPoolValue *CPV =
1973         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1974                                       ARMPCLabelIndex, 0);
1975       // Get the address of the callee into a register
1976       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1977       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1978       Callee = DAG.getLoad(
1979           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1980           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1981     }
1982   } else if (isa<GlobalAddressSDNode>(Callee)) {
1983     // If we're optimizing for minimum size and the function is called three or
1984     // more times in this block, we can improve codesize by calling indirectly
1985     // as BLXr has a 16-bit encoding.
1986     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1987     auto *BB = CLI.CS->getParent();
1988     bool PreferIndirect =
1989         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
1990         count_if(GV->users(), [&BB](const User *U) {
1991           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
1992         }) > 2;
1993 
1994     if (!PreferIndirect) {
1995       isDirect = true;
1996       bool isDef = GV->isStrongDefinitionForLinker();
1997 
1998       // ARM call to a local ARM function is predicable.
1999       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2000       // tBX takes a register source operand.
2001       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2002         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2003         Callee = DAG.getNode(
2004             ARMISD::WrapperPIC, dl, PtrVt,
2005             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2006         Callee = DAG.getLoad(
2007             PtrVt, dl, DAG.getEntryNode(), Callee,
2008             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2009             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2010                                      MachineMemOperand::MOInvariant);
2011       } else if (Subtarget->isTargetCOFF()) {
2012         assert(Subtarget->isTargetWindows() &&
2013                "Windows is the only supported COFF target");
2014         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2015                                    ? ARMII::MO_DLLIMPORT
2016                                    : ARMII::MO_NO_FLAG;
2017         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2018                                             TargetFlags);
2019         if (GV->hasDLLImportStorageClass())
2020           Callee =
2021               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2022                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2023                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2024       } else {
2025         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2026       }
2027     }
2028   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2029     isDirect = true;
2030     // tBX takes a register source operand.
2031     const char *Sym = S->getSymbol();
2032     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2033       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2034       ARMConstantPoolValue *CPV =
2035         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2036                                       ARMPCLabelIndex, 4);
2037       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2038       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2039       Callee = DAG.getLoad(
2040           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2041           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2042       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2043       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2044     } else {
2045       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2046     }
2047   }
2048 
2049   // FIXME: handle tail calls differently.
2050   unsigned CallOpc;
2051   if (Subtarget->isThumb()) {
2052     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2053       CallOpc = ARMISD::CALL_NOLINK;
2054     else
2055       CallOpc = ARMISD::CALL;
2056   } else {
2057     if (!isDirect && !Subtarget->hasV5TOps())
2058       CallOpc = ARMISD::CALL_NOLINK;
2059     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2060              // Emit regular call when code size is the priority
2061              !MF.getFunction()->optForMinSize())
2062       // "mov lr, pc; b _foo" to avoid confusing the RSP
2063       CallOpc = ARMISD::CALL_NOLINK;
2064     else
2065       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2066   }
2067 
2068   std::vector<SDValue> Ops;
2069   Ops.push_back(Chain);
2070   Ops.push_back(Callee);
2071 
2072   // Add argument registers to the end of the list so that they are known live
2073   // into the call.
2074   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2075     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2076                                   RegsToPass[i].second.getValueType()));
2077 
2078   // Add a register mask operand representing the call-preserved registers.
2079   if (!isTailCall) {
2080     const uint32_t *Mask;
2081     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2082     if (isThisReturn) {
2083       // For 'this' returns, use the R0-preserving mask if applicable
2084       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2085       if (!Mask) {
2086         // Set isThisReturn to false if the calling convention is not one that
2087         // allows 'returned' to be modeled in this way, so LowerCallResult does
2088         // not try to pass 'this' straight through
2089         isThisReturn = false;
2090         Mask = ARI->getCallPreservedMask(MF, CallConv);
2091       }
2092     } else
2093       Mask = ARI->getCallPreservedMask(MF, CallConv);
2094 
2095     assert(Mask && "Missing call preserved mask for calling convention");
2096     Ops.push_back(DAG.getRegisterMask(Mask));
2097   }
2098 
2099   if (InFlag.getNode())
2100     Ops.push_back(InFlag);
2101 
2102   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2103   if (isTailCall) {
2104     MF.getFrameInfo().setHasTailCall();
2105     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2106   }
2107 
2108   // Returns a chain and a flag for retval copy to use.
2109   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2110   InFlag = Chain.getValue(1);
2111 
2112   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2113                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2114   if (!Ins.empty())
2115     InFlag = Chain.getValue(1);
2116 
2117   // Handle result values, copying them out of physregs into vregs that we
2118   // return.
2119   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2120                          InVals, isThisReturn,
2121                          isThisReturn ? OutVals[0] : SDValue());
2122 }
2123 
2124 /// HandleByVal - Every parameter *after* a byval parameter is passed
2125 /// on the stack.  Remember the next parameter register to allocate,
2126 /// and then confiscate the rest of the parameter registers to insure
2127 /// this.
2128 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2129                                     unsigned Align) const {
2130   // Byval (as with any stack) slots are always at least 4 byte aligned.
2131   Align = std::max(Align, 4U);
2132 
2133   unsigned Reg = State->AllocateReg(GPRArgRegs);
2134   if (!Reg)
2135     return;
2136 
2137   unsigned AlignInRegs = Align / 4;
2138   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2139   for (unsigned i = 0; i < Waste; ++i)
2140     Reg = State->AllocateReg(GPRArgRegs);
2141 
2142   if (!Reg)
2143     return;
2144 
2145   unsigned Excess = 4 * (ARM::R4 - Reg);
2146 
2147   // Special case when NSAA != SP and parameter size greater than size of
2148   // all remained GPR regs. In that case we can't split parameter, we must
2149   // send it to stack. We also must set NCRN to R4, so waste all
2150   // remained registers.
2151   const unsigned NSAAOffset = State->getNextStackOffset();
2152   if (NSAAOffset != 0 && Size > Excess) {
2153     while (State->AllocateReg(GPRArgRegs))
2154       ;
2155     return;
2156   }
2157 
2158   // First register for byval parameter is the first register that wasn't
2159   // allocated before this method call, so it would be "reg".
2160   // If parameter is small enough to be saved in range [reg, r4), then
2161   // the end (first after last) register would be reg + param-size-in-regs,
2162   // else parameter would be splitted between registers and stack,
2163   // end register would be r4 in this case.
2164   unsigned ByValRegBegin = Reg;
2165   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2166   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2167   // Note, first register is allocated in the beginning of function already,
2168   // allocate remained amount of registers we need.
2169   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2170     State->AllocateReg(GPRArgRegs);
2171   // A byval parameter that is split between registers and memory needs its
2172   // size truncated here.
2173   // In the case where the entire structure fits in registers, we set the
2174   // size in memory to zero.
2175   Size = std::max<int>(Size - Excess, 0);
2176 }
2177 
2178 /// MatchingStackOffset - Return true if the given stack call argument is
2179 /// already available in the same position (relatively) of the caller's
2180 /// incoming argument stack.
2181 static
2182 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2183                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2184                          const TargetInstrInfo *TII) {
2185   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2186   int FI = std::numeric_limits<int>::max();
2187   if (Arg.getOpcode() == ISD::CopyFromReg) {
2188     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2189     if (!TargetRegisterInfo::isVirtualRegister(VR))
2190       return false;
2191     MachineInstr *Def = MRI->getVRegDef(VR);
2192     if (!Def)
2193       return false;
2194     if (!Flags.isByVal()) {
2195       if (!TII->isLoadFromStackSlot(*Def, FI))
2196         return false;
2197     } else {
2198       return false;
2199     }
2200   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2201     if (Flags.isByVal())
2202       // ByVal argument is passed in as a pointer but it's now being
2203       // dereferenced. e.g.
2204       // define @foo(%struct.X* %A) {
2205       //   tail call @bar(%struct.X* byval %A)
2206       // }
2207       return false;
2208     SDValue Ptr = Ld->getBasePtr();
2209     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2210     if (!FINode)
2211       return false;
2212     FI = FINode->getIndex();
2213   } else
2214     return false;
2215 
2216   assert(FI != std::numeric_limits<int>::max());
2217   if (!MFI.isFixedObjectIndex(FI))
2218     return false;
2219   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2220 }
2221 
2222 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2223 /// for tail call optimization. Targets which want to do tail call
2224 /// optimization should implement this function.
2225 bool
2226 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2227                                                      CallingConv::ID CalleeCC,
2228                                                      bool isVarArg,
2229                                                      bool isCalleeStructRet,
2230                                                      bool isCallerStructRet,
2231                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2232                                     const SmallVectorImpl<SDValue> &OutVals,
2233                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2234                                                      SelectionDAG& DAG) const {
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   const Function *CallerF = MF.getFunction();
2237   CallingConv::ID CallerCC = CallerF->getCallingConv();
2238 
2239   assert(Subtarget->supportsTailCall());
2240 
2241   // Look for obvious safe cases to perform tail call optimization that do not
2242   // require ABI changes. This is what gcc calls sibcall.
2243 
2244   // Exception-handling functions need a special set of instructions to indicate
2245   // a return to the hardware. Tail-calling another function would probably
2246   // break this.
2247   if (CallerF->hasFnAttribute("interrupt"))
2248     return false;
2249 
2250   // Also avoid sibcall optimization if either caller or callee uses struct
2251   // return semantics.
2252   if (isCalleeStructRet || isCallerStructRet)
2253     return false;
2254 
2255   // Externally-defined functions with weak linkage should not be
2256   // tail-called on ARM when the OS does not support dynamic
2257   // pre-emption of symbols, as the AAELF spec requires normal calls
2258   // to undefined weak functions to be replaced with a NOP or jump to the
2259   // next instruction. The behaviour of branch instructions in this
2260   // situation (as used for tail calls) is implementation-defined, so we
2261   // cannot rely on the linker replacing the tail call with a return.
2262   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2263     const GlobalValue *GV = G->getGlobal();
2264     const Triple &TT = getTargetMachine().getTargetTriple();
2265     if (GV->hasExternalWeakLinkage() &&
2266         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2267       return false;
2268   }
2269 
2270   // Check that the call results are passed in the same way.
2271   LLVMContext &C = *DAG.getContext();
2272   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2273                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2274                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2275     return false;
2276   // The callee has to preserve all registers the caller needs to preserve.
2277   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2278   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2279   if (CalleeCC != CallerCC) {
2280     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2281     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2282       return false;
2283   }
2284 
2285   // If Caller's vararg or byval argument has been split between registers and
2286   // stack, do not perform tail call, since part of the argument is in caller's
2287   // local frame.
2288   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2289   if (AFI_Caller->getArgRegsSaveSize())
2290     return false;
2291 
2292   // If the callee takes no arguments then go on to check the results of the
2293   // call.
2294   if (!Outs.empty()) {
2295     // Check if stack adjustment is needed. For now, do not do this if any
2296     // argument is passed on the stack.
2297     SmallVector<CCValAssign, 16> ArgLocs;
2298     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2299     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2300     if (CCInfo.getNextStackOffset()) {
2301       // Check if the arguments are already laid out in the right way as
2302       // the caller's fixed stack objects.
2303       MachineFrameInfo &MFI = MF.getFrameInfo();
2304       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2305       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2306       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2307            i != e;
2308            ++i, ++realArgIdx) {
2309         CCValAssign &VA = ArgLocs[i];
2310         EVT RegVT = VA.getLocVT();
2311         SDValue Arg = OutVals[realArgIdx];
2312         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2313         if (VA.getLocInfo() == CCValAssign::Indirect)
2314           return false;
2315         if (VA.needsCustom()) {
2316           // f64 and vector types are split into multiple registers or
2317           // register/stack-slot combinations.  The types will not match
2318           // the registers; give up on memory f64 refs until we figure
2319           // out what to do about this.
2320           if (!VA.isRegLoc())
2321             return false;
2322           if (!ArgLocs[++i].isRegLoc())
2323             return false;
2324           if (RegVT == MVT::v2f64) {
2325             if (!ArgLocs[++i].isRegLoc())
2326               return false;
2327             if (!ArgLocs[++i].isRegLoc())
2328               return false;
2329           }
2330         } else if (!VA.isRegLoc()) {
2331           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2332                                    MFI, MRI, TII))
2333             return false;
2334         }
2335       }
2336     }
2337 
2338     const MachineRegisterInfo &MRI = MF.getRegInfo();
2339     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2340       return false;
2341   }
2342 
2343   return true;
2344 }
2345 
2346 bool
2347 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2348                                   MachineFunction &MF, bool isVarArg,
2349                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2350                                   LLVMContext &Context) const {
2351   SmallVector<CCValAssign, 16> RVLocs;
2352   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2353   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2354 }
2355 
2356 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2357                                     const SDLoc &DL, SelectionDAG &DAG) {
2358   const MachineFunction &MF = DAG.getMachineFunction();
2359   const Function *F = MF.getFunction();
2360 
2361   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2362 
2363   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2364   // version of the "preferred return address". These offsets affect the return
2365   // instruction if this is a return from PL1 without hypervisor extensions.
2366   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2367   //    SWI:     0      "subs pc, lr, #0"
2368   //    ABORT:   +4     "subs pc, lr, #4"
2369   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2370   // UNDEF varies depending on where the exception came from ARM or Thumb
2371   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2372 
2373   int64_t LROffset;
2374   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2375       IntKind == "ABORT")
2376     LROffset = 4;
2377   else if (IntKind == "SWI" || IntKind == "UNDEF")
2378     LROffset = 0;
2379   else
2380     report_fatal_error("Unsupported interrupt attribute. If present, value "
2381                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2382 
2383   RetOps.insert(RetOps.begin() + 1,
2384                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2385 
2386   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2387 }
2388 
2389 SDValue
2390 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2391                                bool isVarArg,
2392                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2393                                const SmallVectorImpl<SDValue> &OutVals,
2394                                const SDLoc &dl, SelectionDAG &DAG) const {
2395 
2396   // CCValAssign - represent the assignment of the return value to a location.
2397   SmallVector<CCValAssign, 16> RVLocs;
2398 
2399   // CCState - Info about the registers and stack slots.
2400   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2401                  *DAG.getContext());
2402 
2403   // Analyze outgoing return values.
2404   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2405 
2406   SDValue Flag;
2407   SmallVector<SDValue, 4> RetOps;
2408   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2409   bool isLittleEndian = Subtarget->isLittle();
2410 
2411   MachineFunction &MF = DAG.getMachineFunction();
2412   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2413   AFI->setReturnRegsCount(RVLocs.size());
2414 
2415   // Copy the result values into the output registers.
2416   for (unsigned i = 0, realRVLocIdx = 0;
2417        i != RVLocs.size();
2418        ++i, ++realRVLocIdx) {
2419     CCValAssign &VA = RVLocs[i];
2420     assert(VA.isRegLoc() && "Can only return in registers!");
2421 
2422     SDValue Arg = OutVals[realRVLocIdx];
2423 
2424     switch (VA.getLocInfo()) {
2425     default: llvm_unreachable("Unknown loc info!");
2426     case CCValAssign::Full: break;
2427     case CCValAssign::BCvt:
2428       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2429       break;
2430     }
2431 
2432     if (VA.needsCustom()) {
2433       if (VA.getLocVT() == MVT::v2f64) {
2434         // Extract the first half and return it in two registers.
2435         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2436                                    DAG.getConstant(0, dl, MVT::i32));
2437         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2438                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2439 
2440         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2441                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2442                                  Flag);
2443         Flag = Chain.getValue(1);
2444         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2445         VA = RVLocs[++i]; // skip ahead to next loc
2446         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2447                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2448                                  Flag);
2449         Flag = Chain.getValue(1);
2450         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2451         VA = RVLocs[++i]; // skip ahead to next loc
2452 
2453         // Extract the 2nd half and fall through to handle it as an f64 value.
2454         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2455                           DAG.getConstant(1, dl, MVT::i32));
2456       }
2457       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2458       // available.
2459       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2460                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2461       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2462                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2463                                Flag);
2464       Flag = Chain.getValue(1);
2465       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2466       VA = RVLocs[++i]; // skip ahead to next loc
2467       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2468                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2469                                Flag);
2470     } else
2471       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2472 
2473     // Guarantee that all emitted copies are
2474     // stuck together, avoiding something bad.
2475     Flag = Chain.getValue(1);
2476     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2477   }
2478   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2479   const MCPhysReg *I =
2480       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2481   if (I) {
2482     for (; *I; ++I) {
2483       if (ARM::GPRRegClass.contains(*I))
2484         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2485       else if (ARM::DPRRegClass.contains(*I))
2486         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2487       else
2488         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2489     }
2490   }
2491 
2492   // Update chain and glue.
2493   RetOps[0] = Chain;
2494   if (Flag.getNode())
2495     RetOps.push_back(Flag);
2496 
2497   // CPUs which aren't M-class use a special sequence to return from
2498   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2499   // though we use "subs pc, lr, #N").
2500   //
2501   // M-class CPUs actually use a normal return sequence with a special
2502   // (hardware-provided) value in LR, so the normal code path works.
2503   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2504       !Subtarget->isMClass()) {
2505     if (Subtarget->isThumb1Only())
2506       report_fatal_error("interrupt attribute is not supported in Thumb1");
2507     return LowerInterruptReturn(RetOps, dl, DAG);
2508   }
2509 
2510   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2511 }
2512 
2513 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2514   if (N->getNumValues() != 1)
2515     return false;
2516   if (!N->hasNUsesOfValue(1, 0))
2517     return false;
2518 
2519   SDValue TCChain = Chain;
2520   SDNode *Copy = *N->use_begin();
2521   if (Copy->getOpcode() == ISD::CopyToReg) {
2522     // If the copy has a glue operand, we conservatively assume it isn't safe to
2523     // perform a tail call.
2524     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2525       return false;
2526     TCChain = Copy->getOperand(0);
2527   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2528     SDNode *VMov = Copy;
2529     // f64 returned in a pair of GPRs.
2530     SmallPtrSet<SDNode*, 2> Copies;
2531     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2532          UI != UE; ++UI) {
2533       if (UI->getOpcode() != ISD::CopyToReg)
2534         return false;
2535       Copies.insert(*UI);
2536     }
2537     if (Copies.size() > 2)
2538       return false;
2539 
2540     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2541          UI != UE; ++UI) {
2542       SDValue UseChain = UI->getOperand(0);
2543       if (Copies.count(UseChain.getNode()))
2544         // Second CopyToReg
2545         Copy = *UI;
2546       else {
2547         // We are at the top of this chain.
2548         // If the copy has a glue operand, we conservatively assume it
2549         // isn't safe to perform a tail call.
2550         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2551           return false;
2552         // First CopyToReg
2553         TCChain = UseChain;
2554       }
2555     }
2556   } else if (Copy->getOpcode() == ISD::BITCAST) {
2557     // f32 returned in a single GPR.
2558     if (!Copy->hasOneUse())
2559       return false;
2560     Copy = *Copy->use_begin();
2561     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2562       return false;
2563     // If the copy has a glue operand, we conservatively assume it isn't safe to
2564     // perform a tail call.
2565     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2566       return false;
2567     TCChain = Copy->getOperand(0);
2568   } else {
2569     return false;
2570   }
2571 
2572   bool HasRet = false;
2573   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2574        UI != UE; ++UI) {
2575     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2576         UI->getOpcode() != ARMISD::INTRET_FLAG)
2577       return false;
2578     HasRet = true;
2579   }
2580 
2581   if (!HasRet)
2582     return false;
2583 
2584   Chain = TCChain;
2585   return true;
2586 }
2587 
2588 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2589   if (!Subtarget->supportsTailCall())
2590     return false;
2591 
2592   auto Attr =
2593       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2594   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2595     return false;
2596 
2597   return true;
2598 }
2599 
2600 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2601 // and pass the lower and high parts through.
2602 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2603   SDLoc DL(Op);
2604   SDValue WriteValue = Op->getOperand(2);
2605 
2606   // This function is only supposed to be called for i64 type argument.
2607   assert(WriteValue.getValueType() == MVT::i64
2608           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2609 
2610   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2611                            DAG.getConstant(0, DL, MVT::i32));
2612   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2613                            DAG.getConstant(1, DL, MVT::i32));
2614   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2615   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2616 }
2617 
2618 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2619 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2620 // one of the above mentioned nodes. It has to be wrapped because otherwise
2621 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2622 // be used to form addressing mode. These wrapped nodes will be selected
2623 // into MOVi.
2624 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2625   EVT PtrVT = Op.getValueType();
2626   // FIXME there is no actual debug info here
2627   SDLoc dl(Op);
2628   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2629   SDValue Res;
2630   if (CP->isMachineConstantPoolEntry())
2631     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2632                                     CP->getAlignment());
2633   else
2634     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2635                                     CP->getAlignment());
2636   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2637 }
2638 
2639 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2640   return MachineJumpTableInfo::EK_Inline;
2641 }
2642 
2643 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2644                                              SelectionDAG &DAG) const {
2645   MachineFunction &MF = DAG.getMachineFunction();
2646   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2647   unsigned ARMPCLabelIndex = 0;
2648   SDLoc DL(Op);
2649   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2650   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2651   SDValue CPAddr;
2652   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2653   if (!IsPositionIndependent) {
2654     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2655   } else {
2656     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2657     ARMPCLabelIndex = AFI->createPICLabelUId();
2658     ARMConstantPoolValue *CPV =
2659       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2660                                       ARMCP::CPBlockAddress, PCAdj);
2661     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2662   }
2663   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2664   SDValue Result = DAG.getLoad(
2665       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2666       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2667   if (!IsPositionIndependent)
2668     return Result;
2669   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2670   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2671 }
2672 
2673 /// \brief Convert a TLS address reference into the correct sequence of loads
2674 /// and calls to compute the variable's address for Darwin, and return an
2675 /// SDValue containing the final node.
2676 
2677 /// Darwin only has one TLS scheme which must be capable of dealing with the
2678 /// fully general situation, in the worst case. This means:
2679 ///     + "extern __thread" declaration.
2680 ///     + Defined in a possibly unknown dynamic library.
2681 ///
2682 /// The general system is that each __thread variable has a [3 x i32] descriptor
2683 /// which contains information used by the runtime to calculate the address. The
2684 /// only part of this the compiler needs to know about is the first word, which
2685 /// contains a function pointer that must be called with the address of the
2686 /// entire descriptor in "r0".
2687 ///
2688 /// Since this descriptor may be in a different unit, in general access must
2689 /// proceed along the usual ARM rules. A common sequence to produce is:
2690 ///
2691 ///     movw rT1, :lower16:_var$non_lazy_ptr
2692 ///     movt rT1, :upper16:_var$non_lazy_ptr
2693 ///     ldr r0, [rT1]
2694 ///     ldr rT2, [r0]
2695 ///     blx rT2
2696 ///     [...address now in r0...]
2697 SDValue
2698 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2699                                                SelectionDAG &DAG) const {
2700   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2701   SDLoc DL(Op);
2702 
2703   // First step is to get the address of the actua global symbol. This is where
2704   // the TLS descriptor lives.
2705   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2706 
2707   // The first entry in the descriptor is a function pointer that we must call
2708   // to obtain the address of the variable.
2709   SDValue Chain = DAG.getEntryNode();
2710   SDValue FuncTLVGet = DAG.getLoad(
2711       MVT::i32, DL, Chain, DescAddr,
2712       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2713       /* Alignment = */ 4,
2714       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2715           MachineMemOperand::MOInvariant);
2716   Chain = FuncTLVGet.getValue(1);
2717 
2718   MachineFunction &F = DAG.getMachineFunction();
2719   MachineFrameInfo &MFI = F.getFrameInfo();
2720   MFI.setAdjustsStack(true);
2721 
2722   // TLS calls preserve all registers except those that absolutely must be
2723   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2724   // silly).
2725   auto TRI =
2726       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2727   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2728   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2729 
2730   // Finally, we can make the call. This is just a degenerate version of a
2731   // normal AArch64 call node: r0 takes the address of the descriptor, and
2732   // returns the address of the variable in this thread.
2733   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2734   Chain =
2735       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2736                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2737                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2738   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2739 }
2740 
2741 SDValue
2742 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2743                                                 SelectionDAG &DAG) const {
2744   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2745 
2746   SDValue Chain = DAG.getEntryNode();
2747   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2748   SDLoc DL(Op);
2749 
2750   // Load the current TEB (thread environment block)
2751   SDValue Ops[] = {Chain,
2752                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2753                    DAG.getConstant(15, DL, MVT::i32),
2754                    DAG.getConstant(0, DL, MVT::i32),
2755                    DAG.getConstant(13, DL, MVT::i32),
2756                    DAG.getConstant(0, DL, MVT::i32),
2757                    DAG.getConstant(2, DL, MVT::i32)};
2758   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2759                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2760 
2761   SDValue TEB = CurrentTEB.getValue(0);
2762   Chain = CurrentTEB.getValue(1);
2763 
2764   // Load the ThreadLocalStoragePointer from the TEB
2765   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2766   SDValue TLSArray =
2767       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2768   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2769 
2770   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2771   // offset into the TLSArray.
2772 
2773   // Load the TLS index from the C runtime
2774   SDValue TLSIndex =
2775       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2776   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2777   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2778 
2779   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2780                               DAG.getConstant(2, DL, MVT::i32));
2781   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2782                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2783                             MachinePointerInfo());
2784 
2785   // Get the offset of the start of the .tls section (section base)
2786   const auto *GA = cast<GlobalAddressSDNode>(Op);
2787   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2788   SDValue Offset = DAG.getLoad(
2789       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2790                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2791       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2792 
2793   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2794 }
2795 
2796 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2797 SDValue
2798 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2799                                                  SelectionDAG &DAG) const {
2800   SDLoc dl(GA);
2801   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2802   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2803   MachineFunction &MF = DAG.getMachineFunction();
2804   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2805   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2806   ARMConstantPoolValue *CPV =
2807     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2808                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2809   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2810   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2811   Argument = DAG.getLoad(
2812       PtrVT, dl, DAG.getEntryNode(), Argument,
2813       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2814   SDValue Chain = Argument.getValue(1);
2815 
2816   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2817   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2818 
2819   // call __tls_get_addr.
2820   ArgListTy Args;
2821   ArgListEntry Entry;
2822   Entry.Node = Argument;
2823   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2824   Args.push_back(Entry);
2825 
2826   // FIXME: is there useful debug info available here?
2827   TargetLowering::CallLoweringInfo CLI(DAG);
2828   CLI.setDebugLoc(dl).setChain(Chain)
2829     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2830                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2831 
2832   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2833   return CallResult.first;
2834 }
2835 
2836 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2837 // "local exec" model.
2838 SDValue
2839 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2840                                         SelectionDAG &DAG,
2841                                         TLSModel::Model model) const {
2842   const GlobalValue *GV = GA->getGlobal();
2843   SDLoc dl(GA);
2844   SDValue Offset;
2845   SDValue Chain = DAG.getEntryNode();
2846   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2847   // Get the Thread Pointer
2848   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2849 
2850   if (model == TLSModel::InitialExec) {
2851     MachineFunction &MF = DAG.getMachineFunction();
2852     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2853     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2854     // Initial exec model.
2855     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2856     ARMConstantPoolValue *CPV =
2857       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2858                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2859                                       true);
2860     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2861     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2862     Offset = DAG.getLoad(
2863         PtrVT, dl, Chain, Offset,
2864         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2865     Chain = Offset.getValue(1);
2866 
2867     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2868     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2869 
2870     Offset = DAG.getLoad(
2871         PtrVT, dl, Chain, Offset,
2872         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2873   } else {
2874     // local exec model
2875     assert(model == TLSModel::LocalExec);
2876     ARMConstantPoolValue *CPV =
2877       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2878     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2879     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2880     Offset = DAG.getLoad(
2881         PtrVT, dl, Chain, Offset,
2882         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2883   }
2884 
2885   // The address of the thread local variable is the add of the thread
2886   // pointer with the offset of the variable.
2887   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2888 }
2889 
2890 SDValue
2891 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2892   if (Subtarget->isTargetDarwin())
2893     return LowerGlobalTLSAddressDarwin(Op, DAG);
2894 
2895   if (Subtarget->isTargetWindows())
2896     return LowerGlobalTLSAddressWindows(Op, DAG);
2897 
2898   // TODO: implement the "local dynamic" model
2899   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2900   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2901   if (DAG.getTarget().Options.EmulatedTLS)
2902     return LowerToTLSEmulatedModel(GA, DAG);
2903 
2904   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2905 
2906   switch (model) {
2907     case TLSModel::GeneralDynamic:
2908     case TLSModel::LocalDynamic:
2909       return LowerToTLSGeneralDynamicModel(GA, DAG);
2910     case TLSModel::InitialExec:
2911     case TLSModel::LocalExec:
2912       return LowerToTLSExecModels(GA, DAG, model);
2913   }
2914   llvm_unreachable("bogus TLS model");
2915 }
2916 
2917 /// Return true if all users of V are within function F, looking through
2918 /// ConstantExprs.
2919 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2920   SmallVector<const User*,4> Worklist;
2921   for (auto *U : V->users())
2922     Worklist.push_back(U);
2923   while (!Worklist.empty()) {
2924     auto *U = Worklist.pop_back_val();
2925     if (isa<ConstantExpr>(U)) {
2926       for (auto *UU : U->users())
2927         Worklist.push_back(UU);
2928       continue;
2929     }
2930 
2931     auto *I = dyn_cast<Instruction>(U);
2932     if (!I || I->getParent()->getParent() != F)
2933       return false;
2934   }
2935   return true;
2936 }
2937 
2938 /// Return true if all users of V are within some (any) function, looking through
2939 /// ConstantExprs. In other words, are there any global constant users?
2940 static bool allUsersAreInFunctions(const Value *V) {
2941   SmallVector<const User*,4> Worklist;
2942   for (auto *U : V->users())
2943     Worklist.push_back(U);
2944   while (!Worklist.empty()) {
2945     auto *U = Worklist.pop_back_val();
2946     if (isa<ConstantExpr>(U)) {
2947       for (auto *UU : U->users())
2948         Worklist.push_back(UU);
2949       continue;
2950     }
2951 
2952     if (!isa<Instruction>(U))
2953       return false;
2954   }
2955   return true;
2956 }
2957 
2958 // Return true if T is an integer, float or an array/vector of either.
2959 static bool isSimpleType(Type *T) {
2960   if (T->isIntegerTy() || T->isFloatingPointTy())
2961     return true;
2962   Type *SubT = nullptr;
2963   if (T->isArrayTy())
2964     SubT = T->getArrayElementType();
2965   else if (T->isVectorTy())
2966     SubT = T->getVectorElementType();
2967   else
2968     return false;
2969   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
2970 }
2971 
2972 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
2973                                      EVT PtrVT, const SDLoc &dl) {
2974   // If we're creating a pool entry for a constant global with unnamed address,
2975   // and the global is small enough, we can emit it inline into the constant pool
2976   // to save ourselves an indirection.
2977   //
2978   // This is a win if the constant is only used in one function (so it doesn't
2979   // need to be duplicated) or duplicating the constant wouldn't increase code
2980   // size (implying the constant is no larger than 4 bytes).
2981   const Function *F = DAG.getMachineFunction().getFunction();
2982 
2983   // We rely on this decision to inline being idemopotent and unrelated to the
2984   // use-site. We know that if we inline a variable at one use site, we'll
2985   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
2986   // doesn't know about this optimization, so bail out if it's enabled else
2987   // we could decide to inline here (and thus never emit the GV) but require
2988   // the GV from fast-isel generated code.
2989   if (!EnableConstpoolPromotion ||
2990       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
2991       return SDValue();
2992 
2993   auto *GVar = dyn_cast<GlobalVariable>(GV);
2994   if (!GVar || !GVar->hasInitializer() ||
2995       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
2996       !GVar->hasLocalLinkage())
2997     return SDValue();
2998 
2999   // Ensure that we don't try and inline any type that contains pointers. If
3000   // we inline a value that contains relocations, we move the relocations from
3001   // .data to .text which is not ideal.
3002   auto *Init = GVar->getInitializer();
3003   if (!isSimpleType(Init->getType()))
3004     return SDValue();
3005 
3006   // The constant islands pass can only really deal with alignment requests
3007   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3008   // any type wanting greater alignment requirements than 4 bytes. We also
3009   // can only promote constants that are multiples of 4 bytes in size or
3010   // are paddable to a multiple of 4. Currently we only try and pad constants
3011   // that are strings for simplicity.
3012   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3013   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3014   unsigned Align = GVar->getAlignment();
3015   unsigned RequiredPadding = 4 - (Size % 4);
3016   bool PaddingPossible =
3017     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3018   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize)
3019     return SDValue();
3020 
3021   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3022   MachineFunction &MF = DAG.getMachineFunction();
3023   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3024 
3025   // We can't bloat the constant pool too much, else the ConstantIslands pass
3026   // may fail to converge. If we haven't promoted this global yet (it may have
3027   // multiple uses), and promoting it would increase the constant pool size (Sz
3028   // > 4), ensure we have space to do so up to MaxTotal.
3029   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3030     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3031         ConstpoolPromotionMaxTotal)
3032       return SDValue();
3033 
3034   // This is only valid if all users are in a single function OR it has users
3035   // in multiple functions but it no larger than a pointer. We also check if
3036   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3037   // address taken.
3038   if (!allUsersAreInFunction(GVar, F) &&
3039       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3040     return SDValue();
3041 
3042   // We're going to inline this global. Pad it out if needed.
3043   if (RequiredPadding != 4) {
3044     StringRef S = CDAInit->getAsString();
3045 
3046     SmallVector<uint8_t,16> V(S.size());
3047     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3048     while (RequiredPadding--)
3049       V.push_back(0);
3050     Init = ConstantDataArray::get(*DAG.getContext(), V);
3051   }
3052 
3053   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3054   SDValue CPAddr =
3055     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3056   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3057     AFI->markGlobalAsPromotedToConstantPool(GVar);
3058     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3059                                       PaddedSize - 4);
3060   }
3061   ++NumConstpoolPromoted;
3062   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3063 }
3064 
3065 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3066                                                  SelectionDAG &DAG) const {
3067   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3068   SDLoc dl(Op);
3069   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3070   const TargetMachine &TM = getTargetMachine();
3071   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3072     GV = GA->getBaseObject();
3073   bool IsRO =
3074       (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3075       isa<Function>(GV);
3076 
3077   // promoteToConstantPool only if not generating XO text section
3078   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3079     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3080       return V;
3081 
3082   if (isPositionIndependent()) {
3083     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3084 
3085     MachineFunction &MF = DAG.getMachineFunction();
3086     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3087     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3088     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3089     SDLoc dl(Op);
3090     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3091     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3092         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3093         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3094         /*AddCurrentAddress=*/UseGOT_PREL);
3095     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3096     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3097     SDValue Result = DAG.getLoad(
3098         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3099         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3100     SDValue Chain = Result.getValue(1);
3101     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3102     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3103     if (UseGOT_PREL)
3104       Result =
3105           DAG.getLoad(PtrVT, dl, Chain, Result,
3106                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3107     return Result;
3108   } else if (Subtarget->isROPI() && IsRO) {
3109     // PC-relative.
3110     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3111     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3112     return Result;
3113   } else if (Subtarget->isRWPI() && !IsRO) {
3114     // SB-relative.
3115     SDValue RelAddr;
3116     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3117       ++NumMovwMovt;
3118       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3119       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3120     } else { // use literal pool for address constant
3121       ARMConstantPoolValue *CPV =
3122         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3123       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3124       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3125       RelAddr = DAG.getLoad(
3126           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3127           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3128     }
3129     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3130     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3131     return Result;
3132   }
3133 
3134   // If we have T2 ops, we can materialize the address directly via movt/movw
3135   // pair. This is always cheaper.
3136   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3137     ++NumMovwMovt;
3138     // FIXME: Once remat is capable of dealing with instructions with register
3139     // operands, expand this into two nodes.
3140     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3141                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3142   } else {
3143     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3144     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3145     return DAG.getLoad(
3146         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3147         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3148   }
3149 }
3150 
3151 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3152                                                     SelectionDAG &DAG) const {
3153   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3154          "ROPI/RWPI not currently supported for Darwin");
3155   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3156   SDLoc dl(Op);
3157   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3158 
3159   if (Subtarget->useMovt(DAG.getMachineFunction()))
3160     ++NumMovwMovt;
3161 
3162   // FIXME: Once remat is capable of dealing with instructions with register
3163   // operands, expand this into multiple nodes
3164   unsigned Wrapper =
3165       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3166 
3167   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3168   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3169 
3170   if (Subtarget->isGVIndirectSymbol(GV))
3171     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3172                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3173   return Result;
3174 }
3175 
3176 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3177                                                      SelectionDAG &DAG) const {
3178   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3179   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3180          "Windows on ARM expects to use movw/movt");
3181   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3182          "ROPI/RWPI not currently supported for Windows");
3183 
3184   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3185   const ARMII::TOF TargetFlags =
3186     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3187   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3188   SDValue Result;
3189   SDLoc DL(Op);
3190 
3191   ++NumMovwMovt;
3192 
3193   // FIXME: Once remat is capable of dealing with instructions with register
3194   // operands, expand this into two nodes.
3195   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3196                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3197                                                   TargetFlags));
3198   if (GV->hasDLLImportStorageClass())
3199     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3200                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3201   return Result;
3202 }
3203 
3204 SDValue
3205 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3206   SDLoc dl(Op);
3207   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3208   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3209                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3210                      Op.getOperand(1), Val);
3211 }
3212 
3213 SDValue
3214 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3215   SDLoc dl(Op);
3216   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3217                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3218 }
3219 
3220 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3221                                                       SelectionDAG &DAG) const {
3222   SDLoc dl(Op);
3223   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3224                      Op.getOperand(0));
3225 }
3226 
3227 SDValue
3228 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3229                                           const ARMSubtarget *Subtarget) const {
3230   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3231   SDLoc dl(Op);
3232   switch (IntNo) {
3233   default: return SDValue();    // Don't custom lower most intrinsics.
3234   case Intrinsic::thread_pointer: {
3235     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3236     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3237   }
3238   case Intrinsic::eh_sjlj_lsda: {
3239     MachineFunction &MF = DAG.getMachineFunction();
3240     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3241     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3242     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3243     SDValue CPAddr;
3244     bool IsPositionIndependent = isPositionIndependent();
3245     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3246     ARMConstantPoolValue *CPV =
3247       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3248                                       ARMCP::CPLSDA, PCAdj);
3249     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3250     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3251     SDValue Result = DAG.getLoad(
3252         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3253         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3254 
3255     if (IsPositionIndependent) {
3256       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3257       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3258     }
3259     return Result;
3260   }
3261   case Intrinsic::arm_neon_vmulls:
3262   case Intrinsic::arm_neon_vmullu: {
3263     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3264       ? ARMISD::VMULLs : ARMISD::VMULLu;
3265     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3266                        Op.getOperand(1), Op.getOperand(2));
3267   }
3268   case Intrinsic::arm_neon_vminnm:
3269   case Intrinsic::arm_neon_vmaxnm: {
3270     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3271       ? ISD::FMINNUM : ISD::FMAXNUM;
3272     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3273                        Op.getOperand(1), Op.getOperand(2));
3274   }
3275   case Intrinsic::arm_neon_vminu:
3276   case Intrinsic::arm_neon_vmaxu: {
3277     if (Op.getValueType().isFloatingPoint())
3278       return SDValue();
3279     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3280       ? ISD::UMIN : ISD::UMAX;
3281     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3282                          Op.getOperand(1), Op.getOperand(2));
3283   }
3284   case Intrinsic::arm_neon_vmins:
3285   case Intrinsic::arm_neon_vmaxs: {
3286     // v{min,max}s is overloaded between signed integers and floats.
3287     if (!Op.getValueType().isFloatingPoint()) {
3288       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3289         ? ISD::SMIN : ISD::SMAX;
3290       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3291                          Op.getOperand(1), Op.getOperand(2));
3292     }
3293     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3294       ? ISD::FMINNAN : ISD::FMAXNAN;
3295     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3296                        Op.getOperand(1), Op.getOperand(2));
3297   }
3298   }
3299 }
3300 
3301 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3302                                  const ARMSubtarget *Subtarget) {
3303   // FIXME: handle "fence singlethread" more efficiently.
3304   SDLoc dl(Op);
3305   if (!Subtarget->hasDataBarrier()) {
3306     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3307     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3308     // here.
3309     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3310            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3311     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3312                        DAG.getConstant(0, dl, MVT::i32));
3313   }
3314 
3315   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3316   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3317   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3318   if (Subtarget->isMClass()) {
3319     // Only a full system barrier exists in the M-class architectures.
3320     Domain = ARM_MB::SY;
3321   } else if (Subtarget->preferISHSTBarriers() &&
3322              Ord == AtomicOrdering::Release) {
3323     // Swift happens to implement ISHST barriers in a way that's compatible with
3324     // Release semantics but weaker than ISH so we'd be fools not to use
3325     // it. Beware: other processors probably don't!
3326     Domain = ARM_MB::ISHST;
3327   }
3328 
3329   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3330                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3331                      DAG.getConstant(Domain, dl, MVT::i32));
3332 }
3333 
3334 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3335                              const ARMSubtarget *Subtarget) {
3336   // ARM pre v5TE and Thumb1 does not have preload instructions.
3337   if (!(Subtarget->isThumb2() ||
3338         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3339     // Just preserve the chain.
3340     return Op.getOperand(0);
3341 
3342   SDLoc dl(Op);
3343   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3344   if (!isRead &&
3345       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3346     // ARMv7 with MP extension has PLDW.
3347     return Op.getOperand(0);
3348 
3349   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3350   if (Subtarget->isThumb()) {
3351     // Invert the bits.
3352     isRead = ~isRead & 1;
3353     isData = ~isData & 1;
3354   }
3355 
3356   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3357                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3358                      DAG.getConstant(isData, dl, MVT::i32));
3359 }
3360 
3361 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3362   MachineFunction &MF = DAG.getMachineFunction();
3363   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3364 
3365   // vastart just stores the address of the VarArgsFrameIndex slot into the
3366   // memory location argument.
3367   SDLoc dl(Op);
3368   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3369   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3370   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3371   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3372                       MachinePointerInfo(SV));
3373 }
3374 
3375 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3376                                                 CCValAssign &NextVA,
3377                                                 SDValue &Root,
3378                                                 SelectionDAG &DAG,
3379                                                 const SDLoc &dl) const {
3380   MachineFunction &MF = DAG.getMachineFunction();
3381   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3382 
3383   const TargetRegisterClass *RC;
3384   if (AFI->isThumb1OnlyFunction())
3385     RC = &ARM::tGPRRegClass;
3386   else
3387     RC = &ARM::GPRRegClass;
3388 
3389   // Transform the arguments stored in physical registers into virtual ones.
3390   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3391   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3392 
3393   SDValue ArgValue2;
3394   if (NextVA.isMemLoc()) {
3395     MachineFrameInfo &MFI = MF.getFrameInfo();
3396     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3397 
3398     // Create load node to retrieve arguments from the stack.
3399     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3400     ArgValue2 = DAG.getLoad(
3401         MVT::i32, dl, Root, FIN,
3402         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3403   } else {
3404     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3405     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3406   }
3407   if (!Subtarget->isLittle())
3408     std::swap (ArgValue, ArgValue2);
3409   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3410 }
3411 
3412 // The remaining GPRs hold either the beginning of variable-argument
3413 // data, or the beginning of an aggregate passed by value (usually
3414 // byval).  Either way, we allocate stack slots adjacent to the data
3415 // provided by our caller, and store the unallocated registers there.
3416 // If this is a variadic function, the va_list pointer will begin with
3417 // these values; otherwise, this reassembles a (byval) structure that
3418 // was split between registers and memory.
3419 // Return: The frame index registers were stored into.
3420 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3421                                       const SDLoc &dl, SDValue &Chain,
3422                                       const Value *OrigArg,
3423                                       unsigned InRegsParamRecordIdx,
3424                                       int ArgOffset, unsigned ArgSize) const {
3425   // Currently, two use-cases possible:
3426   // Case #1. Non-var-args function, and we meet first byval parameter.
3427   //          Setup first unallocated register as first byval register;
3428   //          eat all remained registers
3429   //          (these two actions are performed by HandleByVal method).
3430   //          Then, here, we initialize stack frame with
3431   //          "store-reg" instructions.
3432   // Case #2. Var-args function, that doesn't contain byval parameters.
3433   //          The same: eat all remained unallocated registers,
3434   //          initialize stack frame.
3435 
3436   MachineFunction &MF = DAG.getMachineFunction();
3437   MachineFrameInfo &MFI = MF.getFrameInfo();
3438   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3439   unsigned RBegin, REnd;
3440   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3441     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3442   } else {
3443     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3444     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3445     REnd = ARM::R4;
3446   }
3447 
3448   if (REnd != RBegin)
3449     ArgOffset = -4 * (ARM::R4 - RBegin);
3450 
3451   auto PtrVT = getPointerTy(DAG.getDataLayout());
3452   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3453   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3454 
3455   SmallVector<SDValue, 4> MemOps;
3456   const TargetRegisterClass *RC =
3457       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3458 
3459   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3460     unsigned VReg = MF.addLiveIn(Reg, RC);
3461     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3462     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3463                                  MachinePointerInfo(OrigArg, 4 * i));
3464     MemOps.push_back(Store);
3465     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3466   }
3467 
3468   if (!MemOps.empty())
3469     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3470   return FrameIndex;
3471 }
3472 
3473 // Setup stack frame, the va_list pointer will start from.
3474 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3475                                              const SDLoc &dl, SDValue &Chain,
3476                                              unsigned ArgOffset,
3477                                              unsigned TotalArgRegsSaveSize,
3478                                              bool ForceMutable) const {
3479   MachineFunction &MF = DAG.getMachineFunction();
3480   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3481 
3482   // Try to store any remaining integer argument regs
3483   // to their spots on the stack so that they may be loaded by dereferencing
3484   // the result of va_next.
3485   // If there is no regs to be stored, just point address after last
3486   // argument passed via stack.
3487   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3488                                   CCInfo.getInRegsParamsCount(),
3489                                   CCInfo.getNextStackOffset(), 4);
3490   AFI->setVarArgsFrameIndex(FrameIndex);
3491 }
3492 
3493 SDValue ARMTargetLowering::LowerFormalArguments(
3494     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3495     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3496     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3497   MachineFunction &MF = DAG.getMachineFunction();
3498   MachineFrameInfo &MFI = MF.getFrameInfo();
3499 
3500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3501 
3502   // Assign locations to all of the incoming arguments.
3503   SmallVector<CCValAssign, 16> ArgLocs;
3504   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3505                  *DAG.getContext());
3506   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3507 
3508   SmallVector<SDValue, 16> ArgValues;
3509   SDValue ArgValue;
3510   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3511   unsigned CurArgIdx = 0;
3512 
3513   // Initially ArgRegsSaveSize is zero.
3514   // Then we increase this value each time we meet byval parameter.
3515   // We also increase this value in case of varargs function.
3516   AFI->setArgRegsSaveSize(0);
3517 
3518   // Calculate the amount of stack space that we need to allocate to store
3519   // byval and variadic arguments that are passed in registers.
3520   // We need to know this before we allocate the first byval or variadic
3521   // argument, as they will be allocated a stack slot below the CFA (Canonical
3522   // Frame Address, the stack pointer at entry to the function).
3523   unsigned ArgRegBegin = ARM::R4;
3524   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3525     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3526       break;
3527 
3528     CCValAssign &VA = ArgLocs[i];
3529     unsigned Index = VA.getValNo();
3530     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3531     if (!Flags.isByVal())
3532       continue;
3533 
3534     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3535     unsigned RBegin, REnd;
3536     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3537     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3538 
3539     CCInfo.nextInRegsParam();
3540   }
3541   CCInfo.rewindByValRegsInfo();
3542 
3543   int lastInsIndex = -1;
3544   if (isVarArg && MFI.hasVAStart()) {
3545     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3546     if (RegIdx != array_lengthof(GPRArgRegs))
3547       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3548   }
3549 
3550   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3551   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3552   auto PtrVT = getPointerTy(DAG.getDataLayout());
3553 
3554   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3555     CCValAssign &VA = ArgLocs[i];
3556     if (Ins[VA.getValNo()].isOrigArg()) {
3557       std::advance(CurOrigArg,
3558                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3559       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3560     }
3561     // Arguments stored in registers.
3562     if (VA.isRegLoc()) {
3563       EVT RegVT = VA.getLocVT();
3564 
3565       if (VA.needsCustom()) {
3566         // f64 and vector types are split up into multiple registers or
3567         // combinations of registers and stack slots.
3568         if (VA.getLocVT() == MVT::v2f64) {
3569           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3570                                                    Chain, DAG, dl);
3571           VA = ArgLocs[++i]; // skip ahead to next loc
3572           SDValue ArgValue2;
3573           if (VA.isMemLoc()) {
3574             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3575             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3576             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3577                                     MachinePointerInfo::getFixedStack(
3578                                         DAG.getMachineFunction(), FI));
3579           } else {
3580             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3581                                              Chain, DAG, dl);
3582           }
3583           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3584           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3585                                  ArgValue, ArgValue1,
3586                                  DAG.getIntPtrConstant(0, dl));
3587           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3588                                  ArgValue, ArgValue2,
3589                                  DAG.getIntPtrConstant(1, dl));
3590         } else
3591           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3592 
3593       } else {
3594         const TargetRegisterClass *RC;
3595 
3596         if (RegVT == MVT::f32)
3597           RC = &ARM::SPRRegClass;
3598         else if (RegVT == MVT::f64)
3599           RC = &ARM::DPRRegClass;
3600         else if (RegVT == MVT::v2f64)
3601           RC = &ARM::QPRRegClass;
3602         else if (RegVT == MVT::i32)
3603           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3604                                            : &ARM::GPRRegClass;
3605         else
3606           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3607 
3608         // Transform the arguments in physical registers into virtual ones.
3609         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3610         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3611       }
3612 
3613       // If this is an 8 or 16-bit value, it is really passed promoted
3614       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3615       // truncate to the right size.
3616       switch (VA.getLocInfo()) {
3617       default: llvm_unreachable("Unknown loc info!");
3618       case CCValAssign::Full: break;
3619       case CCValAssign::BCvt:
3620         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3621         break;
3622       case CCValAssign::SExt:
3623         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3624                                DAG.getValueType(VA.getValVT()));
3625         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3626         break;
3627       case CCValAssign::ZExt:
3628         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3629                                DAG.getValueType(VA.getValVT()));
3630         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3631         break;
3632       }
3633 
3634       InVals.push_back(ArgValue);
3635 
3636     } else { // VA.isRegLoc()
3637       // sanity check
3638       assert(VA.isMemLoc());
3639       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3640 
3641       int index = VA.getValNo();
3642 
3643       // Some Ins[] entries become multiple ArgLoc[] entries.
3644       // Process them only once.
3645       if (index != lastInsIndex)
3646         {
3647           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3648           // FIXME: For now, all byval parameter objects are marked mutable.
3649           // This can be changed with more analysis.
3650           // In case of tail call optimization mark all arguments mutable.
3651           // Since they could be overwritten by lowering of arguments in case of
3652           // a tail call.
3653           if (Flags.isByVal()) {
3654             assert(Ins[index].isOrigArg() &&
3655                    "Byval arguments cannot be implicit");
3656             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3657 
3658             int FrameIndex = StoreByValRegs(
3659                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3660                 VA.getLocMemOffset(), Flags.getByValSize());
3661             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3662             CCInfo.nextInRegsParam();
3663           } else {
3664             unsigned FIOffset = VA.getLocMemOffset();
3665             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3666                                            FIOffset, true);
3667 
3668             // Create load nodes to retrieve arguments from the stack.
3669             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3670             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3671                                          MachinePointerInfo::getFixedStack(
3672                                              DAG.getMachineFunction(), FI)));
3673           }
3674           lastInsIndex = index;
3675         }
3676     }
3677   }
3678 
3679   // varargs
3680   if (isVarArg && MFI.hasVAStart())
3681     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3682                          CCInfo.getNextStackOffset(),
3683                          TotalArgRegsSaveSize);
3684 
3685   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3686 
3687   return Chain;
3688 }
3689 
3690 /// isFloatingPointZero - Return true if this is +0.0.
3691 static bool isFloatingPointZero(SDValue Op) {
3692   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3693     return CFP->getValueAPF().isPosZero();
3694   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3695     // Maybe this has already been legalized into the constant pool?
3696     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3697       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3698       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3699         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3700           return CFP->getValueAPF().isPosZero();
3701     }
3702   } else if (Op->getOpcode() == ISD::BITCAST &&
3703              Op->getValueType(0) == MVT::f64) {
3704     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3705     // created by LowerConstantFP().
3706     SDValue BitcastOp = Op->getOperand(0);
3707     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3708         isNullConstant(BitcastOp->getOperand(0)))
3709       return true;
3710   }
3711   return false;
3712 }
3713 
3714 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3715 /// the given operands.
3716 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3717                                      SDValue &ARMcc, SelectionDAG &DAG,
3718                                      const SDLoc &dl) const {
3719   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3720     unsigned C = RHSC->getZExtValue();
3721     if (!isLegalICmpImmediate(C)) {
3722       // Constant does not fit, try adjusting it by one?
3723       switch (CC) {
3724       default: break;
3725       case ISD::SETLT:
3726       case ISD::SETGE:
3727         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3728           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3729           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3730         }
3731         break;
3732       case ISD::SETULT:
3733       case ISD::SETUGE:
3734         if (C != 0 && isLegalICmpImmediate(C-1)) {
3735           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3736           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3737         }
3738         break;
3739       case ISD::SETLE:
3740       case ISD::SETGT:
3741         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3742           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3743           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3744         }
3745         break;
3746       case ISD::SETULE:
3747       case ISD::SETUGT:
3748         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3749           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3750           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3751         }
3752         break;
3753       }
3754     }
3755   }
3756 
3757   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3758   ARMISD::NodeType CompareType;
3759   switch (CondCode) {
3760   default:
3761     CompareType = ARMISD::CMP;
3762     break;
3763   case ARMCC::EQ:
3764   case ARMCC::NE:
3765     // Uses only Z Flag
3766     CompareType = ARMISD::CMPZ;
3767     break;
3768   }
3769   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3770   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3771 }
3772 
3773 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3774 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3775                                      SelectionDAG &DAG, const SDLoc &dl) const {
3776   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3777   SDValue Cmp;
3778   if (!isFloatingPointZero(RHS))
3779     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3780   else
3781     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3782   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3783 }
3784 
3785 /// duplicateCmp - Glue values can have only one use, so this function
3786 /// duplicates a comparison node.
3787 SDValue
3788 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3789   unsigned Opc = Cmp.getOpcode();
3790   SDLoc DL(Cmp);
3791   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3792     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3793 
3794   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3795   Cmp = Cmp.getOperand(0);
3796   Opc = Cmp.getOpcode();
3797   if (Opc == ARMISD::CMPFP)
3798     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3799   else {
3800     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3801     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3802   }
3803   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3804 }
3805 
3806 std::pair<SDValue, SDValue>
3807 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3808                                  SDValue &ARMcc) const {
3809   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3810 
3811   SDValue Value, OverflowCmp;
3812   SDValue LHS = Op.getOperand(0);
3813   SDValue RHS = Op.getOperand(1);
3814   SDLoc dl(Op);
3815 
3816   // FIXME: We are currently always generating CMPs because we don't support
3817   // generating CMN through the backend. This is not as good as the natural
3818   // CMP case because it causes a register dependency and cannot be folded
3819   // later.
3820 
3821   switch (Op.getOpcode()) {
3822   default:
3823     llvm_unreachable("Unknown overflow instruction!");
3824   case ISD::SADDO:
3825     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3826     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3827     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3828     break;
3829   case ISD::UADDO:
3830     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3831     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3832     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3833     break;
3834   case ISD::SSUBO:
3835     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3836     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3837     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3838     break;
3839   case ISD::USUBO:
3840     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3841     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3842     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3843     break;
3844   } // switch (...)
3845 
3846   return std::make_pair(Value, OverflowCmp);
3847 }
3848 
3849 SDValue
3850 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3851   // Let legalize expand this if it isn't a legal type yet.
3852   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3853     return SDValue();
3854 
3855   SDValue Value, OverflowCmp;
3856   SDValue ARMcc;
3857   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3858   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3859   SDLoc dl(Op);
3860   // We use 0 and 1 as false and true values.
3861   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3862   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3863   EVT VT = Op.getValueType();
3864 
3865   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3866                                  ARMcc, CCR, OverflowCmp);
3867 
3868   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3869   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3870 }
3871 
3872 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3873   SDValue Cond = Op.getOperand(0);
3874   SDValue SelectTrue = Op.getOperand(1);
3875   SDValue SelectFalse = Op.getOperand(2);
3876   SDLoc dl(Op);
3877   unsigned Opc = Cond.getOpcode();
3878 
3879   if (Cond.getResNo() == 1 &&
3880       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3881        Opc == ISD::USUBO)) {
3882     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3883       return SDValue();
3884 
3885     SDValue Value, OverflowCmp;
3886     SDValue ARMcc;
3887     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3888     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3889     EVT VT = Op.getValueType();
3890 
3891     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3892                    OverflowCmp, DAG);
3893   }
3894 
3895   // Convert:
3896   //
3897   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3898   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3899   //
3900   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3901     const ConstantSDNode *CMOVTrue =
3902       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3903     const ConstantSDNode *CMOVFalse =
3904       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3905 
3906     if (CMOVTrue && CMOVFalse) {
3907       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3908       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3909 
3910       SDValue True;
3911       SDValue False;
3912       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3913         True = SelectTrue;
3914         False = SelectFalse;
3915       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3916         True = SelectFalse;
3917         False = SelectTrue;
3918       }
3919 
3920       if (True.getNode() && False.getNode()) {
3921         EVT VT = Op.getValueType();
3922         SDValue ARMcc = Cond.getOperand(2);
3923         SDValue CCR = Cond.getOperand(3);
3924         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3925         assert(True.getValueType() == VT);
3926         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3927       }
3928     }
3929   }
3930 
3931   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3932   // undefined bits before doing a full-word comparison with zero.
3933   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3934                      DAG.getConstant(1, dl, Cond.getValueType()));
3935 
3936   return DAG.getSelectCC(dl, Cond,
3937                          DAG.getConstant(0, dl, Cond.getValueType()),
3938                          SelectTrue, SelectFalse, ISD::SETNE);
3939 }
3940 
3941 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3942                                  bool &swpCmpOps, bool &swpVselOps) {
3943   // Start by selecting the GE condition code for opcodes that return true for
3944   // 'equality'
3945   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3946       CC == ISD::SETULE)
3947     CondCode = ARMCC::GE;
3948 
3949   // and GT for opcodes that return false for 'equality'.
3950   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3951            CC == ISD::SETULT)
3952     CondCode = ARMCC::GT;
3953 
3954   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3955   // to swap the compare operands.
3956   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3957       CC == ISD::SETULT)
3958     swpCmpOps = true;
3959 
3960   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3961   // If we have an unordered opcode, we need to swap the operands to the VSEL
3962   // instruction (effectively negating the condition).
3963   //
3964   // This also has the effect of swapping which one of 'less' or 'greater'
3965   // returns true, so we also swap the compare operands. It also switches
3966   // whether we return true for 'equality', so we compensate by picking the
3967   // opposite condition code to our original choice.
3968   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3969       CC == ISD::SETUGT) {
3970     swpCmpOps = !swpCmpOps;
3971     swpVselOps = !swpVselOps;
3972     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3973   }
3974 
3975   // 'ordered' is 'anything but unordered', so use the VS condition code and
3976   // swap the VSEL operands.
3977   if (CC == ISD::SETO) {
3978     CondCode = ARMCC::VS;
3979     swpVselOps = true;
3980   }
3981 
3982   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3983   // code and swap the VSEL operands.
3984   if (CC == ISD::SETUNE) {
3985     CondCode = ARMCC::EQ;
3986     swpVselOps = true;
3987   }
3988 }
3989 
3990 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
3991                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3992                                    SDValue Cmp, SelectionDAG &DAG) const {
3993   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3994     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3995                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3996     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3997                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3998 
3999     SDValue TrueLow = TrueVal.getValue(0);
4000     SDValue TrueHigh = TrueVal.getValue(1);
4001     SDValue FalseLow = FalseVal.getValue(0);
4002     SDValue FalseHigh = FalseVal.getValue(1);
4003 
4004     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4005                               ARMcc, CCR, Cmp);
4006     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4007                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4008 
4009     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4010   } else {
4011     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4012                        Cmp);
4013   }
4014 }
4015 
4016 static bool isGTorGE(ISD::CondCode CC) {
4017   return CC == ISD::SETGT || CC == ISD::SETGE;
4018 }
4019 
4020 static bool isLTorLE(ISD::CondCode CC) {
4021   return CC == ISD::SETLT || CC == ISD::SETLE;
4022 }
4023 
4024 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4025 // All of these conditions (and their <= and >= counterparts) will do:
4026 //          x < k ? k : x
4027 //          x > k ? x : k
4028 //          k < x ? x : k
4029 //          k > x ? k : x
4030 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4031                             const SDValue TrueVal, const SDValue FalseVal,
4032                             const ISD::CondCode CC, const SDValue K) {
4033   return (isGTorGE(CC) &&
4034           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4035          (isLTorLE(CC) &&
4036           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4037 }
4038 
4039 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4040 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4041                             const SDValue TrueVal, const SDValue FalseVal,
4042                             const ISD::CondCode CC, const SDValue K) {
4043   return (isGTorGE(CC) &&
4044           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4045          (isLTorLE(CC) &&
4046           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4047 }
4048 
4049 // Check if two chained conditionals could be converted into SSAT.
4050 //
4051 // SSAT can replace a set of two conditional selectors that bound a number to an
4052 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4053 //
4054 //     x < -k ? -k : (x > k ? k : x)
4055 //     x < -k ? -k : (x < k ? x : k)
4056 //     x > -k ? (x > k ? k : x) : -k
4057 //     x < k ? (x < -k ? -k : x) : k
4058 //     etc.
4059 //
4060 // It returns true if the conversion can be done, false otherwise.
4061 // Additionally, the variable is returned in parameter V and the constant in K.
4062 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4063                                     uint64_t &K) {
4064   SDValue LHS1 = Op.getOperand(0);
4065   SDValue RHS1 = Op.getOperand(1);
4066   SDValue TrueVal1 = Op.getOperand(2);
4067   SDValue FalseVal1 = Op.getOperand(3);
4068   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4069 
4070   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4071   if (Op2.getOpcode() != ISD::SELECT_CC)
4072     return false;
4073 
4074   SDValue LHS2 = Op2.getOperand(0);
4075   SDValue RHS2 = Op2.getOperand(1);
4076   SDValue TrueVal2 = Op2.getOperand(2);
4077   SDValue FalseVal2 = Op2.getOperand(3);
4078   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4079 
4080   // Find out which are the constants and which are the variables
4081   // in each conditional
4082   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4083                                                         ? &RHS1
4084                                                         : nullptr;
4085   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4086                                                         ? &RHS2
4087                                                         : nullptr;
4088   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4089   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4090   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4091   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4092 
4093   // We must detect cases where the original operations worked with 16- or
4094   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4095   // must work with sign-extended values but the select operations return
4096   // the original non-extended value.
4097   SDValue V2TmpReg = V2Tmp;
4098   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4099     V2TmpReg = V2Tmp->getOperand(0);
4100 
4101   // Check that the registers and the constants have the correct values
4102   // in both conditionals
4103   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4104       V2TmpReg != V2)
4105     return false;
4106 
4107   // Figure out which conditional is saturating the lower/upper bound.
4108   const SDValue *LowerCheckOp =
4109       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4110           ? &Op
4111           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4112                 ? &Op2
4113                 : nullptr;
4114   const SDValue *UpperCheckOp =
4115       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4116           ? &Op
4117           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4118                 ? &Op2
4119                 : nullptr;
4120 
4121   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4122     return false;
4123 
4124   // Check that the constant in the lower-bound check is
4125   // the opposite of the constant in the upper-bound check
4126   // in 1's complement.
4127   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4128   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4129   int64_t PosVal = std::max(Val1, Val2);
4130 
4131   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4132        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4133       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4134 
4135     V = V2;
4136     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4137     return true;
4138   }
4139 
4140   return false;
4141 }
4142 
4143 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4144   EVT VT = Op.getValueType();
4145   SDLoc dl(Op);
4146 
4147   // Try to convert two saturating conditional selects into a single SSAT
4148   SDValue SatValue;
4149   uint64_t SatConstant;
4150   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4151       isSaturatingConditional(Op, SatValue, SatConstant))
4152     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4153                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4154 
4155   SDValue LHS = Op.getOperand(0);
4156   SDValue RHS = Op.getOperand(1);
4157   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4158   SDValue TrueVal = Op.getOperand(2);
4159   SDValue FalseVal = Op.getOperand(3);
4160 
4161   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4162     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4163                                                     dl);
4164 
4165     // If softenSetCCOperands only returned one value, we should compare it to
4166     // zero.
4167     if (!RHS.getNode()) {
4168       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4169       CC = ISD::SETNE;
4170     }
4171   }
4172 
4173   if (LHS.getValueType() == MVT::i32) {
4174     // Try to generate VSEL on ARMv8.
4175     // The VSEL instruction can't use all the usual ARM condition
4176     // codes: it only has two bits to select the condition code, so it's
4177     // constrained to use only GE, GT, VS and EQ.
4178     //
4179     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4180     // swap the operands of the previous compare instruction (effectively
4181     // inverting the compare condition, swapping 'less' and 'greater') and
4182     // sometimes need to swap the operands to the VSEL (which inverts the
4183     // condition in the sense of firing whenever the previous condition didn't)
4184     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4185                                     TrueVal.getValueType() == MVT::f64)) {
4186       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4187       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4188           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4189         CC = ISD::getSetCCInverse(CC, true);
4190         std::swap(TrueVal, FalseVal);
4191       }
4192     }
4193 
4194     SDValue ARMcc;
4195     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4196     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4197     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4198   }
4199 
4200   ARMCC::CondCodes CondCode, CondCode2;
4201   FPCCToARMCC(CC, CondCode, CondCode2);
4202 
4203   // Try to generate VMAXNM/VMINNM on ARMv8.
4204   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4205                                   TrueVal.getValueType() == MVT::f64)) {
4206     bool swpCmpOps = false;
4207     bool swpVselOps = false;
4208     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4209 
4210     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4211         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4212       if (swpCmpOps)
4213         std::swap(LHS, RHS);
4214       if (swpVselOps)
4215         std::swap(TrueVal, FalseVal);
4216     }
4217   }
4218 
4219   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4220   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4221   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4222   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4223   if (CondCode2 != ARMCC::AL) {
4224     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4225     // FIXME: Needs another CMP because flag can have but one use.
4226     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
4227     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4228   }
4229   return Result;
4230 }
4231 
4232 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4233 /// to morph to an integer compare sequence.
4234 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4235                            const ARMSubtarget *Subtarget) {
4236   SDNode *N = Op.getNode();
4237   if (!N->hasOneUse())
4238     // Otherwise it requires moving the value from fp to integer registers.
4239     return false;
4240   if (!N->getNumValues())
4241     return false;
4242   EVT VT = Op.getValueType();
4243   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4244     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4245     // vmrs are very slow, e.g. cortex-a8.
4246     return false;
4247 
4248   if (isFloatingPointZero(Op)) {
4249     SeenZero = true;
4250     return true;
4251   }
4252   return ISD::isNormalLoad(N);
4253 }
4254 
4255 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4256   if (isFloatingPointZero(Op))
4257     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4258 
4259   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4260     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4261                        Ld->getPointerInfo(), Ld->getAlignment(),
4262                        Ld->getMemOperand()->getFlags());
4263 
4264   llvm_unreachable("Unknown VFP cmp argument!");
4265 }
4266 
4267 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4268                            SDValue &RetVal1, SDValue &RetVal2) {
4269   SDLoc dl(Op);
4270 
4271   if (isFloatingPointZero(Op)) {
4272     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4273     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4274     return;
4275   }
4276 
4277   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4278     SDValue Ptr = Ld->getBasePtr();
4279     RetVal1 =
4280         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4281                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4282 
4283     EVT PtrType = Ptr.getValueType();
4284     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4285     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4286                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4287     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4288                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4289                           Ld->getMemOperand()->getFlags());
4290     return;
4291   }
4292 
4293   llvm_unreachable("Unknown VFP cmp argument!");
4294 }
4295 
4296 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4297 /// f32 and even f64 comparisons to integer ones.
4298 SDValue
4299 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4300   SDValue Chain = Op.getOperand(0);
4301   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4302   SDValue LHS = Op.getOperand(2);
4303   SDValue RHS = Op.getOperand(3);
4304   SDValue Dest = Op.getOperand(4);
4305   SDLoc dl(Op);
4306 
4307   bool LHSSeenZero = false;
4308   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4309   bool RHSSeenZero = false;
4310   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4311   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4312     // If unsafe fp math optimization is enabled and there are no other uses of
4313     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4314     // to an integer comparison.
4315     if (CC == ISD::SETOEQ)
4316       CC = ISD::SETEQ;
4317     else if (CC == ISD::SETUNE)
4318       CC = ISD::SETNE;
4319 
4320     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4321     SDValue ARMcc;
4322     if (LHS.getValueType() == MVT::f32) {
4323       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4324                         bitcastf32Toi32(LHS, DAG), Mask);
4325       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4326                         bitcastf32Toi32(RHS, DAG), Mask);
4327       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4328       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4329       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4330                          Chain, Dest, ARMcc, CCR, Cmp);
4331     }
4332 
4333     SDValue LHS1, LHS2;
4334     SDValue RHS1, RHS2;
4335     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4336     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4337     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4338     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4339     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4340     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4341     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4342     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4343     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4344   }
4345 
4346   return SDValue();
4347 }
4348 
4349 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4350   SDValue Chain = Op.getOperand(0);
4351   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4352   SDValue LHS = Op.getOperand(2);
4353   SDValue RHS = Op.getOperand(3);
4354   SDValue Dest = Op.getOperand(4);
4355   SDLoc dl(Op);
4356 
4357   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4358     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4359                                                     dl);
4360 
4361     // If softenSetCCOperands only returned one value, we should compare it to
4362     // zero.
4363     if (!RHS.getNode()) {
4364       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4365       CC = ISD::SETNE;
4366     }
4367   }
4368 
4369   if (LHS.getValueType() == MVT::i32) {
4370     SDValue ARMcc;
4371     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4372     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4373     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4374                        Chain, Dest, ARMcc, CCR, Cmp);
4375   }
4376 
4377   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4378 
4379   if (getTargetMachine().Options.UnsafeFPMath &&
4380       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4381        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4382     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4383       return Result;
4384   }
4385 
4386   ARMCC::CondCodes CondCode, CondCode2;
4387   FPCCToARMCC(CC, CondCode, CondCode2);
4388 
4389   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4390   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4391   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4392   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4393   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4394   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4395   if (CondCode2 != ARMCC::AL) {
4396     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4397     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4398     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4399   }
4400   return Res;
4401 }
4402 
4403 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4404   SDValue Chain = Op.getOperand(0);
4405   SDValue Table = Op.getOperand(1);
4406   SDValue Index = Op.getOperand(2);
4407   SDLoc dl(Op);
4408 
4409   EVT PTy = getPointerTy(DAG.getDataLayout());
4410   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4411   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4412   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4413   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4414   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4415   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4416     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4417     // which does another jump to the destination. This also makes it easier
4418     // to translate it to TBB / TBH later (Thumb2 only).
4419     // FIXME: This might not work if the function is extremely large.
4420     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4421                        Addr, Op.getOperand(2), JTI);
4422   }
4423   if (isPositionIndependent() || Subtarget->isROPI()) {
4424     Addr =
4425         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4426                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4427     Chain = Addr.getValue(1);
4428     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4429     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4430   } else {
4431     Addr =
4432         DAG.getLoad(PTy, dl, Chain, Addr,
4433                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4434     Chain = Addr.getValue(1);
4435     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4436   }
4437 }
4438 
4439 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4440   EVT VT = Op.getValueType();
4441   SDLoc dl(Op);
4442 
4443   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4444     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4445       return Op;
4446     return DAG.UnrollVectorOp(Op.getNode());
4447   }
4448 
4449   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4450          "Invalid type for custom lowering!");
4451   if (VT != MVT::v4i16)
4452     return DAG.UnrollVectorOp(Op.getNode());
4453 
4454   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4455   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4456 }
4457 
4458 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4459   EVT VT = Op.getValueType();
4460   if (VT.isVector())
4461     return LowerVectorFP_TO_INT(Op, DAG);
4462   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4463     RTLIB::Libcall LC;
4464     if (Op.getOpcode() == ISD::FP_TO_SINT)
4465       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4466                               Op.getValueType());
4467     else
4468       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4469                               Op.getValueType());
4470     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4471                        /*isSigned*/ false, SDLoc(Op)).first;
4472   }
4473 
4474   return Op;
4475 }
4476 
4477 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4478   EVT VT = Op.getValueType();
4479   SDLoc dl(Op);
4480 
4481   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4482     if (VT.getVectorElementType() == MVT::f32)
4483       return Op;
4484     return DAG.UnrollVectorOp(Op.getNode());
4485   }
4486 
4487   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4488          "Invalid type for custom lowering!");
4489   if (VT != MVT::v4f32)
4490     return DAG.UnrollVectorOp(Op.getNode());
4491 
4492   unsigned CastOpc;
4493   unsigned Opc;
4494   switch (Op.getOpcode()) {
4495   default: llvm_unreachable("Invalid opcode!");
4496   case ISD::SINT_TO_FP:
4497     CastOpc = ISD::SIGN_EXTEND;
4498     Opc = ISD::SINT_TO_FP;
4499     break;
4500   case ISD::UINT_TO_FP:
4501     CastOpc = ISD::ZERO_EXTEND;
4502     Opc = ISD::UINT_TO_FP;
4503     break;
4504   }
4505 
4506   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4507   return DAG.getNode(Opc, dl, VT, Op);
4508 }
4509 
4510 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4511   EVT VT = Op.getValueType();
4512   if (VT.isVector())
4513     return LowerVectorINT_TO_FP(Op, DAG);
4514   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4515     RTLIB::Libcall LC;
4516     if (Op.getOpcode() == ISD::SINT_TO_FP)
4517       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4518                               Op.getValueType());
4519     else
4520       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4521                               Op.getValueType());
4522     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4523                        /*isSigned*/ false, SDLoc(Op)).first;
4524   }
4525 
4526   return Op;
4527 }
4528 
4529 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4530   // Implement fcopysign with a fabs and a conditional fneg.
4531   SDValue Tmp0 = Op.getOperand(0);
4532   SDValue Tmp1 = Op.getOperand(1);
4533   SDLoc dl(Op);
4534   EVT VT = Op.getValueType();
4535   EVT SrcVT = Tmp1.getValueType();
4536   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4537     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4538   bool UseNEON = !InGPR && Subtarget->hasNEON();
4539 
4540   if (UseNEON) {
4541     // Use VBSL to copy the sign bit.
4542     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4543     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4544                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4545     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4546     if (VT == MVT::f64)
4547       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4548                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4549                          DAG.getConstant(32, dl, MVT::i32));
4550     else /*if (VT == MVT::f32)*/
4551       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4552     if (SrcVT == MVT::f32) {
4553       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4554       if (VT == MVT::f64)
4555         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4556                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4557                            DAG.getConstant(32, dl, MVT::i32));
4558     } else if (VT == MVT::f32)
4559       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4560                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4561                          DAG.getConstant(32, dl, MVT::i32));
4562     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4563     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4564 
4565     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4566                                             dl, MVT::i32);
4567     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4568     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4569                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4570 
4571     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4572                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4573                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4574     if (VT == MVT::f32) {
4575       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4576       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4577                         DAG.getConstant(0, dl, MVT::i32));
4578     } else {
4579       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4580     }
4581 
4582     return Res;
4583   }
4584 
4585   // Bitcast operand 1 to i32.
4586   if (SrcVT == MVT::f64)
4587     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4588                        Tmp1).getValue(1);
4589   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4590 
4591   // Or in the signbit with integer operations.
4592   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4593   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4594   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4595   if (VT == MVT::f32) {
4596     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4597                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4598     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4599                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4600   }
4601 
4602   // f64: Or the high part with signbit and then combine two parts.
4603   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4604                      Tmp0);
4605   SDValue Lo = Tmp0.getValue(0);
4606   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4607   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4608   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4609 }
4610 
4611 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4612   MachineFunction &MF = DAG.getMachineFunction();
4613   MachineFrameInfo &MFI = MF.getFrameInfo();
4614   MFI.setReturnAddressIsTaken(true);
4615 
4616   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4617     return SDValue();
4618 
4619   EVT VT = Op.getValueType();
4620   SDLoc dl(Op);
4621   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4622   if (Depth) {
4623     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4624     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4625     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4626                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4627                        MachinePointerInfo());
4628   }
4629 
4630   // Return LR, which contains the return address. Mark it an implicit live-in.
4631   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4632   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4633 }
4634 
4635 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4636   const ARMBaseRegisterInfo &ARI =
4637     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4638   MachineFunction &MF = DAG.getMachineFunction();
4639   MachineFrameInfo &MFI = MF.getFrameInfo();
4640   MFI.setFrameAddressIsTaken(true);
4641 
4642   EVT VT = Op.getValueType();
4643   SDLoc dl(Op);  // FIXME probably not meaningful
4644   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4645   unsigned FrameReg = ARI.getFrameRegister(MF);
4646   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4647   while (Depth--)
4648     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4649                             MachinePointerInfo());
4650   return FrameAddr;
4651 }
4652 
4653 // FIXME? Maybe this could be a TableGen attribute on some registers and
4654 // this table could be generated automatically from RegInfo.
4655 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4656                                               SelectionDAG &DAG) const {
4657   unsigned Reg = StringSwitch<unsigned>(RegName)
4658                        .Case("sp", ARM::SP)
4659                        .Default(0);
4660   if (Reg)
4661     return Reg;
4662   report_fatal_error(Twine("Invalid register name \""
4663                               + StringRef(RegName)  + "\"."));
4664 }
4665 
4666 // Result is 64 bit value so split into two 32 bit values and return as a
4667 // pair of values.
4668 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4669                                 SelectionDAG &DAG) {
4670   SDLoc DL(N);
4671 
4672   // This function is only supposed to be called for i64 type destination.
4673   assert(N->getValueType(0) == MVT::i64
4674           && "ExpandREAD_REGISTER called for non-i64 type result.");
4675 
4676   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4677                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4678                              N->getOperand(0),
4679                              N->getOperand(1));
4680 
4681   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4682                     Read.getValue(1)));
4683   Results.push_back(Read.getOperand(0));
4684 }
4685 
4686 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4687 /// When \p DstVT, the destination type of \p BC, is on the vector
4688 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4689 /// it might be possible to combine them, such that everything stays on the
4690 /// vector register bank.
4691 /// \p return The node that would replace \p BT, if the combine
4692 /// is possible.
4693 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4694                                                 SelectionDAG &DAG) {
4695   SDValue Op = BC->getOperand(0);
4696   EVT DstVT = BC->getValueType(0);
4697 
4698   // The only vector instruction that can produce a scalar (remember,
4699   // since the bitcast was about to be turned into VMOVDRR, the source
4700   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4701   // Moreover, we can do this combine only if there is one use.
4702   // Finally, if the destination type is not a vector, there is not
4703   // much point on forcing everything on the vector bank.
4704   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4705       !Op.hasOneUse())
4706     return SDValue();
4707 
4708   // If the index is not constant, we will introduce an additional
4709   // multiply that will stick.
4710   // Give up in that case.
4711   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4712   if (!Index)
4713     return SDValue();
4714   unsigned DstNumElt = DstVT.getVectorNumElements();
4715 
4716   // Compute the new index.
4717   const APInt &APIntIndex = Index->getAPIntValue();
4718   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4719   NewIndex *= APIntIndex;
4720   // Check if the new constant index fits into i32.
4721   if (NewIndex.getBitWidth() > 32)
4722     return SDValue();
4723 
4724   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4725   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4726   SDLoc dl(Op);
4727   SDValue ExtractSrc = Op.getOperand(0);
4728   EVT VecVT = EVT::getVectorVT(
4729       *DAG.getContext(), DstVT.getScalarType(),
4730       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4731   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4732   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4733                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4734 }
4735 
4736 /// ExpandBITCAST - If the target supports VFP, this function is called to
4737 /// expand a bit convert where either the source or destination type is i64 to
4738 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4739 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4740 /// vectors), since the legalizer won't know what to do with that.
4741 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4743   SDLoc dl(N);
4744   SDValue Op = N->getOperand(0);
4745 
4746   // This function is only supposed to be called for i64 types, either as the
4747   // source or destination of the bit convert.
4748   EVT SrcVT = Op.getValueType();
4749   EVT DstVT = N->getValueType(0);
4750   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4751          "ExpandBITCAST called for non-i64 type");
4752 
4753   // Turn i64->f64 into VMOVDRR.
4754   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4755     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4756     // if we can combine the bitcast with its source.
4757     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4758       return Val;
4759 
4760     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4761                              DAG.getConstant(0, dl, MVT::i32));
4762     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4763                              DAG.getConstant(1, dl, MVT::i32));
4764     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4765                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4766   }
4767 
4768   // Turn f64->i64 into VMOVRRD.
4769   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4770     SDValue Cvt;
4771     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4772         SrcVT.getVectorNumElements() > 1)
4773       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4774                         DAG.getVTList(MVT::i32, MVT::i32),
4775                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4776     else
4777       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4778                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4779     // Merge the pieces into a single i64 value.
4780     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4781   }
4782 
4783   return SDValue();
4784 }
4785 
4786 /// getZeroVector - Returns a vector of specified type with all zero elements.
4787 /// Zero vectors are used to represent vector negation and in those cases
4788 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4789 /// not support i64 elements, so sometimes the zero vectors will need to be
4790 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4791 /// zero vector.
4792 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4793   assert(VT.isVector() && "Expected a vector type");
4794   // The canonical modified immediate encoding of a zero vector is....0!
4795   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4796   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4797   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4798   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4799 }
4800 
4801 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4802 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4803 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4804                                                 SelectionDAG &DAG) const {
4805   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4806   EVT VT = Op.getValueType();
4807   unsigned VTBits = VT.getSizeInBits();
4808   SDLoc dl(Op);
4809   SDValue ShOpLo = Op.getOperand(0);
4810   SDValue ShOpHi = Op.getOperand(1);
4811   SDValue ShAmt  = Op.getOperand(2);
4812   SDValue ARMcc;
4813   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4814   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4815 
4816   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4817 
4818   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4819                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4820   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4821   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4822                                    DAG.getConstant(VTBits, dl, MVT::i32));
4823   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4824   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4825   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4826   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4827                             ISD::SETGE, ARMcc, DAG, dl);
4828   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4829                            ARMcc, CCR, CmpLo);
4830 
4831 
4832   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4833   SDValue HiBigShift = Opc == ISD::SRA
4834                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
4835                                          DAG.getConstant(VTBits - 1, dl, VT))
4836                            : DAG.getConstant(0, dl, VT);
4837   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4838                             ISD::SETGE, ARMcc, DAG, dl);
4839   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4840                            ARMcc, CCR, CmpHi);
4841 
4842   SDValue Ops[2] = { Lo, Hi };
4843   return DAG.getMergeValues(Ops, dl);
4844 }
4845 
4846 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4847 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4848 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4849                                                SelectionDAG &DAG) const {
4850   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4851   EVT VT = Op.getValueType();
4852   unsigned VTBits = VT.getSizeInBits();
4853   SDLoc dl(Op);
4854   SDValue ShOpLo = Op.getOperand(0);
4855   SDValue ShOpHi = Op.getOperand(1);
4856   SDValue ShAmt  = Op.getOperand(2);
4857   SDValue ARMcc;
4858   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4859 
4860   assert(Op.getOpcode() == ISD::SHL_PARTS);
4861   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4862                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4863   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4864   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4865   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4866 
4867   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4868                                    DAG.getConstant(VTBits, dl, MVT::i32));
4869   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4870   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4871                             ISD::SETGE, ARMcc, DAG, dl);
4872   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4873                            ARMcc, CCR, CmpHi);
4874 
4875   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4876                           ISD::SETGE, ARMcc, DAG, dl);
4877   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4878   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
4879                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
4880 
4881   SDValue Ops[2] = { Lo, Hi };
4882   return DAG.getMergeValues(Ops, dl);
4883 }
4884 
4885 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4886                                             SelectionDAG &DAG) const {
4887   // The rounding mode is in bits 23:22 of the FPSCR.
4888   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4889   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4890   // so that the shift + and get folded into a bitfield extract.
4891   SDLoc dl(Op);
4892   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4893                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4894                                               MVT::i32));
4895   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4896                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4897   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4898                               DAG.getConstant(22, dl, MVT::i32));
4899   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4900                      DAG.getConstant(3, dl, MVT::i32));
4901 }
4902 
4903 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4904                          const ARMSubtarget *ST) {
4905   SDLoc dl(N);
4906   EVT VT = N->getValueType(0);
4907   if (VT.isVector()) {
4908     assert(ST->hasNEON());
4909 
4910     // Compute the least significant set bit: LSB = X & -X
4911     SDValue X = N->getOperand(0);
4912     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4913     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4914 
4915     EVT ElemTy = VT.getVectorElementType();
4916 
4917     if (ElemTy == MVT::i8) {
4918       // Compute with: cttz(x) = ctpop(lsb - 1)
4919       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4920                                 DAG.getTargetConstant(1, dl, ElemTy));
4921       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4922       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4923     }
4924 
4925     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4926         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4927       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4928       unsigned NumBits = ElemTy.getSizeInBits();
4929       SDValue WidthMinus1 =
4930           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4931                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4932       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4933       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4934     }
4935 
4936     // Compute with: cttz(x) = ctpop(lsb - 1)
4937 
4938     // Since we can only compute the number of bits in a byte with vcnt.8, we
4939     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4940     // and i64.
4941 
4942     // Compute LSB - 1.
4943     SDValue Bits;
4944     if (ElemTy == MVT::i64) {
4945       // Load constant 0xffff'ffff'ffff'ffff to register.
4946       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4947                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4948       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4949     } else {
4950       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4951                                 DAG.getTargetConstant(1, dl, ElemTy));
4952       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4953     }
4954 
4955     // Count #bits with vcnt.8.
4956     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4957     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4958     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4959 
4960     // Gather the #bits with vpaddl (pairwise add.)
4961     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4962     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4963         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4964         Cnt8);
4965     if (ElemTy == MVT::i16)
4966       return Cnt16;
4967 
4968     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4969     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4970         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4971         Cnt16);
4972     if (ElemTy == MVT::i32)
4973       return Cnt32;
4974 
4975     assert(ElemTy == MVT::i64);
4976     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4977         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4978         Cnt32);
4979     return Cnt64;
4980   }
4981 
4982   if (!ST->hasV6T2Ops())
4983     return SDValue();
4984 
4985   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4986   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4987 }
4988 
4989 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4990 /// for each 16-bit element from operand, repeated.  The basic idea is to
4991 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4992 ///
4993 /// Trace for v4i16:
4994 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4995 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4996 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4997 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4998 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4999 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5000 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5001 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5002 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5003   EVT VT = N->getValueType(0);
5004   SDLoc DL(N);
5005 
5006   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5007   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5008   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5009   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5010   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5011   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5012 }
5013 
5014 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5015 /// bit-count for each 16-bit element from the operand.  We need slightly
5016 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5017 /// 64/128-bit registers.
5018 ///
5019 /// Trace for v4i16:
5020 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5021 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5022 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5023 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5024 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5025   EVT VT = N->getValueType(0);
5026   SDLoc DL(N);
5027 
5028   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5029   if (VT.is64BitVector()) {
5030     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5031     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5032                        DAG.getIntPtrConstant(0, DL));
5033   } else {
5034     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5035                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5036     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5037   }
5038 }
5039 
5040 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5041 /// bit-count for each 32-bit element from the operand.  The idea here is
5042 /// to split the vector into 16-bit elements, leverage the 16-bit count
5043 /// routine, and then combine the results.
5044 ///
5045 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5046 /// input    = [v0    v1    ] (vi: 32-bit elements)
5047 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5048 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5049 /// vrev: N0 = [k1 k0 k3 k2 ]
5050 ///            [k0 k1 k2 k3 ]
5051 ///       N1 =+[k1 k0 k3 k2 ]
5052 ///            [k0 k2 k1 k3 ]
5053 ///       N2 =+[k1 k3 k0 k2 ]
5054 ///            [k0    k2    k1    k3    ]
5055 /// Extended =+[k1    k3    k0    k2    ]
5056 ///            [k0    k2    ]
5057 /// Extracted=+[k1    k3    ]
5058 ///
5059 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5060   EVT VT = N->getValueType(0);
5061   SDLoc DL(N);
5062 
5063   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5064 
5065   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5066   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5067   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5068   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5069   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5070 
5071   if (VT.is64BitVector()) {
5072     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5073     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5074                        DAG.getIntPtrConstant(0, DL));
5075   } else {
5076     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5077                                     DAG.getIntPtrConstant(0, DL));
5078     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5079   }
5080 }
5081 
5082 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5083                           const ARMSubtarget *ST) {
5084   EVT VT = N->getValueType(0);
5085 
5086   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5087   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5088           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5089          "Unexpected type for custom ctpop lowering");
5090 
5091   if (VT.getVectorElementType() == MVT::i32)
5092     return lowerCTPOP32BitElements(N, DAG);
5093   else
5094     return lowerCTPOP16BitElements(N, DAG);
5095 }
5096 
5097 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5098                           const ARMSubtarget *ST) {
5099   EVT VT = N->getValueType(0);
5100   SDLoc dl(N);
5101 
5102   if (!VT.isVector())
5103     return SDValue();
5104 
5105   // Lower vector shifts on NEON to use VSHL.
5106   assert(ST->hasNEON() && "unexpected vector shift");
5107 
5108   // Left shifts translate directly to the vshiftu intrinsic.
5109   if (N->getOpcode() == ISD::SHL)
5110     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5111                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5112                                        MVT::i32),
5113                        N->getOperand(0), N->getOperand(1));
5114 
5115   assert((N->getOpcode() == ISD::SRA ||
5116           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5117 
5118   // NEON uses the same intrinsics for both left and right shifts.  For
5119   // right shifts, the shift amounts are negative, so negate the vector of
5120   // shift amounts.
5121   EVT ShiftVT = N->getOperand(1).getValueType();
5122   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5123                                      getZeroVector(ShiftVT, DAG, dl),
5124                                      N->getOperand(1));
5125   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5126                              Intrinsic::arm_neon_vshifts :
5127                              Intrinsic::arm_neon_vshiftu);
5128   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5129                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5130                      N->getOperand(0), NegatedCount);
5131 }
5132 
5133 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5134                                 const ARMSubtarget *ST) {
5135   EVT VT = N->getValueType(0);
5136   SDLoc dl(N);
5137 
5138   // We can get here for a node like i32 = ISD::SHL i32, i64
5139   if (VT != MVT::i64)
5140     return SDValue();
5141 
5142   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5143          "Unknown shift to lower!");
5144 
5145   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5146   if (!isOneConstant(N->getOperand(1)))
5147     return SDValue();
5148 
5149   // If we are in thumb mode, we don't have RRX.
5150   if (ST->isThumb1Only()) return SDValue();
5151 
5152   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5153   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5154                            DAG.getConstant(0, dl, MVT::i32));
5155   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5156                            DAG.getConstant(1, dl, MVT::i32));
5157 
5158   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5159   // captures the result into a carry flag.
5160   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5161   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5162 
5163   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5164   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5165 
5166   // Merge the pieces into a single i64 value.
5167  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5168 }
5169 
5170 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5171   SDValue TmpOp0, TmpOp1;
5172   bool Invert = false;
5173   bool Swap = false;
5174   unsigned Opc = 0;
5175 
5176   SDValue Op0 = Op.getOperand(0);
5177   SDValue Op1 = Op.getOperand(1);
5178   SDValue CC = Op.getOperand(2);
5179   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5180   EVT VT = Op.getValueType();
5181   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5182   SDLoc dl(Op);
5183 
5184   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5185       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5186     // Special-case integer 64-bit equality comparisons. They aren't legal,
5187     // but they can be lowered with a few vector instructions.
5188     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5189     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5190     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5191     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5192     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5193                               DAG.getCondCode(ISD::SETEQ));
5194     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5195     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5196     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5197     if (SetCCOpcode == ISD::SETNE)
5198       Merged = DAG.getNOT(dl, Merged, CmpVT);
5199     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5200     return Merged;
5201   }
5202 
5203   if (CmpVT.getVectorElementType() == MVT::i64)
5204     // 64-bit comparisons are not legal in general.
5205     return SDValue();
5206 
5207   if (Op1.getValueType().isFloatingPoint()) {
5208     switch (SetCCOpcode) {
5209     default: llvm_unreachable("Illegal FP comparison");
5210     case ISD::SETUNE:
5211     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5212     case ISD::SETOEQ:
5213     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5214     case ISD::SETOLT:
5215     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5216     case ISD::SETOGT:
5217     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5218     case ISD::SETOLE:
5219     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5220     case ISD::SETOGE:
5221     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5222     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5223     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5224     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5225     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5226     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5227     case ISD::SETONE:
5228       // Expand this to (OLT | OGT).
5229       TmpOp0 = Op0;
5230       TmpOp1 = Op1;
5231       Opc = ISD::OR;
5232       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5233       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5234       break;
5235     case ISD::SETUO:
5236       Invert = true;
5237       LLVM_FALLTHROUGH;
5238     case ISD::SETO:
5239       // Expand this to (OLT | OGE).
5240       TmpOp0 = Op0;
5241       TmpOp1 = Op1;
5242       Opc = ISD::OR;
5243       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5244       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5245       break;
5246     }
5247   } else {
5248     // Integer comparisons.
5249     switch (SetCCOpcode) {
5250     default: llvm_unreachable("Illegal integer comparison");
5251     case ISD::SETNE:  Invert = true;
5252     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5253     case ISD::SETLT:  Swap = true;
5254     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5255     case ISD::SETLE:  Swap = true;
5256     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5257     case ISD::SETULT: Swap = true;
5258     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5259     case ISD::SETULE: Swap = true;
5260     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5261     }
5262 
5263     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5264     if (Opc == ARMISD::VCEQ) {
5265 
5266       SDValue AndOp;
5267       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5268         AndOp = Op0;
5269       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5270         AndOp = Op1;
5271 
5272       // Ignore bitconvert.
5273       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5274         AndOp = AndOp.getOperand(0);
5275 
5276       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5277         Opc = ARMISD::VTST;
5278         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5279         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5280         Invert = !Invert;
5281       }
5282     }
5283   }
5284 
5285   if (Swap)
5286     std::swap(Op0, Op1);
5287 
5288   // If one of the operands is a constant vector zero, attempt to fold the
5289   // comparison to a specialized compare-against-zero form.
5290   SDValue SingleOp;
5291   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5292     SingleOp = Op0;
5293   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5294     if (Opc == ARMISD::VCGE)
5295       Opc = ARMISD::VCLEZ;
5296     else if (Opc == ARMISD::VCGT)
5297       Opc = ARMISD::VCLTZ;
5298     SingleOp = Op1;
5299   }
5300 
5301   SDValue Result;
5302   if (SingleOp.getNode()) {
5303     switch (Opc) {
5304     case ARMISD::VCEQ:
5305       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5306     case ARMISD::VCGE:
5307       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5308     case ARMISD::VCLEZ:
5309       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5310     case ARMISD::VCGT:
5311       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5312     case ARMISD::VCLTZ:
5313       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5314     default:
5315       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5316     }
5317   } else {
5318      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5319   }
5320 
5321   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5322 
5323   if (Invert)
5324     Result = DAG.getNOT(dl, Result, VT);
5325 
5326   return Result;
5327 }
5328 
5329 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5330   SDValue LHS = Op.getOperand(0);
5331   SDValue RHS = Op.getOperand(1);
5332   SDValue Carry = Op.getOperand(2);
5333   SDValue Cond = Op.getOperand(3);
5334   SDLoc DL(Op);
5335 
5336   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5337 
5338   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5339   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5340   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5341 
5342   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5343   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5344   SDValue ARMcc = DAG.getConstant(
5345       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5346   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5347   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5348                                    Cmp.getValue(1), SDValue());
5349   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5350                      CCR, Chain.getValue(1));
5351 }
5352 
5353 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5354 /// valid vector constant for a NEON instruction with a "modified immediate"
5355 /// operand (e.g., VMOV).  If so, return the encoded value.
5356 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5357                                  unsigned SplatBitSize, SelectionDAG &DAG,
5358                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5359                                  NEONModImmType type) {
5360   unsigned OpCmode, Imm;
5361 
5362   // SplatBitSize is set to the smallest size that splats the vector, so a
5363   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5364   // immediate instructions others than VMOV do not support the 8-bit encoding
5365   // of a zero vector, and the default encoding of zero is supposed to be the
5366   // 32-bit version.
5367   if (SplatBits == 0)
5368     SplatBitSize = 32;
5369 
5370   switch (SplatBitSize) {
5371   case 8:
5372     if (type != VMOVModImm)
5373       return SDValue();
5374     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5375     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5376     OpCmode = 0xe;
5377     Imm = SplatBits;
5378     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5379     break;
5380 
5381   case 16:
5382     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5383     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5384     if ((SplatBits & ~0xff) == 0) {
5385       // Value = 0x00nn: Op=x, Cmode=100x.
5386       OpCmode = 0x8;
5387       Imm = SplatBits;
5388       break;
5389     }
5390     if ((SplatBits & ~0xff00) == 0) {
5391       // Value = 0xnn00: Op=x, Cmode=101x.
5392       OpCmode = 0xa;
5393       Imm = SplatBits >> 8;
5394       break;
5395     }
5396     return SDValue();
5397 
5398   case 32:
5399     // NEON's 32-bit VMOV supports splat values where:
5400     // * only one byte is nonzero, or
5401     // * the least significant byte is 0xff and the second byte is nonzero, or
5402     // * the least significant 2 bytes are 0xff and the third is nonzero.
5403     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5404     if ((SplatBits & ~0xff) == 0) {
5405       // Value = 0x000000nn: Op=x, Cmode=000x.
5406       OpCmode = 0;
5407       Imm = SplatBits;
5408       break;
5409     }
5410     if ((SplatBits & ~0xff00) == 0) {
5411       // Value = 0x0000nn00: Op=x, Cmode=001x.
5412       OpCmode = 0x2;
5413       Imm = SplatBits >> 8;
5414       break;
5415     }
5416     if ((SplatBits & ~0xff0000) == 0) {
5417       // Value = 0x00nn0000: Op=x, Cmode=010x.
5418       OpCmode = 0x4;
5419       Imm = SplatBits >> 16;
5420       break;
5421     }
5422     if ((SplatBits & ~0xff000000) == 0) {
5423       // Value = 0xnn000000: Op=x, Cmode=011x.
5424       OpCmode = 0x6;
5425       Imm = SplatBits >> 24;
5426       break;
5427     }
5428 
5429     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5430     if (type == OtherModImm) return SDValue();
5431 
5432     if ((SplatBits & ~0xffff) == 0 &&
5433         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5434       // Value = 0x0000nnff: Op=x, Cmode=1100.
5435       OpCmode = 0xc;
5436       Imm = SplatBits >> 8;
5437       break;
5438     }
5439 
5440     if ((SplatBits & ~0xffffff) == 0 &&
5441         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5442       // Value = 0x00nnffff: Op=x, Cmode=1101.
5443       OpCmode = 0xd;
5444       Imm = SplatBits >> 16;
5445       break;
5446     }
5447 
5448     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5449     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5450     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5451     // and fall through here to test for a valid 64-bit splat.  But, then the
5452     // caller would also need to check and handle the change in size.
5453     return SDValue();
5454 
5455   case 64: {
5456     if (type != VMOVModImm)
5457       return SDValue();
5458     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5459     uint64_t BitMask = 0xff;
5460     uint64_t Val = 0;
5461     unsigned ImmMask = 1;
5462     Imm = 0;
5463     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5464       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5465         Val |= BitMask;
5466         Imm |= ImmMask;
5467       } else if ((SplatBits & BitMask) != 0) {
5468         return SDValue();
5469       }
5470       BitMask <<= 8;
5471       ImmMask <<= 1;
5472     }
5473 
5474     if (DAG.getDataLayout().isBigEndian())
5475       // swap higher and lower 32 bit word
5476       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5477 
5478     // Op=1, Cmode=1110.
5479     OpCmode = 0x1e;
5480     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5481     break;
5482   }
5483 
5484   default:
5485     llvm_unreachable("unexpected size for isNEONModifiedImm");
5486   }
5487 
5488   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5489   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5490 }
5491 
5492 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5493                                            const ARMSubtarget *ST) const {
5494   bool IsDouble = Op.getValueType() == MVT::f64;
5495   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5496   const APFloat &FPVal = CFP->getValueAPF();
5497 
5498   // Prevent floating-point constants from using literal loads
5499   // when execute-only is enabled.
5500   if (ST->genExecuteOnly()) {
5501     APInt INTVal = FPVal.bitcastToAPInt();
5502     SDLoc DL(CFP);
5503     if (IsDouble) {
5504       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5505       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5506       if (!ST->isLittle())
5507         std::swap(Lo, Hi);
5508       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5509     } else {
5510       return DAG.getConstant(INTVal, DL, MVT::i32);
5511     }
5512   }
5513 
5514   if (!ST->hasVFP3())
5515     return SDValue();
5516 
5517   // Use the default (constant pool) lowering for double constants when we have
5518   // an SP-only FPU
5519   if (IsDouble && Subtarget->isFPOnlySP())
5520     return SDValue();
5521 
5522   // Try splatting with a VMOV.f32...
5523   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5524 
5525   if (ImmVal != -1) {
5526     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5527       // We have code in place to select a valid ConstantFP already, no need to
5528       // do any mangling.
5529       return Op;
5530     }
5531 
5532     // It's a float and we are trying to use NEON operations where
5533     // possible. Lower it to a splat followed by an extract.
5534     SDLoc DL(Op);
5535     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5536     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5537                                       NewVal);
5538     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5539                        DAG.getConstant(0, DL, MVT::i32));
5540   }
5541 
5542   // The rest of our options are NEON only, make sure that's allowed before
5543   // proceeding..
5544   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5545     return SDValue();
5546 
5547   EVT VMovVT;
5548   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5549 
5550   // It wouldn't really be worth bothering for doubles except for one very
5551   // important value, which does happen to match: 0.0. So make sure we don't do
5552   // anything stupid.
5553   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5554     return SDValue();
5555 
5556   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5557   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5558                                      VMovVT, false, VMOVModImm);
5559   if (NewVal != SDValue()) {
5560     SDLoc DL(Op);
5561     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5562                                       NewVal);
5563     if (IsDouble)
5564       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5565 
5566     // It's a float: cast and extract a vector element.
5567     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5568                                        VecConstant);
5569     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5570                        DAG.getConstant(0, DL, MVT::i32));
5571   }
5572 
5573   // Finally, try a VMVN.i32
5574   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5575                              false, VMVNModImm);
5576   if (NewVal != SDValue()) {
5577     SDLoc DL(Op);
5578     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5579 
5580     if (IsDouble)
5581       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5582 
5583     // It's a float: cast and extract a vector element.
5584     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5585                                        VecConstant);
5586     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5587                        DAG.getConstant(0, DL, MVT::i32));
5588   }
5589 
5590   return SDValue();
5591 }
5592 
5593 // check if an VEXT instruction can handle the shuffle mask when the
5594 // vector sources of the shuffle are the same.
5595 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5596   unsigned NumElts = VT.getVectorNumElements();
5597 
5598   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5599   if (M[0] < 0)
5600     return false;
5601 
5602   Imm = M[0];
5603 
5604   // If this is a VEXT shuffle, the immediate value is the index of the first
5605   // element.  The other shuffle indices must be the successive elements after
5606   // the first one.
5607   unsigned ExpectedElt = Imm;
5608   for (unsigned i = 1; i < NumElts; ++i) {
5609     // Increment the expected index.  If it wraps around, just follow it
5610     // back to index zero and keep going.
5611     ++ExpectedElt;
5612     if (ExpectedElt == NumElts)
5613       ExpectedElt = 0;
5614 
5615     if (M[i] < 0) continue; // ignore UNDEF indices
5616     if (ExpectedElt != static_cast<unsigned>(M[i]))
5617       return false;
5618   }
5619 
5620   return true;
5621 }
5622 
5623 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5624                        bool &ReverseVEXT, unsigned &Imm) {
5625   unsigned NumElts = VT.getVectorNumElements();
5626   ReverseVEXT = false;
5627 
5628   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5629   if (M[0] < 0)
5630     return false;
5631 
5632   Imm = M[0];
5633 
5634   // If this is a VEXT shuffle, the immediate value is the index of the first
5635   // element.  The other shuffle indices must be the successive elements after
5636   // the first one.
5637   unsigned ExpectedElt = Imm;
5638   for (unsigned i = 1; i < NumElts; ++i) {
5639     // Increment the expected index.  If it wraps around, it may still be
5640     // a VEXT but the source vectors must be swapped.
5641     ExpectedElt += 1;
5642     if (ExpectedElt == NumElts * 2) {
5643       ExpectedElt = 0;
5644       ReverseVEXT = true;
5645     }
5646 
5647     if (M[i] < 0) continue; // ignore UNDEF indices
5648     if (ExpectedElt != static_cast<unsigned>(M[i]))
5649       return false;
5650   }
5651 
5652   // Adjust the index value if the source operands will be swapped.
5653   if (ReverseVEXT)
5654     Imm -= NumElts;
5655 
5656   return true;
5657 }
5658 
5659 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5660 /// instruction with the specified blocksize.  (The order of the elements
5661 /// within each block of the vector is reversed.)
5662 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5663   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5664          "Only possible block sizes for VREV are: 16, 32, 64");
5665 
5666   unsigned EltSz = VT.getScalarSizeInBits();
5667   if (EltSz == 64)
5668     return false;
5669 
5670   unsigned NumElts = VT.getVectorNumElements();
5671   unsigned BlockElts = M[0] + 1;
5672   // If the first shuffle index is UNDEF, be optimistic.
5673   if (M[0] < 0)
5674     BlockElts = BlockSize / EltSz;
5675 
5676   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5677     return false;
5678 
5679   for (unsigned i = 0; i < NumElts; ++i) {
5680     if (M[i] < 0) continue; // ignore UNDEF indices
5681     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5682       return false;
5683   }
5684 
5685   return true;
5686 }
5687 
5688 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5689   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5690   // range, then 0 is placed into the resulting vector. So pretty much any mask
5691   // of 8 elements can work here.
5692   return VT == MVT::v8i8 && M.size() == 8;
5693 }
5694 
5695 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5696 // checking that pairs of elements in the shuffle mask represent the same index
5697 // in each vector, incrementing the expected index by 2 at each step.
5698 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5699 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5700 //  v2={e,f,g,h}
5701 // WhichResult gives the offset for each element in the mask based on which
5702 // of the two results it belongs to.
5703 //
5704 // The transpose can be represented either as:
5705 // result1 = shufflevector v1, v2, result1_shuffle_mask
5706 // result2 = shufflevector v1, v2, result2_shuffle_mask
5707 // where v1/v2 and the shuffle masks have the same number of elements
5708 // (here WhichResult (see below) indicates which result is being checked)
5709 //
5710 // or as:
5711 // results = shufflevector v1, v2, shuffle_mask
5712 // where both results are returned in one vector and the shuffle mask has twice
5713 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5714 // want to check the low half and high half of the shuffle mask as if it were
5715 // the other case
5716 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5717   unsigned EltSz = VT.getScalarSizeInBits();
5718   if (EltSz == 64)
5719     return false;
5720 
5721   unsigned NumElts = VT.getVectorNumElements();
5722   if (M.size() != NumElts && M.size() != NumElts*2)
5723     return false;
5724 
5725   // If the mask is twice as long as the input vector then we need to check the
5726   // upper and lower parts of the mask with a matching value for WhichResult
5727   // FIXME: A mask with only even values will be rejected in case the first
5728   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5729   // M[0] is used to determine WhichResult
5730   for (unsigned i = 0; i < M.size(); i += NumElts) {
5731     if (M.size() == NumElts * 2)
5732       WhichResult = i / NumElts;
5733     else
5734       WhichResult = M[i] == 0 ? 0 : 1;
5735     for (unsigned j = 0; j < NumElts; j += 2) {
5736       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5737           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5738         return false;
5739     }
5740   }
5741 
5742   if (M.size() == NumElts*2)
5743     WhichResult = 0;
5744 
5745   return true;
5746 }
5747 
5748 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5749 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5750 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5751 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5752   unsigned EltSz = VT.getScalarSizeInBits();
5753   if (EltSz == 64)
5754     return false;
5755 
5756   unsigned NumElts = VT.getVectorNumElements();
5757   if (M.size() != NumElts && M.size() != NumElts*2)
5758     return false;
5759 
5760   for (unsigned i = 0; i < M.size(); i += NumElts) {
5761     if (M.size() == NumElts * 2)
5762       WhichResult = i / NumElts;
5763     else
5764       WhichResult = M[i] == 0 ? 0 : 1;
5765     for (unsigned j = 0; j < NumElts; j += 2) {
5766       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5767           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5768         return false;
5769     }
5770   }
5771 
5772   if (M.size() == NumElts*2)
5773     WhichResult = 0;
5774 
5775   return true;
5776 }
5777 
5778 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5779 // that the mask elements are either all even and in steps of size 2 or all odd
5780 // and in steps of size 2.
5781 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5782 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5783 //  v2={e,f,g,h}
5784 // Requires similar checks to that of isVTRNMask with
5785 // respect the how results are returned.
5786 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5787   unsigned EltSz = VT.getScalarSizeInBits();
5788   if (EltSz == 64)
5789     return false;
5790 
5791   unsigned NumElts = VT.getVectorNumElements();
5792   if (M.size() != NumElts && M.size() != NumElts*2)
5793     return false;
5794 
5795   for (unsigned i = 0; i < M.size(); i += NumElts) {
5796     WhichResult = M[i] == 0 ? 0 : 1;
5797     for (unsigned j = 0; j < NumElts; ++j) {
5798       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5799         return false;
5800     }
5801   }
5802 
5803   if (M.size() == NumElts*2)
5804     WhichResult = 0;
5805 
5806   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5807   if (VT.is64BitVector() && EltSz == 32)
5808     return false;
5809 
5810   return true;
5811 }
5812 
5813 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5814 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5815 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5816 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5817   unsigned EltSz = VT.getScalarSizeInBits();
5818   if (EltSz == 64)
5819     return false;
5820 
5821   unsigned NumElts = VT.getVectorNumElements();
5822   if (M.size() != NumElts && M.size() != NumElts*2)
5823     return false;
5824 
5825   unsigned Half = NumElts / 2;
5826   for (unsigned i = 0; i < M.size(); i += NumElts) {
5827     WhichResult = M[i] == 0 ? 0 : 1;
5828     for (unsigned j = 0; j < NumElts; j += Half) {
5829       unsigned Idx = WhichResult;
5830       for (unsigned k = 0; k < Half; ++k) {
5831         int MIdx = M[i + j + k];
5832         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5833           return false;
5834         Idx += 2;
5835       }
5836     }
5837   }
5838 
5839   if (M.size() == NumElts*2)
5840     WhichResult = 0;
5841 
5842   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5843   if (VT.is64BitVector() && EltSz == 32)
5844     return false;
5845 
5846   return true;
5847 }
5848 
5849 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5850 // that pairs of elements of the shufflemask represent the same index in each
5851 // vector incrementing sequentially through the vectors.
5852 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5853 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5854 //  v2={e,f,g,h}
5855 // Requires similar checks to that of isVTRNMask with respect the how results
5856 // are returned.
5857 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5858   unsigned EltSz = VT.getScalarSizeInBits();
5859   if (EltSz == 64)
5860     return false;
5861 
5862   unsigned NumElts = VT.getVectorNumElements();
5863   if (M.size() != NumElts && M.size() != NumElts*2)
5864     return false;
5865 
5866   for (unsigned i = 0; i < M.size(); i += NumElts) {
5867     WhichResult = M[i] == 0 ? 0 : 1;
5868     unsigned Idx = WhichResult * NumElts / 2;
5869     for (unsigned j = 0; j < NumElts; j += 2) {
5870       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5871           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5872         return false;
5873       Idx += 1;
5874     }
5875   }
5876 
5877   if (M.size() == NumElts*2)
5878     WhichResult = 0;
5879 
5880   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5881   if (VT.is64BitVector() && EltSz == 32)
5882     return false;
5883 
5884   return true;
5885 }
5886 
5887 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5888 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5889 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5890 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5891   unsigned EltSz = VT.getScalarSizeInBits();
5892   if (EltSz == 64)
5893     return false;
5894 
5895   unsigned NumElts = VT.getVectorNumElements();
5896   if (M.size() != NumElts && M.size() != NumElts*2)
5897     return false;
5898 
5899   for (unsigned i = 0; i < M.size(); i += NumElts) {
5900     WhichResult = M[i] == 0 ? 0 : 1;
5901     unsigned Idx = WhichResult * NumElts / 2;
5902     for (unsigned j = 0; j < NumElts; j += 2) {
5903       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5904           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5905         return false;
5906       Idx += 1;
5907     }
5908   }
5909 
5910   if (M.size() == NumElts*2)
5911     WhichResult = 0;
5912 
5913   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5914   if (VT.is64BitVector() && EltSz == 32)
5915     return false;
5916 
5917   return true;
5918 }
5919 
5920 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5921 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5922 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5923                                            unsigned &WhichResult,
5924                                            bool &isV_UNDEF) {
5925   isV_UNDEF = false;
5926   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5927     return ARMISD::VTRN;
5928   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5929     return ARMISD::VUZP;
5930   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5931     return ARMISD::VZIP;
5932 
5933   isV_UNDEF = true;
5934   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5935     return ARMISD::VTRN;
5936   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5937     return ARMISD::VUZP;
5938   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5939     return ARMISD::VZIP;
5940 
5941   return 0;
5942 }
5943 
5944 /// \return true if this is a reverse operation on an vector.
5945 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5946   unsigned NumElts = VT.getVectorNumElements();
5947   // Make sure the mask has the right size.
5948   if (NumElts != M.size())
5949       return false;
5950 
5951   // Look for <15, ..., 3, -1, 1, 0>.
5952   for (unsigned i = 0; i != NumElts; ++i)
5953     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5954       return false;
5955 
5956   return true;
5957 }
5958 
5959 // If N is an integer constant that can be moved into a register in one
5960 // instruction, return an SDValue of such a constant (will become a MOV
5961 // instruction).  Otherwise return null.
5962 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5963                                      const ARMSubtarget *ST, const SDLoc &dl) {
5964   uint64_t Val;
5965   if (!isa<ConstantSDNode>(N))
5966     return SDValue();
5967   Val = cast<ConstantSDNode>(N)->getZExtValue();
5968 
5969   if (ST->isThumb1Only()) {
5970     if (Val <= 255 || ~Val <= 255)
5971       return DAG.getConstant(Val, dl, MVT::i32);
5972   } else {
5973     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5974       return DAG.getConstant(Val, dl, MVT::i32);
5975   }
5976   return SDValue();
5977 }
5978 
5979 // If this is a case we can't handle, return null and let the default
5980 // expansion code take care of it.
5981 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5982                                              const ARMSubtarget *ST) const {
5983   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5984   SDLoc dl(Op);
5985   EVT VT = Op.getValueType();
5986 
5987   APInt SplatBits, SplatUndef;
5988   unsigned SplatBitSize;
5989   bool HasAnyUndefs;
5990   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5991     if (SplatUndef.isAllOnesValue())
5992       return DAG.getUNDEF(VT);
5993 
5994     if (SplatBitSize <= 64) {
5995       // Check if an immediate VMOV works.
5996       EVT VmovVT;
5997       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5998                                       SplatUndef.getZExtValue(), SplatBitSize,
5999                                       DAG, dl, VmovVT, VT.is128BitVector(),
6000                                       VMOVModImm);
6001       if (Val.getNode()) {
6002         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6003         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6004       }
6005 
6006       // Try an immediate VMVN.
6007       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6008       Val = isNEONModifiedImm(NegatedImm,
6009                                       SplatUndef.getZExtValue(), SplatBitSize,
6010                                       DAG, dl, VmovVT, VT.is128BitVector(),
6011                                       VMVNModImm);
6012       if (Val.getNode()) {
6013         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6014         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6015       }
6016 
6017       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6018       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6019         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6020         if (ImmVal != -1) {
6021           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6022           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6023         }
6024       }
6025     }
6026   }
6027 
6028   // Scan through the operands to see if only one value is used.
6029   //
6030   // As an optimisation, even if more than one value is used it may be more
6031   // profitable to splat with one value then change some lanes.
6032   //
6033   // Heuristically we decide to do this if the vector has a "dominant" value,
6034   // defined as splatted to more than half of the lanes.
6035   unsigned NumElts = VT.getVectorNumElements();
6036   bool isOnlyLowElement = true;
6037   bool usesOnlyOneValue = true;
6038   bool hasDominantValue = false;
6039   bool isConstant = true;
6040 
6041   // Map of the number of times a particular SDValue appears in the
6042   // element list.
6043   DenseMap<SDValue, unsigned> ValueCounts;
6044   SDValue Value;
6045   for (unsigned i = 0; i < NumElts; ++i) {
6046     SDValue V = Op.getOperand(i);
6047     if (V.isUndef())
6048       continue;
6049     if (i > 0)
6050       isOnlyLowElement = false;
6051     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6052       isConstant = false;
6053 
6054     ValueCounts.insert(std::make_pair(V, 0));
6055     unsigned &Count = ValueCounts[V];
6056 
6057     // Is this value dominant? (takes up more than half of the lanes)
6058     if (++Count > (NumElts / 2)) {
6059       hasDominantValue = true;
6060       Value = V;
6061     }
6062   }
6063   if (ValueCounts.size() != 1)
6064     usesOnlyOneValue = false;
6065   if (!Value.getNode() && !ValueCounts.empty())
6066     Value = ValueCounts.begin()->first;
6067 
6068   if (ValueCounts.empty())
6069     return DAG.getUNDEF(VT);
6070 
6071   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6072   // Keep going if we are hitting this case.
6073   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6074     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6075 
6076   unsigned EltSize = VT.getScalarSizeInBits();
6077 
6078   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6079   // i32 and try again.
6080   if (hasDominantValue && EltSize <= 32) {
6081     if (!isConstant) {
6082       SDValue N;
6083 
6084       // If we are VDUPing a value that comes directly from a vector, that will
6085       // cause an unnecessary move to and from a GPR, where instead we could
6086       // just use VDUPLANE. We can only do this if the lane being extracted
6087       // is at a constant index, as the VDUP from lane instructions only have
6088       // constant-index forms.
6089       ConstantSDNode *constIndex;
6090       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6091           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6092         // We need to create a new undef vector to use for the VDUPLANE if the
6093         // size of the vector from which we get the value is different than the
6094         // size of the vector that we need to create. We will insert the element
6095         // such that the register coalescer will remove unnecessary copies.
6096         if (VT != Value->getOperand(0).getValueType()) {
6097           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6098                              VT.getVectorNumElements();
6099           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6100                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6101                         Value, DAG.getConstant(index, dl, MVT::i32)),
6102                            DAG.getConstant(index, dl, MVT::i32));
6103         } else
6104           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6105                         Value->getOperand(0), Value->getOperand(1));
6106       } else
6107         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6108 
6109       if (!usesOnlyOneValue) {
6110         // The dominant value was splatted as 'N', but we now have to insert
6111         // all differing elements.
6112         for (unsigned I = 0; I < NumElts; ++I) {
6113           if (Op.getOperand(I) == Value)
6114             continue;
6115           SmallVector<SDValue, 3> Ops;
6116           Ops.push_back(N);
6117           Ops.push_back(Op.getOperand(I));
6118           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6119           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6120         }
6121       }
6122       return N;
6123     }
6124     if (VT.getVectorElementType().isFloatingPoint()) {
6125       SmallVector<SDValue, 8> Ops;
6126       for (unsigned i = 0; i < NumElts; ++i)
6127         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6128                                   Op.getOperand(i)));
6129       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6130       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6131       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6132       if (Val.getNode())
6133         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6134     }
6135     if (usesOnlyOneValue) {
6136       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6137       if (isConstant && Val.getNode())
6138         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6139     }
6140   }
6141 
6142   // If all elements are constants and the case above didn't get hit, fall back
6143   // to the default expansion, which will generate a load from the constant
6144   // pool.
6145   if (isConstant)
6146     return SDValue();
6147 
6148   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6149   if (NumElts >= 4) {
6150     SDValue shuffle = ReconstructShuffle(Op, DAG);
6151     if (shuffle != SDValue())
6152       return shuffle;
6153   }
6154 
6155   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6156     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6157     // into two 64-bit vectors; we might discover a better way to lower it.
6158     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6159     EVT ExtVT = VT.getVectorElementType();
6160     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6161     SDValue Lower =
6162         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6163     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6164       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6165     SDValue Upper = DAG.getBuildVector(
6166         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6167     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6168       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6169     if (Lower && Upper)
6170       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6171   }
6172 
6173   // Vectors with 32- or 64-bit elements can be built by directly assigning
6174   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6175   // will be legalized.
6176   if (EltSize >= 32) {
6177     // Do the expansion with floating-point types, since that is what the VFP
6178     // registers are defined to use, and since i64 is not legal.
6179     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6180     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6181     SmallVector<SDValue, 8> Ops;
6182     for (unsigned i = 0; i < NumElts; ++i)
6183       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6184     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6185     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6186   }
6187 
6188   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6189   // know the default expansion would otherwise fall back on something even
6190   // worse. For a vector with one or two non-undef values, that's
6191   // scalar_to_vector for the elements followed by a shuffle (provided the
6192   // shuffle is valid for the target) and materialization element by element
6193   // on the stack followed by a load for everything else.
6194   if (!isConstant && !usesOnlyOneValue) {
6195     SDValue Vec = DAG.getUNDEF(VT);
6196     for (unsigned i = 0 ; i < NumElts; ++i) {
6197       SDValue V = Op.getOperand(i);
6198       if (V.isUndef())
6199         continue;
6200       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6201       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6202     }
6203     return Vec;
6204   }
6205 
6206   return SDValue();
6207 }
6208 
6209 // Gather data to see if the operation can be modelled as a
6210 // shuffle in combination with VEXTs.
6211 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6212                                               SelectionDAG &DAG) const {
6213   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6214   SDLoc dl(Op);
6215   EVT VT = Op.getValueType();
6216   unsigned NumElts = VT.getVectorNumElements();
6217 
6218   struct ShuffleSourceInfo {
6219     SDValue Vec;
6220     unsigned MinElt = std::numeric_limits<unsigned>::max();
6221     unsigned MaxElt = 0;
6222 
6223     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6224     // be compatible with the shuffle we intend to construct. As a result
6225     // ShuffleVec will be some sliding window into the original Vec.
6226     SDValue ShuffleVec;
6227 
6228     // Code should guarantee that element i in Vec starts at element "WindowBase
6229     // + i * WindowScale in ShuffleVec".
6230     int WindowBase = 0;
6231     int WindowScale = 1;
6232 
6233     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6234 
6235     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6236   };
6237 
6238   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6239   // node.
6240   SmallVector<ShuffleSourceInfo, 2> Sources;
6241   for (unsigned i = 0; i < NumElts; ++i) {
6242     SDValue V = Op.getOperand(i);
6243     if (V.isUndef())
6244       continue;
6245     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6246       // A shuffle can only come from building a vector from various
6247       // elements of other vectors.
6248       return SDValue();
6249     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6250       // Furthermore, shuffles require a constant mask, whereas extractelts
6251       // accept variable indices.
6252       return SDValue();
6253     }
6254 
6255     // Add this element source to the list if it's not already there.
6256     SDValue SourceVec = V.getOperand(0);
6257     auto Source = llvm::find(Sources, SourceVec);
6258     if (Source == Sources.end())
6259       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6260 
6261     // Update the minimum and maximum lane number seen.
6262     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6263     Source->MinElt = std::min(Source->MinElt, EltNo);
6264     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6265   }
6266 
6267   // Currently only do something sane when at most two source vectors
6268   // are involved.
6269   if (Sources.size() > 2)
6270     return SDValue();
6271 
6272   // Find out the smallest element size among result and two sources, and use
6273   // it as element size to build the shuffle_vector.
6274   EVT SmallestEltTy = VT.getVectorElementType();
6275   for (auto &Source : Sources) {
6276     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6277     if (SrcEltTy.bitsLT(SmallestEltTy))
6278       SmallestEltTy = SrcEltTy;
6279   }
6280   unsigned ResMultiplier =
6281       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6282   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6283   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6284 
6285   // If the source vector is too wide or too narrow, we may nevertheless be able
6286   // to construct a compatible shuffle either by concatenating it with UNDEF or
6287   // extracting a suitable range of elements.
6288   for (auto &Src : Sources) {
6289     EVT SrcVT = Src.ShuffleVec.getValueType();
6290 
6291     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6292       continue;
6293 
6294     // This stage of the search produces a source with the same element type as
6295     // the original, but with a total width matching the BUILD_VECTOR output.
6296     EVT EltVT = SrcVT.getVectorElementType();
6297     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6298     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6299 
6300     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6301       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6302         return SDValue();
6303       // We can pad out the smaller vector for free, so if it's part of a
6304       // shuffle...
6305       Src.ShuffleVec =
6306           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6307                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6308       continue;
6309     }
6310 
6311     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6312       return SDValue();
6313 
6314     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6315       // Span too large for a VEXT to cope
6316       return SDValue();
6317     }
6318 
6319     if (Src.MinElt >= NumSrcElts) {
6320       // The extraction can just take the second half
6321       Src.ShuffleVec =
6322           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6323                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6324       Src.WindowBase = -NumSrcElts;
6325     } else if (Src.MaxElt < NumSrcElts) {
6326       // The extraction can just take the first half
6327       Src.ShuffleVec =
6328           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6329                       DAG.getConstant(0, dl, MVT::i32));
6330     } else {
6331       // An actual VEXT is needed
6332       SDValue VEXTSrc1 =
6333           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6334                       DAG.getConstant(0, dl, MVT::i32));
6335       SDValue VEXTSrc2 =
6336           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6337                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6338 
6339       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6340                                    VEXTSrc2,
6341                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6342       Src.WindowBase = -Src.MinElt;
6343     }
6344   }
6345 
6346   // Another possible incompatibility occurs from the vector element types. We
6347   // can fix this by bitcasting the source vectors to the same type we intend
6348   // for the shuffle.
6349   for (auto &Src : Sources) {
6350     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6351     if (SrcEltTy == SmallestEltTy)
6352       continue;
6353     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6354     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6355     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6356     Src.WindowBase *= Src.WindowScale;
6357   }
6358 
6359   // Final sanity check before we try to actually produce a shuffle.
6360   DEBUG(
6361     for (auto Src : Sources)
6362       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6363   );
6364 
6365   // The stars all align, our next step is to produce the mask for the shuffle.
6366   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6367   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6368   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6369     SDValue Entry = Op.getOperand(i);
6370     if (Entry.isUndef())
6371       continue;
6372 
6373     auto Src = llvm::find(Sources, Entry.getOperand(0));
6374     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6375 
6376     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6377     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6378     // segment.
6379     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6380     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6381                                VT.getScalarSizeInBits());
6382     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6383 
6384     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6385     // starting at the appropriate offset.
6386     int *LaneMask = &Mask[i * ResMultiplier];
6387 
6388     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6389     ExtractBase += NumElts * (Src - Sources.begin());
6390     for (int j = 0; j < LanesDefined; ++j)
6391       LaneMask[j] = ExtractBase + j;
6392   }
6393 
6394   // Final check before we try to produce nonsense...
6395   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6396     return SDValue();
6397 
6398   // We can't handle more than two sources. This should have already
6399   // been checked before this point.
6400   assert(Sources.size() <= 2 && "Too many sources!");
6401 
6402   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6403   for (unsigned i = 0; i < Sources.size(); ++i)
6404     ShuffleOps[i] = Sources[i].ShuffleVec;
6405 
6406   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6407                                          ShuffleOps[1], Mask);
6408   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6409 }
6410 
6411 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6412 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6413 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6414 /// are assumed to be legal.
6415 bool
6416 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6417                                       EVT VT) const {
6418   if (VT.getVectorNumElements() == 4 &&
6419       (VT.is128BitVector() || VT.is64BitVector())) {
6420     unsigned PFIndexes[4];
6421     for (unsigned i = 0; i != 4; ++i) {
6422       if (M[i] < 0)
6423         PFIndexes[i] = 8;
6424       else
6425         PFIndexes[i] = M[i];
6426     }
6427 
6428     // Compute the index in the perfect shuffle table.
6429     unsigned PFTableIndex =
6430       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6431     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6432     unsigned Cost = (PFEntry >> 30);
6433 
6434     if (Cost <= 4)
6435       return true;
6436   }
6437 
6438   bool ReverseVEXT, isV_UNDEF;
6439   unsigned Imm, WhichResult;
6440 
6441   unsigned EltSize = VT.getScalarSizeInBits();
6442   return (EltSize >= 32 ||
6443           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6444           isVREVMask(M, VT, 64) ||
6445           isVREVMask(M, VT, 32) ||
6446           isVREVMask(M, VT, 16) ||
6447           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6448           isVTBLMask(M, VT) ||
6449           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6450           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6451 }
6452 
6453 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6454 /// the specified operations to build the shuffle.
6455 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6456                                       SDValue RHS, SelectionDAG &DAG,
6457                                       const SDLoc &dl) {
6458   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6459   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6460   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6461 
6462   enum {
6463     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6464     OP_VREV,
6465     OP_VDUP0,
6466     OP_VDUP1,
6467     OP_VDUP2,
6468     OP_VDUP3,
6469     OP_VEXT1,
6470     OP_VEXT2,
6471     OP_VEXT3,
6472     OP_VUZPL, // VUZP, left result
6473     OP_VUZPR, // VUZP, right result
6474     OP_VZIPL, // VZIP, left result
6475     OP_VZIPR, // VZIP, right result
6476     OP_VTRNL, // VTRN, left result
6477     OP_VTRNR  // VTRN, right result
6478   };
6479 
6480   if (OpNum == OP_COPY) {
6481     if (LHSID == (1*9+2)*9+3) return LHS;
6482     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6483     return RHS;
6484   }
6485 
6486   SDValue OpLHS, OpRHS;
6487   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6488   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6489   EVT VT = OpLHS.getValueType();
6490 
6491   switch (OpNum) {
6492   default: llvm_unreachable("Unknown shuffle opcode!");
6493   case OP_VREV:
6494     // VREV divides the vector in half and swaps within the half.
6495     if (VT.getVectorElementType() == MVT::i32 ||
6496         VT.getVectorElementType() == MVT::f32)
6497       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6498     // vrev <4 x i16> -> VREV32
6499     if (VT.getVectorElementType() == MVT::i16)
6500       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6501     // vrev <4 x i8> -> VREV16
6502     assert(VT.getVectorElementType() == MVT::i8);
6503     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6504   case OP_VDUP0:
6505   case OP_VDUP1:
6506   case OP_VDUP2:
6507   case OP_VDUP3:
6508     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6509                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6510   case OP_VEXT1:
6511   case OP_VEXT2:
6512   case OP_VEXT3:
6513     return DAG.getNode(ARMISD::VEXT, dl, VT,
6514                        OpLHS, OpRHS,
6515                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6516   case OP_VUZPL:
6517   case OP_VUZPR:
6518     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6519                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6520   case OP_VZIPL:
6521   case OP_VZIPR:
6522     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6523                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6524   case OP_VTRNL:
6525   case OP_VTRNR:
6526     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6527                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6528   }
6529 }
6530 
6531 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6532                                        ArrayRef<int> ShuffleMask,
6533                                        SelectionDAG &DAG) {
6534   // Check to see if we can use the VTBL instruction.
6535   SDValue V1 = Op.getOperand(0);
6536   SDValue V2 = Op.getOperand(1);
6537   SDLoc DL(Op);
6538 
6539   SmallVector<SDValue, 8> VTBLMask;
6540   for (ArrayRef<int>::iterator
6541          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6542     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6543 
6544   if (V2.getNode()->isUndef())
6545     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6546                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6547 
6548   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6549                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6550 }
6551 
6552 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6553                                                       SelectionDAG &DAG) {
6554   SDLoc DL(Op);
6555   SDValue OpLHS = Op.getOperand(0);
6556   EVT VT = OpLHS.getValueType();
6557 
6558   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6559          "Expect an v8i16/v16i8 type");
6560   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6561   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6562   // extract the first 8 bytes into the top double word and the last 8 bytes
6563   // into the bottom double word. The v8i16 case is similar.
6564   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6565   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6566                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6567 }
6568 
6569 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6570   SDValue V1 = Op.getOperand(0);
6571   SDValue V2 = Op.getOperand(1);
6572   SDLoc dl(Op);
6573   EVT VT = Op.getValueType();
6574   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6575 
6576   // Convert shuffles that are directly supported on NEON to target-specific
6577   // DAG nodes, instead of keeping them as shuffles and matching them again
6578   // during code selection.  This is more efficient and avoids the possibility
6579   // of inconsistencies between legalization and selection.
6580   // FIXME: floating-point vectors should be canonicalized to integer vectors
6581   // of the same time so that they get CSEd properly.
6582   ArrayRef<int> ShuffleMask = SVN->getMask();
6583 
6584   unsigned EltSize = VT.getScalarSizeInBits();
6585   if (EltSize <= 32) {
6586     if (SVN->isSplat()) {
6587       int Lane = SVN->getSplatIndex();
6588       // If this is undef splat, generate it via "just" vdup, if possible.
6589       if (Lane == -1) Lane = 0;
6590 
6591       // Test if V1 is a SCALAR_TO_VECTOR.
6592       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6593         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6594       }
6595       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6596       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6597       // reaches it).
6598       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6599           !isa<ConstantSDNode>(V1.getOperand(0))) {
6600         bool IsScalarToVector = true;
6601         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6602           if (!V1.getOperand(i).isUndef()) {
6603             IsScalarToVector = false;
6604             break;
6605           }
6606         if (IsScalarToVector)
6607           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6608       }
6609       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6610                          DAG.getConstant(Lane, dl, MVT::i32));
6611     }
6612 
6613     bool ReverseVEXT;
6614     unsigned Imm;
6615     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6616       if (ReverseVEXT)
6617         std::swap(V1, V2);
6618       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6619                          DAG.getConstant(Imm, dl, MVT::i32));
6620     }
6621 
6622     if (isVREVMask(ShuffleMask, VT, 64))
6623       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6624     if (isVREVMask(ShuffleMask, VT, 32))
6625       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6626     if (isVREVMask(ShuffleMask, VT, 16))
6627       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6628 
6629     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6630       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6631                          DAG.getConstant(Imm, dl, MVT::i32));
6632     }
6633 
6634     // Check for Neon shuffles that modify both input vectors in place.
6635     // If both results are used, i.e., if there are two shuffles with the same
6636     // source operands and with masks corresponding to both results of one of
6637     // these operations, DAG memoization will ensure that a single node is
6638     // used for both shuffles.
6639     unsigned WhichResult;
6640     bool isV_UNDEF;
6641     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6642             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6643       if (isV_UNDEF)
6644         V2 = V1;
6645       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6646           .getValue(WhichResult);
6647     }
6648 
6649     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6650     // shuffles that produce a result larger than their operands with:
6651     //   shuffle(concat(v1, undef), concat(v2, undef))
6652     // ->
6653     //   shuffle(concat(v1, v2), undef)
6654     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6655     //
6656     // This is useful in the general case, but there are special cases where
6657     // native shuffles produce larger results: the two-result ops.
6658     //
6659     // Look through the concat when lowering them:
6660     //   shuffle(concat(v1, v2), undef)
6661     // ->
6662     //   concat(VZIP(v1, v2):0, :1)
6663     //
6664     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6665       SDValue SubV1 = V1->getOperand(0);
6666       SDValue SubV2 = V1->getOperand(1);
6667       EVT SubVT = SubV1.getValueType();
6668 
6669       // We expect these to have been canonicalized to -1.
6670       assert(llvm::all_of(ShuffleMask, [&](int i) {
6671         return i < (int)VT.getVectorNumElements();
6672       }) && "Unexpected shuffle index into UNDEF operand!");
6673 
6674       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6675               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6676         if (isV_UNDEF)
6677           SubV2 = SubV1;
6678         assert((WhichResult == 0) &&
6679                "In-place shuffle of concat can only have one result!");
6680         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6681                                   SubV1, SubV2);
6682         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6683                            Res.getValue(1));
6684       }
6685     }
6686   }
6687 
6688   // If the shuffle is not directly supported and it has 4 elements, use
6689   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6690   unsigned NumElts = VT.getVectorNumElements();
6691   if (NumElts == 4) {
6692     unsigned PFIndexes[4];
6693     for (unsigned i = 0; i != 4; ++i) {
6694       if (ShuffleMask[i] < 0)
6695         PFIndexes[i] = 8;
6696       else
6697         PFIndexes[i] = ShuffleMask[i];
6698     }
6699 
6700     // Compute the index in the perfect shuffle table.
6701     unsigned PFTableIndex =
6702       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6703     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6704     unsigned Cost = (PFEntry >> 30);
6705 
6706     if (Cost <= 4)
6707       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6708   }
6709 
6710   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6711   if (EltSize >= 32) {
6712     // Do the expansion with floating-point types, since that is what the VFP
6713     // registers are defined to use, and since i64 is not legal.
6714     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6715     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6716     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6717     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6718     SmallVector<SDValue, 8> Ops;
6719     for (unsigned i = 0; i < NumElts; ++i) {
6720       if (ShuffleMask[i] < 0)
6721         Ops.push_back(DAG.getUNDEF(EltVT));
6722       else
6723         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6724                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6725                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6726                                                   dl, MVT::i32)));
6727     }
6728     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6729     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6730   }
6731 
6732   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6733     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6734 
6735   if (VT == MVT::v8i8)
6736     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6737       return NewOp;
6738 
6739   return SDValue();
6740 }
6741 
6742 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6743   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6744   SDValue Lane = Op.getOperand(2);
6745   if (!isa<ConstantSDNode>(Lane))
6746     return SDValue();
6747 
6748   return Op;
6749 }
6750 
6751 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6752   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6753   SDValue Lane = Op.getOperand(1);
6754   if (!isa<ConstantSDNode>(Lane))
6755     return SDValue();
6756 
6757   SDValue Vec = Op.getOperand(0);
6758   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6759     SDLoc dl(Op);
6760     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6761   }
6762 
6763   return Op;
6764 }
6765 
6766 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6767   // The only time a CONCAT_VECTORS operation can have legal types is when
6768   // two 64-bit vectors are concatenated to a 128-bit vector.
6769   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6770          "unexpected CONCAT_VECTORS");
6771   SDLoc dl(Op);
6772   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6773   SDValue Op0 = Op.getOperand(0);
6774   SDValue Op1 = Op.getOperand(1);
6775   if (!Op0.isUndef())
6776     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6777                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6778                       DAG.getIntPtrConstant(0, dl));
6779   if (!Op1.isUndef())
6780     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6781                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6782                       DAG.getIntPtrConstant(1, dl));
6783   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6784 }
6785 
6786 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6787 /// element has been zero/sign-extended, depending on the isSigned parameter,
6788 /// from an integer type half its size.
6789 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6790                                    bool isSigned) {
6791   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6792   EVT VT = N->getValueType(0);
6793   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6794     SDNode *BVN = N->getOperand(0).getNode();
6795     if (BVN->getValueType(0) != MVT::v4i32 ||
6796         BVN->getOpcode() != ISD::BUILD_VECTOR)
6797       return false;
6798     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6799     unsigned HiElt = 1 - LoElt;
6800     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6801     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6802     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6803     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6804     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6805       return false;
6806     if (isSigned) {
6807       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6808           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6809         return true;
6810     } else {
6811       if (Hi0->isNullValue() && Hi1->isNullValue())
6812         return true;
6813     }
6814     return false;
6815   }
6816 
6817   if (N->getOpcode() != ISD::BUILD_VECTOR)
6818     return false;
6819 
6820   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6821     SDNode *Elt = N->getOperand(i).getNode();
6822     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6823       unsigned EltSize = VT.getScalarSizeInBits();
6824       unsigned HalfSize = EltSize / 2;
6825       if (isSigned) {
6826         if (!isIntN(HalfSize, C->getSExtValue()))
6827           return false;
6828       } else {
6829         if (!isUIntN(HalfSize, C->getZExtValue()))
6830           return false;
6831       }
6832       continue;
6833     }
6834     return false;
6835   }
6836 
6837   return true;
6838 }
6839 
6840 /// isSignExtended - Check if a node is a vector value that is sign-extended
6841 /// or a constant BUILD_VECTOR with sign-extended elements.
6842 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6843   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6844     return true;
6845   if (isExtendedBUILD_VECTOR(N, DAG, true))
6846     return true;
6847   return false;
6848 }
6849 
6850 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6851 /// or a constant BUILD_VECTOR with zero-extended elements.
6852 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6853   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6854     return true;
6855   if (isExtendedBUILD_VECTOR(N, DAG, false))
6856     return true;
6857   return false;
6858 }
6859 
6860 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6861   if (OrigVT.getSizeInBits() >= 64)
6862     return OrigVT;
6863 
6864   assert(OrigVT.isSimple() && "Expecting a simple value type");
6865 
6866   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6867   switch (OrigSimpleTy) {
6868   default: llvm_unreachable("Unexpected Vector Type");
6869   case MVT::v2i8:
6870   case MVT::v2i16:
6871      return MVT::v2i32;
6872   case MVT::v4i8:
6873     return  MVT::v4i16;
6874   }
6875 }
6876 
6877 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6878 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6879 /// We insert the required extension here to get the vector to fill a D register.
6880 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6881                                             const EVT &OrigTy,
6882                                             const EVT &ExtTy,
6883                                             unsigned ExtOpcode) {
6884   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6885   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6886   // 64-bits we need to insert a new extension so that it will be 64-bits.
6887   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6888   if (OrigTy.getSizeInBits() >= 64)
6889     return N;
6890 
6891   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6892   EVT NewVT = getExtensionTo64Bits(OrigTy);
6893 
6894   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6895 }
6896 
6897 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6898 /// does not do any sign/zero extension. If the original vector is less
6899 /// than 64 bits, an appropriate extension will be added after the load to
6900 /// reach a total size of 64 bits. We have to add the extension separately
6901 /// because ARM does not have a sign/zero extending load for vectors.
6902 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6903   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6904 
6905   // The load already has the right type.
6906   if (ExtendedTy == LD->getMemoryVT())
6907     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6908                        LD->getBasePtr(), LD->getPointerInfo(),
6909                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6910 
6911   // We need to create a zextload/sextload. We cannot just create a load
6912   // followed by a zext/zext node because LowerMUL is also run during normal
6913   // operation legalization where we can't create illegal types.
6914   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6915                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6916                         LD->getMemoryVT(), LD->getAlignment(),
6917                         LD->getMemOperand()->getFlags());
6918 }
6919 
6920 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6921 /// extending load, or BUILD_VECTOR with extended elements, return the
6922 /// unextended value. The unextended vector should be 64 bits so that it can
6923 /// be used as an operand to a VMULL instruction. If the original vector size
6924 /// before extension is less than 64 bits we add a an extension to resize
6925 /// the vector to 64 bits.
6926 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6927   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6928     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6929                                         N->getOperand(0)->getValueType(0),
6930                                         N->getValueType(0),
6931                                         N->getOpcode());
6932 
6933   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6934     return SkipLoadExtensionForVMULL(LD, DAG);
6935 
6936   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6937   // have been legalized as a BITCAST from v4i32.
6938   if (N->getOpcode() == ISD::BITCAST) {
6939     SDNode *BVN = N->getOperand(0).getNode();
6940     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6941            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6942     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6943     return DAG.getBuildVector(
6944         MVT::v2i32, SDLoc(N),
6945         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
6946   }
6947   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6948   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6949   EVT VT = N->getValueType(0);
6950   unsigned EltSize = VT.getScalarSizeInBits() / 2;
6951   unsigned NumElts = VT.getVectorNumElements();
6952   MVT TruncVT = MVT::getIntegerVT(EltSize);
6953   SmallVector<SDValue, 8> Ops;
6954   SDLoc dl(N);
6955   for (unsigned i = 0; i != NumElts; ++i) {
6956     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6957     const APInt &CInt = C->getAPIntValue();
6958     // Element types smaller than 32 bits are not legal, so use i32 elements.
6959     // The values are implicitly truncated so sext vs. zext doesn't matter.
6960     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6961   }
6962   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
6963 }
6964 
6965 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6966   unsigned Opcode = N->getOpcode();
6967   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6968     SDNode *N0 = N->getOperand(0).getNode();
6969     SDNode *N1 = N->getOperand(1).getNode();
6970     return N0->hasOneUse() && N1->hasOneUse() &&
6971       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6972   }
6973   return false;
6974 }
6975 
6976 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6977   unsigned Opcode = N->getOpcode();
6978   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6979     SDNode *N0 = N->getOperand(0).getNode();
6980     SDNode *N1 = N->getOperand(1).getNode();
6981     return N0->hasOneUse() && N1->hasOneUse() &&
6982       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6983   }
6984   return false;
6985 }
6986 
6987 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6988   // Multiplications are only custom-lowered for 128-bit vectors so that
6989   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6990   EVT VT = Op.getValueType();
6991   assert(VT.is128BitVector() && VT.isInteger() &&
6992          "unexpected type for custom-lowering ISD::MUL");
6993   SDNode *N0 = Op.getOperand(0).getNode();
6994   SDNode *N1 = Op.getOperand(1).getNode();
6995   unsigned NewOpc = 0;
6996   bool isMLA = false;
6997   bool isN0SExt = isSignExtended(N0, DAG);
6998   bool isN1SExt = isSignExtended(N1, DAG);
6999   if (isN0SExt && isN1SExt)
7000     NewOpc = ARMISD::VMULLs;
7001   else {
7002     bool isN0ZExt = isZeroExtended(N0, DAG);
7003     bool isN1ZExt = isZeroExtended(N1, DAG);
7004     if (isN0ZExt && isN1ZExt)
7005       NewOpc = ARMISD::VMULLu;
7006     else if (isN1SExt || isN1ZExt) {
7007       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7008       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7009       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7010         NewOpc = ARMISD::VMULLs;
7011         isMLA = true;
7012       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7013         NewOpc = ARMISD::VMULLu;
7014         isMLA = true;
7015       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7016         std::swap(N0, N1);
7017         NewOpc = ARMISD::VMULLu;
7018         isMLA = true;
7019       }
7020     }
7021 
7022     if (!NewOpc) {
7023       if (VT == MVT::v2i64)
7024         // Fall through to expand this.  It is not legal.
7025         return SDValue();
7026       else
7027         // Other vector multiplications are legal.
7028         return Op;
7029     }
7030   }
7031 
7032   // Legalize to a VMULL instruction.
7033   SDLoc DL(Op);
7034   SDValue Op0;
7035   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7036   if (!isMLA) {
7037     Op0 = SkipExtensionForVMULL(N0, DAG);
7038     assert(Op0.getValueType().is64BitVector() &&
7039            Op1.getValueType().is64BitVector() &&
7040            "unexpected types for extended operands to VMULL");
7041     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7042   }
7043 
7044   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7045   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7046   //   vmull q0, d4, d6
7047   //   vmlal q0, d5, d6
7048   // is faster than
7049   //   vaddl q0, d4, d5
7050   //   vmovl q1, d6
7051   //   vmul  q0, q0, q1
7052   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7053   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7054   EVT Op1VT = Op1.getValueType();
7055   return DAG.getNode(N0->getOpcode(), DL, VT,
7056                      DAG.getNode(NewOpc, DL, VT,
7057                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7058                      DAG.getNode(NewOpc, DL, VT,
7059                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7060 }
7061 
7062 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7063                               SelectionDAG &DAG) {
7064   // TODO: Should this propagate fast-math-flags?
7065 
7066   // Convert to float
7067   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7068   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7069   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7070   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7071   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7072   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7073   // Get reciprocal estimate.
7074   // float4 recip = vrecpeq_f32(yf);
7075   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7076                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7077                    Y);
7078   // Because char has a smaller range than uchar, we can actually get away
7079   // without any newton steps.  This requires that we use a weird bias
7080   // of 0xb000, however (again, this has been exhaustively tested).
7081   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7082   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7083   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7084   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7085   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7086   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7087   // Convert back to short.
7088   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7089   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7090   return X;
7091 }
7092 
7093 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7094                                SelectionDAG &DAG) {
7095   // TODO: Should this propagate fast-math-flags?
7096 
7097   SDValue N2;
7098   // Convert to float.
7099   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7100   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7101   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7102   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7103   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7104   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7105 
7106   // Use reciprocal estimate and one refinement step.
7107   // float4 recip = vrecpeq_f32(yf);
7108   // recip *= vrecpsq_f32(yf, recip);
7109   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7110                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7111                    N1);
7112   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7113                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7114                    N1, N2);
7115   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7116   // Because short has a smaller range than ushort, we can actually get away
7117   // with only a single newton step.  This requires that we use a weird bias
7118   // of 89, however (again, this has been exhaustively tested).
7119   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7120   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7121   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7122   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7123   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7124   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7125   // Convert back to integer and return.
7126   // return vmovn_s32(vcvt_s32_f32(result));
7127   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7128   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7129   return N0;
7130 }
7131 
7132 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7133   EVT VT = Op.getValueType();
7134   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7135          "unexpected type for custom-lowering ISD::SDIV");
7136 
7137   SDLoc dl(Op);
7138   SDValue N0 = Op.getOperand(0);
7139   SDValue N1 = Op.getOperand(1);
7140   SDValue N2, N3;
7141 
7142   if (VT == MVT::v8i8) {
7143     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7144     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7145 
7146     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7147                      DAG.getIntPtrConstant(4, dl));
7148     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7149                      DAG.getIntPtrConstant(4, dl));
7150     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7151                      DAG.getIntPtrConstant(0, dl));
7152     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7153                      DAG.getIntPtrConstant(0, dl));
7154 
7155     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7156     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7157 
7158     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7159     N0 = LowerCONCAT_VECTORS(N0, DAG);
7160 
7161     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7162     return N0;
7163   }
7164   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7165 }
7166 
7167 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7168   // TODO: Should this propagate fast-math-flags?
7169   EVT VT = Op.getValueType();
7170   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7171          "unexpected type for custom-lowering ISD::UDIV");
7172 
7173   SDLoc dl(Op);
7174   SDValue N0 = Op.getOperand(0);
7175   SDValue N1 = Op.getOperand(1);
7176   SDValue N2, N3;
7177 
7178   if (VT == MVT::v8i8) {
7179     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7180     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7181 
7182     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7183                      DAG.getIntPtrConstant(4, dl));
7184     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7185                      DAG.getIntPtrConstant(4, dl));
7186     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7187                      DAG.getIntPtrConstant(0, dl));
7188     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7189                      DAG.getIntPtrConstant(0, dl));
7190 
7191     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7192     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7193 
7194     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7195     N0 = LowerCONCAT_VECTORS(N0, DAG);
7196 
7197     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7198                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7199                                      MVT::i32),
7200                      N0);
7201     return N0;
7202   }
7203 
7204   // v4i16 sdiv ... Convert to float.
7205   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7206   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7207   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7208   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7209   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7210   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7211 
7212   // Use reciprocal estimate and two refinement steps.
7213   // float4 recip = vrecpeq_f32(yf);
7214   // recip *= vrecpsq_f32(yf, recip);
7215   // recip *= vrecpsq_f32(yf, recip);
7216   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7217                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7218                    BN1);
7219   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7220                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7221                    BN1, N2);
7222   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7223   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7224                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7225                    BN1, N2);
7226   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7227   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7228   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7229   // and that it will never cause us to return an answer too large).
7230   // float4 result = as_float4(as_int4(xf*recip) + 2);
7231   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7232   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7233   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7234   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7235   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7236   // Convert back to integer and return.
7237   // return vmovn_u32(vcvt_s32_f32(result));
7238   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7239   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7240   return N0;
7241 }
7242 
7243 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7244   EVT VT = Op.getNode()->getValueType(0);
7245   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7246 
7247   unsigned Opc;
7248   bool ExtraOp = false;
7249   switch (Op.getOpcode()) {
7250   default: llvm_unreachable("Invalid code");
7251   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7252   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7253   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7254   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7255   }
7256 
7257   if (!ExtraOp)
7258     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7259                        Op.getOperand(1));
7260   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7261                      Op.getOperand(1), Op.getOperand(2));
7262 }
7263 
7264 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7265   assert(Subtarget->isTargetDarwin());
7266 
7267   // For iOS, we want to call an alternative entry point: __sincos_stret,
7268   // return values are passed via sret.
7269   SDLoc dl(Op);
7270   SDValue Arg = Op.getOperand(0);
7271   EVT ArgVT = Arg.getValueType();
7272   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7273   auto PtrVT = getPointerTy(DAG.getDataLayout());
7274 
7275   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7277 
7278   // Pair of floats / doubles used to pass the result.
7279   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7280   auto &DL = DAG.getDataLayout();
7281 
7282   ArgListTy Args;
7283   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7284   SDValue SRet;
7285   if (ShouldUseSRet) {
7286     // Create stack object for sret.
7287     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7288     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7289     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7290     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7291 
7292     ArgListEntry Entry;
7293     Entry.Node = SRet;
7294     Entry.Ty = RetTy->getPointerTo();
7295     Entry.isSExt = false;
7296     Entry.isZExt = false;
7297     Entry.isSRet = true;
7298     Args.push_back(Entry);
7299     RetTy = Type::getVoidTy(*DAG.getContext());
7300   }
7301 
7302   ArgListEntry Entry;
7303   Entry.Node = Arg;
7304   Entry.Ty = ArgTy;
7305   Entry.isSExt = false;
7306   Entry.isZExt = false;
7307   Args.push_back(Entry);
7308 
7309   const char *LibcallName =
7310       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7311   RTLIB::Libcall LC =
7312       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7313   CallingConv::ID CC = getLibcallCallingConv(LC);
7314   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7315 
7316   TargetLowering::CallLoweringInfo CLI(DAG);
7317   CLI.setDebugLoc(dl)
7318       .setChain(DAG.getEntryNode())
7319       .setCallee(CC, RetTy, Callee, std::move(Args))
7320       .setDiscardResult(ShouldUseSRet);
7321   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7322 
7323   if (!ShouldUseSRet)
7324     return CallResult.first;
7325 
7326   SDValue LoadSin =
7327       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7328 
7329   // Address of cos field.
7330   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7331                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7332   SDValue LoadCos =
7333       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7334 
7335   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7336   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7337                      LoadSin.getValue(0), LoadCos.getValue(0));
7338 }
7339 
7340 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7341                                                   bool Signed,
7342                                                   SDValue &Chain) const {
7343   EVT VT = Op.getValueType();
7344   assert((VT == MVT::i32 || VT == MVT::i64) &&
7345          "unexpected type for custom lowering DIV");
7346   SDLoc dl(Op);
7347 
7348   const auto &DL = DAG.getDataLayout();
7349   const auto &TLI = DAG.getTargetLoweringInfo();
7350 
7351   const char *Name = nullptr;
7352   if (Signed)
7353     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7354   else
7355     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7356 
7357   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7358 
7359   ARMTargetLowering::ArgListTy Args;
7360 
7361   for (auto AI : {1, 0}) {
7362     ArgListEntry Arg;
7363     Arg.Node = Op.getOperand(AI);
7364     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7365     Args.push_back(Arg);
7366   }
7367 
7368   CallLoweringInfo CLI(DAG);
7369   CLI.setDebugLoc(dl)
7370     .setChain(Chain)
7371     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7372                ES, std::move(Args));
7373 
7374   return LowerCallTo(CLI).first;
7375 }
7376 
7377 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7378                                             bool Signed) const {
7379   assert(Op.getValueType() == MVT::i32 &&
7380          "unexpected type for custom lowering DIV");
7381   SDLoc dl(Op);
7382 
7383   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7384                                DAG.getEntryNode(), Op.getOperand(1));
7385 
7386   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7387 }
7388 
7389 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7390   SDLoc DL(N);
7391   SDValue Op = N->getOperand(1);
7392   if (N->getValueType(0) == MVT::i32)
7393     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7394   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7395                            DAG.getConstant(0, DL, MVT::i32));
7396   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7397                            DAG.getConstant(1, DL, MVT::i32));
7398   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7399                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7400 }
7401 
7402 void ARMTargetLowering::ExpandDIV_Windows(
7403     SDValue Op, SelectionDAG &DAG, bool Signed,
7404     SmallVectorImpl<SDValue> &Results) const {
7405   const auto &DL = DAG.getDataLayout();
7406   const auto &TLI = DAG.getTargetLoweringInfo();
7407 
7408   assert(Op.getValueType() == MVT::i64 &&
7409          "unexpected type for custom lowering DIV");
7410   SDLoc dl(Op);
7411 
7412   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7413 
7414   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7415 
7416   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7417   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7418                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7419   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7420 
7421   Results.push_back(Lower);
7422   Results.push_back(Upper);
7423 }
7424 
7425 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7426   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7427     // Acquire/Release load/store is not legal for targets without a dmb or
7428     // equivalent available.
7429     return SDValue();
7430 
7431   // Monotonic load/store is legal for all targets.
7432   return Op;
7433 }
7434 
7435 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7436                                     SmallVectorImpl<SDValue> &Results,
7437                                     SelectionDAG &DAG,
7438                                     const ARMSubtarget *Subtarget) {
7439   SDLoc DL(N);
7440   // Under Power Management extensions, the cycle-count is:
7441   //    mrc p15, #0, <Rt>, c9, c13, #0
7442   SDValue Ops[] = { N->getOperand(0), // Chain
7443                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7444                     DAG.getConstant(15, DL, MVT::i32),
7445                     DAG.getConstant(0, DL, MVT::i32),
7446                     DAG.getConstant(9, DL, MVT::i32),
7447                     DAG.getConstant(13, DL, MVT::i32),
7448                     DAG.getConstant(0, DL, MVT::i32)
7449   };
7450 
7451   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7452                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7453   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7454                                 DAG.getConstant(0, DL, MVT::i32)));
7455   Results.push_back(Cycles32.getValue(1));
7456 }
7457 
7458 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7459   SDLoc dl(V.getNode());
7460   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7461   SDValue VHi = DAG.getAnyExtOrTrunc(
7462       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7463       dl, MVT::i32);
7464   SDValue RegClass =
7465       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7466   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7467   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7468   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7469   return SDValue(
7470       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7471 }
7472 
7473 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7474                                        SmallVectorImpl<SDValue> & Results,
7475                                        SelectionDAG &DAG) {
7476   assert(N->getValueType(0) == MVT::i64 &&
7477          "AtomicCmpSwap on types less than 64 should be legal");
7478   SDValue Ops[] = {N->getOperand(1),
7479                    createGPRPairNode(DAG, N->getOperand(2)),
7480                    createGPRPairNode(DAG, N->getOperand(3)),
7481                    N->getOperand(0)};
7482   SDNode *CmpSwap = DAG.getMachineNode(
7483       ARM::CMP_SWAP_64, SDLoc(N),
7484       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7485 
7486   MachineFunction &MF = DAG.getMachineFunction();
7487   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7488   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7489   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7490 
7491   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7492                                                SDValue(CmpSwap, 0)));
7493   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7494                                                SDValue(CmpSwap, 0)));
7495   Results.push_back(SDValue(CmpSwap, 2));
7496 }
7497 
7498 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7499                           SelectionDAG &DAG) {
7500   const auto &TLI = DAG.getTargetLoweringInfo();
7501 
7502   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7503          "Custom lowering is MSVCRT specific!");
7504 
7505   SDLoc dl(Op);
7506   SDValue Val = Op.getOperand(0);
7507   MVT Ty = Val->getSimpleValueType(0);
7508   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7509   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7510                                          TLI.getPointerTy(DAG.getDataLayout()));
7511 
7512   TargetLowering::ArgListTy Args;
7513   TargetLowering::ArgListEntry Entry;
7514 
7515   Entry.Node = Val;
7516   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7517   Entry.isZExt = true;
7518   Args.push_back(Entry);
7519 
7520   Entry.Node = Exponent;
7521   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7522   Entry.isZExt = true;
7523   Args.push_back(Entry);
7524 
7525   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7526 
7527   // In the in-chain to the call is the entry node  If we are emitting a
7528   // tailcall, the chain will be mutated if the node has a non-entry input
7529   // chain.
7530   SDValue InChain = DAG.getEntryNode();
7531   SDValue TCChain = InChain;
7532 
7533   const auto *F = DAG.getMachineFunction().getFunction();
7534   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7535               F->getReturnType() == LCRTy;
7536   if (IsTC)
7537     InChain = TCChain;
7538 
7539   TargetLowering::CallLoweringInfo CLI(DAG);
7540   CLI.setDebugLoc(dl)
7541       .setChain(InChain)
7542       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7543       .setTailCall(IsTC);
7544   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7545 
7546   // Return the chain (the DAG root) if it is a tail call
7547   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7548 }
7549 
7550 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7551   switch (Op.getOpcode()) {
7552   default: llvm_unreachable("Don't know how to custom lower this!");
7553   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7554   case ISD::ConstantPool:
7555     if (Subtarget->genExecuteOnly())
7556       llvm_unreachable("execute-only should not generate constant pools");
7557     return LowerConstantPool(Op, DAG);
7558   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7559   case ISD::GlobalAddress:
7560     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7561     default: llvm_unreachable("unknown object format");
7562     case Triple::COFF:
7563       return LowerGlobalAddressWindows(Op, DAG);
7564     case Triple::ELF:
7565       return LowerGlobalAddressELF(Op, DAG);
7566     case Triple::MachO:
7567       return LowerGlobalAddressDarwin(Op, DAG);
7568     }
7569   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7570   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7571   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7572   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7573   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7574   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7575   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7576   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7577   case ISD::SINT_TO_FP:
7578   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7579   case ISD::FP_TO_SINT:
7580   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7581   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7582   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7583   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7584   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7585   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7586   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7587   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7588                                                                Subtarget);
7589   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7590   case ISD::SHL:
7591   case ISD::SRL:
7592   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7593   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7594   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7595   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7596   case ISD::SRL_PARTS:
7597   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7598   case ISD::CTTZ:
7599   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7600   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7601   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7602   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7603   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7604   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7605   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7606   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7607   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7608   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7609   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7610   case ISD::MUL:           return LowerMUL(Op, DAG);
7611   case ISD::SDIV:
7612     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7613       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7614     return LowerSDIV(Op, DAG);
7615   case ISD::UDIV:
7616     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7617       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7618     return LowerUDIV(Op, DAG);
7619   case ISD::ADDC:
7620   case ISD::ADDE:
7621   case ISD::SUBC:
7622   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7623   case ISD::SADDO:
7624   case ISD::UADDO:
7625   case ISD::SSUBO:
7626   case ISD::USUBO:
7627     return LowerXALUO(Op, DAG);
7628   case ISD::ATOMIC_LOAD:
7629   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7630   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7631   case ISD::SDIVREM:
7632   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7633   case ISD::DYNAMIC_STACKALLOC:
7634     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7635       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7636     llvm_unreachable("Don't know how to custom lower this!");
7637   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7638   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7639   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7640   case ARMISD::WIN__DBZCHK: return SDValue();
7641   }
7642 }
7643 
7644 /// ReplaceNodeResults - Replace the results of node with an illegal result
7645 /// type with new values built out of custom code.
7646 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7647                                            SmallVectorImpl<SDValue> &Results,
7648                                            SelectionDAG &DAG) const {
7649   SDValue Res;
7650   switch (N->getOpcode()) {
7651   default:
7652     llvm_unreachable("Don't know how to custom expand this!");
7653   case ISD::READ_REGISTER:
7654     ExpandREAD_REGISTER(N, Results, DAG);
7655     break;
7656   case ISD::BITCAST:
7657     Res = ExpandBITCAST(N, DAG);
7658     break;
7659   case ISD::SRL:
7660   case ISD::SRA:
7661     Res = Expand64BitShift(N, DAG, Subtarget);
7662     break;
7663   case ISD::SREM:
7664   case ISD::UREM:
7665     Res = LowerREM(N, DAG);
7666     break;
7667   case ISD::SDIVREM:
7668   case ISD::UDIVREM:
7669     Res = LowerDivRem(SDValue(N, 0), DAG);
7670     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7671     Results.push_back(Res.getValue(0));
7672     Results.push_back(Res.getValue(1));
7673     return;
7674   case ISD::READCYCLECOUNTER:
7675     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7676     return;
7677   case ISD::UDIV:
7678   case ISD::SDIV:
7679     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7680     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7681                              Results);
7682   case ISD::ATOMIC_CMP_SWAP:
7683     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7684     return;
7685   }
7686   if (Res.getNode())
7687     Results.push_back(Res);
7688 }
7689 
7690 //===----------------------------------------------------------------------===//
7691 //                           ARM Scheduler Hooks
7692 //===----------------------------------------------------------------------===//
7693 
7694 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7695 /// registers the function context.
7696 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7697                                                MachineBasicBlock *MBB,
7698                                                MachineBasicBlock *DispatchBB,
7699                                                int FI) const {
7700   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7701          "ROPI/RWPI not currently supported with SjLj");
7702   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7703   DebugLoc dl = MI.getDebugLoc();
7704   MachineFunction *MF = MBB->getParent();
7705   MachineRegisterInfo *MRI = &MF->getRegInfo();
7706   MachineConstantPool *MCP = MF->getConstantPool();
7707   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7708   const Function *F = MF->getFunction();
7709 
7710   bool isThumb = Subtarget->isThumb();
7711   bool isThumb2 = Subtarget->isThumb2();
7712 
7713   unsigned PCLabelId = AFI->createPICLabelUId();
7714   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7715   ARMConstantPoolValue *CPV =
7716     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7717   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7718 
7719   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7720                                            : &ARM::GPRRegClass;
7721 
7722   // Grab constant pool and fixed stack memory operands.
7723   MachineMemOperand *CPMMO =
7724       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7725                                MachineMemOperand::MOLoad, 4, 4);
7726 
7727   MachineMemOperand *FIMMOSt =
7728       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7729                                MachineMemOperand::MOStore, 4, 4);
7730 
7731   // Load the address of the dispatch MBB into the jump buffer.
7732   if (isThumb2) {
7733     // Incoming value: jbuf
7734     //   ldr.n  r5, LCPI1_1
7735     //   orr    r5, r5, #1
7736     //   add    r5, pc
7737     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7738     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7739     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7740         .addConstantPoolIndex(CPI)
7741         .addMemOperand(CPMMO)
7742         .add(predOps(ARMCC::AL));
7743     // Set the low bit because of thumb mode.
7744     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7745     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7746         .addReg(NewVReg1, RegState::Kill)
7747         .addImm(0x01)
7748         .add(predOps(ARMCC::AL))
7749         .add(condCodeOp());
7750     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7751     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7752       .addReg(NewVReg2, RegState::Kill)
7753       .addImm(PCLabelId);
7754     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7755         .addReg(NewVReg3, RegState::Kill)
7756         .addFrameIndex(FI)
7757         .addImm(36) // &jbuf[1] :: pc
7758         .addMemOperand(FIMMOSt)
7759         .add(predOps(ARMCC::AL));
7760   } else if (isThumb) {
7761     // Incoming value: jbuf
7762     //   ldr.n  r1, LCPI1_4
7763     //   add    r1, pc
7764     //   mov    r2, #1
7765     //   orrs   r1, r2
7766     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7767     //   str    r1, [r2]
7768     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7769     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7770         .addConstantPoolIndex(CPI)
7771         .addMemOperand(CPMMO)
7772         .add(predOps(ARMCC::AL));
7773     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7774     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7775       .addReg(NewVReg1, RegState::Kill)
7776       .addImm(PCLabelId);
7777     // Set the low bit because of thumb mode.
7778     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7779     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7780         .addReg(ARM::CPSR, RegState::Define)
7781         .addImm(1)
7782         .add(predOps(ARMCC::AL));
7783     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7784     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7785         .addReg(ARM::CPSR, RegState::Define)
7786         .addReg(NewVReg2, RegState::Kill)
7787         .addReg(NewVReg3, RegState::Kill)
7788         .add(predOps(ARMCC::AL));
7789     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7790     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7791             .addFrameIndex(FI)
7792             .addImm(36); // &jbuf[1] :: pc
7793     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7794         .addReg(NewVReg4, RegState::Kill)
7795         .addReg(NewVReg5, RegState::Kill)
7796         .addImm(0)
7797         .addMemOperand(FIMMOSt)
7798         .add(predOps(ARMCC::AL));
7799   } else {
7800     // Incoming value: jbuf
7801     //   ldr  r1, LCPI1_1
7802     //   add  r1, pc, r1
7803     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7804     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7805     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7806         .addConstantPoolIndex(CPI)
7807         .addImm(0)
7808         .addMemOperand(CPMMO)
7809         .add(predOps(ARMCC::AL));
7810     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7811     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7812         .addReg(NewVReg1, RegState::Kill)
7813         .addImm(PCLabelId)
7814         .add(predOps(ARMCC::AL));
7815     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7816         .addReg(NewVReg2, RegState::Kill)
7817         .addFrameIndex(FI)
7818         .addImm(36) // &jbuf[1] :: pc
7819         .addMemOperand(FIMMOSt)
7820         .add(predOps(ARMCC::AL));
7821   }
7822 }
7823 
7824 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7825                                               MachineBasicBlock *MBB) const {
7826   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7827   DebugLoc dl = MI.getDebugLoc();
7828   MachineFunction *MF = MBB->getParent();
7829   MachineRegisterInfo *MRI = &MF->getRegInfo();
7830   MachineFrameInfo &MFI = MF->getFrameInfo();
7831   int FI = MFI.getFunctionContextIndex();
7832 
7833   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7834                                                         : &ARM::GPRnopcRegClass;
7835 
7836   // Get a mapping of the call site numbers to all of the landing pads they're
7837   // associated with.
7838   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
7839   unsigned MaxCSNum = 0;
7840   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7841        ++BB) {
7842     if (!BB->isEHPad()) continue;
7843 
7844     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7845     // pad.
7846     for (MachineBasicBlock::iterator
7847            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7848       if (!II->isEHLabel()) continue;
7849 
7850       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7851       if (!MF->hasCallSiteLandingPad(Sym)) continue;
7852 
7853       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
7854       for (SmallVectorImpl<unsigned>::iterator
7855              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7856            CSI != CSE; ++CSI) {
7857         CallSiteNumToLPad[*CSI].push_back(&*BB);
7858         MaxCSNum = std::max(MaxCSNum, *CSI);
7859       }
7860       break;
7861     }
7862   }
7863 
7864   // Get an ordered list of the machine basic blocks for the jump table.
7865   std::vector<MachineBasicBlock*> LPadList;
7866   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7867   LPadList.reserve(CallSiteNumToLPad.size());
7868   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7869     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7870     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7871            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7872       LPadList.push_back(*II);
7873       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7874     }
7875   }
7876 
7877   assert(!LPadList.empty() &&
7878          "No landing pad destinations for the dispatch jump table!");
7879 
7880   // Create the jump table and associated information.
7881   MachineJumpTableInfo *JTI =
7882     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7883   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7884 
7885   // Create the MBBs for the dispatch code.
7886 
7887   // Shove the dispatch's address into the return slot in the function context.
7888   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7889   DispatchBB->setIsEHPad();
7890 
7891   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7892   unsigned trap_opcode;
7893   if (Subtarget->isThumb())
7894     trap_opcode = ARM::tTRAP;
7895   else
7896     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7897 
7898   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7899   DispatchBB->addSuccessor(TrapBB);
7900 
7901   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7902   DispatchBB->addSuccessor(DispContBB);
7903 
7904   // Insert and MBBs.
7905   MF->insert(MF->end(), DispatchBB);
7906   MF->insert(MF->end(), DispContBB);
7907   MF->insert(MF->end(), TrapBB);
7908 
7909   // Insert code into the entry block that creates and registers the function
7910   // context.
7911   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7912 
7913   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7914       MachinePointerInfo::getFixedStack(*MF, FI),
7915       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7916 
7917   MachineInstrBuilder MIB;
7918   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7919 
7920   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7921   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7922 
7923   // Add a register mask with no preserved registers.  This results in all
7924   // registers being marked as clobbered. This can't work if the dispatch block
7925   // is in a Thumb1 function and is linked with ARM code which uses the FP
7926   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
7927   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
7928 
7929   bool IsPositionIndependent = isPositionIndependent();
7930   unsigned NumLPads = LPadList.size();
7931   if (Subtarget->isThumb2()) {
7932     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7933     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7934         .addFrameIndex(FI)
7935         .addImm(4)
7936         .addMemOperand(FIMMOLd)
7937         .add(predOps(ARMCC::AL));
7938 
7939     if (NumLPads < 256) {
7940       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7941           .addReg(NewVReg1)
7942           .addImm(LPadList.size())
7943           .add(predOps(ARMCC::AL));
7944     } else {
7945       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7946       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7947           .addImm(NumLPads & 0xFFFF)
7948           .add(predOps(ARMCC::AL));
7949 
7950       unsigned VReg2 = VReg1;
7951       if ((NumLPads & 0xFFFF0000) != 0) {
7952         VReg2 = MRI->createVirtualRegister(TRC);
7953         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7954             .addReg(VReg1)
7955             .addImm(NumLPads >> 16)
7956             .add(predOps(ARMCC::AL));
7957       }
7958 
7959       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7960           .addReg(NewVReg1)
7961           .addReg(VReg2)
7962           .add(predOps(ARMCC::AL));
7963     }
7964 
7965     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7966       .addMBB(TrapBB)
7967       .addImm(ARMCC::HI)
7968       .addReg(ARM::CPSR);
7969 
7970     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7971     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
7972         .addJumpTableIndex(MJTI)
7973         .add(predOps(ARMCC::AL));
7974 
7975     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7976     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7977         .addReg(NewVReg3, RegState::Kill)
7978         .addReg(NewVReg1)
7979         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
7980         .add(predOps(ARMCC::AL))
7981         .add(condCodeOp());
7982 
7983     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7984       .addReg(NewVReg4, RegState::Kill)
7985       .addReg(NewVReg1)
7986       .addJumpTableIndex(MJTI);
7987   } else if (Subtarget->isThumb()) {
7988     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7989     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7990         .addFrameIndex(FI)
7991         .addImm(1)
7992         .addMemOperand(FIMMOLd)
7993         .add(predOps(ARMCC::AL));
7994 
7995     if (NumLPads < 256) {
7996       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7997           .addReg(NewVReg1)
7998           .addImm(NumLPads)
7999           .add(predOps(ARMCC::AL));
8000     } else {
8001       MachineConstantPool *ConstantPool = MF->getConstantPool();
8002       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8003       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8004 
8005       // MachineConstantPool wants an explicit alignment.
8006       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8007       if (Align == 0)
8008         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8009       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8010 
8011       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8012       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8013           .addReg(VReg1, RegState::Define)
8014           .addConstantPoolIndex(Idx)
8015           .add(predOps(ARMCC::AL));
8016       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8017           .addReg(NewVReg1)
8018           .addReg(VReg1)
8019           .add(predOps(ARMCC::AL));
8020     }
8021 
8022     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8023       .addMBB(TrapBB)
8024       .addImm(ARMCC::HI)
8025       .addReg(ARM::CPSR);
8026 
8027     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8028     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8029         .addReg(ARM::CPSR, RegState::Define)
8030         .addReg(NewVReg1)
8031         .addImm(2)
8032         .add(predOps(ARMCC::AL));
8033 
8034     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8035     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8036         .addJumpTableIndex(MJTI)
8037         .add(predOps(ARMCC::AL));
8038 
8039     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8040     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8041         .addReg(ARM::CPSR, RegState::Define)
8042         .addReg(NewVReg2, RegState::Kill)
8043         .addReg(NewVReg3)
8044         .add(predOps(ARMCC::AL));
8045 
8046     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8047         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8048 
8049     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8050     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8051         .addReg(NewVReg4, RegState::Kill)
8052         .addImm(0)
8053         .addMemOperand(JTMMOLd)
8054         .add(predOps(ARMCC::AL));
8055 
8056     unsigned NewVReg6 = NewVReg5;
8057     if (IsPositionIndependent) {
8058       NewVReg6 = MRI->createVirtualRegister(TRC);
8059       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8060           .addReg(ARM::CPSR, RegState::Define)
8061           .addReg(NewVReg5, RegState::Kill)
8062           .addReg(NewVReg3)
8063           .add(predOps(ARMCC::AL));
8064     }
8065 
8066     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8067       .addReg(NewVReg6, RegState::Kill)
8068       .addJumpTableIndex(MJTI);
8069   } else {
8070     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8071     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8072         .addFrameIndex(FI)
8073         .addImm(4)
8074         .addMemOperand(FIMMOLd)
8075         .add(predOps(ARMCC::AL));
8076 
8077     if (NumLPads < 256) {
8078       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8079           .addReg(NewVReg1)
8080           .addImm(NumLPads)
8081           .add(predOps(ARMCC::AL));
8082     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8083       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8084       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8085           .addImm(NumLPads & 0xFFFF)
8086           .add(predOps(ARMCC::AL));
8087 
8088       unsigned VReg2 = VReg1;
8089       if ((NumLPads & 0xFFFF0000) != 0) {
8090         VReg2 = MRI->createVirtualRegister(TRC);
8091         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8092             .addReg(VReg1)
8093             .addImm(NumLPads >> 16)
8094             .add(predOps(ARMCC::AL));
8095       }
8096 
8097       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8098           .addReg(NewVReg1)
8099           .addReg(VReg2)
8100           .add(predOps(ARMCC::AL));
8101     } else {
8102       MachineConstantPool *ConstantPool = MF->getConstantPool();
8103       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8104       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8105 
8106       // MachineConstantPool wants an explicit alignment.
8107       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8108       if (Align == 0)
8109         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8110       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8111 
8112       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8113       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8114           .addReg(VReg1, RegState::Define)
8115           .addConstantPoolIndex(Idx)
8116           .addImm(0)
8117           .add(predOps(ARMCC::AL));
8118       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8119           .addReg(NewVReg1)
8120           .addReg(VReg1, RegState::Kill)
8121           .add(predOps(ARMCC::AL));
8122     }
8123 
8124     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8125       .addMBB(TrapBB)
8126       .addImm(ARMCC::HI)
8127       .addReg(ARM::CPSR);
8128 
8129     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8130     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8131         .addReg(NewVReg1)
8132         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8133         .add(predOps(ARMCC::AL))
8134         .add(condCodeOp());
8135     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8136     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8137         .addJumpTableIndex(MJTI)
8138         .add(predOps(ARMCC::AL));
8139 
8140     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8141         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8142     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8143     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8144         .addReg(NewVReg3, RegState::Kill)
8145         .addReg(NewVReg4)
8146         .addImm(0)
8147         .addMemOperand(JTMMOLd)
8148         .add(predOps(ARMCC::AL));
8149 
8150     if (IsPositionIndependent) {
8151       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8152         .addReg(NewVReg5, RegState::Kill)
8153         .addReg(NewVReg4)
8154         .addJumpTableIndex(MJTI);
8155     } else {
8156       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8157         .addReg(NewVReg5, RegState::Kill)
8158         .addJumpTableIndex(MJTI);
8159     }
8160   }
8161 
8162   // Add the jump table entries as successors to the MBB.
8163   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8164   for (std::vector<MachineBasicBlock*>::iterator
8165          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8166     MachineBasicBlock *CurMBB = *I;
8167     if (SeenMBBs.insert(CurMBB).second)
8168       DispContBB->addSuccessor(CurMBB);
8169   }
8170 
8171   // N.B. the order the invoke BBs are processed in doesn't matter here.
8172   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8173   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8174   for (MachineBasicBlock *BB : InvokeBBs) {
8175 
8176     // Remove the landing pad successor from the invoke block and replace it
8177     // with the new dispatch block.
8178     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8179                                                   BB->succ_end());
8180     while (!Successors.empty()) {
8181       MachineBasicBlock *SMBB = Successors.pop_back_val();
8182       if (SMBB->isEHPad()) {
8183         BB->removeSuccessor(SMBB);
8184         MBBLPads.push_back(SMBB);
8185       }
8186     }
8187 
8188     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8189     BB->normalizeSuccProbs();
8190 
8191     // Find the invoke call and mark all of the callee-saved registers as
8192     // 'implicit defined' so that they're spilled. This prevents code from
8193     // moving instructions to before the EH block, where they will never be
8194     // executed.
8195     for (MachineBasicBlock::reverse_iterator
8196            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8197       if (!II->isCall()) continue;
8198 
8199       DenseMap<unsigned, bool> DefRegs;
8200       for (MachineInstr::mop_iterator
8201              OI = II->operands_begin(), OE = II->operands_end();
8202            OI != OE; ++OI) {
8203         if (!OI->isReg()) continue;
8204         DefRegs[OI->getReg()] = true;
8205       }
8206 
8207       MachineInstrBuilder MIB(*MF, &*II);
8208 
8209       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8210         unsigned Reg = SavedRegs[i];
8211         if (Subtarget->isThumb2() &&
8212             !ARM::tGPRRegClass.contains(Reg) &&
8213             !ARM::hGPRRegClass.contains(Reg))
8214           continue;
8215         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8216           continue;
8217         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8218           continue;
8219         if (!DefRegs[Reg])
8220           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8221       }
8222 
8223       break;
8224     }
8225   }
8226 
8227   // Mark all former landing pads as non-landing pads. The dispatch is the only
8228   // landing pad now.
8229   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8230          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8231     (*I)->setIsEHPad(false);
8232 
8233   // The instruction is gone now.
8234   MI.eraseFromParent();
8235 }
8236 
8237 static
8238 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8239   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8240        E = MBB->succ_end(); I != E; ++I)
8241     if (*I != Succ)
8242       return *I;
8243   llvm_unreachable("Expecting a BB with two successors!");
8244 }
8245 
8246 /// Return the load opcode for a given load size. If load size >= 8,
8247 /// neon opcode will be returned.
8248 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8249   if (LdSize >= 8)
8250     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8251                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8252   if (IsThumb1)
8253     return LdSize == 4 ? ARM::tLDRi
8254                        : LdSize == 2 ? ARM::tLDRHi
8255                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8256   if (IsThumb2)
8257     return LdSize == 4 ? ARM::t2LDR_POST
8258                        : LdSize == 2 ? ARM::t2LDRH_POST
8259                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8260   return LdSize == 4 ? ARM::LDR_POST_IMM
8261                      : LdSize == 2 ? ARM::LDRH_POST
8262                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8263 }
8264 
8265 /// Return the store opcode for a given store size. If store size >= 8,
8266 /// neon opcode will be returned.
8267 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8268   if (StSize >= 8)
8269     return StSize == 16 ? ARM::VST1q32wb_fixed
8270                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8271   if (IsThumb1)
8272     return StSize == 4 ? ARM::tSTRi
8273                        : StSize == 2 ? ARM::tSTRHi
8274                                      : StSize == 1 ? ARM::tSTRBi : 0;
8275   if (IsThumb2)
8276     return StSize == 4 ? ARM::t2STR_POST
8277                        : StSize == 2 ? ARM::t2STRH_POST
8278                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8279   return StSize == 4 ? ARM::STR_POST_IMM
8280                      : StSize == 2 ? ARM::STRH_POST
8281                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8282 }
8283 
8284 /// Emit a post-increment load operation with given size. The instructions
8285 /// will be added to BB at Pos.
8286 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8287                        const TargetInstrInfo *TII, const DebugLoc &dl,
8288                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8289                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8290   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8291   assert(LdOpc != 0 && "Should have a load opcode");
8292   if (LdSize >= 8) {
8293     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8294         .addReg(AddrOut, RegState::Define)
8295         .addReg(AddrIn)
8296         .addImm(0)
8297         .add(predOps(ARMCC::AL));
8298   } else if (IsThumb1) {
8299     // load + update AddrIn
8300     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8301         .addReg(AddrIn)
8302         .addImm(0)
8303         .add(predOps(ARMCC::AL));
8304     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8305         .add(t1CondCodeOp())
8306         .addReg(AddrIn)
8307         .addImm(LdSize)
8308         .add(predOps(ARMCC::AL));
8309   } else if (IsThumb2) {
8310     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8311         .addReg(AddrOut, RegState::Define)
8312         .addReg(AddrIn)
8313         .addImm(LdSize)
8314         .add(predOps(ARMCC::AL));
8315   } else { // arm
8316     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8317         .addReg(AddrOut, RegState::Define)
8318         .addReg(AddrIn)
8319         .addReg(0)
8320         .addImm(LdSize)
8321         .add(predOps(ARMCC::AL));
8322   }
8323 }
8324 
8325 /// Emit a post-increment store operation with given size. The instructions
8326 /// will be added to BB at Pos.
8327 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8328                        const TargetInstrInfo *TII, const DebugLoc &dl,
8329                        unsigned StSize, unsigned Data, unsigned AddrIn,
8330                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8331   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8332   assert(StOpc != 0 && "Should have a store opcode");
8333   if (StSize >= 8) {
8334     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8335         .addReg(AddrIn)
8336         .addImm(0)
8337         .addReg(Data)
8338         .add(predOps(ARMCC::AL));
8339   } else if (IsThumb1) {
8340     // store + update AddrIn
8341     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8342         .addReg(Data)
8343         .addReg(AddrIn)
8344         .addImm(0)
8345         .add(predOps(ARMCC::AL));
8346     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8347         .add(t1CondCodeOp())
8348         .addReg(AddrIn)
8349         .addImm(StSize)
8350         .add(predOps(ARMCC::AL));
8351   } else if (IsThumb2) {
8352     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8353         .addReg(Data)
8354         .addReg(AddrIn)
8355         .addImm(StSize)
8356         .add(predOps(ARMCC::AL));
8357   } else { // arm
8358     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8359         .addReg(Data)
8360         .addReg(AddrIn)
8361         .addReg(0)
8362         .addImm(StSize)
8363         .add(predOps(ARMCC::AL));
8364   }
8365 }
8366 
8367 MachineBasicBlock *
8368 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8369                                    MachineBasicBlock *BB) const {
8370   // This pseudo instruction has 3 operands: dst, src, size
8371   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8372   // Otherwise, we will generate unrolled scalar copies.
8373   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8374   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8375   MachineFunction::iterator It = ++BB->getIterator();
8376 
8377   unsigned dest = MI.getOperand(0).getReg();
8378   unsigned src = MI.getOperand(1).getReg();
8379   unsigned SizeVal = MI.getOperand(2).getImm();
8380   unsigned Align = MI.getOperand(3).getImm();
8381   DebugLoc dl = MI.getDebugLoc();
8382 
8383   MachineFunction *MF = BB->getParent();
8384   MachineRegisterInfo &MRI = MF->getRegInfo();
8385   unsigned UnitSize = 0;
8386   const TargetRegisterClass *TRC = nullptr;
8387   const TargetRegisterClass *VecTRC = nullptr;
8388 
8389   bool IsThumb1 = Subtarget->isThumb1Only();
8390   bool IsThumb2 = Subtarget->isThumb2();
8391   bool IsThumb = Subtarget->isThumb();
8392 
8393   if (Align & 1) {
8394     UnitSize = 1;
8395   } else if (Align & 2) {
8396     UnitSize = 2;
8397   } else {
8398     // Check whether we can use NEON instructions.
8399     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8400         Subtarget->hasNEON()) {
8401       if ((Align % 16 == 0) && SizeVal >= 16)
8402         UnitSize = 16;
8403       else if ((Align % 8 == 0) && SizeVal >= 8)
8404         UnitSize = 8;
8405     }
8406     // Can't use NEON instructions.
8407     if (UnitSize == 0)
8408       UnitSize = 4;
8409   }
8410 
8411   // Select the correct opcode and register class for unit size load/store
8412   bool IsNeon = UnitSize >= 8;
8413   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8414   if (IsNeon)
8415     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8416                             : UnitSize == 8 ? &ARM::DPRRegClass
8417                                             : nullptr;
8418 
8419   unsigned BytesLeft = SizeVal % UnitSize;
8420   unsigned LoopSize = SizeVal - BytesLeft;
8421 
8422   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8423     // Use LDR and STR to copy.
8424     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8425     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8426     unsigned srcIn = src;
8427     unsigned destIn = dest;
8428     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8429       unsigned srcOut = MRI.createVirtualRegister(TRC);
8430       unsigned destOut = MRI.createVirtualRegister(TRC);
8431       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8432       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8433                  IsThumb1, IsThumb2);
8434       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8435                  IsThumb1, IsThumb2);
8436       srcIn = srcOut;
8437       destIn = destOut;
8438     }
8439 
8440     // Handle the leftover bytes with LDRB and STRB.
8441     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8442     // [destOut] = STRB_POST(scratch, destIn, 1)
8443     for (unsigned i = 0; i < BytesLeft; i++) {
8444       unsigned srcOut = MRI.createVirtualRegister(TRC);
8445       unsigned destOut = MRI.createVirtualRegister(TRC);
8446       unsigned scratch = MRI.createVirtualRegister(TRC);
8447       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8448                  IsThumb1, IsThumb2);
8449       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8450                  IsThumb1, IsThumb2);
8451       srcIn = srcOut;
8452       destIn = destOut;
8453     }
8454     MI.eraseFromParent(); // The instruction is gone now.
8455     return BB;
8456   }
8457 
8458   // Expand the pseudo op to a loop.
8459   // thisMBB:
8460   //   ...
8461   //   movw varEnd, # --> with thumb2
8462   //   movt varEnd, #
8463   //   ldrcp varEnd, idx --> without thumb2
8464   //   fallthrough --> loopMBB
8465   // loopMBB:
8466   //   PHI varPhi, varEnd, varLoop
8467   //   PHI srcPhi, src, srcLoop
8468   //   PHI destPhi, dst, destLoop
8469   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8470   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8471   //   subs varLoop, varPhi, #UnitSize
8472   //   bne loopMBB
8473   //   fallthrough --> exitMBB
8474   // exitMBB:
8475   //   epilogue to handle left-over bytes
8476   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8477   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8478   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8479   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8480   MF->insert(It, loopMBB);
8481   MF->insert(It, exitMBB);
8482 
8483   // Transfer the remainder of BB and its successor edges to exitMBB.
8484   exitMBB->splice(exitMBB->begin(), BB,
8485                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8486   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8487 
8488   // Load an immediate to varEnd.
8489   unsigned varEnd = MRI.createVirtualRegister(TRC);
8490   if (Subtarget->useMovt(*MF)) {
8491     unsigned Vtmp = varEnd;
8492     if ((LoopSize & 0xFFFF0000) != 0)
8493       Vtmp = MRI.createVirtualRegister(TRC);
8494     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8495         .addImm(LoopSize & 0xFFFF)
8496         .add(predOps(ARMCC::AL));
8497 
8498     if ((LoopSize & 0xFFFF0000) != 0)
8499       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8500           .addReg(Vtmp)
8501           .addImm(LoopSize >> 16)
8502           .add(predOps(ARMCC::AL));
8503   } else {
8504     MachineConstantPool *ConstantPool = MF->getConstantPool();
8505     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8506     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8507 
8508     // MachineConstantPool wants an explicit alignment.
8509     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8510     if (Align == 0)
8511       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8512     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8513 
8514     if (IsThumb)
8515       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8516           .addReg(varEnd, RegState::Define)
8517           .addConstantPoolIndex(Idx)
8518           .add(predOps(ARMCC::AL));
8519     else
8520       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8521           .addReg(varEnd, RegState::Define)
8522           .addConstantPoolIndex(Idx)
8523           .addImm(0)
8524           .add(predOps(ARMCC::AL));
8525   }
8526   BB->addSuccessor(loopMBB);
8527 
8528   // Generate the loop body:
8529   //   varPhi = PHI(varLoop, varEnd)
8530   //   srcPhi = PHI(srcLoop, src)
8531   //   destPhi = PHI(destLoop, dst)
8532   MachineBasicBlock *entryBB = BB;
8533   BB = loopMBB;
8534   unsigned varLoop = MRI.createVirtualRegister(TRC);
8535   unsigned varPhi = MRI.createVirtualRegister(TRC);
8536   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8537   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8538   unsigned destLoop = MRI.createVirtualRegister(TRC);
8539   unsigned destPhi = MRI.createVirtualRegister(TRC);
8540 
8541   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8542     .addReg(varLoop).addMBB(loopMBB)
8543     .addReg(varEnd).addMBB(entryBB);
8544   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8545     .addReg(srcLoop).addMBB(loopMBB)
8546     .addReg(src).addMBB(entryBB);
8547   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8548     .addReg(destLoop).addMBB(loopMBB)
8549     .addReg(dest).addMBB(entryBB);
8550 
8551   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8552   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8553   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8554   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8555              IsThumb1, IsThumb2);
8556   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8557              IsThumb1, IsThumb2);
8558 
8559   // Decrement loop variable by UnitSize.
8560   if (IsThumb1) {
8561     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8562         .add(t1CondCodeOp())
8563         .addReg(varPhi)
8564         .addImm(UnitSize)
8565         .add(predOps(ARMCC::AL));
8566   } else {
8567     MachineInstrBuilder MIB =
8568         BuildMI(*BB, BB->end(), dl,
8569                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8570     MIB.addReg(varPhi)
8571         .addImm(UnitSize)
8572         .add(predOps(ARMCC::AL))
8573         .add(condCodeOp());
8574     MIB->getOperand(5).setReg(ARM::CPSR);
8575     MIB->getOperand(5).setIsDef(true);
8576   }
8577   BuildMI(*BB, BB->end(), dl,
8578           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8579       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8580 
8581   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8582   BB->addSuccessor(loopMBB);
8583   BB->addSuccessor(exitMBB);
8584 
8585   // Add epilogue to handle BytesLeft.
8586   BB = exitMBB;
8587   auto StartOfExit = exitMBB->begin();
8588 
8589   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8590   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8591   unsigned srcIn = srcLoop;
8592   unsigned destIn = destLoop;
8593   for (unsigned i = 0; i < BytesLeft; i++) {
8594     unsigned srcOut = MRI.createVirtualRegister(TRC);
8595     unsigned destOut = MRI.createVirtualRegister(TRC);
8596     unsigned scratch = MRI.createVirtualRegister(TRC);
8597     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8598                IsThumb1, IsThumb2);
8599     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8600                IsThumb1, IsThumb2);
8601     srcIn = srcOut;
8602     destIn = destOut;
8603   }
8604 
8605   MI.eraseFromParent(); // The instruction is gone now.
8606   return BB;
8607 }
8608 
8609 MachineBasicBlock *
8610 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8611                                        MachineBasicBlock *MBB) const {
8612   const TargetMachine &TM = getTargetMachine();
8613   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8614   DebugLoc DL = MI.getDebugLoc();
8615 
8616   assert(Subtarget->isTargetWindows() &&
8617          "__chkstk is only supported on Windows");
8618   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8619 
8620   // __chkstk takes the number of words to allocate on the stack in R4, and
8621   // returns the stack adjustment in number of bytes in R4.  This will not
8622   // clober any other registers (other than the obvious lr).
8623   //
8624   // Although, technically, IP should be considered a register which may be
8625   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8626   // thumb-2 environment, so there is no interworking required.  As a result, we
8627   // do not expect a veneer to be emitted by the linker, clobbering IP.
8628   //
8629   // Each module receives its own copy of __chkstk, so no import thunk is
8630   // required, again, ensuring that IP is not clobbered.
8631   //
8632   // Finally, although some linkers may theoretically provide a trampoline for
8633   // out of range calls (which is quite common due to a 32M range limitation of
8634   // branches for Thumb), we can generate the long-call version via
8635   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8636   // IP.
8637 
8638   switch (TM.getCodeModel()) {
8639   case CodeModel::Small:
8640   case CodeModel::Medium:
8641   case CodeModel::Default:
8642   case CodeModel::Kernel:
8643     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8644         .add(predOps(ARMCC::AL))
8645         .addExternalSymbol("__chkstk")
8646         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8647         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8648         .addReg(ARM::R12,
8649                 RegState::Implicit | RegState::Define | RegState::Dead);
8650     break;
8651   case CodeModel::Large:
8652   case CodeModel::JITDefault: {
8653     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8654     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8655 
8656     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8657       .addExternalSymbol("__chkstk");
8658     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8659         .add(predOps(ARMCC::AL))
8660         .addReg(Reg, RegState::Kill)
8661         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8662         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8663         .addReg(ARM::R12,
8664                 RegState::Implicit | RegState::Define | RegState::Dead);
8665     break;
8666   }
8667   }
8668 
8669   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8670       .addReg(ARM::SP, RegState::Kill)
8671       .addReg(ARM::R4, RegState::Kill)
8672       .setMIFlags(MachineInstr::FrameSetup)
8673       .add(predOps(ARMCC::AL))
8674       .add(condCodeOp());
8675 
8676   MI.eraseFromParent();
8677   return MBB;
8678 }
8679 
8680 MachineBasicBlock *
8681 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8682                                        MachineBasicBlock *MBB) const {
8683   DebugLoc DL = MI.getDebugLoc();
8684   MachineFunction *MF = MBB->getParent();
8685   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8686 
8687   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8688   MF->insert(++MBB->getIterator(), ContBB);
8689   ContBB->splice(ContBB->begin(), MBB,
8690                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8691   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8692   MBB->addSuccessor(ContBB);
8693 
8694   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8695   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8696   MF->push_back(TrapBB);
8697   MBB->addSuccessor(TrapBB);
8698 
8699   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8700       .addReg(MI.getOperand(0).getReg())
8701       .addImm(0)
8702       .add(predOps(ARMCC::AL));
8703   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8704       .addMBB(TrapBB)
8705       .addImm(ARMCC::EQ)
8706       .addReg(ARM::CPSR);
8707 
8708   MI.eraseFromParent();
8709   return ContBB;
8710 }
8711 
8712 MachineBasicBlock *
8713 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8714                                                MachineBasicBlock *BB) const {
8715   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8716   DebugLoc dl = MI.getDebugLoc();
8717   bool isThumb2 = Subtarget->isThumb2();
8718   switch (MI.getOpcode()) {
8719   default: {
8720     MI.print(errs());
8721     llvm_unreachable("Unexpected instr type to insert");
8722   }
8723 
8724   // Thumb1 post-indexed loads are really just single-register LDMs.
8725   case ARM::tLDR_postidx: {
8726     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8727         .add(MI.getOperand(1))  // Rn_wb
8728         .add(MI.getOperand(2))  // Rn
8729         .add(MI.getOperand(3))  // PredImm
8730         .add(MI.getOperand(4))  // PredReg
8731         .add(MI.getOperand(0)); // Rt
8732     MI.eraseFromParent();
8733     return BB;
8734   }
8735 
8736   // The Thumb2 pre-indexed stores have the same MI operands, they just
8737   // define them differently in the .td files from the isel patterns, so
8738   // they need pseudos.
8739   case ARM::t2STR_preidx:
8740     MI.setDesc(TII->get(ARM::t2STR_PRE));
8741     return BB;
8742   case ARM::t2STRB_preidx:
8743     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8744     return BB;
8745   case ARM::t2STRH_preidx:
8746     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8747     return BB;
8748 
8749   case ARM::STRi_preidx:
8750   case ARM::STRBi_preidx: {
8751     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8752                                                          : ARM::STRB_PRE_IMM;
8753     // Decode the offset.
8754     unsigned Offset = MI.getOperand(4).getImm();
8755     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8756     Offset = ARM_AM::getAM2Offset(Offset);
8757     if (isSub)
8758       Offset = -Offset;
8759 
8760     MachineMemOperand *MMO = *MI.memoperands_begin();
8761     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8762         .add(MI.getOperand(0)) // Rn_wb
8763         .add(MI.getOperand(1)) // Rt
8764         .add(MI.getOperand(2)) // Rn
8765         .addImm(Offset)        // offset (skip GPR==zero_reg)
8766         .add(MI.getOperand(5)) // pred
8767         .add(MI.getOperand(6))
8768         .addMemOperand(MMO);
8769     MI.eraseFromParent();
8770     return BB;
8771   }
8772   case ARM::STRr_preidx:
8773   case ARM::STRBr_preidx:
8774   case ARM::STRH_preidx: {
8775     unsigned NewOpc;
8776     switch (MI.getOpcode()) {
8777     default: llvm_unreachable("unexpected opcode!");
8778     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8779     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8780     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8781     }
8782     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8783     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8784       MIB.add(MI.getOperand(i));
8785     MI.eraseFromParent();
8786     return BB;
8787   }
8788 
8789   case ARM::tMOVCCr_pseudo: {
8790     // To "insert" a SELECT_CC instruction, we actually have to insert the
8791     // diamond control-flow pattern.  The incoming instruction knows the
8792     // destination vreg to set, the condition code register to branch on, the
8793     // true/false values to select between, and a branch opcode to use.
8794     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8795     MachineFunction::iterator It = ++BB->getIterator();
8796 
8797     //  thisMBB:
8798     //  ...
8799     //   TrueVal = ...
8800     //   cmpTY ccX, r1, r2
8801     //   bCC copy1MBB
8802     //   fallthrough --> copy0MBB
8803     MachineBasicBlock *thisMBB  = BB;
8804     MachineFunction *F = BB->getParent();
8805     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8806     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8807     F->insert(It, copy0MBB);
8808     F->insert(It, sinkMBB);
8809 
8810     // Transfer the remainder of BB and its successor edges to sinkMBB.
8811     sinkMBB->splice(sinkMBB->begin(), BB,
8812                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8813     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8814 
8815     BB->addSuccessor(copy0MBB);
8816     BB->addSuccessor(sinkMBB);
8817 
8818     BuildMI(BB, dl, TII->get(ARM::tBcc))
8819         .addMBB(sinkMBB)
8820         .addImm(MI.getOperand(3).getImm())
8821         .addReg(MI.getOperand(4).getReg());
8822 
8823     //  copy0MBB:
8824     //   %FalseValue = ...
8825     //   # fallthrough to sinkMBB
8826     BB = copy0MBB;
8827 
8828     // Update machine-CFG edges
8829     BB->addSuccessor(sinkMBB);
8830 
8831     //  sinkMBB:
8832     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8833     //  ...
8834     BB = sinkMBB;
8835     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8836         .addReg(MI.getOperand(1).getReg())
8837         .addMBB(copy0MBB)
8838         .addReg(MI.getOperand(2).getReg())
8839         .addMBB(thisMBB);
8840 
8841     MI.eraseFromParent(); // The pseudo instruction is gone now.
8842     return BB;
8843   }
8844 
8845   case ARM::BCCi64:
8846   case ARM::BCCZi64: {
8847     // If there is an unconditional branch to the other successor, remove it.
8848     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8849 
8850     // Compare both parts that make up the double comparison separately for
8851     // equality.
8852     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8853 
8854     unsigned LHS1 = MI.getOperand(1).getReg();
8855     unsigned LHS2 = MI.getOperand(2).getReg();
8856     if (RHSisZero) {
8857       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8858           .addReg(LHS1)
8859           .addImm(0)
8860           .add(predOps(ARMCC::AL));
8861       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8862         .addReg(LHS2).addImm(0)
8863         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8864     } else {
8865       unsigned RHS1 = MI.getOperand(3).getReg();
8866       unsigned RHS2 = MI.getOperand(4).getReg();
8867       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8868           .addReg(LHS1)
8869           .addReg(RHS1)
8870           .add(predOps(ARMCC::AL));
8871       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8872         .addReg(LHS2).addReg(RHS2)
8873         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8874     }
8875 
8876     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8877     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8878     if (MI.getOperand(0).getImm() == ARMCC::NE)
8879       std::swap(destMBB, exitMBB);
8880 
8881     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8882       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8883     if (isThumb2)
8884       BuildMI(BB, dl, TII->get(ARM::t2B))
8885           .addMBB(exitMBB)
8886           .add(predOps(ARMCC::AL));
8887     else
8888       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8889 
8890     MI.eraseFromParent(); // The pseudo instruction is gone now.
8891     return BB;
8892   }
8893 
8894   case ARM::Int_eh_sjlj_setjmp:
8895   case ARM::Int_eh_sjlj_setjmp_nofp:
8896   case ARM::tInt_eh_sjlj_setjmp:
8897   case ARM::t2Int_eh_sjlj_setjmp:
8898   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8899     return BB;
8900 
8901   case ARM::Int_eh_sjlj_setup_dispatch:
8902     EmitSjLjDispatchBlock(MI, BB);
8903     return BB;
8904 
8905   case ARM::ABS:
8906   case ARM::t2ABS: {
8907     // To insert an ABS instruction, we have to insert the
8908     // diamond control-flow pattern.  The incoming instruction knows the
8909     // source vreg to test against 0, the destination vreg to set,
8910     // the condition code register to branch on, the
8911     // true/false values to select between, and a branch opcode to use.
8912     // It transforms
8913     //     V1 = ABS V0
8914     // into
8915     //     V2 = MOVS V0
8916     //     BCC                      (branch to SinkBB if V0 >= 0)
8917     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8918     //     SinkBB: V1 = PHI(V2, V3)
8919     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8920     MachineFunction::iterator BBI = ++BB->getIterator();
8921     MachineFunction *Fn = BB->getParent();
8922     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8923     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8924     Fn->insert(BBI, RSBBB);
8925     Fn->insert(BBI, SinkBB);
8926 
8927     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8928     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8929     bool ABSSrcKIll = MI.getOperand(1).isKill();
8930     bool isThumb2 = Subtarget->isThumb2();
8931     MachineRegisterInfo &MRI = Fn->getRegInfo();
8932     // In Thumb mode S must not be specified if source register is the SP or
8933     // PC and if destination register is the SP, so restrict register class
8934     unsigned NewRsbDstReg =
8935       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8936 
8937     // Transfer the remainder of BB and its successor edges to sinkMBB.
8938     SinkBB->splice(SinkBB->begin(), BB,
8939                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8940     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8941 
8942     BB->addSuccessor(RSBBB);
8943     BB->addSuccessor(SinkBB);
8944 
8945     // fall through to SinkMBB
8946     RSBBB->addSuccessor(SinkBB);
8947 
8948     // insert a cmp at the end of BB
8949     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8950         .addReg(ABSSrcReg)
8951         .addImm(0)
8952         .add(predOps(ARMCC::AL));
8953 
8954     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8955     BuildMI(BB, dl,
8956       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8957       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8958 
8959     // insert rsbri in RSBBB
8960     // Note: BCC and rsbri will be converted into predicated rsbmi
8961     // by if-conversion pass
8962     BuildMI(*RSBBB, RSBBB->begin(), dl,
8963             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8964         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8965         .addImm(0)
8966         .add(predOps(ARMCC::AL))
8967         .add(condCodeOp());
8968 
8969     // insert PHI in SinkBB,
8970     // reuse ABSDstReg to not change uses of ABS instruction
8971     BuildMI(*SinkBB, SinkBB->begin(), dl,
8972       TII->get(ARM::PHI), ABSDstReg)
8973       .addReg(NewRsbDstReg).addMBB(RSBBB)
8974       .addReg(ABSSrcReg).addMBB(BB);
8975 
8976     // remove ABS instruction
8977     MI.eraseFromParent();
8978 
8979     // return last added BB
8980     return SinkBB;
8981   }
8982   case ARM::COPY_STRUCT_BYVAL_I32:
8983     ++NumLoopByVals;
8984     return EmitStructByval(MI, BB);
8985   case ARM::WIN__CHKSTK:
8986     return EmitLowered__chkstk(MI, BB);
8987   case ARM::WIN__DBZCHK:
8988     return EmitLowered__dbzchk(MI, BB);
8989   }
8990 }
8991 
8992 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8993 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8994 /// instead of as a custom inserter because we need the use list from the SDNode.
8995 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8996                                     MachineInstr &MI, const SDNode *Node) {
8997   bool isThumb1 = Subtarget->isThumb1Only();
8998 
8999   DebugLoc DL = MI.getDebugLoc();
9000   MachineFunction *MF = MI.getParent()->getParent();
9001   MachineRegisterInfo &MRI = MF->getRegInfo();
9002   MachineInstrBuilder MIB(*MF, MI);
9003 
9004   // If the new dst/src is unused mark it as dead.
9005   if (!Node->hasAnyUseOfValue(0)) {
9006     MI.getOperand(0).setIsDead(true);
9007   }
9008   if (!Node->hasAnyUseOfValue(1)) {
9009     MI.getOperand(1).setIsDead(true);
9010   }
9011 
9012   // The MEMCPY both defines and kills the scratch registers.
9013   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9014     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9015                                                          : &ARM::GPRRegClass);
9016     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9017   }
9018 }
9019 
9020 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9021                                                       SDNode *Node) const {
9022   if (MI.getOpcode() == ARM::MEMCPY) {
9023     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9024     return;
9025   }
9026 
9027   const MCInstrDesc *MCID = &MI.getDesc();
9028   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9029   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9030   // operand is still set to noreg. If needed, set the optional operand's
9031   // register to CPSR, and remove the redundant implicit def.
9032   //
9033   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9034 
9035   // Rename pseudo opcodes.
9036   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9037   if (NewOpc) {
9038     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9039     MCID = &TII->get(NewOpc);
9040 
9041     assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
9042            "converted opcode should be the same except for cc_out");
9043 
9044     MI.setDesc(*MCID);
9045 
9046     // Add the optional cc_out operand
9047     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9048   }
9049   unsigned ccOutIdx = MCID->getNumOperands() - 1;
9050 
9051   // Any ARM instruction that sets the 's' bit should specify an optional
9052   // "cc_out" operand in the last operand position.
9053   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9054     assert(!NewOpc && "Optional cc_out operand required");
9055     return;
9056   }
9057   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9058   // since we already have an optional CPSR def.
9059   bool definesCPSR = false;
9060   bool deadCPSR = false;
9061   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9062        ++i) {
9063     const MachineOperand &MO = MI.getOperand(i);
9064     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9065       definesCPSR = true;
9066       if (MO.isDead())
9067         deadCPSR = true;
9068       MI.RemoveOperand(i);
9069       break;
9070     }
9071   }
9072   if (!definesCPSR) {
9073     assert(!NewOpc && "Optional cc_out operand required");
9074     return;
9075   }
9076   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9077   if (deadCPSR) {
9078     assert(!MI.getOperand(ccOutIdx).getReg() &&
9079            "expect uninitialized optional cc_out operand");
9080     return;
9081   }
9082 
9083   // If this instruction was defined with an optional CPSR def and its dag node
9084   // had a live implicit CPSR def, then activate the optional CPSR def.
9085   MachineOperand &MO = MI.getOperand(ccOutIdx);
9086   MO.setReg(ARM::CPSR);
9087   MO.setIsDef(true);
9088 }
9089 
9090 //===----------------------------------------------------------------------===//
9091 //                           ARM Optimization Hooks
9092 //===----------------------------------------------------------------------===//
9093 
9094 // Helper function that checks if N is a null or all ones constant.
9095 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9096   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9097 }
9098 
9099 // Return true if N is conditionally 0 or all ones.
9100 // Detects these expressions where cc is an i1 value:
9101 //
9102 //   (select cc 0, y)   [AllOnes=0]
9103 //   (select cc y, 0)   [AllOnes=0]
9104 //   (zext cc)          [AllOnes=0]
9105 //   (sext cc)          [AllOnes=0/1]
9106 //   (select cc -1, y)  [AllOnes=1]
9107 //   (select cc y, -1)  [AllOnes=1]
9108 //
9109 // Invert is set when N is the null/all ones constant when CC is false.
9110 // OtherOp is set to the alternative value of N.
9111 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9112                                        SDValue &CC, bool &Invert,
9113                                        SDValue &OtherOp,
9114                                        SelectionDAG &DAG) {
9115   switch (N->getOpcode()) {
9116   default: return false;
9117   case ISD::SELECT: {
9118     CC = N->getOperand(0);
9119     SDValue N1 = N->getOperand(1);
9120     SDValue N2 = N->getOperand(2);
9121     if (isZeroOrAllOnes(N1, AllOnes)) {
9122       Invert = false;
9123       OtherOp = N2;
9124       return true;
9125     }
9126     if (isZeroOrAllOnes(N2, AllOnes)) {
9127       Invert = true;
9128       OtherOp = N1;
9129       return true;
9130     }
9131     return false;
9132   }
9133   case ISD::ZERO_EXTEND:
9134     // (zext cc) can never be the all ones value.
9135     if (AllOnes)
9136       return false;
9137     LLVM_FALLTHROUGH;
9138   case ISD::SIGN_EXTEND: {
9139     SDLoc dl(N);
9140     EVT VT = N->getValueType(0);
9141     CC = N->getOperand(0);
9142     if (CC.getValueType() != MVT::i1)
9143       return false;
9144     Invert = !AllOnes;
9145     if (AllOnes)
9146       // When looking for an AllOnes constant, N is an sext, and the 'other'
9147       // value is 0.
9148       OtherOp = DAG.getConstant(0, dl, VT);
9149     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9150       // When looking for a 0 constant, N can be zext or sext.
9151       OtherOp = DAG.getConstant(1, dl, VT);
9152     else
9153       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9154                                 VT);
9155     return true;
9156   }
9157   }
9158 }
9159 
9160 // Combine a constant select operand into its use:
9161 //
9162 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9163 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9164 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9165 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9166 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9167 //
9168 // The transform is rejected if the select doesn't have a constant operand that
9169 // is null, or all ones when AllOnes is set.
9170 //
9171 // Also recognize sext/zext from i1:
9172 //
9173 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9174 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9175 //
9176 // These transformations eventually create predicated instructions.
9177 //
9178 // @param N       The node to transform.
9179 // @param Slct    The N operand that is a select.
9180 // @param OtherOp The other N operand (x above).
9181 // @param DCI     Context.
9182 // @param AllOnes Require the select constant to be all ones instead of null.
9183 // @returns The new node, or SDValue() on failure.
9184 static
9185 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9186                             TargetLowering::DAGCombinerInfo &DCI,
9187                             bool AllOnes = false) {
9188   SelectionDAG &DAG = DCI.DAG;
9189   EVT VT = N->getValueType(0);
9190   SDValue NonConstantVal;
9191   SDValue CCOp;
9192   bool SwapSelectOps;
9193   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9194                                   NonConstantVal, DAG))
9195     return SDValue();
9196 
9197   // Slct is now know to be the desired identity constant when CC is true.
9198   SDValue TrueVal = OtherOp;
9199   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9200                                  OtherOp, NonConstantVal);
9201   // Unless SwapSelectOps says CC should be false.
9202   if (SwapSelectOps)
9203     std::swap(TrueVal, FalseVal);
9204 
9205   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9206                      CCOp, TrueVal, FalseVal);
9207 }
9208 
9209 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9210 static
9211 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9212                                        TargetLowering::DAGCombinerInfo &DCI) {
9213   SDValue N0 = N->getOperand(0);
9214   SDValue N1 = N->getOperand(1);
9215   if (N0.getNode()->hasOneUse())
9216     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9217       return Result;
9218   if (N1.getNode()->hasOneUse())
9219     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9220       return Result;
9221   return SDValue();
9222 }
9223 
9224 static bool IsVUZPShuffleNode(SDNode *N) {
9225   // VUZP shuffle node.
9226   if (N->getOpcode() == ARMISD::VUZP)
9227     return true;
9228 
9229   // "VUZP" on i32 is an alias for VTRN.
9230   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9231     return true;
9232 
9233   return false;
9234 }
9235 
9236 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9237                                  TargetLowering::DAGCombinerInfo &DCI,
9238                                  const ARMSubtarget *Subtarget) {
9239   // Look for ADD(VUZP.0, VUZP.1).
9240   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9241       N0 == N1)
9242    return SDValue();
9243 
9244   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9245   if (!N->getValueType(0).is64BitVector())
9246     return SDValue();
9247 
9248   // Generate vpadd.
9249   SelectionDAG &DAG = DCI.DAG;
9250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9251   SDLoc dl(N);
9252   SDNode *Unzip = N0.getNode();
9253   EVT VT = N->getValueType(0);
9254 
9255   SmallVector<SDValue, 8> Ops;
9256   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9257                                 TLI.getPointerTy(DAG.getDataLayout())));
9258   Ops.push_back(Unzip->getOperand(0));
9259   Ops.push_back(Unzip->getOperand(1));
9260 
9261   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9262 }
9263 
9264 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9265                                       TargetLowering::DAGCombinerInfo &DCI,
9266                                       const ARMSubtarget *Subtarget) {
9267   // Check for two extended operands.
9268   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9269         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9270       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9271         N1.getOpcode() == ISD::ZERO_EXTEND))
9272     return SDValue();
9273 
9274   SDValue N00 = N0.getOperand(0);
9275   SDValue N10 = N1.getOperand(0);
9276 
9277   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9278   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9279       N00 == N10)
9280     return SDValue();
9281 
9282   // We only recognize Q register paddl here; this can't be reached until
9283   // after type legalization.
9284   if (!N00.getValueType().is64BitVector() ||
9285       !N0.getValueType().is128BitVector())
9286     return SDValue();
9287 
9288   // Generate vpaddl.
9289   SelectionDAG &DAG = DCI.DAG;
9290   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9291   SDLoc dl(N);
9292   EVT VT = N->getValueType(0);
9293 
9294   SmallVector<SDValue, 8> Ops;
9295   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9296   unsigned Opcode;
9297   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9298     Opcode = Intrinsic::arm_neon_vpaddls;
9299   else
9300     Opcode = Intrinsic::arm_neon_vpaddlu;
9301   Ops.push_back(DAG.getConstant(Opcode, dl,
9302                                 TLI.getPointerTy(DAG.getDataLayout())));
9303   EVT ElemTy = N00.getValueType().getVectorElementType();
9304   unsigned NumElts = VT.getVectorNumElements();
9305   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9306   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9307                                N00.getOperand(0), N00.getOperand(1));
9308   Ops.push_back(Concat);
9309 
9310   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9311 }
9312 
9313 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9314 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9315 // much easier to match.
9316 static SDValue
9317 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9318                                TargetLowering::DAGCombinerInfo &DCI,
9319                                const ARMSubtarget *Subtarget) {
9320   // Only perform optimization if after legalize, and if NEON is available. We
9321   // also expected both operands to be BUILD_VECTORs.
9322   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9323       || N0.getOpcode() != ISD::BUILD_VECTOR
9324       || N1.getOpcode() != ISD::BUILD_VECTOR)
9325     return SDValue();
9326 
9327   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9328   EVT VT = N->getValueType(0);
9329   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9330     return SDValue();
9331 
9332   // Check that the vector operands are of the right form.
9333   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9334   // operands, where N is the size of the formed vector.
9335   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9336   // index such that we have a pair wise add pattern.
9337 
9338   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9339   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9340     return SDValue();
9341   SDValue Vec = N0->getOperand(0)->getOperand(0);
9342   SDNode *V = Vec.getNode();
9343   unsigned nextIndex = 0;
9344 
9345   // For each operands to the ADD which are BUILD_VECTORs,
9346   // check to see if each of their operands are an EXTRACT_VECTOR with
9347   // the same vector and appropriate index.
9348   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9349     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9350         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9351 
9352       SDValue ExtVec0 = N0->getOperand(i);
9353       SDValue ExtVec1 = N1->getOperand(i);
9354 
9355       // First operand is the vector, verify its the same.
9356       if (V != ExtVec0->getOperand(0).getNode() ||
9357           V != ExtVec1->getOperand(0).getNode())
9358         return SDValue();
9359 
9360       // Second is the constant, verify its correct.
9361       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9362       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9363 
9364       // For the constant, we want to see all the even or all the odd.
9365       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9366           || C1->getZExtValue() != nextIndex+1)
9367         return SDValue();
9368 
9369       // Increment index.
9370       nextIndex+=2;
9371     } else
9372       return SDValue();
9373   }
9374 
9375   // Don't generate vpaddl+vmovn; we'll match it to vpadd later.
9376   if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9377     return SDValue();
9378 
9379   // Create VPADDL node.
9380   SelectionDAG &DAG = DCI.DAG;
9381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9382 
9383   SDLoc dl(N);
9384 
9385   // Build operand list.
9386   SmallVector<SDValue, 8> Ops;
9387   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9388                                 TLI.getPointerTy(DAG.getDataLayout())));
9389 
9390   // Input is the vector.
9391   Ops.push_back(Vec);
9392 
9393   // Get widened type and narrowed type.
9394   MVT widenType;
9395   unsigned numElem = VT.getVectorNumElements();
9396 
9397   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9398   switch (inputLaneType.getSimpleVT().SimpleTy) {
9399     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9400     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9401     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9402     default:
9403       llvm_unreachable("Invalid vector element type for padd optimization.");
9404   }
9405 
9406   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9407   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9408   return DAG.getNode(ExtOp, dl, VT, tmp);
9409 }
9410 
9411 static SDValue findMUL_LOHI(SDValue V) {
9412   if (V->getOpcode() == ISD::UMUL_LOHI ||
9413       V->getOpcode() == ISD::SMUL_LOHI)
9414     return V;
9415   return SDValue();
9416 }
9417 
9418 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
9419                                      TargetLowering::DAGCombinerInfo &DCI,
9420                                      const ARMSubtarget *Subtarget) {
9421   // Look for multiply add opportunities.
9422   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9423   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9424   // a glue link from the first add to the second add.
9425   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9426   // a S/UMLAL instruction.
9427   //                  UMUL_LOHI
9428   //                 / :lo    \ :hi
9429   //                /          \          [no multiline comment]
9430   //    loAdd ->  ADDE         |
9431   //                 \ :glue  /
9432   //                  \      /
9433   //                    ADDC   <- hiAdd
9434   //
9435   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
9436   SDValue AddcOp0 = AddcNode->getOperand(0);
9437   SDValue AddcOp1 = AddcNode->getOperand(1);
9438 
9439   // Check if the two operands are from the same mul_lohi node.
9440   if (AddcOp0.getNode() == AddcOp1.getNode())
9441     return SDValue();
9442 
9443   assert(AddcNode->getNumValues() == 2 &&
9444          AddcNode->getValueType(0) == MVT::i32 &&
9445          "Expect ADDC with two result values. First: i32");
9446 
9447   // Check that we have a glued ADDC node.
9448   if (AddcNode->getValueType(1) != MVT::Glue)
9449     return SDValue();
9450 
9451   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
9452   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9453       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9454       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9455       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9456     return SDValue();
9457 
9458   // Look for the glued ADDE.
9459   SDNode* AddeNode = AddcNode->getGluedUser();
9460   if (!AddeNode)
9461     return SDValue();
9462 
9463   // Make sure it is really an ADDE.
9464   if (AddeNode->getOpcode() != ISD::ADDE)
9465     return SDValue();
9466 
9467   assert(AddeNode->getNumOperands() == 3 &&
9468          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
9469          "ADDE node has the wrong inputs");
9470 
9471   // Check for the triangle shape.
9472   SDValue AddeOp0 = AddeNode->getOperand(0);
9473   SDValue AddeOp1 = AddeNode->getOperand(1);
9474 
9475   // Make sure that the ADDE operands are not coming from the same node.
9476   if (AddeOp0.getNode() == AddeOp1.getNode())
9477     return SDValue();
9478 
9479   // Find the MUL_LOHI node walking up ADDE's operands.
9480   bool IsLeftOperandMUL = false;
9481   SDValue MULOp = findMUL_LOHI(AddeOp0);
9482   if (MULOp == SDValue())
9483    MULOp = findMUL_LOHI(AddeOp1);
9484   else
9485     IsLeftOperandMUL = true;
9486   if (MULOp == SDValue())
9487     return SDValue();
9488 
9489   // Figure out the right opcode.
9490   unsigned Opc = MULOp->getOpcode();
9491   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9492 
9493   // Figure out the high and low input values to the MLAL node.
9494   SDValue* HiAdd = nullptr;
9495   SDValue* LoMul = nullptr;
9496   SDValue* LowAdd = nullptr;
9497 
9498   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9499   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9500     return SDValue();
9501 
9502   if (IsLeftOperandMUL)
9503     HiAdd = &AddeOp1;
9504   else
9505     HiAdd = &AddeOp0;
9506 
9507 
9508   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9509   // whose low result is fed to the ADDC we are checking.
9510 
9511   if (AddcOp0 == MULOp.getValue(0)) {
9512     LoMul = &AddcOp0;
9513     LowAdd = &AddcOp1;
9514   }
9515   if (AddcOp1 == MULOp.getValue(0)) {
9516     LoMul = &AddcOp1;
9517     LowAdd = &AddcOp0;
9518   }
9519 
9520   if (!LoMul)
9521     return SDValue();
9522 
9523   // Create the merged node.
9524   SelectionDAG &DAG = DCI.DAG;
9525 
9526   // Build operand list.
9527   SmallVector<SDValue, 8> Ops;
9528   Ops.push_back(LoMul->getOperand(0));
9529   Ops.push_back(LoMul->getOperand(1));
9530   Ops.push_back(*LowAdd);
9531   Ops.push_back(*HiAdd);
9532 
9533   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9534                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9535 
9536   // Replace the ADDs' nodes uses by the MLA node's values.
9537   SDValue HiMLALResult(MLALNode.getNode(), 1);
9538   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9539 
9540   SDValue LoMLALResult(MLALNode.getNode(), 0);
9541   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9542 
9543   // Return original node to notify the driver to stop replacing.
9544   SDValue resNode(AddcNode, 0);
9545   return resNode;
9546 }
9547 
9548 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode,
9549                                       TargetLowering::DAGCombinerInfo &DCI,
9550                                       const ARMSubtarget *Subtarget) {
9551   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9552   // While trying to combine for the other MLAL nodes, first search for the
9553   // chance to use UMAAL. Check if Addc uses another addc node which can first
9554   // be combined into a UMLAL. The other pattern is AddcNode being combined
9555   // into an UMLAL and then using another addc is handled in ISelDAGToDAG.
9556 
9557   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() ||
9558       (Subtarget->isThumb() && !Subtarget->hasThumb2()))
9559     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9560 
9561   SDNode *PrevAddc = nullptr;
9562   if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC)
9563     PrevAddc = AddcNode->getOperand(0).getNode();
9564   else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC)
9565     PrevAddc = AddcNode->getOperand(1).getNode();
9566 
9567   // If there's no addc chains, just return a search for any MLAL.
9568   if (PrevAddc == nullptr)
9569     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9570 
9571   // Try to convert the addc operand to an MLAL and if that fails try to
9572   // combine AddcNode.
9573   SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget);
9574   if (MLAL != SDValue(PrevAddc, 0))
9575     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9576 
9577   // Find the converted UMAAL or quit if it doesn't exist.
9578   SDNode *UmlalNode = nullptr;
9579   SDValue AddHi;
9580   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9581     UmlalNode = AddcNode->getOperand(0).getNode();
9582     AddHi = AddcNode->getOperand(1);
9583   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9584     UmlalNode = AddcNode->getOperand(1).getNode();
9585     AddHi = AddcNode->getOperand(0);
9586   } else {
9587     return SDValue();
9588   }
9589 
9590   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9591   // the ADDC as well as Zero.
9592   auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3));
9593 
9594   if (!Zero || Zero->getZExtValue() != 0)
9595     return SDValue();
9596 
9597   // Check that we have a glued ADDC node.
9598   if (AddcNode->getValueType(1) != MVT::Glue)
9599     return SDValue();
9600 
9601   // Look for the glued ADDE.
9602   SDNode* AddeNode = AddcNode->getGluedUser();
9603   if (!AddeNode)
9604     return SDValue();
9605 
9606   if ((AddeNode->getOperand(0).getNode() == Zero &&
9607        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9608       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9609        AddeNode->getOperand(1).getNode() == Zero)) {
9610 
9611     SelectionDAG &DAG = DCI.DAG;
9612     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9613                       UmlalNode->getOperand(2), AddHi };
9614     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9615                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9616 
9617     // Replace the ADDs' nodes uses by the UMAAL node's values.
9618     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9619     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9620 
9621     // Return original node to notify the driver to stop replacing.
9622     return SDValue(AddcNode, 0);
9623   }
9624   return SDValue();
9625 }
9626 
9627 /// PerformADDCCombine - Target-specific dag combine transform from
9628 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or
9629 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9630 static SDValue PerformADDCCombine(SDNode *N,
9631                                  TargetLowering::DAGCombinerInfo &DCI,
9632                                  const ARMSubtarget *Subtarget) {
9633   if (Subtarget->isThumb1Only()) return SDValue();
9634 
9635   // Only perform the checks after legalize when the pattern is available.
9636   if (DCI.isBeforeLegalize()) return SDValue();
9637 
9638   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9639 }
9640 
9641 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9642 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9643 /// called with the default operands, and if that fails, with commuted
9644 /// operands.
9645 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9646                                           TargetLowering::DAGCombinerInfo &DCI,
9647                                           const ARMSubtarget *Subtarget){
9648   // Attempt to create vpadd for this add.
9649   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
9650     return Result;
9651 
9652   // Attempt to create vpaddl for this add.
9653   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
9654     return Result;
9655   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
9656                                                       Subtarget))
9657     return Result;
9658 
9659   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9660   if (N0.getNode()->hasOneUse())
9661     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9662       return Result;
9663   return SDValue();
9664 }
9665 
9666 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9667 ///
9668 static SDValue PerformADDCombine(SDNode *N,
9669                                  TargetLowering::DAGCombinerInfo &DCI,
9670                                  const ARMSubtarget *Subtarget) {
9671   SDValue N0 = N->getOperand(0);
9672   SDValue N1 = N->getOperand(1);
9673 
9674   // First try with the default operand order.
9675   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9676     return Result;
9677 
9678   // If that didn't work, try again with the operands commuted.
9679   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9680 }
9681 
9682 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9683 ///
9684 static SDValue PerformSUBCombine(SDNode *N,
9685                                  TargetLowering::DAGCombinerInfo &DCI) {
9686   SDValue N0 = N->getOperand(0);
9687   SDValue N1 = N->getOperand(1);
9688 
9689   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9690   if (N1.getNode()->hasOneUse())
9691     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9692       return Result;
9693 
9694   return SDValue();
9695 }
9696 
9697 /// PerformVMULCombine
9698 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9699 /// special multiplier accumulator forwarding.
9700 ///   vmul d3, d0, d2
9701 ///   vmla d3, d1, d2
9702 /// is faster than
9703 ///   vadd d3, d0, d1
9704 ///   vmul d3, d3, d2
9705 //  However, for (A + B) * (A + B),
9706 //    vadd d2, d0, d1
9707 //    vmul d3, d0, d2
9708 //    vmla d3, d1, d2
9709 //  is slower than
9710 //    vadd d2, d0, d1
9711 //    vmul d3, d2, d2
9712 static SDValue PerformVMULCombine(SDNode *N,
9713                                   TargetLowering::DAGCombinerInfo &DCI,
9714                                   const ARMSubtarget *Subtarget) {
9715   if (!Subtarget->hasVMLxForwarding())
9716     return SDValue();
9717 
9718   SelectionDAG &DAG = DCI.DAG;
9719   SDValue N0 = N->getOperand(0);
9720   SDValue N1 = N->getOperand(1);
9721   unsigned Opcode = N0.getOpcode();
9722   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9723       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9724     Opcode = N1.getOpcode();
9725     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9726         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9727       return SDValue();
9728     std::swap(N0, N1);
9729   }
9730 
9731   if (N0 == N1)
9732     return SDValue();
9733 
9734   EVT VT = N->getValueType(0);
9735   SDLoc DL(N);
9736   SDValue N00 = N0->getOperand(0);
9737   SDValue N01 = N0->getOperand(1);
9738   return DAG.getNode(Opcode, DL, VT,
9739                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9740                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9741 }
9742 
9743 static SDValue PerformMULCombine(SDNode *N,
9744                                  TargetLowering::DAGCombinerInfo &DCI,
9745                                  const ARMSubtarget *Subtarget) {
9746   SelectionDAG &DAG = DCI.DAG;
9747 
9748   if (Subtarget->isThumb1Only())
9749     return SDValue();
9750 
9751   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9752     return SDValue();
9753 
9754   EVT VT = N->getValueType(0);
9755   if (VT.is64BitVector() || VT.is128BitVector())
9756     return PerformVMULCombine(N, DCI, Subtarget);
9757   if (VT != MVT::i32)
9758     return SDValue();
9759 
9760   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9761   if (!C)
9762     return SDValue();
9763 
9764   int64_t MulAmt = C->getSExtValue();
9765   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9766 
9767   ShiftAmt = ShiftAmt & (32 - 1);
9768   SDValue V = N->getOperand(0);
9769   SDLoc DL(N);
9770 
9771   SDValue Res;
9772   MulAmt >>= ShiftAmt;
9773 
9774   if (MulAmt >= 0) {
9775     if (isPowerOf2_32(MulAmt - 1)) {
9776       // (mul x, 2^N + 1) => (add (shl x, N), x)
9777       Res = DAG.getNode(ISD::ADD, DL, VT,
9778                         V,
9779                         DAG.getNode(ISD::SHL, DL, VT,
9780                                     V,
9781                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9782                                                     MVT::i32)));
9783     } else if (isPowerOf2_32(MulAmt + 1)) {
9784       // (mul x, 2^N - 1) => (sub (shl x, N), x)
9785       Res = DAG.getNode(ISD::SUB, DL, VT,
9786                         DAG.getNode(ISD::SHL, DL, VT,
9787                                     V,
9788                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
9789                                                     MVT::i32)),
9790                         V);
9791     } else
9792       return SDValue();
9793   } else {
9794     uint64_t MulAmtAbs = -MulAmt;
9795     if (isPowerOf2_32(MulAmtAbs + 1)) {
9796       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9797       Res = DAG.getNode(ISD::SUB, DL, VT,
9798                         V,
9799                         DAG.getNode(ISD::SHL, DL, VT,
9800                                     V,
9801                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9802                                                     MVT::i32)));
9803     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9804       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9805       Res = DAG.getNode(ISD::ADD, DL, VT,
9806                         V,
9807                         DAG.getNode(ISD::SHL, DL, VT,
9808                                     V,
9809                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9810                                                     MVT::i32)));
9811       Res = DAG.getNode(ISD::SUB, DL, VT,
9812                         DAG.getConstant(0, DL, MVT::i32), Res);
9813 
9814     } else
9815       return SDValue();
9816   }
9817 
9818   if (ShiftAmt != 0)
9819     Res = DAG.getNode(ISD::SHL, DL, VT,
9820                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9821 
9822   // Do not add new nodes to DAG combiner worklist.
9823   DCI.CombineTo(N, Res, false);
9824   return SDValue();
9825 }
9826 
9827 static SDValue PerformANDCombine(SDNode *N,
9828                                  TargetLowering::DAGCombinerInfo &DCI,
9829                                  const ARMSubtarget *Subtarget) {
9830   // Attempt to use immediate-form VBIC
9831   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9832   SDLoc dl(N);
9833   EVT VT = N->getValueType(0);
9834   SelectionDAG &DAG = DCI.DAG;
9835 
9836   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9837     return SDValue();
9838 
9839   APInt SplatBits, SplatUndef;
9840   unsigned SplatBitSize;
9841   bool HasAnyUndefs;
9842   if (BVN &&
9843       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9844     if (SplatBitSize <= 64) {
9845       EVT VbicVT;
9846       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9847                                       SplatUndef.getZExtValue(), SplatBitSize,
9848                                       DAG, dl, VbicVT, VT.is128BitVector(),
9849                                       OtherModImm);
9850       if (Val.getNode()) {
9851         SDValue Input =
9852           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9853         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9854         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9855       }
9856     }
9857   }
9858 
9859   if (!Subtarget->isThumb1Only()) {
9860     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9861     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9862       return Result;
9863   }
9864 
9865   return SDValue();
9866 }
9867 
9868 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
9869 static SDValue PerformORCombine(SDNode *N,
9870                                 TargetLowering::DAGCombinerInfo &DCI,
9871                                 const ARMSubtarget *Subtarget) {
9872   // Attempt to use immediate-form VORR
9873   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9874   SDLoc dl(N);
9875   EVT VT = N->getValueType(0);
9876   SelectionDAG &DAG = DCI.DAG;
9877 
9878   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9879     return SDValue();
9880 
9881   APInt SplatBits, SplatUndef;
9882   unsigned SplatBitSize;
9883   bool HasAnyUndefs;
9884   if (BVN && Subtarget->hasNEON() &&
9885       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9886     if (SplatBitSize <= 64) {
9887       EVT VorrVT;
9888       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9889                                       SplatUndef.getZExtValue(), SplatBitSize,
9890                                       DAG, dl, VorrVT, VT.is128BitVector(),
9891                                       OtherModImm);
9892       if (Val.getNode()) {
9893         SDValue Input =
9894           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9895         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9896         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9897       }
9898     }
9899   }
9900 
9901   if (!Subtarget->isThumb1Only()) {
9902     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9903     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9904       return Result;
9905   }
9906 
9907   // The code below optimizes (or (and X, Y), Z).
9908   // The AND operand needs to have a single user to make these optimizations
9909   // profitable.
9910   SDValue N0 = N->getOperand(0);
9911   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9912     return SDValue();
9913   SDValue N1 = N->getOperand(1);
9914 
9915   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9916   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9917       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9918     APInt SplatUndef;
9919     unsigned SplatBitSize;
9920     bool HasAnyUndefs;
9921 
9922     APInt SplatBits0, SplatBits1;
9923     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9924     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9925     // Ensure that the second operand of both ands are constants
9926     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9927                                       HasAnyUndefs) && !HasAnyUndefs) {
9928         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9929                                           HasAnyUndefs) && !HasAnyUndefs) {
9930             // Ensure that the bit width of the constants are the same and that
9931             // the splat arguments are logical inverses as per the pattern we
9932             // are trying to simplify.
9933             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9934                 SplatBits0 == ~SplatBits1) {
9935                 // Canonicalize the vector type to make instruction selection
9936                 // simpler.
9937                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9938                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9939                                              N0->getOperand(1),
9940                                              N0->getOperand(0),
9941                                              N1->getOperand(0));
9942                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9943             }
9944         }
9945     }
9946   }
9947 
9948   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9949   // reasonable.
9950 
9951   // BFI is only available on V6T2+
9952   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9953     return SDValue();
9954 
9955   SDLoc DL(N);
9956   // 1) or (and A, mask), val => ARMbfi A, val, mask
9957   //      iff (val & mask) == val
9958   //
9959   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9960   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9961   //          && mask == ~mask2
9962   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9963   //          && ~mask == mask2
9964   //  (i.e., copy a bitfield value into another bitfield of the same width)
9965 
9966   if (VT != MVT::i32)
9967     return SDValue();
9968 
9969   SDValue N00 = N0.getOperand(0);
9970 
9971   // The value and the mask need to be constants so we can verify this is
9972   // actually a bitfield set. If the mask is 0xffff, we can do better
9973   // via a movt instruction, so don't use BFI in that case.
9974   SDValue MaskOp = N0.getOperand(1);
9975   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9976   if (!MaskC)
9977     return SDValue();
9978   unsigned Mask = MaskC->getZExtValue();
9979   if (Mask == 0xffff)
9980     return SDValue();
9981   SDValue Res;
9982   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9983   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9984   if (N1C) {
9985     unsigned Val = N1C->getZExtValue();
9986     if ((Val & ~Mask) != Val)
9987       return SDValue();
9988 
9989     if (ARM::isBitFieldInvertedMask(Mask)) {
9990       Val >>= countTrailingZeros(~Mask);
9991 
9992       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9993                         DAG.getConstant(Val, DL, MVT::i32),
9994                         DAG.getConstant(Mask, DL, MVT::i32));
9995 
9996       // Do not add new nodes to DAG combiner worklist.
9997       DCI.CombineTo(N, Res, false);
9998       return SDValue();
9999     }
10000   } else if (N1.getOpcode() == ISD::AND) {
10001     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10002     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10003     if (!N11C)
10004       return SDValue();
10005     unsigned Mask2 = N11C->getZExtValue();
10006 
10007     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10008     // as is to match.
10009     if (ARM::isBitFieldInvertedMask(Mask) &&
10010         (Mask == ~Mask2)) {
10011       // The pack halfword instruction works better for masks that fit it,
10012       // so use that when it's available.
10013       if (Subtarget->hasT2ExtractPack() &&
10014           (Mask == 0xffff || Mask == 0xffff0000))
10015         return SDValue();
10016       // 2a
10017       unsigned amt = countTrailingZeros(Mask2);
10018       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10019                         DAG.getConstant(amt, DL, MVT::i32));
10020       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10021                         DAG.getConstant(Mask, DL, MVT::i32));
10022       // Do not add new nodes to DAG combiner worklist.
10023       DCI.CombineTo(N, Res, false);
10024       return SDValue();
10025     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10026                (~Mask == Mask2)) {
10027       // The pack halfword instruction works better for masks that fit it,
10028       // so use that when it's available.
10029       if (Subtarget->hasT2ExtractPack() &&
10030           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10031         return SDValue();
10032       // 2b
10033       unsigned lsb = countTrailingZeros(Mask);
10034       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10035                         DAG.getConstant(lsb, DL, MVT::i32));
10036       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10037                         DAG.getConstant(Mask2, DL, MVT::i32));
10038       // Do not add new nodes to DAG combiner worklist.
10039       DCI.CombineTo(N, Res, false);
10040       return SDValue();
10041     }
10042   }
10043 
10044   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10045       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10046       ARM::isBitFieldInvertedMask(~Mask)) {
10047     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10048     // where lsb(mask) == #shamt and masked bits of B are known zero.
10049     SDValue ShAmt = N00.getOperand(1);
10050     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10051     unsigned LSB = countTrailingZeros(Mask);
10052     if (ShAmtC != LSB)
10053       return SDValue();
10054 
10055     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10056                       DAG.getConstant(~Mask, DL, MVT::i32));
10057 
10058     // Do not add new nodes to DAG combiner worklist.
10059     DCI.CombineTo(N, Res, false);
10060   }
10061 
10062   return SDValue();
10063 }
10064 
10065 static SDValue PerformXORCombine(SDNode *N,
10066                                  TargetLowering::DAGCombinerInfo &DCI,
10067                                  const ARMSubtarget *Subtarget) {
10068   EVT VT = N->getValueType(0);
10069   SelectionDAG &DAG = DCI.DAG;
10070 
10071   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10072     return SDValue();
10073 
10074   if (!Subtarget->isThumb1Only()) {
10075     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10076     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10077       return Result;
10078   }
10079 
10080   return SDValue();
10081 }
10082 
10083 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10084 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10085 // their position in "to" (Rd).
10086 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10087   assert(N->getOpcode() == ARMISD::BFI);
10088 
10089   SDValue From = N->getOperand(1);
10090   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10091   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10092 
10093   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10094   // #C in the base of the SHR.
10095   if (From->getOpcode() == ISD::SRL &&
10096       isa<ConstantSDNode>(From->getOperand(1))) {
10097     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10098     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10099     FromMask <<= Shift.getLimitedValue(31);
10100     From = From->getOperand(0);
10101   }
10102 
10103   return From;
10104 }
10105 
10106 // If A and B contain one contiguous set of bits, does A | B == A . B?
10107 //
10108 // Neither A nor B must be zero.
10109 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10110   unsigned LastActiveBitInA =  A.countTrailingZeros();
10111   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10112   return LastActiveBitInA - 1 == FirstActiveBitInB;
10113 }
10114 
10115 static SDValue FindBFIToCombineWith(SDNode *N) {
10116   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10117   // if one exists.
10118   APInt ToMask, FromMask;
10119   SDValue From = ParseBFI(N, ToMask, FromMask);
10120   SDValue To = N->getOperand(0);
10121 
10122   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10123   // aren't compatible, but not if they set the same bit in their destination as
10124   // we do (or that of any BFI we're going to combine with).
10125   SDValue V = To;
10126   APInt CombinedToMask = ToMask;
10127   while (V.getOpcode() == ARMISD::BFI) {
10128     APInt NewToMask, NewFromMask;
10129     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10130     if (NewFrom != From) {
10131       // This BFI has a different base. Keep going.
10132       CombinedToMask |= NewToMask;
10133       V = V.getOperand(0);
10134       continue;
10135     }
10136 
10137     // Do the written bits conflict with any we've seen so far?
10138     if ((NewToMask & CombinedToMask).getBoolValue())
10139       // Conflicting bits - bail out because going further is unsafe.
10140       return SDValue();
10141 
10142     // Are the new bits contiguous when combined with the old bits?
10143     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10144         BitsProperlyConcatenate(FromMask, NewFromMask))
10145       return V;
10146     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10147         BitsProperlyConcatenate(NewFromMask, FromMask))
10148       return V;
10149 
10150     // We've seen a write to some bits, so track it.
10151     CombinedToMask |= NewToMask;
10152     // Keep going...
10153     V = V.getOperand(0);
10154   }
10155 
10156   return SDValue();
10157 }
10158 
10159 static SDValue PerformBFICombine(SDNode *N,
10160                                  TargetLowering::DAGCombinerInfo &DCI) {
10161   SDValue N1 = N->getOperand(1);
10162   if (N1.getOpcode() == ISD::AND) {
10163     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10164     // the bits being cleared by the AND are not demanded by the BFI.
10165     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10166     if (!N11C)
10167       return SDValue();
10168     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10169     unsigned LSB = countTrailingZeros(~InvMask);
10170     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10171     assert(Width <
10172                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10173            "undefined behavior");
10174     unsigned Mask = (1u << Width) - 1;
10175     unsigned Mask2 = N11C->getZExtValue();
10176     if ((Mask & (~Mask2)) == 0)
10177       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10178                              N->getOperand(0), N1.getOperand(0),
10179                              N->getOperand(2));
10180   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10181     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10182     // Keep track of any consecutive bits set that all come from the same base
10183     // value. We can combine these together into a single BFI.
10184     SDValue CombineBFI = FindBFIToCombineWith(N);
10185     if (CombineBFI == SDValue())
10186       return SDValue();
10187 
10188     // We've found a BFI.
10189     APInt ToMask1, FromMask1;
10190     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10191 
10192     APInt ToMask2, FromMask2;
10193     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10194     assert(From1 == From2);
10195     (void)From2;
10196 
10197     // First, unlink CombineBFI.
10198     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10199     // Then create a new BFI, combining the two together.
10200     APInt NewFromMask = FromMask1 | FromMask2;
10201     APInt NewToMask = ToMask1 | ToMask2;
10202 
10203     EVT VT = N->getValueType(0);
10204     SDLoc dl(N);
10205 
10206     if (NewFromMask[0] == 0)
10207       From1 = DCI.DAG.getNode(
10208         ISD::SRL, dl, VT, From1,
10209         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10210     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10211                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10212   }
10213   return SDValue();
10214 }
10215 
10216 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10217 /// ARMISD::VMOVRRD.
10218 static SDValue PerformVMOVRRDCombine(SDNode *N,
10219                                      TargetLowering::DAGCombinerInfo &DCI,
10220                                      const ARMSubtarget *Subtarget) {
10221   // vmovrrd(vmovdrr x, y) -> x,y
10222   SDValue InDouble = N->getOperand(0);
10223   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10224     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10225 
10226   // vmovrrd(load f64) -> (load i32), (load i32)
10227   SDNode *InNode = InDouble.getNode();
10228   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10229       InNode->getValueType(0) == MVT::f64 &&
10230       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10231       !cast<LoadSDNode>(InNode)->isVolatile()) {
10232     // TODO: Should this be done for non-FrameIndex operands?
10233     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10234 
10235     SelectionDAG &DAG = DCI.DAG;
10236     SDLoc DL(LD);
10237     SDValue BasePtr = LD->getBasePtr();
10238     SDValue NewLD1 =
10239         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10240                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10241 
10242     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10243                                     DAG.getConstant(4, DL, MVT::i32));
10244     SDValue NewLD2 = DAG.getLoad(
10245         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10246         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10247 
10248     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10249     if (DCI.DAG.getDataLayout().isBigEndian())
10250       std::swap (NewLD1, NewLD2);
10251     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10252     return Result;
10253   }
10254 
10255   return SDValue();
10256 }
10257 
10258 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10259 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10260 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10261   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10262   SDValue Op0 = N->getOperand(0);
10263   SDValue Op1 = N->getOperand(1);
10264   if (Op0.getOpcode() == ISD::BITCAST)
10265     Op0 = Op0.getOperand(0);
10266   if (Op1.getOpcode() == ISD::BITCAST)
10267     Op1 = Op1.getOperand(0);
10268   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10269       Op0.getNode() == Op1.getNode() &&
10270       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10271     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10272                        N->getValueType(0), Op0.getOperand(0));
10273   return SDValue();
10274 }
10275 
10276 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10277 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10278 /// i64 vector to have f64 elements, since the value can then be loaded
10279 /// directly into a VFP register.
10280 static bool hasNormalLoadOperand(SDNode *N) {
10281   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10282   for (unsigned i = 0; i < NumElts; ++i) {
10283     SDNode *Elt = N->getOperand(i).getNode();
10284     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10285       return true;
10286   }
10287   return false;
10288 }
10289 
10290 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10291 /// ISD::BUILD_VECTOR.
10292 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10293                                           TargetLowering::DAGCombinerInfo &DCI,
10294                                           const ARMSubtarget *Subtarget) {
10295   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10296   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10297   // into a pair of GPRs, which is fine when the value is used as a scalar,
10298   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10299   SelectionDAG &DAG = DCI.DAG;
10300   if (N->getNumOperands() == 2)
10301     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10302       return RV;
10303 
10304   // Load i64 elements as f64 values so that type legalization does not split
10305   // them up into i32 values.
10306   EVT VT = N->getValueType(0);
10307   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10308     return SDValue();
10309   SDLoc dl(N);
10310   SmallVector<SDValue, 8> Ops;
10311   unsigned NumElts = VT.getVectorNumElements();
10312   for (unsigned i = 0; i < NumElts; ++i) {
10313     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10314     Ops.push_back(V);
10315     // Make the DAGCombiner fold the bitcast.
10316     DCI.AddToWorklist(V.getNode());
10317   }
10318   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10319   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10320   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10321 }
10322 
10323 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10324 static SDValue
10325 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10326   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10327   // At that time, we may have inserted bitcasts from integer to float.
10328   // If these bitcasts have survived DAGCombine, change the lowering of this
10329   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10330   // force to use floating point types.
10331 
10332   // Make sure we can change the type of the vector.
10333   // This is possible iff:
10334   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10335   //    1.1. Vector is used only once.
10336   //    1.2. Use is a bit convert to an integer type.
10337   // 2. The size of its operands are 32-bits (64-bits are not legal).
10338   EVT VT = N->getValueType(0);
10339   EVT EltVT = VT.getVectorElementType();
10340 
10341   // Check 1.1. and 2.
10342   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10343     return SDValue();
10344 
10345   // By construction, the input type must be float.
10346   assert(EltVT == MVT::f32 && "Unexpected type!");
10347 
10348   // Check 1.2.
10349   SDNode *Use = *N->use_begin();
10350   if (Use->getOpcode() != ISD::BITCAST ||
10351       Use->getValueType(0).isFloatingPoint())
10352     return SDValue();
10353 
10354   // Check profitability.
10355   // Model is, if more than half of the relevant operands are bitcast from
10356   // i32, turn the build_vector into a sequence of insert_vector_elt.
10357   // Relevant operands are everything that is not statically
10358   // (i.e., at compile time) bitcasted.
10359   unsigned NumOfBitCastedElts = 0;
10360   unsigned NumElts = VT.getVectorNumElements();
10361   unsigned NumOfRelevantElts = NumElts;
10362   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10363     SDValue Elt = N->getOperand(Idx);
10364     if (Elt->getOpcode() == ISD::BITCAST) {
10365       // Assume only bit cast to i32 will go away.
10366       if (Elt->getOperand(0).getValueType() == MVT::i32)
10367         ++NumOfBitCastedElts;
10368     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10369       // Constants are statically casted, thus do not count them as
10370       // relevant operands.
10371       --NumOfRelevantElts;
10372   }
10373 
10374   // Check if more than half of the elements require a non-free bitcast.
10375   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10376     return SDValue();
10377 
10378   SelectionDAG &DAG = DCI.DAG;
10379   // Create the new vector type.
10380   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10381   // Check if the type is legal.
10382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10383   if (!TLI.isTypeLegal(VecVT))
10384     return SDValue();
10385 
10386   // Combine:
10387   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10388   // => BITCAST INSERT_VECTOR_ELT
10389   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10390   //                      (BITCAST EN), N.
10391   SDValue Vec = DAG.getUNDEF(VecVT);
10392   SDLoc dl(N);
10393   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10394     SDValue V = N->getOperand(Idx);
10395     if (V.isUndef())
10396       continue;
10397     if (V.getOpcode() == ISD::BITCAST &&
10398         V->getOperand(0).getValueType() == MVT::i32)
10399       // Fold obvious case.
10400       V = V.getOperand(0);
10401     else {
10402       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10403       // Make the DAGCombiner fold the bitcasts.
10404       DCI.AddToWorklist(V.getNode());
10405     }
10406     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10407     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10408   }
10409   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10410   // Make the DAGCombiner fold the bitcasts.
10411   DCI.AddToWorklist(Vec.getNode());
10412   return Vec;
10413 }
10414 
10415 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10416 /// ISD::INSERT_VECTOR_ELT.
10417 static SDValue PerformInsertEltCombine(SDNode *N,
10418                                        TargetLowering::DAGCombinerInfo &DCI) {
10419   // Bitcast an i64 load inserted into a vector to f64.
10420   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10421   EVT VT = N->getValueType(0);
10422   SDNode *Elt = N->getOperand(1).getNode();
10423   if (VT.getVectorElementType() != MVT::i64 ||
10424       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10425     return SDValue();
10426 
10427   SelectionDAG &DAG = DCI.DAG;
10428   SDLoc dl(N);
10429   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10430                                  VT.getVectorNumElements());
10431   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10432   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10433   // Make the DAGCombiner fold the bitcasts.
10434   DCI.AddToWorklist(Vec.getNode());
10435   DCI.AddToWorklist(V.getNode());
10436   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10437                                Vec, V, N->getOperand(2));
10438   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10439 }
10440 
10441 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10442 /// ISD::VECTOR_SHUFFLE.
10443 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10444   // The LLVM shufflevector instruction does not require the shuffle mask
10445   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10446   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10447   // operands do not match the mask length, they are extended by concatenating
10448   // them with undef vectors.  That is probably the right thing for other
10449   // targets, but for NEON it is better to concatenate two double-register
10450   // size vector operands into a single quad-register size vector.  Do that
10451   // transformation here:
10452   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10453   //   shuffle(concat(v1, v2), undef)
10454   SDValue Op0 = N->getOperand(0);
10455   SDValue Op1 = N->getOperand(1);
10456   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10457       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10458       Op0.getNumOperands() != 2 ||
10459       Op1.getNumOperands() != 2)
10460     return SDValue();
10461   SDValue Concat0Op1 = Op0.getOperand(1);
10462   SDValue Concat1Op1 = Op1.getOperand(1);
10463   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10464     return SDValue();
10465   // Skip the transformation if any of the types are illegal.
10466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10467   EVT VT = N->getValueType(0);
10468   if (!TLI.isTypeLegal(VT) ||
10469       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10470       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10471     return SDValue();
10472 
10473   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10474                                   Op0.getOperand(0), Op1.getOperand(0));
10475   // Translate the shuffle mask.
10476   SmallVector<int, 16> NewMask;
10477   unsigned NumElts = VT.getVectorNumElements();
10478   unsigned HalfElts = NumElts/2;
10479   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10480   for (unsigned n = 0; n < NumElts; ++n) {
10481     int MaskElt = SVN->getMaskElt(n);
10482     int NewElt = -1;
10483     if (MaskElt < (int)HalfElts)
10484       NewElt = MaskElt;
10485     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10486       NewElt = HalfElts + MaskElt - NumElts;
10487     NewMask.push_back(NewElt);
10488   }
10489   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10490                               DAG.getUNDEF(VT), NewMask);
10491 }
10492 
10493 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10494 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10495 /// base address updates.
10496 /// For generic load/stores, the memory type is assumed to be a vector.
10497 /// The caller is assumed to have checked legality.
10498 static SDValue CombineBaseUpdate(SDNode *N,
10499                                  TargetLowering::DAGCombinerInfo &DCI) {
10500   SelectionDAG &DAG = DCI.DAG;
10501   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10502                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10503   const bool isStore = N->getOpcode() == ISD::STORE;
10504   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10505   SDValue Addr = N->getOperand(AddrOpIdx);
10506   MemSDNode *MemN = cast<MemSDNode>(N);
10507   SDLoc dl(N);
10508 
10509   // Search for a use of the address operand that is an increment.
10510   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10511          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10512     SDNode *User = *UI;
10513     if (User->getOpcode() != ISD::ADD ||
10514         UI.getUse().getResNo() != Addr.getResNo())
10515       continue;
10516 
10517     // Check that the add is independent of the load/store.  Otherwise, folding
10518     // it would create a cycle.
10519     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10520       continue;
10521 
10522     // Find the new opcode for the updating load/store.
10523     bool isLoadOp = true;
10524     bool isLaneOp = false;
10525     unsigned NewOpc = 0;
10526     unsigned NumVecs = 0;
10527     if (isIntrinsic) {
10528       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10529       switch (IntNo) {
10530       default: llvm_unreachable("unexpected intrinsic for Neon base update");
10531       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
10532         NumVecs = 1; break;
10533       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
10534         NumVecs = 2; break;
10535       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
10536         NumVecs = 3; break;
10537       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
10538         NumVecs = 4; break;
10539       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10540         NumVecs = 2; isLaneOp = true; break;
10541       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10542         NumVecs = 3; isLaneOp = true; break;
10543       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10544         NumVecs = 4; isLaneOp = true; break;
10545       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
10546         NumVecs = 1; isLoadOp = false; break;
10547       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
10548         NumVecs = 2; isLoadOp = false; break;
10549       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
10550         NumVecs = 3; isLoadOp = false; break;
10551       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
10552         NumVecs = 4; isLoadOp = false; break;
10553       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10554         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10555       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10556         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10557       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10558         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10559       }
10560     } else {
10561       isLaneOp = true;
10562       switch (N->getOpcode()) {
10563       default: llvm_unreachable("unexpected opcode for Neon base update");
10564       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
10565       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10566       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10567       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10568       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
10569         NumVecs = 1; isLaneOp = false; break;
10570       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
10571         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10572       }
10573     }
10574 
10575     // Find the size of memory referenced by the load/store.
10576     EVT VecTy;
10577     if (isLoadOp) {
10578       VecTy = N->getValueType(0);
10579     } else if (isIntrinsic) {
10580       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10581     } else {
10582       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10583       VecTy = N->getOperand(1).getValueType();
10584     }
10585 
10586     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10587     if (isLaneOp)
10588       NumBytes /= VecTy.getVectorNumElements();
10589 
10590     // If the increment is a constant, it must match the memory ref size.
10591     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10592     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10593       uint64_t IncVal = CInc->getZExtValue();
10594       if (IncVal != NumBytes)
10595         continue;
10596     } else if (NumBytes >= 3 * 16) {
10597       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10598       // separate instructions that make it harder to use a non-constant update.
10599       continue;
10600     }
10601 
10602     // OK, we found an ADD we can fold into the base update.
10603     // Now, create a _UPD node, taking care of not breaking alignment.
10604 
10605     EVT AlignedVecTy = VecTy;
10606     unsigned Alignment = MemN->getAlignment();
10607 
10608     // If this is a less-than-standard-aligned load/store, change the type to
10609     // match the standard alignment.
10610     // The alignment is overlooked when selecting _UPD variants; and it's
10611     // easier to introduce bitcasts here than fix that.
10612     // There are 3 ways to get to this base-update combine:
10613     // - intrinsics: they are assumed to be properly aligned (to the standard
10614     //   alignment of the memory type), so we don't need to do anything.
10615     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10616     //   intrinsics, so, likewise, there's nothing to do.
10617     // - generic load/store instructions: the alignment is specified as an
10618     //   explicit operand, rather than implicitly as the standard alignment
10619     //   of the memory type (like the intrisics).  We need to change the
10620     //   memory type to match the explicit alignment.  That way, we don't
10621     //   generate non-standard-aligned ARMISD::VLDx nodes.
10622     if (isa<LSBaseSDNode>(N)) {
10623       if (Alignment == 0)
10624         Alignment = 1;
10625       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10626         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10627         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10628         assert(!isLaneOp && "Unexpected generic load/store lane.");
10629         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10630         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10631       }
10632       // Don't set an explicit alignment on regular load/stores that we want
10633       // to transform to VLD/VST 1_UPD nodes.
10634       // This matches the behavior of regular load/stores, which only get an
10635       // explicit alignment if the MMO alignment is larger than the standard
10636       // alignment of the memory type.
10637       // Intrinsics, however, always get an explicit alignment, set to the
10638       // alignment of the MMO.
10639       Alignment = 1;
10640     }
10641 
10642     // Create the new updating load/store node.
10643     // First, create an SDVTList for the new updating node's results.
10644     EVT Tys[6];
10645     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10646     unsigned n;
10647     for (n = 0; n < NumResultVecs; ++n)
10648       Tys[n] = AlignedVecTy;
10649     Tys[n++] = MVT::i32;
10650     Tys[n] = MVT::Other;
10651     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10652 
10653     // Then, gather the new node's operands.
10654     SmallVector<SDValue, 8> Ops;
10655     Ops.push_back(N->getOperand(0)); // incoming chain
10656     Ops.push_back(N->getOperand(AddrOpIdx));
10657     Ops.push_back(Inc);
10658 
10659     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10660       // Try to match the intrinsic's signature
10661       Ops.push_back(StN->getValue());
10662     } else {
10663       // Loads (and of course intrinsics) match the intrinsics' signature,
10664       // so just add all but the alignment operand.
10665       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10666         Ops.push_back(N->getOperand(i));
10667     }
10668 
10669     // For all node types, the alignment operand is always the last one.
10670     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10671 
10672     // If this is a non-standard-aligned STORE, the penultimate operand is the
10673     // stored value.  Bitcast it to the aligned type.
10674     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10675       SDValue &StVal = Ops[Ops.size()-2];
10676       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10677     }
10678 
10679     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
10680     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
10681                                            MemN->getMemOperand());
10682 
10683     // Update the uses.
10684     SmallVector<SDValue, 5> NewResults;
10685     for (unsigned i = 0; i < NumResultVecs; ++i)
10686       NewResults.push_back(SDValue(UpdN.getNode(), i));
10687 
10688     // If this is an non-standard-aligned LOAD, the first result is the loaded
10689     // value.  Bitcast it to the expected result type.
10690     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10691       SDValue &LdVal = NewResults[0];
10692       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10693     }
10694 
10695     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10696     DCI.CombineTo(N, NewResults);
10697     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10698 
10699     break;
10700   }
10701   return SDValue();
10702 }
10703 
10704 static SDValue PerformVLDCombine(SDNode *N,
10705                                  TargetLowering::DAGCombinerInfo &DCI) {
10706   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10707     return SDValue();
10708 
10709   return CombineBaseUpdate(N, DCI);
10710 }
10711 
10712 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10713 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10714 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10715 /// return true.
10716 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10717   SelectionDAG &DAG = DCI.DAG;
10718   EVT VT = N->getValueType(0);
10719   // vldN-dup instructions only support 64-bit vectors for N > 1.
10720   if (!VT.is64BitVector())
10721     return false;
10722 
10723   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10724   SDNode *VLD = N->getOperand(0).getNode();
10725   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10726     return false;
10727   unsigned NumVecs = 0;
10728   unsigned NewOpc = 0;
10729   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10730   if (IntNo == Intrinsic::arm_neon_vld2lane) {
10731     NumVecs = 2;
10732     NewOpc = ARMISD::VLD2DUP;
10733   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10734     NumVecs = 3;
10735     NewOpc = ARMISD::VLD3DUP;
10736   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10737     NumVecs = 4;
10738     NewOpc = ARMISD::VLD4DUP;
10739   } else {
10740     return false;
10741   }
10742 
10743   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10744   // numbers match the load.
10745   unsigned VLDLaneNo =
10746     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10747   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10748        UI != UE; ++UI) {
10749     // Ignore uses of the chain result.
10750     if (UI.getUse().getResNo() == NumVecs)
10751       continue;
10752     SDNode *User = *UI;
10753     if (User->getOpcode() != ARMISD::VDUPLANE ||
10754         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10755       return false;
10756   }
10757 
10758   // Create the vldN-dup node.
10759   EVT Tys[5];
10760   unsigned n;
10761   for (n = 0; n < NumVecs; ++n)
10762     Tys[n] = VT;
10763   Tys[n] = MVT::Other;
10764   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10765   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10766   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10767   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10768                                            Ops, VLDMemInt->getMemoryVT(),
10769                                            VLDMemInt->getMemOperand());
10770 
10771   // Update the uses.
10772   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10773        UI != UE; ++UI) {
10774     unsigned ResNo = UI.getUse().getResNo();
10775     // Ignore uses of the chain result.
10776     if (ResNo == NumVecs)
10777       continue;
10778     SDNode *User = *UI;
10779     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10780   }
10781 
10782   // Now the vldN-lane intrinsic is dead except for its chain result.
10783   // Update uses of the chain.
10784   std::vector<SDValue> VLDDupResults;
10785   for (unsigned n = 0; n < NumVecs; ++n)
10786     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10787   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10788   DCI.CombineTo(VLD, VLDDupResults);
10789 
10790   return true;
10791 }
10792 
10793 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10794 /// ARMISD::VDUPLANE.
10795 static SDValue PerformVDUPLANECombine(SDNode *N,
10796                                       TargetLowering::DAGCombinerInfo &DCI) {
10797   SDValue Op = N->getOperand(0);
10798 
10799   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
10800   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
10801   if (CombineVLDDUP(N, DCI))
10802     return SDValue(N, 0);
10803 
10804   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
10805   // redundant.  Ignore bit_converts for now; element sizes are checked below.
10806   while (Op.getOpcode() == ISD::BITCAST)
10807     Op = Op.getOperand(0);
10808   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
10809     return SDValue();
10810 
10811   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
10812   unsigned EltSize = Op.getScalarValueSizeInBits();
10813   // The canonical VMOV for a zero vector uses a 32-bit element size.
10814   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10815   unsigned EltBits;
10816   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
10817     EltSize = 8;
10818   EVT VT = N->getValueType(0);
10819   if (EltSize > VT.getScalarSizeInBits())
10820     return SDValue();
10821 
10822   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
10823 }
10824 
10825 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
10826 static SDValue PerformVDUPCombine(SDNode *N,
10827                                   TargetLowering::DAGCombinerInfo &DCI) {
10828   SelectionDAG &DAG = DCI.DAG;
10829   SDValue Op = N->getOperand(0);
10830 
10831   // Match VDUP(LOAD) -> VLD1DUP.
10832   // We match this pattern here rather than waiting for isel because the
10833   // transform is only legal for unindexed loads.
10834   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
10835   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
10836       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
10837     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
10838                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
10839     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
10840     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
10841                                              Ops, LD->getMemoryVT(),
10842                                              LD->getMemOperand());
10843     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
10844     return VLDDup;
10845   }
10846 
10847   return SDValue();
10848 }
10849 
10850 static SDValue PerformLOADCombine(SDNode *N,
10851                                   TargetLowering::DAGCombinerInfo &DCI) {
10852   EVT VT = N->getValueType(0);
10853 
10854   // If this is a legal vector load, try to combine it into a VLD1_UPD.
10855   if (ISD::isNormalLoad(N) && VT.isVector() &&
10856       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10857     return CombineBaseUpdate(N, DCI);
10858 
10859   return SDValue();
10860 }
10861 
10862 /// PerformSTORECombine - Target-specific dag combine xforms for
10863 /// ISD::STORE.
10864 static SDValue PerformSTORECombine(SDNode *N,
10865                                    TargetLowering::DAGCombinerInfo &DCI) {
10866   StoreSDNode *St = cast<StoreSDNode>(N);
10867   if (St->isVolatile())
10868     return SDValue();
10869 
10870   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
10871   // pack all of the elements in one place.  Next, store to memory in fewer
10872   // chunks.
10873   SDValue StVal = St->getValue();
10874   EVT VT = StVal.getValueType();
10875   if (St->isTruncatingStore() && VT.isVector()) {
10876     SelectionDAG &DAG = DCI.DAG;
10877     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10878     EVT StVT = St->getMemoryVT();
10879     unsigned NumElems = VT.getVectorNumElements();
10880     assert(StVT != VT && "Cannot truncate to the same type");
10881     unsigned FromEltSz = VT.getScalarSizeInBits();
10882     unsigned ToEltSz = StVT.getScalarSizeInBits();
10883 
10884     // From, To sizes and ElemCount must be pow of two
10885     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
10886 
10887     // We are going to use the original vector elt for storing.
10888     // Accumulated smaller vector elements must be a multiple of the store size.
10889     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
10890 
10891     unsigned SizeRatio  = FromEltSz / ToEltSz;
10892     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
10893 
10894     // Create a type on which we perform the shuffle.
10895     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
10896                                      NumElems*SizeRatio);
10897     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
10898 
10899     SDLoc DL(St);
10900     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
10901     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
10902     for (unsigned i = 0; i < NumElems; ++i)
10903       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
10904                           ? (i + 1) * SizeRatio - 1
10905                           : i * SizeRatio;
10906 
10907     // Can't shuffle using an illegal type.
10908     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10909 
10910     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10911                                 DAG.getUNDEF(WideVec.getValueType()),
10912                                 ShuffleVec);
10913     // At this point all of the data is stored at the bottom of the
10914     // register. We now need to save it to mem.
10915 
10916     // Find the largest store unit
10917     MVT StoreType = MVT::i8;
10918     for (MVT Tp : MVT::integer_valuetypes()) {
10919       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10920         StoreType = Tp;
10921     }
10922     // Didn't find a legal store type.
10923     if (!TLI.isTypeLegal(StoreType))
10924       return SDValue();
10925 
10926     // Bitcast the original vector into a vector of store-size units
10927     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10928             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10929     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10930     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10931     SmallVector<SDValue, 8> Chains;
10932     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10933                                         TLI.getPointerTy(DAG.getDataLayout()));
10934     SDValue BasePtr = St->getBasePtr();
10935 
10936     // Perform one or more big stores into memory.
10937     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10938     for (unsigned I = 0; I < E; I++) {
10939       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10940                                    StoreType, ShuffWide,
10941                                    DAG.getIntPtrConstant(I, DL));
10942       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10943                                 St->getPointerInfo(), St->getAlignment(),
10944                                 St->getMemOperand()->getFlags());
10945       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10946                             Increment);
10947       Chains.push_back(Ch);
10948     }
10949     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10950   }
10951 
10952   if (!ISD::isNormalStore(St))
10953     return SDValue();
10954 
10955   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10956   // ARM stores of arguments in the same cache line.
10957   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10958       StVal.getNode()->hasOneUse()) {
10959     SelectionDAG  &DAG = DCI.DAG;
10960     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10961     SDLoc DL(St);
10962     SDValue BasePtr = St->getBasePtr();
10963     SDValue NewST1 = DAG.getStore(
10964         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
10965         BasePtr, St->getPointerInfo(), St->getAlignment(),
10966         St->getMemOperand()->getFlags());
10967 
10968     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10969                                     DAG.getConstant(4, DL, MVT::i32));
10970     return DAG.getStore(NewST1.getValue(0), DL,
10971                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10972                         OffsetPtr, St->getPointerInfo(),
10973                         std::min(4U, St->getAlignment() / 2),
10974                         St->getMemOperand()->getFlags());
10975   }
10976 
10977   if (StVal.getValueType() == MVT::i64 &&
10978       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10979 
10980     // Bitcast an i64 store extracted from a vector to f64.
10981     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10982     SelectionDAG &DAG = DCI.DAG;
10983     SDLoc dl(StVal);
10984     SDValue IntVec = StVal.getOperand(0);
10985     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10986                                    IntVec.getValueType().getVectorNumElements());
10987     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10988     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10989                                  Vec, StVal.getOperand(1));
10990     dl = SDLoc(N);
10991     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10992     // Make the DAGCombiner fold the bitcasts.
10993     DCI.AddToWorklist(Vec.getNode());
10994     DCI.AddToWorklist(ExtElt.getNode());
10995     DCI.AddToWorklist(V.getNode());
10996     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10997                         St->getPointerInfo(), St->getAlignment(),
10998                         St->getMemOperand()->getFlags(), St->getAAInfo());
10999   }
11000 
11001   // If this is a legal vector store, try to combine it into a VST1_UPD.
11002   if (ISD::isNormalStore(N) && VT.isVector() &&
11003       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11004     return CombineBaseUpdate(N, DCI);
11005 
11006   return SDValue();
11007 }
11008 
11009 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11010 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11011 /// when the VMUL has a constant operand that is a power of 2.
11012 ///
11013 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11014 ///  vmul.f32        d16, d17, d16
11015 ///  vcvt.s32.f32    d16, d16
11016 /// becomes:
11017 ///  vcvt.s32.f32    d16, d16, #3
11018 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11019                                   const ARMSubtarget *Subtarget) {
11020   if (!Subtarget->hasNEON())
11021     return SDValue();
11022 
11023   SDValue Op = N->getOperand(0);
11024   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11025       Op.getOpcode() != ISD::FMUL)
11026     return SDValue();
11027 
11028   SDValue ConstVec = Op->getOperand(1);
11029   if (!isa<BuildVectorSDNode>(ConstVec))
11030     return SDValue();
11031 
11032   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11033   uint32_t FloatBits = FloatTy.getSizeInBits();
11034   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11035   uint32_t IntBits = IntTy.getSizeInBits();
11036   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11037   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11038     // These instructions only exist converting from f32 to i32. We can handle
11039     // smaller integers by generating an extra truncate, but larger ones would
11040     // be lossy. We also can't handle more then 4 lanes, since these intructions
11041     // only support v2i32/v4i32 types.
11042     return SDValue();
11043   }
11044 
11045   BitVector UndefElements;
11046   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11047   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11048   if (C == -1 || C == 0 || C > 32)
11049     return SDValue();
11050 
11051   SDLoc dl(N);
11052   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11053   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11054     Intrinsic::arm_neon_vcvtfp2fxu;
11055   SDValue FixConv = DAG.getNode(
11056       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11057       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11058       DAG.getConstant(C, dl, MVT::i32));
11059 
11060   if (IntBits < FloatBits)
11061     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11062 
11063   return FixConv;
11064 }
11065 
11066 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11067 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11068 /// when the VDIV has a constant operand that is a power of 2.
11069 ///
11070 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11071 ///  vcvt.f32.s32    d16, d16
11072 ///  vdiv.f32        d16, d17, d16
11073 /// becomes:
11074 ///  vcvt.f32.s32    d16, d16, #3
11075 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11076                                   const ARMSubtarget *Subtarget) {
11077   if (!Subtarget->hasNEON())
11078     return SDValue();
11079 
11080   SDValue Op = N->getOperand(0);
11081   unsigned OpOpcode = Op.getNode()->getOpcode();
11082   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11083       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11084     return SDValue();
11085 
11086   SDValue ConstVec = N->getOperand(1);
11087   if (!isa<BuildVectorSDNode>(ConstVec))
11088     return SDValue();
11089 
11090   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11091   uint32_t FloatBits = FloatTy.getSizeInBits();
11092   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11093   uint32_t IntBits = IntTy.getSizeInBits();
11094   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11095   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11096     // These instructions only exist converting from i32 to f32. We can handle
11097     // smaller integers by generating an extra extend, but larger ones would
11098     // be lossy. We also can't handle more then 4 lanes, since these intructions
11099     // only support v2i32/v4i32 types.
11100     return SDValue();
11101   }
11102 
11103   BitVector UndefElements;
11104   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11105   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11106   if (C == -1 || C == 0 || C > 32)
11107     return SDValue();
11108 
11109   SDLoc dl(N);
11110   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11111   SDValue ConvInput = Op.getOperand(0);
11112   if (IntBits < FloatBits)
11113     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11114                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11115                             ConvInput);
11116 
11117   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11118     Intrinsic::arm_neon_vcvtfxu2fp;
11119   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11120                      Op.getValueType(),
11121                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11122                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11123 }
11124 
11125 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11126 /// operand of a vector shift operation, where all the elements of the
11127 /// build_vector must have the same constant integer value.
11128 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11129   // Ignore bit_converts.
11130   while (Op.getOpcode() == ISD::BITCAST)
11131     Op = Op.getOperand(0);
11132   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11133   APInt SplatBits, SplatUndef;
11134   unsigned SplatBitSize;
11135   bool HasAnyUndefs;
11136   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11137                                       HasAnyUndefs, ElementBits) ||
11138       SplatBitSize > ElementBits)
11139     return false;
11140   Cnt = SplatBits.getSExtValue();
11141   return true;
11142 }
11143 
11144 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11145 /// operand of a vector shift left operation.  That value must be in the range:
11146 ///   0 <= Value < ElementBits for a left shift; or
11147 ///   0 <= Value <= ElementBits for a long left shift.
11148 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11149   assert(VT.isVector() && "vector shift count is not a vector type");
11150   int64_t ElementBits = VT.getScalarSizeInBits();
11151   if (! getVShiftImm(Op, ElementBits, Cnt))
11152     return false;
11153   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11154 }
11155 
11156 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11157 /// operand of a vector shift right operation.  For a shift opcode, the value
11158 /// is positive, but for an intrinsic the value count must be negative. The
11159 /// absolute value must be in the range:
11160 ///   1 <= |Value| <= ElementBits for a right shift; or
11161 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11162 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11163                          int64_t &Cnt) {
11164   assert(VT.isVector() && "vector shift count is not a vector type");
11165   int64_t ElementBits = VT.getScalarSizeInBits();
11166   if (! getVShiftImm(Op, ElementBits, Cnt))
11167     return false;
11168   if (!isIntrinsic)
11169     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11170   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11171     Cnt = -Cnt;
11172     return true;
11173   }
11174   return false;
11175 }
11176 
11177 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11178 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11179   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11180   switch (IntNo) {
11181   default:
11182     // Don't do anything for most intrinsics.
11183     break;
11184 
11185   // Vector shifts: check for immediate versions and lower them.
11186   // Note: This is done during DAG combining instead of DAG legalizing because
11187   // the build_vectors for 64-bit vector element shift counts are generally
11188   // not legal, and it is hard to see their values after they get legalized to
11189   // loads from a constant pool.
11190   case Intrinsic::arm_neon_vshifts:
11191   case Intrinsic::arm_neon_vshiftu:
11192   case Intrinsic::arm_neon_vrshifts:
11193   case Intrinsic::arm_neon_vrshiftu:
11194   case Intrinsic::arm_neon_vrshiftn:
11195   case Intrinsic::arm_neon_vqshifts:
11196   case Intrinsic::arm_neon_vqshiftu:
11197   case Intrinsic::arm_neon_vqshiftsu:
11198   case Intrinsic::arm_neon_vqshiftns:
11199   case Intrinsic::arm_neon_vqshiftnu:
11200   case Intrinsic::arm_neon_vqshiftnsu:
11201   case Intrinsic::arm_neon_vqrshiftns:
11202   case Intrinsic::arm_neon_vqrshiftnu:
11203   case Intrinsic::arm_neon_vqrshiftnsu: {
11204     EVT VT = N->getOperand(1).getValueType();
11205     int64_t Cnt;
11206     unsigned VShiftOpc = 0;
11207 
11208     switch (IntNo) {
11209     case Intrinsic::arm_neon_vshifts:
11210     case Intrinsic::arm_neon_vshiftu:
11211       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11212         VShiftOpc = ARMISD::VSHL;
11213         break;
11214       }
11215       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11216         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11217                      ARMISD::VSHRs : ARMISD::VSHRu);
11218         break;
11219       }
11220       return SDValue();
11221 
11222     case Intrinsic::arm_neon_vrshifts:
11223     case Intrinsic::arm_neon_vrshiftu:
11224       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11225         break;
11226       return SDValue();
11227 
11228     case Intrinsic::arm_neon_vqshifts:
11229     case Intrinsic::arm_neon_vqshiftu:
11230       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11231         break;
11232       return SDValue();
11233 
11234     case Intrinsic::arm_neon_vqshiftsu:
11235       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11236         break;
11237       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11238 
11239     case Intrinsic::arm_neon_vrshiftn:
11240     case Intrinsic::arm_neon_vqshiftns:
11241     case Intrinsic::arm_neon_vqshiftnu:
11242     case Intrinsic::arm_neon_vqshiftnsu:
11243     case Intrinsic::arm_neon_vqrshiftns:
11244     case Intrinsic::arm_neon_vqrshiftnu:
11245     case Intrinsic::arm_neon_vqrshiftnsu:
11246       // Narrowing shifts require an immediate right shift.
11247       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11248         break;
11249       llvm_unreachable("invalid shift count for narrowing vector shift "
11250                        "intrinsic");
11251 
11252     default:
11253       llvm_unreachable("unhandled vector shift");
11254     }
11255 
11256     switch (IntNo) {
11257     case Intrinsic::arm_neon_vshifts:
11258     case Intrinsic::arm_neon_vshiftu:
11259       // Opcode already set above.
11260       break;
11261     case Intrinsic::arm_neon_vrshifts:
11262       VShiftOpc = ARMISD::VRSHRs; break;
11263     case Intrinsic::arm_neon_vrshiftu:
11264       VShiftOpc = ARMISD::VRSHRu; break;
11265     case Intrinsic::arm_neon_vrshiftn:
11266       VShiftOpc = ARMISD::VRSHRN; break;
11267     case Intrinsic::arm_neon_vqshifts:
11268       VShiftOpc = ARMISD::VQSHLs; break;
11269     case Intrinsic::arm_neon_vqshiftu:
11270       VShiftOpc = ARMISD::VQSHLu; break;
11271     case Intrinsic::arm_neon_vqshiftsu:
11272       VShiftOpc = ARMISD::VQSHLsu; break;
11273     case Intrinsic::arm_neon_vqshiftns:
11274       VShiftOpc = ARMISD::VQSHRNs; break;
11275     case Intrinsic::arm_neon_vqshiftnu:
11276       VShiftOpc = ARMISD::VQSHRNu; break;
11277     case Intrinsic::arm_neon_vqshiftnsu:
11278       VShiftOpc = ARMISD::VQSHRNsu; break;
11279     case Intrinsic::arm_neon_vqrshiftns:
11280       VShiftOpc = ARMISD::VQRSHRNs; break;
11281     case Intrinsic::arm_neon_vqrshiftnu:
11282       VShiftOpc = ARMISD::VQRSHRNu; break;
11283     case Intrinsic::arm_neon_vqrshiftnsu:
11284       VShiftOpc = ARMISD::VQRSHRNsu; break;
11285     }
11286 
11287     SDLoc dl(N);
11288     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11289                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11290   }
11291 
11292   case Intrinsic::arm_neon_vshiftins: {
11293     EVT VT = N->getOperand(1).getValueType();
11294     int64_t Cnt;
11295     unsigned VShiftOpc = 0;
11296 
11297     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11298       VShiftOpc = ARMISD::VSLI;
11299     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11300       VShiftOpc = ARMISD::VSRI;
11301     else {
11302       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11303     }
11304 
11305     SDLoc dl(N);
11306     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11307                        N->getOperand(1), N->getOperand(2),
11308                        DAG.getConstant(Cnt, dl, MVT::i32));
11309   }
11310 
11311   case Intrinsic::arm_neon_vqrshifts:
11312   case Intrinsic::arm_neon_vqrshiftu:
11313     // No immediate versions of these to check for.
11314     break;
11315   }
11316 
11317   return SDValue();
11318 }
11319 
11320 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11321 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11322 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11323 /// vector element shift counts are generally not legal, and it is hard to see
11324 /// their values after they get legalized to loads from a constant pool.
11325 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11326                                    const ARMSubtarget *ST) {
11327   EVT VT = N->getValueType(0);
11328   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11329     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11330     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11331     SDValue N1 = N->getOperand(1);
11332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11333       SDValue N0 = N->getOperand(0);
11334       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11335           DAG.MaskedValueIsZero(N0.getOperand(0),
11336                                 APInt::getHighBitsSet(32, 16)))
11337         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11338     }
11339   }
11340 
11341   // Nothing to be done for scalar shifts.
11342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11343   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11344     return SDValue();
11345 
11346   assert(ST->hasNEON() && "unexpected vector shift");
11347   int64_t Cnt;
11348 
11349   switch (N->getOpcode()) {
11350   default: llvm_unreachable("unexpected shift opcode");
11351 
11352   case ISD::SHL:
11353     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11354       SDLoc dl(N);
11355       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11356                          DAG.getConstant(Cnt, dl, MVT::i32));
11357     }
11358     break;
11359 
11360   case ISD::SRA:
11361   case ISD::SRL:
11362     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11363       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11364                             ARMISD::VSHRs : ARMISD::VSHRu);
11365       SDLoc dl(N);
11366       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11367                          DAG.getConstant(Cnt, dl, MVT::i32));
11368     }
11369   }
11370   return SDValue();
11371 }
11372 
11373 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11374 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11375 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11376                                     const ARMSubtarget *ST) {
11377   SDValue N0 = N->getOperand(0);
11378 
11379   // Check for sign- and zero-extensions of vector extract operations of 8-
11380   // and 16-bit vector elements.  NEON supports these directly.  They are
11381   // handled during DAG combining because type legalization will promote them
11382   // to 32-bit types and it is messy to recognize the operations after that.
11383   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11384     SDValue Vec = N0.getOperand(0);
11385     SDValue Lane = N0.getOperand(1);
11386     EVT VT = N->getValueType(0);
11387     EVT EltVT = N0.getValueType();
11388     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11389 
11390     if (VT == MVT::i32 &&
11391         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11392         TLI.isTypeLegal(Vec.getValueType()) &&
11393         isa<ConstantSDNode>(Lane)) {
11394 
11395       unsigned Opc = 0;
11396       switch (N->getOpcode()) {
11397       default: llvm_unreachable("unexpected opcode");
11398       case ISD::SIGN_EXTEND:
11399         Opc = ARMISD::VGETLANEs;
11400         break;
11401       case ISD::ZERO_EXTEND:
11402       case ISD::ANY_EXTEND:
11403         Opc = ARMISD::VGETLANEu;
11404         break;
11405       }
11406       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11407     }
11408   }
11409 
11410   return SDValue();
11411 }
11412 
11413 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
11414                              APInt &KnownOne) {
11415   if (Op.getOpcode() == ARMISD::BFI) {
11416     // Conservatively, we can recurse down the first operand
11417     // and just mask out all affected bits.
11418     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
11419 
11420     // The operand to BFI is already a mask suitable for removing the bits it
11421     // sets.
11422     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
11423     const APInt &Mask = CI->getAPIntValue();
11424     KnownZero &= Mask;
11425     KnownOne &= Mask;
11426     return;
11427   }
11428   if (Op.getOpcode() == ARMISD::CMOV) {
11429     APInt KZ2(KnownZero.getBitWidth(), 0);
11430     APInt KO2(KnownOne.getBitWidth(), 0);
11431     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
11432     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
11433 
11434     KnownZero &= KZ2;
11435     KnownOne &= KO2;
11436     return;
11437   }
11438   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
11439 }
11440 
11441 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11442   // If we have a CMOV, OR and AND combination such as:
11443   //   if (x & CN)
11444   //     y |= CM;
11445   //
11446   // And:
11447   //   * CN is a single bit;
11448   //   * All bits covered by CM are known zero in y
11449   //
11450   // Then we can convert this into a sequence of BFI instructions. This will
11451   // always be a win if CM is a single bit, will always be no worse than the
11452   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11453   // three bits (due to the extra IT instruction).
11454 
11455   SDValue Op0 = CMOV->getOperand(0);
11456   SDValue Op1 = CMOV->getOperand(1);
11457   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11458   auto CC = CCNode->getAPIntValue().getLimitedValue();
11459   SDValue CmpZ = CMOV->getOperand(4);
11460 
11461   // The compare must be against zero.
11462   if (!isNullConstant(CmpZ->getOperand(1)))
11463     return SDValue();
11464 
11465   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11466   SDValue And = CmpZ->getOperand(0);
11467   if (And->getOpcode() != ISD::AND)
11468     return SDValue();
11469   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11470   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11471     return SDValue();
11472   SDValue X = And->getOperand(0);
11473 
11474   if (CC == ARMCC::EQ) {
11475     // We're performing an "equal to zero" compare. Swap the operands so we
11476     // canonicalize on a "not equal to zero" compare.
11477     std::swap(Op0, Op1);
11478   } else {
11479     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11480   }
11481 
11482   if (Op1->getOpcode() != ISD::OR)
11483     return SDValue();
11484 
11485   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11486   if (!OrC)
11487     return SDValue();
11488   SDValue Y = Op1->getOperand(0);
11489 
11490   if (Op0 != Y)
11491     return SDValue();
11492 
11493   // Now, is it profitable to continue?
11494   APInt OrCI = OrC->getAPIntValue();
11495   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11496   if (OrCI.countPopulation() > Heuristic)
11497     return SDValue();
11498 
11499   // Lastly, can we determine that the bits defined by OrCI
11500   // are zero in Y?
11501   APInt KnownZero, KnownOne;
11502   computeKnownBits(DAG, Y, KnownZero, KnownOne);
11503   if ((OrCI & KnownZero) != OrCI)
11504     return SDValue();
11505 
11506   // OK, we can do the combine.
11507   SDValue V = Y;
11508   SDLoc dl(X);
11509   EVT VT = X.getValueType();
11510   unsigned BitInX = AndC->getAPIntValue().logBase2();
11511 
11512   if (BitInX != 0) {
11513     // We must shift X first.
11514     X = DAG.getNode(ISD::SRL, dl, VT, X,
11515                     DAG.getConstant(BitInX, dl, VT));
11516   }
11517 
11518   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11519        BitInY < NumActiveBits; ++BitInY) {
11520     if (OrCI[BitInY] == 0)
11521       continue;
11522     APInt Mask(VT.getSizeInBits(), 0);
11523     Mask.setBit(BitInY);
11524     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11525                     // Confusingly, the operand is an *inverted* mask.
11526                     DAG.getConstant(~Mask, dl, VT));
11527   }
11528 
11529   return V;
11530 }
11531 
11532 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11533 SDValue
11534 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11535   SDValue Cmp = N->getOperand(4);
11536   if (Cmp.getOpcode() != ARMISD::CMPZ)
11537     // Only looking at NE cases.
11538     return SDValue();
11539 
11540   EVT VT = N->getValueType(0);
11541   SDLoc dl(N);
11542   SDValue LHS = Cmp.getOperand(0);
11543   SDValue RHS = Cmp.getOperand(1);
11544   SDValue Chain = N->getOperand(0);
11545   SDValue BB = N->getOperand(1);
11546   SDValue ARMcc = N->getOperand(2);
11547   ARMCC::CondCodes CC =
11548     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11549 
11550   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11551   // -> (brcond Chain BB CC CPSR Cmp)
11552   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11553       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11554       LHS->getOperand(0)->hasOneUse()) {
11555     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11556     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11557     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11558     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11559     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11560         (LHS01C && LHS01C->getZExtValue() == 1) &&
11561         (LHS1C && LHS1C->getZExtValue() == 1) &&
11562         (RHSC && RHSC->getZExtValue() == 0)) {
11563       return DAG.getNode(
11564           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11565           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11566     }
11567   }
11568 
11569   return SDValue();
11570 }
11571 
11572 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11573 SDValue
11574 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11575   SDValue Cmp = N->getOperand(4);
11576   if (Cmp.getOpcode() != ARMISD::CMPZ)
11577     // Only looking at EQ and NE cases.
11578     return SDValue();
11579 
11580   EVT VT = N->getValueType(0);
11581   SDLoc dl(N);
11582   SDValue LHS = Cmp.getOperand(0);
11583   SDValue RHS = Cmp.getOperand(1);
11584   SDValue FalseVal = N->getOperand(0);
11585   SDValue TrueVal = N->getOperand(1);
11586   SDValue ARMcc = N->getOperand(2);
11587   ARMCC::CondCodes CC =
11588     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11589 
11590   // BFI is only available on V6T2+.
11591   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11592     SDValue R = PerformCMOVToBFICombine(N, DAG);
11593     if (R)
11594       return R;
11595   }
11596 
11597   // Simplify
11598   //   mov     r1, r0
11599   //   cmp     r1, x
11600   //   mov     r0, y
11601   //   moveq   r0, x
11602   // to
11603   //   cmp     r0, x
11604   //   movne   r0, y
11605   //
11606   //   mov     r1, r0
11607   //   cmp     r1, x
11608   //   mov     r0, x
11609   //   movne   r0, y
11610   // to
11611   //   cmp     r0, x
11612   //   movne   r0, y
11613   /// FIXME: Turn this into a target neutral optimization?
11614   SDValue Res;
11615   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11616     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11617                       N->getOperand(3), Cmp);
11618   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11619     SDValue ARMcc;
11620     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11621     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11622                       N->getOperand(3), NewCmp);
11623   }
11624 
11625   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11626   // -> (cmov F T CC CPSR Cmp)
11627   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11628     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11629     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11630     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11631     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11632         (LHS1C && LHS1C->getZExtValue() == 1) &&
11633         (RHSC && RHSC->getZExtValue() == 0)) {
11634       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11635                          LHS->getOperand(2), LHS->getOperand(3),
11636                          LHS->getOperand(4));
11637     }
11638   }
11639 
11640   if (Res.getNode()) {
11641     APInt KnownZero, KnownOne;
11642     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11643     // Capture demanded bits information that would be otherwise lost.
11644     if (KnownZero == 0xfffffffe)
11645       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11646                         DAG.getValueType(MVT::i1));
11647     else if (KnownZero == 0xffffff00)
11648       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11649                         DAG.getValueType(MVT::i8));
11650     else if (KnownZero == 0xffff0000)
11651       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11652                         DAG.getValueType(MVT::i16));
11653   }
11654 
11655   return Res;
11656 }
11657 
11658 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11659                                              DAGCombinerInfo &DCI) const {
11660   switch (N->getOpcode()) {
11661   default: break;
11662   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
11663   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11664   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11665   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11666   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11667   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11668   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11669   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11670   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11671   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11672   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11673   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11674   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11675   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11676   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11677   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
11678   case ISD::FP_TO_SINT:
11679   case ISD::FP_TO_UINT:
11680     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11681   case ISD::FDIV:
11682     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11683   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11684   case ISD::SHL:
11685   case ISD::SRA:
11686   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11687   case ISD::SIGN_EXTEND:
11688   case ISD::ZERO_EXTEND:
11689   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11690   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11691   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11692   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11693   case ARMISD::VLD1DUP:
11694   case ARMISD::VLD2DUP:
11695   case ARMISD::VLD3DUP:
11696   case ARMISD::VLD4DUP:
11697     return PerformVLDCombine(N, DCI);
11698   case ARMISD::BUILD_VECTOR:
11699     return PerformARMBUILD_VECTORCombine(N, DCI);
11700   case ISD::INTRINSIC_VOID:
11701   case ISD::INTRINSIC_W_CHAIN:
11702     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11703     case Intrinsic::arm_neon_vld1:
11704     case Intrinsic::arm_neon_vld2:
11705     case Intrinsic::arm_neon_vld3:
11706     case Intrinsic::arm_neon_vld4:
11707     case Intrinsic::arm_neon_vld2lane:
11708     case Intrinsic::arm_neon_vld3lane:
11709     case Intrinsic::arm_neon_vld4lane:
11710     case Intrinsic::arm_neon_vst1:
11711     case Intrinsic::arm_neon_vst2:
11712     case Intrinsic::arm_neon_vst3:
11713     case Intrinsic::arm_neon_vst4:
11714     case Intrinsic::arm_neon_vst2lane:
11715     case Intrinsic::arm_neon_vst3lane:
11716     case Intrinsic::arm_neon_vst4lane:
11717       return PerformVLDCombine(N, DCI);
11718     default: break;
11719     }
11720     break;
11721   }
11722   return SDValue();
11723 }
11724 
11725 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11726                                                           EVT VT) const {
11727   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11728 }
11729 
11730 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11731                                                        unsigned,
11732                                                        unsigned,
11733                                                        bool *Fast) const {
11734   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11735   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11736 
11737   switch (VT.getSimpleVT().SimpleTy) {
11738   default:
11739     return false;
11740   case MVT::i8:
11741   case MVT::i16:
11742   case MVT::i32: {
11743     // Unaligned access can use (for example) LRDB, LRDH, LDR
11744     if (AllowsUnaligned) {
11745       if (Fast)
11746         *Fast = Subtarget->hasV7Ops();
11747       return true;
11748     }
11749     return false;
11750   }
11751   case MVT::f64:
11752   case MVT::v2f64: {
11753     // For any little-endian targets with neon, we can support unaligned ld/st
11754     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
11755     // A big-endian target may also explicitly support unaligned accesses
11756     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
11757       if (Fast)
11758         *Fast = true;
11759       return true;
11760     }
11761     return false;
11762   }
11763   }
11764 }
11765 
11766 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
11767                        unsigned AlignCheck) {
11768   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
11769           (DstAlign == 0 || DstAlign % AlignCheck == 0));
11770 }
11771 
11772 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
11773                                            unsigned DstAlign, unsigned SrcAlign,
11774                                            bool IsMemset, bool ZeroMemset,
11775                                            bool MemcpyStrSrc,
11776                                            MachineFunction &MF) const {
11777   const Function *F = MF.getFunction();
11778 
11779   // See if we can use NEON instructions for this...
11780   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
11781       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11782     bool Fast;
11783     if (Size >= 16 &&
11784         (memOpAlign(SrcAlign, DstAlign, 16) ||
11785          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
11786       return MVT::v2f64;
11787     } else if (Size >= 8 &&
11788                (memOpAlign(SrcAlign, DstAlign, 8) ||
11789                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
11790                  Fast))) {
11791       return MVT::f64;
11792     }
11793   }
11794 
11795   // Lowering to i32/i16 if the size permits.
11796   if (Size >= 4)
11797     return MVT::i32;
11798   else if (Size >= 2)
11799     return MVT::i16;
11800 
11801   // Let the target-independent logic figure it out.
11802   return MVT::Other;
11803 }
11804 
11805 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11806   if (Val.getOpcode() != ISD::LOAD)
11807     return false;
11808 
11809   EVT VT1 = Val.getValueType();
11810   if (!VT1.isSimple() || !VT1.isInteger() ||
11811       !VT2.isSimple() || !VT2.isInteger())
11812     return false;
11813 
11814   switch (VT1.getSimpleVT().SimpleTy) {
11815   default: break;
11816   case MVT::i1:
11817   case MVT::i8:
11818   case MVT::i16:
11819     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
11820     return true;
11821   }
11822 
11823   return false;
11824 }
11825 
11826 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
11827   EVT VT = ExtVal.getValueType();
11828 
11829   if (!isTypeLegal(VT))
11830     return false;
11831 
11832   // Don't create a loadext if we can fold the extension into a wide/long
11833   // instruction.
11834   // If there's more than one user instruction, the loadext is desirable no
11835   // matter what.  There can be two uses by the same instruction.
11836   if (ExtVal->use_empty() ||
11837       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
11838     return true;
11839 
11840   SDNode *U = *ExtVal->use_begin();
11841   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
11842        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
11843     return false;
11844 
11845   return true;
11846 }
11847 
11848 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
11849   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11850     return false;
11851 
11852   if (!isTypeLegal(EVT::getEVT(Ty1)))
11853     return false;
11854 
11855   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
11856 
11857   // Assuming the caller doesn't have a zeroext or signext return parameter,
11858   // truncation all the way down to i1 is valid.
11859   return true;
11860 }
11861 
11862 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
11863                                                 const AddrMode &AM, Type *Ty,
11864                                                 unsigned AS) const {
11865   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
11866     if (Subtarget->hasFPAO())
11867       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
11868     return 0;
11869   }
11870   return -1;
11871 }
11872 
11873 
11874 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
11875   if (V < 0)
11876     return false;
11877 
11878   unsigned Scale = 1;
11879   switch (VT.getSimpleVT().SimpleTy) {
11880   default: return false;
11881   case MVT::i1:
11882   case MVT::i8:
11883     // Scale == 1;
11884     break;
11885   case MVT::i16:
11886     // Scale == 2;
11887     Scale = 2;
11888     break;
11889   case MVT::i32:
11890     // Scale == 4;
11891     Scale = 4;
11892     break;
11893   }
11894 
11895   if ((V & (Scale - 1)) != 0)
11896     return false;
11897   V /= Scale;
11898   return V == (V & ((1LL << 5) - 1));
11899 }
11900 
11901 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
11902                                       const ARMSubtarget *Subtarget) {
11903   bool isNeg = false;
11904   if (V < 0) {
11905     isNeg = true;
11906     V = - V;
11907   }
11908 
11909   switch (VT.getSimpleVT().SimpleTy) {
11910   default: return false;
11911   case MVT::i1:
11912   case MVT::i8:
11913   case MVT::i16:
11914   case MVT::i32:
11915     // + imm12 or - imm8
11916     if (isNeg)
11917       return V == (V & ((1LL << 8) - 1));
11918     return V == (V & ((1LL << 12) - 1));
11919   case MVT::f32:
11920   case MVT::f64:
11921     // Same as ARM mode. FIXME: NEON?
11922     if (!Subtarget->hasVFP2())
11923       return false;
11924     if ((V & 3) != 0)
11925       return false;
11926     V >>= 2;
11927     return V == (V & ((1LL << 8) - 1));
11928   }
11929 }
11930 
11931 /// isLegalAddressImmediate - Return true if the integer value can be used
11932 /// as the offset of the target addressing mode for load / store of the
11933 /// given type.
11934 static bool isLegalAddressImmediate(int64_t V, EVT VT,
11935                                     const ARMSubtarget *Subtarget) {
11936   if (V == 0)
11937     return true;
11938 
11939   if (!VT.isSimple())
11940     return false;
11941 
11942   if (Subtarget->isThumb1Only())
11943     return isLegalT1AddressImmediate(V, VT);
11944   else if (Subtarget->isThumb2())
11945     return isLegalT2AddressImmediate(V, VT, Subtarget);
11946 
11947   // ARM mode.
11948   if (V < 0)
11949     V = - V;
11950   switch (VT.getSimpleVT().SimpleTy) {
11951   default: return false;
11952   case MVT::i1:
11953   case MVT::i8:
11954   case MVT::i32:
11955     // +- imm12
11956     return V == (V & ((1LL << 12) - 1));
11957   case MVT::i16:
11958     // +- imm8
11959     return V == (V & ((1LL << 8) - 1));
11960   case MVT::f32:
11961   case MVT::f64:
11962     if (!Subtarget->hasVFP2()) // FIXME: NEON?
11963       return false;
11964     if ((V & 3) != 0)
11965       return false;
11966     V >>= 2;
11967     return V == (V & ((1LL << 8) - 1));
11968   }
11969 }
11970 
11971 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
11972                                                       EVT VT) const {
11973   int Scale = AM.Scale;
11974   if (Scale < 0)
11975     return false;
11976 
11977   switch (VT.getSimpleVT().SimpleTy) {
11978   default: return false;
11979   case MVT::i1:
11980   case MVT::i8:
11981   case MVT::i16:
11982   case MVT::i32:
11983     if (Scale == 1)
11984       return true;
11985     // r + r << imm
11986     Scale = Scale & ~1;
11987     return Scale == 2 || Scale == 4 || Scale == 8;
11988   case MVT::i64:
11989     // r + r
11990     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11991       return true;
11992     return false;
11993   case MVT::isVoid:
11994     // Note, we allow "void" uses (basically, uses that aren't loads or
11995     // stores), because arm allows folding a scale into many arithmetic
11996     // operations.  This should be made more precise and revisited later.
11997 
11998     // Allow r << imm, but the imm has to be a multiple of two.
11999     if (Scale & 1) return false;
12000     return isPowerOf2_32(Scale);
12001   }
12002 }
12003 
12004 /// isLegalAddressingMode - Return true if the addressing mode represented
12005 /// by AM is legal for this target, for a load/store of the specified type.
12006 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12007                                               const AddrMode &AM, Type *Ty,
12008                                               unsigned AS) const {
12009   EVT VT = getValueType(DL, Ty, true);
12010   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12011     return false;
12012 
12013   // Can never fold addr of global into load/store.
12014   if (AM.BaseGV)
12015     return false;
12016 
12017   switch (AM.Scale) {
12018   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12019     break;
12020   case 1:
12021     if (Subtarget->isThumb1Only())
12022       return false;
12023     LLVM_FALLTHROUGH;
12024   default:
12025     // ARM doesn't support any R+R*scale+imm addr modes.
12026     if (AM.BaseOffs)
12027       return false;
12028 
12029     if (!VT.isSimple())
12030       return false;
12031 
12032     if (Subtarget->isThumb2())
12033       return isLegalT2ScaledAddressingMode(AM, VT);
12034 
12035     int Scale = AM.Scale;
12036     switch (VT.getSimpleVT().SimpleTy) {
12037     default: return false;
12038     case MVT::i1:
12039     case MVT::i8:
12040     case MVT::i32:
12041       if (Scale < 0) Scale = -Scale;
12042       if (Scale == 1)
12043         return true;
12044       // r + r << imm
12045       return isPowerOf2_32(Scale & ~1);
12046     case MVT::i16:
12047     case MVT::i64:
12048       // r + r
12049       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12050         return true;
12051       return false;
12052 
12053     case MVT::isVoid:
12054       // Note, we allow "void" uses (basically, uses that aren't loads or
12055       // stores), because arm allows folding a scale into many arithmetic
12056       // operations.  This should be made more precise and revisited later.
12057 
12058       // Allow r << imm, but the imm has to be a multiple of two.
12059       if (Scale & 1) return false;
12060       return isPowerOf2_32(Scale);
12061     }
12062   }
12063   return true;
12064 }
12065 
12066 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12067 /// icmp immediate, that is the target has icmp instructions which can compare
12068 /// a register against the immediate without having to materialize the
12069 /// immediate into a register.
12070 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12071   // Thumb2 and ARM modes can use cmn for negative immediates.
12072   if (!Subtarget->isThumb())
12073     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12074   if (Subtarget->isThumb2())
12075     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12076   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12077   return Imm >= 0 && Imm <= 255;
12078 }
12079 
12080 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12081 /// *or sub* immediate, that is the target has add or sub instructions which can
12082 /// add a register with the immediate without having to materialize the
12083 /// immediate into a register.
12084 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12085   // Same encoding for add/sub, just flip the sign.
12086   int64_t AbsImm = std::abs(Imm);
12087   if (!Subtarget->isThumb())
12088     return ARM_AM::getSOImmVal(AbsImm) != -1;
12089   if (Subtarget->isThumb2())
12090     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12091   // Thumb1 only has 8-bit unsigned immediate.
12092   return AbsImm >= 0 && AbsImm <= 255;
12093 }
12094 
12095 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12096                                       bool isSEXTLoad, SDValue &Base,
12097                                       SDValue &Offset, bool &isInc,
12098                                       SelectionDAG &DAG) {
12099   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12100     return false;
12101 
12102   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12103     // AddressingMode 3
12104     Base = Ptr->getOperand(0);
12105     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12106       int RHSC = (int)RHS->getZExtValue();
12107       if (RHSC < 0 && RHSC > -256) {
12108         assert(Ptr->getOpcode() == ISD::ADD);
12109         isInc = false;
12110         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12111         return true;
12112       }
12113     }
12114     isInc = (Ptr->getOpcode() == ISD::ADD);
12115     Offset = Ptr->getOperand(1);
12116     return true;
12117   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12118     // AddressingMode 2
12119     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12120       int RHSC = (int)RHS->getZExtValue();
12121       if (RHSC < 0 && RHSC > -0x1000) {
12122         assert(Ptr->getOpcode() == ISD::ADD);
12123         isInc = false;
12124         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12125         Base = Ptr->getOperand(0);
12126         return true;
12127       }
12128     }
12129 
12130     if (Ptr->getOpcode() == ISD::ADD) {
12131       isInc = true;
12132       ARM_AM::ShiftOpc ShOpcVal=
12133         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12134       if (ShOpcVal != ARM_AM::no_shift) {
12135         Base = Ptr->getOperand(1);
12136         Offset = Ptr->getOperand(0);
12137       } else {
12138         Base = Ptr->getOperand(0);
12139         Offset = Ptr->getOperand(1);
12140       }
12141       return true;
12142     }
12143 
12144     isInc = (Ptr->getOpcode() == ISD::ADD);
12145     Base = Ptr->getOperand(0);
12146     Offset = Ptr->getOperand(1);
12147     return true;
12148   }
12149 
12150   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12151   return false;
12152 }
12153 
12154 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12155                                      bool isSEXTLoad, SDValue &Base,
12156                                      SDValue &Offset, bool &isInc,
12157                                      SelectionDAG &DAG) {
12158   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12159     return false;
12160 
12161   Base = Ptr->getOperand(0);
12162   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12163     int RHSC = (int)RHS->getZExtValue();
12164     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12165       assert(Ptr->getOpcode() == ISD::ADD);
12166       isInc = false;
12167       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12168       return true;
12169     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12170       isInc = Ptr->getOpcode() == ISD::ADD;
12171       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12172       return true;
12173     }
12174   }
12175 
12176   return false;
12177 }
12178 
12179 /// getPreIndexedAddressParts - returns true by value, base pointer and
12180 /// offset pointer and addressing mode by reference if the node's address
12181 /// can be legally represented as pre-indexed load / store address.
12182 bool
12183 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12184                                              SDValue &Offset,
12185                                              ISD::MemIndexedMode &AM,
12186                                              SelectionDAG &DAG) const {
12187   if (Subtarget->isThumb1Only())
12188     return false;
12189 
12190   EVT VT;
12191   SDValue Ptr;
12192   bool isSEXTLoad = false;
12193   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12194     Ptr = LD->getBasePtr();
12195     VT  = LD->getMemoryVT();
12196     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12197   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12198     Ptr = ST->getBasePtr();
12199     VT  = ST->getMemoryVT();
12200   } else
12201     return false;
12202 
12203   bool isInc;
12204   bool isLegal = false;
12205   if (Subtarget->isThumb2())
12206     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12207                                        Offset, isInc, DAG);
12208   else
12209     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12210                                         Offset, isInc, DAG);
12211   if (!isLegal)
12212     return false;
12213 
12214   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12215   return true;
12216 }
12217 
12218 /// getPostIndexedAddressParts - returns true by value, base pointer and
12219 /// offset pointer and addressing mode by reference if this node can be
12220 /// combined with a load / store to form a post-indexed load / store.
12221 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12222                                                    SDValue &Base,
12223                                                    SDValue &Offset,
12224                                                    ISD::MemIndexedMode &AM,
12225                                                    SelectionDAG &DAG) const {
12226   EVT VT;
12227   SDValue Ptr;
12228   bool isSEXTLoad = false, isNonExt;
12229   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12230     VT  = LD->getMemoryVT();
12231     Ptr = LD->getBasePtr();
12232     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12233     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12234   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12235     VT  = ST->getMemoryVT();
12236     Ptr = ST->getBasePtr();
12237     isNonExt = !ST->isTruncatingStore();
12238   } else
12239     return false;
12240 
12241   if (Subtarget->isThumb1Only()) {
12242     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12243     // must be non-extending/truncating, i32, with an offset of 4.
12244     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12245     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12246       return false;
12247     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12248     if (!RHS || RHS->getZExtValue() != 4)
12249       return false;
12250 
12251     Offset = Op->getOperand(1);
12252     Base = Op->getOperand(0);
12253     AM = ISD::POST_INC;
12254     return true;
12255   }
12256 
12257   bool isInc;
12258   bool isLegal = false;
12259   if (Subtarget->isThumb2())
12260     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12261                                        isInc, DAG);
12262   else
12263     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12264                                         isInc, DAG);
12265   if (!isLegal)
12266     return false;
12267 
12268   if (Ptr != Base) {
12269     // Swap base ptr and offset to catch more post-index load / store when
12270     // it's legal. In Thumb2 mode, offset must be an immediate.
12271     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12272         !Subtarget->isThumb2())
12273       std::swap(Base, Offset);
12274 
12275     // Post-indexed load / store update the base pointer.
12276     if (Ptr != Base)
12277       return false;
12278   }
12279 
12280   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12281   return true;
12282 }
12283 
12284 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12285                                                       APInt &KnownZero,
12286                                                       APInt &KnownOne,
12287                                                       const SelectionDAG &DAG,
12288                                                       unsigned Depth) const {
12289   unsigned BitWidth = KnownOne.getBitWidth();
12290   KnownZero = KnownOne = APInt(BitWidth, 0);
12291   switch (Op.getOpcode()) {
12292   default: break;
12293   case ARMISD::ADDC:
12294   case ARMISD::ADDE:
12295   case ARMISD::SUBC:
12296   case ARMISD::SUBE:
12297     // These nodes' second result is a boolean
12298     if (Op.getResNo() == 0)
12299       break;
12300     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12301     break;
12302   case ARMISD::CMOV: {
12303     // Bits are known zero/one if known on the LHS and RHS.
12304     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
12305     if (KnownZero == 0 && KnownOne == 0) return;
12306 
12307     APInt KnownZeroRHS, KnownOneRHS;
12308     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
12309     KnownZero &= KnownZeroRHS;
12310     KnownOne  &= KnownOneRHS;
12311     return;
12312   }
12313   case ISD::INTRINSIC_W_CHAIN: {
12314     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12315     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12316     switch (IntID) {
12317     default: return;
12318     case Intrinsic::arm_ldaex:
12319     case Intrinsic::arm_ldrex: {
12320       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12321       unsigned MemBits = VT.getScalarSizeInBits();
12322       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12323       return;
12324     }
12325     }
12326   }
12327   }
12328 }
12329 
12330 //===----------------------------------------------------------------------===//
12331 //                           ARM Inline Assembly Support
12332 //===----------------------------------------------------------------------===//
12333 
12334 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12335   // Looking for "rev" which is V6+.
12336   if (!Subtarget->hasV6Ops())
12337     return false;
12338 
12339   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12340   std::string AsmStr = IA->getAsmString();
12341   SmallVector<StringRef, 4> AsmPieces;
12342   SplitString(AsmStr, AsmPieces, ";\n");
12343 
12344   switch (AsmPieces.size()) {
12345   default: return false;
12346   case 1:
12347     AsmStr = AsmPieces[0];
12348     AsmPieces.clear();
12349     SplitString(AsmStr, AsmPieces, " \t,");
12350 
12351     // rev $0, $1
12352     if (AsmPieces.size() == 3 &&
12353         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12354         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12355       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12356       if (Ty && Ty->getBitWidth() == 32)
12357         return IntrinsicLowering::LowerToByteSwap(CI);
12358     }
12359     break;
12360   }
12361 
12362   return false;
12363 }
12364 
12365 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12366   // At this point, we have to lower this constraint to something else, so we
12367   // lower it to an "r" or "w". However, by doing this we will force the result
12368   // to be in register, while the X constraint is much more permissive.
12369   //
12370   // Although we are correct (we are free to emit anything, without
12371   // constraints), we might break use cases that would expect us to be more
12372   // efficient and emit something else.
12373   if (!Subtarget->hasVFP2())
12374     return "r";
12375   if (ConstraintVT.isFloatingPoint())
12376     return "w";
12377   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12378      (ConstraintVT.getSizeInBits() == 64 ||
12379       ConstraintVT.getSizeInBits() == 128))
12380     return "w";
12381 
12382   return "r";
12383 }
12384 
12385 /// getConstraintType - Given a constraint letter, return the type of
12386 /// constraint it is for this target.
12387 ARMTargetLowering::ConstraintType
12388 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12389   if (Constraint.size() == 1) {
12390     switch (Constraint[0]) {
12391     default:  break;
12392     case 'l': return C_RegisterClass;
12393     case 'w': return C_RegisterClass;
12394     case 'h': return C_RegisterClass;
12395     case 'x': return C_RegisterClass;
12396     case 't': return C_RegisterClass;
12397     case 'j': return C_Other; // Constant for movw.
12398       // An address with a single base register. Due to the way we
12399       // currently handle addresses it is the same as an 'r' memory constraint.
12400     case 'Q': return C_Memory;
12401     }
12402   } else if (Constraint.size() == 2) {
12403     switch (Constraint[0]) {
12404     default: break;
12405     // All 'U+' constraints are addresses.
12406     case 'U': return C_Memory;
12407     }
12408   }
12409   return TargetLowering::getConstraintType(Constraint);
12410 }
12411 
12412 /// Examine constraint type and operand type and determine a weight value.
12413 /// This object must already have been set up with the operand type
12414 /// and the current alternative constraint selected.
12415 TargetLowering::ConstraintWeight
12416 ARMTargetLowering::getSingleConstraintMatchWeight(
12417     AsmOperandInfo &info, const char *constraint) const {
12418   ConstraintWeight weight = CW_Invalid;
12419   Value *CallOperandVal = info.CallOperandVal;
12420     // If we don't have a value, we can't do a match,
12421     // but allow it at the lowest weight.
12422   if (!CallOperandVal)
12423     return CW_Default;
12424   Type *type = CallOperandVal->getType();
12425   // Look at the constraint type.
12426   switch (*constraint) {
12427   default:
12428     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12429     break;
12430   case 'l':
12431     if (type->isIntegerTy()) {
12432       if (Subtarget->isThumb())
12433         weight = CW_SpecificReg;
12434       else
12435         weight = CW_Register;
12436     }
12437     break;
12438   case 'w':
12439     if (type->isFloatingPointTy())
12440       weight = CW_Register;
12441     break;
12442   }
12443   return weight;
12444 }
12445 
12446 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12447 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12448     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12449   if (Constraint.size() == 1) {
12450     // GCC ARM Constraint Letters
12451     switch (Constraint[0]) {
12452     case 'l': // Low regs or general regs.
12453       if (Subtarget->isThumb())
12454         return RCPair(0U, &ARM::tGPRRegClass);
12455       return RCPair(0U, &ARM::GPRRegClass);
12456     case 'h': // High regs or no regs.
12457       if (Subtarget->isThumb())
12458         return RCPair(0U, &ARM::hGPRRegClass);
12459       break;
12460     case 'r':
12461       if (Subtarget->isThumb1Only())
12462         return RCPair(0U, &ARM::tGPRRegClass);
12463       return RCPair(0U, &ARM::GPRRegClass);
12464     case 'w':
12465       if (VT == MVT::Other)
12466         break;
12467       if (VT == MVT::f32)
12468         return RCPair(0U, &ARM::SPRRegClass);
12469       if (VT.getSizeInBits() == 64)
12470         return RCPair(0U, &ARM::DPRRegClass);
12471       if (VT.getSizeInBits() == 128)
12472         return RCPair(0U, &ARM::QPRRegClass);
12473       break;
12474     case 'x':
12475       if (VT == MVT::Other)
12476         break;
12477       if (VT == MVT::f32)
12478         return RCPair(0U, &ARM::SPR_8RegClass);
12479       if (VT.getSizeInBits() == 64)
12480         return RCPair(0U, &ARM::DPR_8RegClass);
12481       if (VT.getSizeInBits() == 128)
12482         return RCPair(0U, &ARM::QPR_8RegClass);
12483       break;
12484     case 't':
12485       if (VT == MVT::f32)
12486         return RCPair(0U, &ARM::SPRRegClass);
12487       break;
12488     }
12489   }
12490   if (StringRef("{cc}").equals_lower(Constraint))
12491     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12492 
12493   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12494 }
12495 
12496 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12497 /// vector.  If it is invalid, don't add anything to Ops.
12498 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12499                                                      std::string &Constraint,
12500                                                      std::vector<SDValue>&Ops,
12501                                                      SelectionDAG &DAG) const {
12502   SDValue Result;
12503 
12504   // Currently only support length 1 constraints.
12505   if (Constraint.length() != 1) return;
12506 
12507   char ConstraintLetter = Constraint[0];
12508   switch (ConstraintLetter) {
12509   default: break;
12510   case 'j':
12511   case 'I': case 'J': case 'K': case 'L':
12512   case 'M': case 'N': case 'O':
12513     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12514     if (!C)
12515       return;
12516 
12517     int64_t CVal64 = C->getSExtValue();
12518     int CVal = (int) CVal64;
12519     // None of these constraints allow values larger than 32 bits.  Check
12520     // that the value fits in an int.
12521     if (CVal != CVal64)
12522       return;
12523 
12524     switch (ConstraintLetter) {
12525       case 'j':
12526         // Constant suitable for movw, must be between 0 and
12527         // 65535.
12528         if (Subtarget->hasV6T2Ops())
12529           if (CVal >= 0 && CVal <= 65535)
12530             break;
12531         return;
12532       case 'I':
12533         if (Subtarget->isThumb1Only()) {
12534           // This must be a constant between 0 and 255, for ADD
12535           // immediates.
12536           if (CVal >= 0 && CVal <= 255)
12537             break;
12538         } else if (Subtarget->isThumb2()) {
12539           // A constant that can be used as an immediate value in a
12540           // data-processing instruction.
12541           if (ARM_AM::getT2SOImmVal(CVal) != -1)
12542             break;
12543         } else {
12544           // A constant that can be used as an immediate value in a
12545           // data-processing instruction.
12546           if (ARM_AM::getSOImmVal(CVal) != -1)
12547             break;
12548         }
12549         return;
12550 
12551       case 'J':
12552         if (Subtarget->isThumb1Only()) {
12553           // This must be a constant between -255 and -1, for negated ADD
12554           // immediates. This can be used in GCC with an "n" modifier that
12555           // prints the negated value, for use with SUB instructions. It is
12556           // not useful otherwise but is implemented for compatibility.
12557           if (CVal >= -255 && CVal <= -1)
12558             break;
12559         } else {
12560           // This must be a constant between -4095 and 4095. It is not clear
12561           // what this constraint is intended for. Implemented for
12562           // compatibility with GCC.
12563           if (CVal >= -4095 && CVal <= 4095)
12564             break;
12565         }
12566         return;
12567 
12568       case 'K':
12569         if (Subtarget->isThumb1Only()) {
12570           // A 32-bit value where only one byte has a nonzero value. Exclude
12571           // zero to match GCC. This constraint is used by GCC internally for
12572           // constants that can be loaded with a move/shift combination.
12573           // It is not useful otherwise but is implemented for compatibility.
12574           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12575             break;
12576         } else if (Subtarget->isThumb2()) {
12577           // A constant whose bitwise inverse can be used as an immediate
12578           // value in a data-processing instruction. This can be used in GCC
12579           // with a "B" modifier that prints the inverted value, for use with
12580           // BIC and MVN instructions. It is not useful otherwise but is
12581           // implemented for compatibility.
12582           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12583             break;
12584         } else {
12585           // A constant whose bitwise inverse can be used as an immediate
12586           // value in a data-processing instruction. This can be used in GCC
12587           // with a "B" modifier that prints the inverted value, for use with
12588           // BIC and MVN instructions. It is not useful otherwise but is
12589           // implemented for compatibility.
12590           if (ARM_AM::getSOImmVal(~CVal) != -1)
12591             break;
12592         }
12593         return;
12594 
12595       case 'L':
12596         if (Subtarget->isThumb1Only()) {
12597           // This must be a constant between -7 and 7,
12598           // for 3-operand ADD/SUB immediate instructions.
12599           if (CVal >= -7 && CVal < 7)
12600             break;
12601         } else if (Subtarget->isThumb2()) {
12602           // A constant whose negation can be used as an immediate value in a
12603           // data-processing instruction. This can be used in GCC with an "n"
12604           // modifier that prints the negated value, for use with SUB
12605           // instructions. It is not useful otherwise but is implemented for
12606           // compatibility.
12607           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12608             break;
12609         } else {
12610           // A constant whose negation can be used as an immediate value in a
12611           // data-processing instruction. This can be used in GCC with an "n"
12612           // modifier that prints the negated value, for use with SUB
12613           // instructions. It is not useful otherwise but is implemented for
12614           // compatibility.
12615           if (ARM_AM::getSOImmVal(-CVal) != -1)
12616             break;
12617         }
12618         return;
12619 
12620       case 'M':
12621         if (Subtarget->isThumb1Only()) {
12622           // This must be a multiple of 4 between 0 and 1020, for
12623           // ADD sp + immediate.
12624           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12625             break;
12626         } else {
12627           // A power of two or a constant between 0 and 32.  This is used in
12628           // GCC for the shift amount on shifted register operands, but it is
12629           // useful in general for any shift amounts.
12630           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12631             break;
12632         }
12633         return;
12634 
12635       case 'N':
12636         if (Subtarget->isThumb()) {  // FIXME thumb2
12637           // This must be a constant between 0 and 31, for shift amounts.
12638           if (CVal >= 0 && CVal <= 31)
12639             break;
12640         }
12641         return;
12642 
12643       case 'O':
12644         if (Subtarget->isThumb()) {  // FIXME thumb2
12645           // This must be a multiple of 4 between -508 and 508, for
12646           // ADD/SUB sp = sp + immediate.
12647           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12648             break;
12649         }
12650         return;
12651     }
12652     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12653     break;
12654   }
12655 
12656   if (Result.getNode()) {
12657     Ops.push_back(Result);
12658     return;
12659   }
12660   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12661 }
12662 
12663 static RTLIB::Libcall getDivRemLibcall(
12664     const SDNode *N, MVT::SimpleValueType SVT) {
12665   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12666           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12667          "Unhandled Opcode in getDivRemLibcall");
12668   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12669                   N->getOpcode() == ISD::SREM;
12670   RTLIB::Libcall LC;
12671   switch (SVT) {
12672   default: llvm_unreachable("Unexpected request for libcall!");
12673   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
12674   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12675   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12676   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12677   }
12678   return LC;
12679 }
12680 
12681 static TargetLowering::ArgListTy getDivRemArgList(
12682     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
12683   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12684           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12685          "Unhandled Opcode in getDivRemArgList");
12686   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12687                   N->getOpcode() == ISD::SREM;
12688   TargetLowering::ArgListTy Args;
12689   TargetLowering::ArgListEntry Entry;
12690   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12691     EVT ArgVT = N->getOperand(i).getValueType();
12692     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12693     Entry.Node = N->getOperand(i);
12694     Entry.Ty = ArgTy;
12695     Entry.isSExt = isSigned;
12696     Entry.isZExt = !isSigned;
12697     Args.push_back(Entry);
12698   }
12699   if (Subtarget->isTargetWindows() && Args.size() >= 2)
12700     std::swap(Args[0], Args[1]);
12701   return Args;
12702 }
12703 
12704 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12705   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12706           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
12707           Subtarget->isTargetWindows()) &&
12708          "Register-based DivRem lowering only");
12709   unsigned Opcode = Op->getOpcode();
12710   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12711          "Invalid opcode for Div/Rem lowering");
12712   bool isSigned = (Opcode == ISD::SDIVREM);
12713   EVT VT = Op->getValueType(0);
12714   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12715   SDLoc dl(Op);
12716 
12717   // If the target has hardware divide, use divide + multiply + subtract:
12718   //     div = a / b
12719   //     rem = a - b * div
12720   //     return {div, rem}
12721   // This should be lowered into UDIV/SDIV + MLS later on.
12722   if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() &&
12723       Op->getSimpleValueType(0) == MVT::i32) {
12724     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
12725     const SDValue Dividend = Op->getOperand(0);
12726     const SDValue Divisor = Op->getOperand(1);
12727     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
12728     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
12729     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
12730 
12731     SDValue Values[2] = {Div, Rem};
12732     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
12733   }
12734 
12735   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12736                                        VT.getSimpleVT().SimpleTy);
12737   SDValue InChain = DAG.getEntryNode();
12738 
12739   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12740                                                     DAG.getContext(),
12741                                                     Subtarget);
12742 
12743   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12744                                          getPointerTy(DAG.getDataLayout()));
12745 
12746   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12747 
12748   if (Subtarget->isTargetWindows())
12749     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
12750 
12751   TargetLowering::CallLoweringInfo CLI(DAG);
12752   CLI.setDebugLoc(dl).setChain(InChain)
12753     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
12754     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
12755 
12756   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
12757   return CallInfo.first;
12758 }
12759 
12760 // Lowers REM using divmod helpers
12761 // see RTABI section 4.2/4.3
12762 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
12763   // Build return types (div and rem)
12764   std::vector<Type*> RetTyParams;
12765   Type *RetTyElement;
12766 
12767   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
12768   default: llvm_unreachable("Unexpected request for libcall!");
12769   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
12770   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
12771   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
12772   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
12773   }
12774 
12775   RetTyParams.push_back(RetTyElement);
12776   RetTyParams.push_back(RetTyElement);
12777   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
12778   Type *RetTy = StructType::get(*DAG.getContext(), ret);
12779 
12780   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
12781                                                              SimpleTy);
12782   SDValue InChain = DAG.getEntryNode();
12783   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
12784                                                     Subtarget);
12785   bool isSigned = N->getOpcode() == ISD::SREM;
12786   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12787                                          getPointerTy(DAG.getDataLayout()));
12788 
12789   if (Subtarget->isTargetWindows())
12790     InChain = WinDBZCheckDenominator(DAG, N, InChain);
12791 
12792   // Lower call
12793   CallLoweringInfo CLI(DAG);
12794   CLI.setChain(InChain)
12795      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
12796      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
12797   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12798 
12799   // Return second (rem) result operand (first contains div)
12800   SDNode *ResNode = CallResult.first.getNode();
12801   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
12802   return ResNode->getOperand(1);
12803 }
12804 
12805 SDValue
12806 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
12807   assert(Subtarget->isTargetWindows() && "unsupported target platform");
12808   SDLoc DL(Op);
12809 
12810   // Get the inputs.
12811   SDValue Chain = Op.getOperand(0);
12812   SDValue Size  = Op.getOperand(1);
12813 
12814   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
12815                               DAG.getConstant(2, DL, MVT::i32));
12816 
12817   SDValue Flag;
12818   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
12819   Flag = Chain.getValue(1);
12820 
12821   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12822   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
12823 
12824   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
12825   Chain = NewSP.getValue(1);
12826 
12827   SDValue Ops[2] = { NewSP, Chain };
12828   return DAG.getMergeValues(Ops, DL);
12829 }
12830 
12831 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12832   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
12833          "Unexpected type for custom-lowering FP_EXTEND");
12834 
12835   RTLIB::Libcall LC;
12836   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
12837 
12838   SDValue SrcVal = Op.getOperand(0);
12839   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12840                      SDLoc(Op)).first;
12841 }
12842 
12843 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12844   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
12845          Subtarget->isFPOnlySP() &&
12846          "Unexpected type for custom-lowering FP_ROUND");
12847 
12848   RTLIB::Libcall LC;
12849   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
12850 
12851   SDValue SrcVal = Op.getOperand(0);
12852   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12853                      SDLoc(Op)).first;
12854 }
12855 
12856 bool
12857 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12858   // The ARM target isn't yet aware of offsets.
12859   return false;
12860 }
12861 
12862 bool ARM::isBitFieldInvertedMask(unsigned v) {
12863   if (v == 0xffffffff)
12864     return false;
12865 
12866   // there can be 1's on either or both "outsides", all the "inside"
12867   // bits must be 0's
12868   return isShiftedMask_32(~v);
12869 }
12870 
12871 /// isFPImmLegal - Returns true if the target can instruction select the
12872 /// specified FP immediate natively. If false, the legalizer will
12873 /// materialize the FP immediate as a load from a constant pool.
12874 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12875   if (!Subtarget->hasVFP3())
12876     return false;
12877   if (VT == MVT::f32)
12878     return ARM_AM::getFP32Imm(Imm) != -1;
12879   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
12880     return ARM_AM::getFP64Imm(Imm) != -1;
12881   return false;
12882 }
12883 
12884 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
12885 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
12886 /// specified in the intrinsic calls.
12887 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12888                                            const CallInst &I,
12889                                            unsigned Intrinsic) const {
12890   switch (Intrinsic) {
12891   case Intrinsic::arm_neon_vld1:
12892   case Intrinsic::arm_neon_vld2:
12893   case Intrinsic::arm_neon_vld3:
12894   case Intrinsic::arm_neon_vld4:
12895   case Intrinsic::arm_neon_vld2lane:
12896   case Intrinsic::arm_neon_vld3lane:
12897   case Intrinsic::arm_neon_vld4lane: {
12898     Info.opc = ISD::INTRINSIC_W_CHAIN;
12899     // Conservatively set memVT to the entire set of vectors loaded.
12900     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12901     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
12902     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12903     Info.ptrVal = I.getArgOperand(0);
12904     Info.offset = 0;
12905     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12906     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12907     Info.vol = false; // volatile loads with NEON intrinsics not supported
12908     Info.readMem = true;
12909     Info.writeMem = false;
12910     return true;
12911   }
12912   case Intrinsic::arm_neon_vst1:
12913   case Intrinsic::arm_neon_vst2:
12914   case Intrinsic::arm_neon_vst3:
12915   case Intrinsic::arm_neon_vst4:
12916   case Intrinsic::arm_neon_vst2lane:
12917   case Intrinsic::arm_neon_vst3lane:
12918   case Intrinsic::arm_neon_vst4lane: {
12919     Info.opc = ISD::INTRINSIC_VOID;
12920     // Conservatively set memVT to the entire set of vectors stored.
12921     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12922     unsigned NumElts = 0;
12923     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
12924       Type *ArgTy = I.getArgOperand(ArgI)->getType();
12925       if (!ArgTy->isVectorTy())
12926         break;
12927       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
12928     }
12929     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12930     Info.ptrVal = I.getArgOperand(0);
12931     Info.offset = 0;
12932     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12933     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12934     Info.vol = false; // volatile stores with NEON intrinsics not supported
12935     Info.readMem = false;
12936     Info.writeMem = true;
12937     return true;
12938   }
12939   case Intrinsic::arm_ldaex:
12940   case Intrinsic::arm_ldrex: {
12941     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12942     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
12943     Info.opc = ISD::INTRINSIC_W_CHAIN;
12944     Info.memVT = MVT::getVT(PtrTy->getElementType());
12945     Info.ptrVal = I.getArgOperand(0);
12946     Info.offset = 0;
12947     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12948     Info.vol = true;
12949     Info.readMem = true;
12950     Info.writeMem = false;
12951     return true;
12952   }
12953   case Intrinsic::arm_stlex:
12954   case Intrinsic::arm_strex: {
12955     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12956     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
12957     Info.opc = ISD::INTRINSIC_W_CHAIN;
12958     Info.memVT = MVT::getVT(PtrTy->getElementType());
12959     Info.ptrVal = I.getArgOperand(1);
12960     Info.offset = 0;
12961     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12962     Info.vol = true;
12963     Info.readMem = false;
12964     Info.writeMem = true;
12965     return true;
12966   }
12967   case Intrinsic::arm_stlexd:
12968   case Intrinsic::arm_strexd:
12969     Info.opc = ISD::INTRINSIC_W_CHAIN;
12970     Info.memVT = MVT::i64;
12971     Info.ptrVal = I.getArgOperand(2);
12972     Info.offset = 0;
12973     Info.align = 8;
12974     Info.vol = true;
12975     Info.readMem = false;
12976     Info.writeMem = true;
12977     return true;
12978 
12979   case Intrinsic::arm_ldaexd:
12980   case Intrinsic::arm_ldrexd:
12981     Info.opc = ISD::INTRINSIC_W_CHAIN;
12982     Info.memVT = MVT::i64;
12983     Info.ptrVal = I.getArgOperand(0);
12984     Info.offset = 0;
12985     Info.align = 8;
12986     Info.vol = true;
12987     Info.readMem = true;
12988     Info.writeMem = false;
12989     return true;
12990 
12991   default:
12992     break;
12993   }
12994 
12995   return false;
12996 }
12997 
12998 /// \brief Returns true if it is beneficial to convert a load of a constant
12999 /// to just the constant itself.
13000 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13001                                                           Type *Ty) const {
13002   assert(Ty->isIntegerTy());
13003 
13004   unsigned Bits = Ty->getPrimitiveSizeInBits();
13005   if (Bits == 0 || Bits > 32)
13006     return false;
13007   return true;
13008 }
13009 
13010 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT,
13011                                                 unsigned Index) const {
13012   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13013     return false;
13014 
13015   return (Index == 0 || Index == ResVT.getVectorNumElements());
13016 }
13017 
13018 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13019                                         ARM_MB::MemBOpt Domain) const {
13020   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13021 
13022   // First, if the target has no DMB, see what fallback we can use.
13023   if (!Subtarget->hasDataBarrier()) {
13024     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13025     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13026     // here.
13027     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13028       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13029       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13030                         Builder.getInt32(0), Builder.getInt32(7),
13031                         Builder.getInt32(10), Builder.getInt32(5)};
13032       return Builder.CreateCall(MCR, args);
13033     } else {
13034       // Instead of using barriers, atomic accesses on these subtargets use
13035       // libcalls.
13036       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13037     }
13038   } else {
13039     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13040     // Only a full system barrier exists in the M-class architectures.
13041     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13042     Constant *CDomain = Builder.getInt32(Domain);
13043     return Builder.CreateCall(DMB, CDomain);
13044   }
13045 }
13046 
13047 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13048 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13049                                          AtomicOrdering Ord, bool IsStore,
13050                                          bool IsLoad) const {
13051   switch (Ord) {
13052   case AtomicOrdering::NotAtomic:
13053   case AtomicOrdering::Unordered:
13054     llvm_unreachable("Invalid fence: unordered/non-atomic");
13055   case AtomicOrdering::Monotonic:
13056   case AtomicOrdering::Acquire:
13057     return nullptr; // Nothing to do
13058   case AtomicOrdering::SequentiallyConsistent:
13059     if (!IsStore)
13060       return nullptr; // Nothing to do
13061     /*FALLTHROUGH*/
13062   case AtomicOrdering::Release:
13063   case AtomicOrdering::AcquireRelease:
13064     if (Subtarget->preferISHSTBarriers())
13065       return makeDMB(Builder, ARM_MB::ISHST);
13066     // FIXME: add a comment with a link to documentation justifying this.
13067     else
13068       return makeDMB(Builder, ARM_MB::ISH);
13069   }
13070   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13071 }
13072 
13073 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13074                                           AtomicOrdering Ord, bool IsStore,
13075                                           bool IsLoad) const {
13076   switch (Ord) {
13077   case AtomicOrdering::NotAtomic:
13078   case AtomicOrdering::Unordered:
13079     llvm_unreachable("Invalid fence: unordered/not-atomic");
13080   case AtomicOrdering::Monotonic:
13081   case AtomicOrdering::Release:
13082     return nullptr; // Nothing to do
13083   case AtomicOrdering::Acquire:
13084   case AtomicOrdering::AcquireRelease:
13085   case AtomicOrdering::SequentiallyConsistent:
13086     return makeDMB(Builder, ARM_MB::ISH);
13087   }
13088   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13089 }
13090 
13091 // Loads and stores less than 64-bits are already atomic; ones above that
13092 // are doomed anyway, so defer to the default libcall and blame the OS when
13093 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13094 // anything for those.
13095 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13096   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13097   return (Size == 64) && !Subtarget->isMClass();
13098 }
13099 
13100 // Loads and stores less than 64-bits are already atomic; ones above that
13101 // are doomed anyway, so defer to the default libcall and blame the OS when
13102 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13103 // anything for those.
13104 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13105 // guarantee, see DDI0406C ARM architecture reference manual,
13106 // sections A8.8.72-74 LDRD)
13107 TargetLowering::AtomicExpansionKind
13108 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13109   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13110   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13111                                                   : AtomicExpansionKind::None;
13112 }
13113 
13114 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13115 // and up to 64 bits on the non-M profiles
13116 TargetLowering::AtomicExpansionKind
13117 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13118   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13119   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13120   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13121              ? AtomicExpansionKind::LLSC
13122              : AtomicExpansionKind::None;
13123 }
13124 
13125 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13126     AtomicCmpXchgInst *AI) const {
13127   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13128   // implement cmpxchg without spilling. If the address being exchanged is also
13129   // on the stack and close enough to the spill slot, this can lead to a
13130   // situation where the monitor always gets cleared and the atomic operation
13131   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13132   bool hasAtomicCmpXchg =
13133       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13134   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13135 }
13136 
13137 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13138     const Instruction *I) const {
13139   return InsertFencesForAtomic;
13140 }
13141 
13142 // This has so far only been implemented for MachO.
13143 bool ARMTargetLowering::useLoadStackGuardNode() const {
13144   return Subtarget->isTargetMachO();
13145 }
13146 
13147 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13148                                                   unsigned &Cost) const {
13149   // If we do not have NEON, vector types are not natively supported.
13150   if (!Subtarget->hasNEON())
13151     return false;
13152 
13153   // Floating point values and vector values map to the same register file.
13154   // Therefore, although we could do a store extract of a vector type, this is
13155   // better to leave at float as we have more freedom in the addressing mode for
13156   // those.
13157   if (VectorTy->isFPOrFPVectorTy())
13158     return false;
13159 
13160   // If the index is unknown at compile time, this is very expensive to lower
13161   // and it is not possible to combine the store with the extract.
13162   if (!isa<ConstantInt>(Idx))
13163     return false;
13164 
13165   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13166   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13167   // We can do a store + vector extract on any vector that fits perfectly in a D
13168   // or Q register.
13169   if (BitWidth == 64 || BitWidth == 128) {
13170     Cost = 0;
13171     return true;
13172   }
13173   return false;
13174 }
13175 
13176 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13177   return Subtarget->hasV6T2Ops();
13178 }
13179 
13180 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13181   return Subtarget->hasV6T2Ops();
13182 }
13183 
13184 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13185                                          AtomicOrdering Ord) const {
13186   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13187   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13188   bool IsAcquire = isAcquireOrStronger(Ord);
13189 
13190   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13191   // intrinsic must return {i32, i32} and we have to recombine them into a
13192   // single i64 here.
13193   if (ValTy->getPrimitiveSizeInBits() == 64) {
13194     Intrinsic::ID Int =
13195         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13196     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13197 
13198     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13199     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13200 
13201     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13202     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13203     if (!Subtarget->isLittle())
13204       std::swap (Lo, Hi);
13205     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13206     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13207     return Builder.CreateOr(
13208         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13209   }
13210 
13211   Type *Tys[] = { Addr->getType() };
13212   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13213   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13214 
13215   return Builder.CreateTruncOrBitCast(
13216       Builder.CreateCall(Ldrex, Addr),
13217       cast<PointerType>(Addr->getType())->getElementType());
13218 }
13219 
13220 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13221     IRBuilder<> &Builder) const {
13222   if (!Subtarget->hasV7Ops())
13223     return;
13224   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13225   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13226 }
13227 
13228 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13229                                                Value *Addr,
13230                                                AtomicOrdering Ord) const {
13231   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13232   bool IsRelease = isReleaseOrStronger(Ord);
13233 
13234   // Since the intrinsics must have legal type, the i64 intrinsics take two
13235   // parameters: "i32, i32". We must marshal Val into the appropriate form
13236   // before the call.
13237   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13238     Intrinsic::ID Int =
13239         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13240     Function *Strex = Intrinsic::getDeclaration(M, Int);
13241     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13242 
13243     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13244     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13245     if (!Subtarget->isLittle())
13246       std::swap (Lo, Hi);
13247     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13248     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13249   }
13250 
13251   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13252   Type *Tys[] = { Addr->getType() };
13253   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13254 
13255   return Builder.CreateCall(
13256       Strex, {Builder.CreateZExtOrBitCast(
13257                   Val, Strex->getFunctionType()->getParamType(0)),
13258               Addr});
13259 }
13260 
13261 /// \brief Lower an interleaved load into a vldN intrinsic.
13262 ///
13263 /// E.g. Lower an interleaved load (Factor = 2):
13264 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13265 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13266 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13267 ///
13268 ///      Into:
13269 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13270 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13271 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13272 bool ARMTargetLowering::lowerInterleavedLoad(
13273     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13274     ArrayRef<unsigned> Indices, unsigned Factor) const {
13275   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13276          "Invalid interleave factor");
13277   assert(!Shuffles.empty() && "Empty shufflevector input");
13278   assert(Shuffles.size() == Indices.size() &&
13279          "Unmatched number of shufflevectors and indices");
13280 
13281   VectorType *VecTy = Shuffles[0]->getType();
13282   Type *EltTy = VecTy->getVectorElementType();
13283 
13284   const DataLayout &DL = LI->getModule()->getDataLayout();
13285   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13286   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13287 
13288   // Skip if we do not have NEON and skip illegal vector types and vector types
13289   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
13290   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
13291     return false;
13292 
13293   // Skip if the vector has f16 elements: even though we could do an i16 vldN,
13294   // we can't hold the f16 vectors and will end up converting via f32.
13295   if (EltTy->isHalfTy())
13296     return false;
13297 
13298   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13299   // load integer vectors first and then convert to pointer vectors.
13300   if (EltTy->isPointerTy())
13301     VecTy =
13302         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13303 
13304   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13305                                             Intrinsic::arm_neon_vld3,
13306                                             Intrinsic::arm_neon_vld4};
13307 
13308   IRBuilder<> Builder(LI);
13309   SmallVector<Value *, 2> Ops;
13310 
13311   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13312   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
13313   Ops.push_back(Builder.getInt32(LI->getAlignment()));
13314 
13315   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13316 
13317   Type *Tys[] = { VecTy, Int8Ptr };
13318   Function *VldnFunc =
13319       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13320   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13321 
13322   // Replace uses of each shufflevector with the corresponding vector loaded
13323   // by ldN.
13324   for (unsigned i = 0; i < Shuffles.size(); i++) {
13325     ShuffleVectorInst *SV = Shuffles[i];
13326     unsigned Index = Indices[i];
13327 
13328     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13329 
13330     // Convert the integer vector to pointer vector if the element is pointer.
13331     if (EltTy->isPointerTy())
13332       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13333 
13334     SV->replaceAllUsesWith(SubVec);
13335   }
13336 
13337   return true;
13338 }
13339 
13340 /// \brief Lower an interleaved store into a vstN intrinsic.
13341 ///
13342 /// E.g. Lower an interleaved store (Factor = 3):
13343 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13344 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13345 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13346 ///
13347 ///      Into:
13348 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13349 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13350 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13351 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13352 ///
13353 /// Note that the new shufflevectors will be removed and we'll only generate one
13354 /// vst3 instruction in CodeGen.
13355 ///
13356 /// Example for a more general valid mask (Factor 3). Lower:
13357 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
13358 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
13359 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
13360 ///
13361 ///      Into:
13362 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
13363 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
13364 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
13365 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13366 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13367                                               ShuffleVectorInst *SVI,
13368                                               unsigned Factor) const {
13369   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13370          "Invalid interleave factor");
13371 
13372   VectorType *VecTy = SVI->getType();
13373   assert(VecTy->getVectorNumElements() % Factor == 0 &&
13374          "Invalid interleaved store");
13375 
13376   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
13377   Type *EltTy = VecTy->getVectorElementType();
13378   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
13379 
13380   const DataLayout &DL = SI->getModule()->getDataLayout();
13381   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
13382   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13383 
13384   // Skip if we do not have NEON and skip illegal vector types and vector types
13385   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
13386   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
13387       EltIs64Bits)
13388     return false;
13389 
13390   // Skip if the vector has f16 elements: even though we could do an i16 vldN,
13391   // we can't hold the f16 vectors and will end up converting via f32.
13392   if (EltTy->isHalfTy())
13393     return false;
13394 
13395   Value *Op0 = SVI->getOperand(0);
13396   Value *Op1 = SVI->getOperand(1);
13397   IRBuilder<> Builder(SI);
13398 
13399   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13400   // vectors to integer vectors.
13401   if (EltTy->isPointerTy()) {
13402     Type *IntTy = DL.getIntPtrType(EltTy);
13403 
13404     // Convert to the corresponding integer vector.
13405     Type *IntVecTy =
13406         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13407     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13408     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13409 
13410     SubVecTy = VectorType::get(IntTy, LaneLen);
13411   }
13412 
13413   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13414                                              Intrinsic::arm_neon_vst3,
13415                                              Intrinsic::arm_neon_vst4};
13416   SmallVector<Value *, 6> Ops;
13417 
13418   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13419   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
13420 
13421   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
13422 
13423   Type *Tys[] = { Int8Ptr, SubVecTy };
13424   Function *VstNFunc = Intrinsic::getDeclaration(
13425       SI->getModule(), StoreInts[Factor - 2], Tys);
13426 
13427   // Split the shufflevector operands into sub vectors for the new vstN call.
13428   auto Mask = SVI->getShuffleMask();
13429   for (unsigned i = 0; i < Factor; i++) {
13430     if (Mask[i] >= 0) {
13431       Ops.push_back(Builder.CreateShuffleVector(
13432           Op0, Op1, createSequentialMask(Builder, Mask[i], LaneLen, 0)));
13433     } else {
13434       unsigned StartMask = 0;
13435       for (unsigned j = 1; j < LaneLen; j++) {
13436         if (Mask[j*Factor + i] >= 0) {
13437           StartMask = Mask[j*Factor + i] - j;
13438           break;
13439         }
13440       }
13441       // Note: If all elements in a chunk are undefs, StartMask=0!
13442       // Note: Filling undef gaps with random elements is ok, since
13443       // those elements were being written anyway (with undefs).
13444       // In the case of all undefs we're defaulting to using elems from 0
13445       // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
13446       Ops.push_back(Builder.CreateShuffleVector(
13447           Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
13448     }
13449   }
13450 
13451   Ops.push_back(Builder.getInt32(SI->getAlignment()));
13452   Builder.CreateCall(VstNFunc, Ops);
13453   return true;
13454 }
13455 
13456 enum HABaseType {
13457   HA_UNKNOWN = 0,
13458   HA_FLOAT,
13459   HA_DOUBLE,
13460   HA_VECT64,
13461   HA_VECT128
13462 };
13463 
13464 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13465                                    uint64_t &Members) {
13466   if (auto *ST = dyn_cast<StructType>(Ty)) {
13467     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13468       uint64_t SubMembers = 0;
13469       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13470         return false;
13471       Members += SubMembers;
13472     }
13473   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13474     uint64_t SubMembers = 0;
13475     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13476       return false;
13477     Members += SubMembers * AT->getNumElements();
13478   } else if (Ty->isFloatTy()) {
13479     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13480       return false;
13481     Members = 1;
13482     Base = HA_FLOAT;
13483   } else if (Ty->isDoubleTy()) {
13484     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13485       return false;
13486     Members = 1;
13487     Base = HA_DOUBLE;
13488   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13489     Members = 1;
13490     switch (Base) {
13491     case HA_FLOAT:
13492     case HA_DOUBLE:
13493       return false;
13494     case HA_VECT64:
13495       return VT->getBitWidth() == 64;
13496     case HA_VECT128:
13497       return VT->getBitWidth() == 128;
13498     case HA_UNKNOWN:
13499       switch (VT->getBitWidth()) {
13500       case 64:
13501         Base = HA_VECT64;
13502         return true;
13503       case 128:
13504         Base = HA_VECT128;
13505         return true;
13506       default:
13507         return false;
13508       }
13509     }
13510   }
13511 
13512   return (Members > 0 && Members <= 4);
13513 }
13514 
13515 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13516 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13517 /// passing according to AAPCS rules.
13518 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13519     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13520   if (getEffectiveCallingConv(CallConv, isVarArg) !=
13521       CallingConv::ARM_AAPCS_VFP)
13522     return false;
13523 
13524   HABaseType Base = HA_UNKNOWN;
13525   uint64_t Members = 0;
13526   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13527   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13528 
13529   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13530   return IsHA || IsIntArray;
13531 }
13532 
13533 unsigned ARMTargetLowering::getExceptionPointerRegister(
13534     const Constant *PersonalityFn) const {
13535   // Platforms which do not use SjLj EH may return values in these registers
13536   // via the personality function.
13537   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
13538 }
13539 
13540 unsigned ARMTargetLowering::getExceptionSelectorRegister(
13541     const Constant *PersonalityFn) const {
13542   // Platforms which do not use SjLj EH may return values in these registers
13543   // via the personality function.
13544   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
13545 }
13546 
13547 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13548   // Update IsSplitCSR in ARMFunctionInfo.
13549   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
13550   AFI->setIsSplitCSR(true);
13551 }
13552 
13553 void ARMTargetLowering::insertCopiesSplitCSR(
13554     MachineBasicBlock *Entry,
13555     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13556   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
13557   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13558   if (!IStart)
13559     return;
13560 
13561   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13562   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13563   MachineBasicBlock::iterator MBBI = Entry->begin();
13564   for (const MCPhysReg *I = IStart; *I; ++I) {
13565     const TargetRegisterClass *RC = nullptr;
13566     if (ARM::GPRRegClass.contains(*I))
13567       RC = &ARM::GPRRegClass;
13568     else if (ARM::DPRRegClass.contains(*I))
13569       RC = &ARM::DPRRegClass;
13570     else
13571       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13572 
13573     unsigned NewVR = MRI->createVirtualRegister(RC);
13574     // Create copy from CSR to a virtual register.
13575     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13576     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13577     // nounwind. If we want to generalize this later, we may need to emit
13578     // CFI pseudo-instructions.
13579     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13580                Attribute::NoUnwind) &&
13581            "Function should be nounwind in insertCopiesSplitCSR!");
13582     Entry->addLiveIn(*I);
13583     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13584         .addReg(*I);
13585 
13586     // Insert the copy-back instructions right before the terminator.
13587     for (auto *Exit : Exits)
13588       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13589               TII->get(TargetOpcode::COPY), *I)
13590           .addReg(NewVR);
13591   }
13592 }
13593