1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMISelLowering.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.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/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.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/DataLayout.h"
65 #include "llvm/IR/DebugLoc.h"
66 #include "llvm/IR/DerivedTypes.h"
67 #include "llvm/IR/Function.h"
68 #include "llvm/IR/GlobalAlias.h"
69 #include "llvm/IR/GlobalValue.h"
70 #include "llvm/IR/GlobalVariable.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/InlineAsm.h"
73 #include "llvm/IR/Instruction.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/Module.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/User.h"
80 #include "llvm/IR/Value.h"
81 #include "llvm/MC/MCInstrDesc.h"
82 #include "llvm/MC/MCInstrItineraries.h"
83 #include "llvm/MC/MCRegisterInfo.h"
84 #include "llvm/MC/MCSchedule.h"
85 #include "llvm/Support/AtomicOrdering.h"
86 #include "llvm/Support/BranchProbability.h"
87 #include "llvm/Support/Casting.h"
88 #include "llvm/Support/CodeGen.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Compiler.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/ErrorHandling.h"
93 #include "llvm/Support/KnownBits.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 <string>
106 #include <tuple>
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(false)); // FIXME: set to true by default once PR32780 is fixed
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 (auto Opcode : {ISD::ABS, 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   setBooleanContents(ZeroOrOneBooleanContent);
225   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
226 
227   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
228       !Subtarget->isTargetWatchOS()) {
229     const auto &E = Subtarget->getTargetTriple().getEnvironment();
230 
231     bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
232                       E == Triple::MuslEABIHF;
233     // Windows is a special case.  Technically, we will replace all of the "GNU"
234     // calls with calls to MSVCRT if appropriate and adjust the calling
235     // convention then.
236     IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
237 
238     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
239       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
240                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
241                                        : CallingConv::ARM_AAPCS);
242   }
243 
244   if (Subtarget->isTargetMachO()) {
245     // Uses VFP for Thumb libfuncs if available.
246     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
247         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
248       static const struct {
249         const RTLIB::Libcall Op;
250         const char * const Name;
251         const ISD::CondCode Cond;
252       } LibraryCalls[] = {
253         // Single-precision floating-point arithmetic.
254         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
255         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
256         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
257         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
258 
259         // Double-precision floating-point arithmetic.
260         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
262         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
263         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
264 
265         // Single-precision comparisons.
266         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
267         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
268         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
269         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
270         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
271         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
272         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
273         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
274 
275         // Double-precision comparisons.
276         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
277         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
278         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
279         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
280         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
281         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
282         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
283         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
284 
285         // Floating-point to integer conversions.
286         // i64 conversions are done via library routines even when generating VFP
287         // instructions, so use the same ones.
288         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
289         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
290         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
291         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
292 
293         // Conversions between floating types.
294         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
295         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
296 
297         // Integer to floating-point conversions.
298         // i64 conversions are done via library routines even when generating VFP
299         // instructions, so use the same ones.
300         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
301         // e.g., __floatunsidf vs. __floatunssidfvfp.
302         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
303         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
304         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
305         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
306       };
307 
308       for (const auto &LC : LibraryCalls) {
309         setLibcallName(LC.Op, LC.Name);
310         if (LC.Cond != ISD::SETCC_INVALID)
311           setCmpLibcallCC(LC.Op, LC.Cond);
312       }
313     }
314 
315     // Set the correct calling convention for ARMv7k WatchOS. It's just
316     // AAPCS_VFP for functions as simple as libcalls.
317     if (Subtarget->isTargetWatchABI()) {
318       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
319         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
320     }
321   }
322 
323   // These libcalls are not available in 32-bit.
324   setLibcallName(RTLIB::SHL_I128, nullptr);
325   setLibcallName(RTLIB::SRL_I128, nullptr);
326   setLibcallName(RTLIB::SRA_I128, nullptr);
327 
328   // RTLIB
329   if (Subtarget->isAAPCS_ABI() &&
330       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
331        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
332     static const struct {
333       const RTLIB::Libcall Op;
334       const char * const Name;
335       const CallingConv::ID CC;
336       const ISD::CondCode Cond;
337     } LibraryCalls[] = {
338       // Double-precision floating-point arithmetic helper functions
339       // RTABI chapter 4.1.2, Table 2
340       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 
345       // Double-precision floating-point comparison helper functions
346       // RTABI chapter 4.1.2, Table 3
347       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
348       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
349       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
352       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
353       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
354       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
355 
356       // Single-precision floating-point arithmetic helper functions
357       // RTABI chapter 4.1.2, Table 4
358       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
361       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
362 
363       // Single-precision floating-point comparison helper functions
364       // RTABI chapter 4.1.2, Table 5
365       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
366       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
367       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
370       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
371       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
372       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
373 
374       // Floating-point to integer conversions.
375       // RTABI chapter 4.1.2, Table 6
376       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384 
385       // Conversions between floating types.
386       // RTABI chapter 4.1.2, Table 7
387       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390 
391       // Integer to floating-point conversions.
392       // RTABI chapter 4.1.2, Table 8
393       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401 
402       // Long long helper functions
403       // RTABI chapter 4.2, Table 9
404       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408 
409       // Integer division functions
410       // RTABI chapter 4.3.1
411       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
419     };
420 
421     for (const auto &LC : LibraryCalls) {
422       setLibcallName(LC.Op, LC.Name);
423       setLibcallCallingConv(LC.Op, LC.CC);
424       if (LC.Cond != ISD::SETCC_INVALID)
425         setCmpLibcallCC(LC.Op, LC.Cond);
426     }
427 
428     // EABI dependent RTLIB
429     if (TM.Options.EABIVersion == EABI::EABI4 ||
430         TM.Options.EABIVersion == EABI::EABI5) {
431       static const struct {
432         const RTLIB::Libcall Op;
433         const char *const Name;
434         const CallingConv::ID CC;
435         const ISD::CondCode Cond;
436       } MemOpsLibraryCalls[] = {
437         // Memory operations
438         // RTABI chapter 4.3.4
439         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
441         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
442       };
443 
444       for (const auto &LC : MemOpsLibraryCalls) {
445         setLibcallName(LC.Op, LC.Name);
446         setLibcallCallingConv(LC.Op, LC.CC);
447         if (LC.Cond != ISD::SETCC_INVALID)
448           setCmpLibcallCC(LC.Op, LC.Cond);
449       }
450     }
451   }
452 
453   if (Subtarget->isTargetWindows()) {
454     static const struct {
455       const RTLIB::Libcall Op;
456       const char * const Name;
457       const CallingConv::ID CC;
458     } LibraryCalls[] = {
459       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
464       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
465       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
466       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
467     };
468 
469     for (const auto &LC : LibraryCalls) {
470       setLibcallName(LC.Op, LC.Name);
471       setLibcallCallingConv(LC.Op, LC.CC);
472     }
473   }
474 
475   // Use divmod compiler-rt calls for iOS 5.0 and later.
476   if (Subtarget->isTargetMachO() &&
477       !(Subtarget->isTargetIOS() &&
478         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
479     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
480     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
481   }
482 
483   // The half <-> float conversion functions are always soft-float on
484   // non-watchos platforms, but are needed for some targets which use a
485   // hard-float calling convention by default.
486   if (!Subtarget->isTargetWatchABI()) {
487     if (Subtarget->isAAPCS_ABI()) {
488       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
489       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
490       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
491     } else {
492       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
493       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
494       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
495     }
496   }
497 
498   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
499   // a __gnu_ prefix (which is the default).
500   if (Subtarget->isTargetAEABI()) {
501     static const struct {
502       const RTLIB::Libcall Op;
503       const char * const Name;
504       const CallingConv::ID CC;
505     } LibraryCalls[] = {
506       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
507       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
508       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
509     };
510 
511     for (const auto &LC : LibraryCalls) {
512       setLibcallName(LC.Op, LC.Name);
513       setLibcallCallingConv(LC.Op, LC.CC);
514     }
515   }
516 
517   if (Subtarget->isThumb1Only())
518     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
519   else
520     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
521 
522   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
523       !Subtarget->isThumb1Only()) {
524     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
525     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
526   }
527 
528   for (MVT VT : MVT::vector_valuetypes()) {
529     for (MVT InnerVT : MVT::vector_valuetypes()) {
530       setTruncStoreAction(VT, InnerVT, Expand);
531       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
532       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
533       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
534     }
535 
536     setOperationAction(ISD::MULHS, VT, Expand);
537     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
538     setOperationAction(ISD::MULHU, VT, Expand);
539     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
540 
541     setOperationAction(ISD::BSWAP, VT, Expand);
542   }
543 
544   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
545   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
546 
547   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
548   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
549 
550   if (Subtarget->hasNEON()) {
551     addDRTypeForNEON(MVT::v2f32);
552     addDRTypeForNEON(MVT::v8i8);
553     addDRTypeForNEON(MVT::v4i16);
554     addDRTypeForNEON(MVT::v2i32);
555     addDRTypeForNEON(MVT::v1i64);
556 
557     addQRTypeForNEON(MVT::v4f32);
558     addQRTypeForNEON(MVT::v2f64);
559     addQRTypeForNEON(MVT::v16i8);
560     addQRTypeForNEON(MVT::v8i16);
561     addQRTypeForNEON(MVT::v4i32);
562     addQRTypeForNEON(MVT::v2i64);
563 
564     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
565     // neither Neon nor VFP support any arithmetic operations on it.
566     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
567     // supported for v4f32.
568     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
569     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
570     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
571     // FIXME: Code duplication: FDIV and FREM are expanded always, see
572     // ARMTargetLowering::addTypeForNEON method for details.
573     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
574     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
575     // FIXME: Create unittest.
576     // In another words, find a way when "copysign" appears in DAG with vector
577     // operands.
578     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
579     // FIXME: Code duplication: SETCC has custom operation action, see
580     // ARMTargetLowering::addTypeForNEON method for details.
581     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
582     // FIXME: Create unittest for FNEG and for FABS.
583     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
584     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
585     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
586     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
587     setOperationAction(ISD::FCOS, 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::FPOW, MVT::v4f32, Expand);
606     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
607     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
608     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
609     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
610     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
611     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
612     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
613     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
614     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
615     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
616 
617     // Mark v2f32 intrinsics.
618     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
619     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
620     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
621     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
622     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
623     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
624     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
625     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
626     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
627     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
628     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
629     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
630     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
631     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
632 
633     // Neon does not support some operations on v1i64 and v2i64 types.
634     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
635     // Custom handling for some quad-vector types to detect VMULL.
636     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
637     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
638     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
639     // Custom handling for some vector types to avoid expensive expansions
640     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
641     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
642     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
643     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
644     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
645     // a destination type that is wider than the source, and nor does
646     // it have a FP_TO_[SU]INT instruction with a narrower destination than
647     // source.
648     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
649     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
650     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
651     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
652 
653     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
654     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
655 
656     // NEON does not have single instruction CTPOP for vectors with element
657     // types wider than 8-bits.  However, custom lowering can leverage the
658     // v8i8/v16i8 vcnt instruction.
659     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
660     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
661     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
662     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
663     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
664     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
665 
666     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
667     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
668 
669     // NEON does not have single instruction CTTZ for vectors.
670     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
671     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
672     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
673     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
674 
675     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
676     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
677     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
678     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
679 
680     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
681     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
682     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
683     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
684 
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
686     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
687     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
689 
690     // NEON only has FMA instructions as of VFP4.
691     if (!Subtarget->hasVFP4()) {
692       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
693       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
694     }
695 
696     setTargetDAGCombine(ISD::INTRINSIC_VOID);
697     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
698     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
699     setTargetDAGCombine(ISD::SHL);
700     setTargetDAGCombine(ISD::SRL);
701     setTargetDAGCombine(ISD::SRA);
702     setTargetDAGCombine(ISD::SIGN_EXTEND);
703     setTargetDAGCombine(ISD::ZERO_EXTEND);
704     setTargetDAGCombine(ISD::ANY_EXTEND);
705     setTargetDAGCombine(ISD::BUILD_VECTOR);
706     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
707     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
708     setTargetDAGCombine(ISD::STORE);
709     setTargetDAGCombine(ISD::FP_TO_SINT);
710     setTargetDAGCombine(ISD::FP_TO_UINT);
711     setTargetDAGCombine(ISD::FDIV);
712     setTargetDAGCombine(ISD::LOAD);
713 
714     // It is legal to extload from v4i8 to v4i16 or v4i32.
715     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
716                    MVT::v2i32}) {
717       for (MVT VT : MVT::integer_vector_valuetypes()) {
718         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
719         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
720         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
721       }
722     }
723   }
724 
725   if (Subtarget->isFPOnlySP()) {
726     // When targeting a floating-point unit with only single-precision
727     // operations, f64 is legal for the few double-precision instructions which
728     // are present However, no double-precision operations other than moves,
729     // loads and stores are provided by the hardware.
730     setOperationAction(ISD::FADD,       MVT::f64, Expand);
731     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
732     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
733     setOperationAction(ISD::FMA,        MVT::f64, Expand);
734     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
735     setOperationAction(ISD::FREM,       MVT::f64, Expand);
736     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
737     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
738     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
739     setOperationAction(ISD::FABS,       MVT::f64, Expand);
740     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
741     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
742     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
743     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
744     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
745     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
746     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
747     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
748     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
749     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
750     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
751     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
752     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
753     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
754     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
755     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
756     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
757     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
758     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
759     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
760     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
761     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
762   }
763 
764   computeRegisterProperties(Subtarget->getRegisterInfo());
765 
766   // ARM does not have floating-point extending loads.
767   for (MVT VT : MVT::fp_valuetypes()) {
768     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
769     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
770   }
771 
772   // ... or truncating stores
773   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
774   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
775   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
776 
777   // ARM does not have i1 sign extending load.
778   for (MVT VT : MVT::integer_valuetypes())
779     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
780 
781   // ARM supports all 4 flavors of integer indexed load / store.
782   if (!Subtarget->isThumb1Only()) {
783     for (unsigned im = (unsigned)ISD::PRE_INC;
784          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
785       setIndexedLoadAction(im,  MVT::i1,  Legal);
786       setIndexedLoadAction(im,  MVT::i8,  Legal);
787       setIndexedLoadAction(im,  MVT::i16, Legal);
788       setIndexedLoadAction(im,  MVT::i32, Legal);
789       setIndexedStoreAction(im, MVT::i1,  Legal);
790       setIndexedStoreAction(im, MVT::i8,  Legal);
791       setIndexedStoreAction(im, MVT::i16, Legal);
792       setIndexedStoreAction(im, MVT::i32, Legal);
793     }
794   } else {
795     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
796     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
797     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
798   }
799 
800   setOperationAction(ISD::SADDO, MVT::i32, Custom);
801   setOperationAction(ISD::UADDO, MVT::i32, Custom);
802   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
803   setOperationAction(ISD::USUBO, MVT::i32, Custom);
804 
805   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
806   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
807 
808   // i64 operation support.
809   setOperationAction(ISD::MUL,     MVT::i64, Expand);
810   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
811   if (Subtarget->isThumb1Only()) {
812     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
813     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
814   }
815   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
816       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
817     setOperationAction(ISD::MULHS, MVT::i32, Expand);
818 
819   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
820   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
821   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
822   setOperationAction(ISD::SRL,       MVT::i64, Custom);
823   setOperationAction(ISD::SRA,       MVT::i64, Custom);
824   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
825 
826   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
827   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
828   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
829   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
830 
831   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
832     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
833 
834   // ARM does not have ROTL.
835   setOperationAction(ISD::ROTL, MVT::i32, Expand);
836   for (MVT VT : MVT::vector_valuetypes()) {
837     setOperationAction(ISD::ROTL, VT, Expand);
838     setOperationAction(ISD::ROTR, VT, Expand);
839   }
840   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
841   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
842   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
843     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
844 
845   // @llvm.readcyclecounter requires the Performance Monitors extension.
846   // Default to the 0 expansion on unsupported platforms.
847   // FIXME: Technically there are older ARM CPUs that have
848   // implementation-specific ways of obtaining this information.
849   if (Subtarget->hasPerfMon())
850     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
851 
852   // Only ARMv6 has BSWAP.
853   if (!Subtarget->hasV6Ops())
854     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
855 
856   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
857                                         : Subtarget->hasDivideInARMMode();
858   if (!hasDivide) {
859     // These are expanded into libcalls if the cpu doesn't have HW divider.
860     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
861     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
862   }
863 
864   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
865     setOperationAction(ISD::SDIV, MVT::i32, Custom);
866     setOperationAction(ISD::UDIV, MVT::i32, Custom);
867 
868     setOperationAction(ISD::SDIV, MVT::i64, Custom);
869     setOperationAction(ISD::UDIV, MVT::i64, Custom);
870   }
871 
872   setOperationAction(ISD::SREM,  MVT::i32, Expand);
873   setOperationAction(ISD::UREM,  MVT::i32, Expand);
874 
875   // Register based DivRem for AEABI (RTABI 4.2)
876   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
877       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
878       Subtarget->isTargetWindows()) {
879     setOperationAction(ISD::SREM, MVT::i64, Custom);
880     setOperationAction(ISD::UREM, MVT::i64, Custom);
881     HasStandaloneRem = false;
882 
883     if (Subtarget->isTargetWindows()) {
884       const struct {
885         const RTLIB::Libcall Op;
886         const char * const Name;
887         const CallingConv::ID CC;
888       } LibraryCalls[] = {
889         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
890         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
891         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
892         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
893 
894         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
895         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
896         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
897         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
898       };
899 
900       for (const auto &LC : LibraryCalls) {
901         setLibcallName(LC.Op, LC.Name);
902         setLibcallCallingConv(LC.Op, LC.CC);
903       }
904     } else {
905       const struct {
906         const RTLIB::Libcall Op;
907         const char * const Name;
908         const CallingConv::ID CC;
909       } LibraryCalls[] = {
910         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
911         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
912         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
913         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
914 
915         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
916         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
918         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
919       };
920 
921       for (const auto &LC : LibraryCalls) {
922         setLibcallName(LC.Op, LC.Name);
923         setLibcallCallingConv(LC.Op, LC.CC);
924       }
925     }
926 
927     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
928     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
929     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
930     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
931   } else {
932     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
933     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
934   }
935 
936   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
937     for (auto &VT : {MVT::f32, MVT::f64})
938       setOperationAction(ISD::FPOWI, VT, Custom);
939 
940   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
941   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
942   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
943   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
944 
945   setOperationAction(ISD::TRAP, MVT::Other, Legal);
946 
947   // Use the default implementation.
948   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
949   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
950   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
951   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
952   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
953   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
954 
955   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
956     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
957   else
958     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
959 
960   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
961   // the default expansion.
962   InsertFencesForAtomic = false;
963   if (Subtarget->hasAnyDataBarrier() &&
964       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
965     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
966     // to ldrex/strex loops already.
967     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
968     if (!Subtarget->isThumb() || !Subtarget->isMClass())
969       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
970 
971     // On v8, we have particularly efficient implementations of atomic fences
972     // if they can be combined with nearby atomic loads and stores.
973     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
974       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
975       InsertFencesForAtomic = true;
976     }
977   } else {
978     // If there's anything we can use as a barrier, go through custom lowering
979     // for ATOMIC_FENCE.
980     // If target has DMB in thumb, Fences can be inserted.
981     if (Subtarget->hasDataBarrier())
982       InsertFencesForAtomic = true;
983 
984     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
985                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
986 
987     // Set them all for expansion, which will force libcalls.
988     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
989     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
990     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
991     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
992     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1000     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1001     // Unordered/Monotonic case.
1002     if (!InsertFencesForAtomic) {
1003       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1004       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1005     }
1006   }
1007 
1008   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1009 
1010   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1011   if (!Subtarget->hasV6Ops()) {
1012     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1013     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1014   }
1015   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1016 
1017   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1018       !Subtarget->isThumb1Only()) {
1019     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1020     // iff target supports vfp2.
1021     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1022     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1023   }
1024 
1025   // We want to custom lower some of our intrinsics.
1026   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1027   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1028   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1029   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1030   if (Subtarget->useSjLjEH())
1031     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1032 
1033   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1034   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1035   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1036   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1037   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1038   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1039   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1040   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1041   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1042 
1043   // Thumb-1 cannot currently select ARMISD::SUBE.
1044   if (!Subtarget->isThumb1Only())
1045     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1046 
1047   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1048   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1049   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1050   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1051   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1052 
1053   // We don't support sin/cos/fmod/copysign/pow
1054   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1055   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1056   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1057   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1058   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1059   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1060   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1061   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1062   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1063       !Subtarget->isThumb1Only()) {
1064     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1065     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1066   }
1067   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1068   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1069 
1070   if (!Subtarget->hasVFP4()) {
1071     setOperationAction(ISD::FMA, MVT::f64, Expand);
1072     setOperationAction(ISD::FMA, MVT::f32, Expand);
1073   }
1074 
1075   // Various VFP goodness
1076   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1077     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1078     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1079       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1080       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1081     }
1082 
1083     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1084     if (!Subtarget->hasFP16()) {
1085       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1086       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1087     }
1088   }
1089 
1090   // Combine sin / cos into one node or libcall if possible.
1091   if (Subtarget->hasSinCos()) {
1092     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1093     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1094     if (Subtarget->isTargetWatchABI()) {
1095       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1096       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1097     }
1098     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1099       // For iOS, we don't want to the normal expansion of a libcall to
1100       // sincos. We want to issue a libcall to __sincos_stret.
1101       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1102       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1103     }
1104   }
1105 
1106   // FP-ARMv8 implements a lot of rounding-like FP operations.
1107   if (Subtarget->hasFPARMv8()) {
1108     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1109     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1110     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1111     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1112     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1113     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1114     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1115     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1116     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1117     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1118     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1119     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1120 
1121     if (!Subtarget->isFPOnlySP()) {
1122       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1123       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1124       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1125       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1126       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1127       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1128       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1129       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1130     }
1131   }
1132 
1133   if (Subtarget->hasNEON()) {
1134     // vmin and vmax aren't available in a scalar form, so we use
1135     // a NEON instruction with an undef lane instead.
1136     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1137     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1138     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1139     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1140     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1141     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1142   }
1143 
1144   // We have target-specific dag combine patterns for the following nodes:
1145   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1146   setTargetDAGCombine(ISD::ADD);
1147   setTargetDAGCombine(ISD::SUB);
1148   setTargetDAGCombine(ISD::MUL);
1149   setTargetDAGCombine(ISD::AND);
1150   setTargetDAGCombine(ISD::OR);
1151   setTargetDAGCombine(ISD::XOR);
1152 
1153   if (Subtarget->hasV6Ops())
1154     setTargetDAGCombine(ISD::SRL);
1155 
1156   setStackPointerRegisterToSaveRestore(ARM::SP);
1157 
1158   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1159       !Subtarget->hasVFP2())
1160     setSchedulingPreference(Sched::RegPressure);
1161   else
1162     setSchedulingPreference(Sched::Hybrid);
1163 
1164   //// temporary - rewrite interface to use type
1165   MaxStoresPerMemset = 8;
1166   MaxStoresPerMemsetOptSize = 4;
1167   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1168   MaxStoresPerMemcpyOptSize = 2;
1169   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1170   MaxStoresPerMemmoveOptSize = 2;
1171 
1172   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1173   // are at least 4 bytes aligned.
1174   setMinStackArgumentAlignment(4);
1175 
1176   // Prefer likely predicted branches to selects on out-of-order cores.
1177   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1178 
1179   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1180 }
1181 
1182 bool ARMTargetLowering::useSoftFloat() const {
1183   return Subtarget->useSoftFloat();
1184 }
1185 
1186 // FIXME: It might make sense to define the representative register class as the
1187 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1188 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1189 // SPR's representative would be DPR_VFP2. This should work well if register
1190 // pressure tracking were modified such that a register use would increment the
1191 // pressure of the register class's representative and all of it's super
1192 // classes' representatives transitively. We have not implemented this because
1193 // of the difficulty prior to coalescing of modeling operand register classes
1194 // due to the common occurrence of cross class copies and subregister insertions
1195 // and extractions.
1196 std::pair<const TargetRegisterClass *, uint8_t>
1197 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1198                                            MVT VT) const {
1199   const TargetRegisterClass *RRC = nullptr;
1200   uint8_t Cost = 1;
1201   switch (VT.SimpleTy) {
1202   default:
1203     return TargetLowering::findRepresentativeClass(TRI, VT);
1204   // Use DPR as representative register class for all floating point
1205   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1206   // the cost is 1 for both f32 and f64.
1207   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1208   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1209     RRC = &ARM::DPRRegClass;
1210     // When NEON is used for SP, only half of the register file is available
1211     // because operations that define both SP and DP results will be constrained
1212     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1213     // coalescing by double-counting the SP regs. See the FIXME above.
1214     if (Subtarget->useNEONForSinglePrecisionFP())
1215       Cost = 2;
1216     break;
1217   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1218   case MVT::v4f32: case MVT::v2f64:
1219     RRC = &ARM::DPRRegClass;
1220     Cost = 2;
1221     break;
1222   case MVT::v4i64:
1223     RRC = &ARM::DPRRegClass;
1224     Cost = 4;
1225     break;
1226   case MVT::v8i64:
1227     RRC = &ARM::DPRRegClass;
1228     Cost = 8;
1229     break;
1230   }
1231   return std::make_pair(RRC, Cost);
1232 }
1233 
1234 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1235   switch ((ARMISD::NodeType)Opcode) {
1236   case ARMISD::FIRST_NUMBER:  break;
1237   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1238   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1239   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1240   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1241   case ARMISD::CALL:          return "ARMISD::CALL";
1242   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1243   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1244   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1245   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1246   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1247   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1248   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1249   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1250   case ARMISD::CMP:           return "ARMISD::CMP";
1251   case ARMISD::CMN:           return "ARMISD::CMN";
1252   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1253   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1254   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1255   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1256   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1257 
1258   case ARMISD::CMOV:          return "ARMISD::CMOV";
1259 
1260   case ARMISD::SSAT:          return "ARMISD::SSAT";
1261 
1262   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1263   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1264   case ARMISD::RRX:           return "ARMISD::RRX";
1265 
1266   case ARMISD::ADDC:          return "ARMISD::ADDC";
1267   case ARMISD::ADDE:          return "ARMISD::ADDE";
1268   case ARMISD::SUBC:          return "ARMISD::SUBC";
1269   case ARMISD::SUBE:          return "ARMISD::SUBE";
1270 
1271   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1272   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1273 
1274   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1275   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1276   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1277 
1278   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1279 
1280   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1281 
1282   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1283 
1284   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1285 
1286   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1287 
1288   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1289   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1290 
1291   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1292   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1293   case ARMISD::VCGE:          return "ARMISD::VCGE";
1294   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1295   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1296   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1297   case ARMISD::VCGT:          return "ARMISD::VCGT";
1298   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1299   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1300   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1301   case ARMISD::VTST:          return "ARMISD::VTST";
1302 
1303   case ARMISD::VSHL:          return "ARMISD::VSHL";
1304   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1305   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1306   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1307   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1308   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1309   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1310   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1311   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1312   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1313   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1314   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1315   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1316   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1317   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1318   case ARMISD::VSLI:          return "ARMISD::VSLI";
1319   case ARMISD::VSRI:          return "ARMISD::VSRI";
1320   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1321   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1322   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1323   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1324   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1325   case ARMISD::VDUP:          return "ARMISD::VDUP";
1326   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1327   case ARMISD::VEXT:          return "ARMISD::VEXT";
1328   case ARMISD::VREV64:        return "ARMISD::VREV64";
1329   case ARMISD::VREV32:        return "ARMISD::VREV32";
1330   case ARMISD::VREV16:        return "ARMISD::VREV16";
1331   case ARMISD::VZIP:          return "ARMISD::VZIP";
1332   case ARMISD::VUZP:          return "ARMISD::VUZP";
1333   case ARMISD::VTRN:          return "ARMISD::VTRN";
1334   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1335   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1336   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1337   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1338   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1339   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1340   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1341   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1342   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1343   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1344   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1345   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1346   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1347   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1348   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1349   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1350   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1351   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1352   case ARMISD::BFI:           return "ARMISD::BFI";
1353   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1354   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1355   case ARMISD::VBSL:          return "ARMISD::VBSL";
1356   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1357   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1358   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1359   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1360   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1361   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1362   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1363   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1364   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1365   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1366   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1367   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1368   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1369   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1370   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1371   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1372   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1373   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1374   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1375   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1376   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1377   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1378   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1379   }
1380   return nullptr;
1381 }
1382 
1383 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1384                                           EVT VT) const {
1385   if (!VT.isVector())
1386     return getPointerTy(DL);
1387   return VT.changeVectorElementTypeToInteger();
1388 }
1389 
1390 /// getRegClassFor - Return the register class that should be used for the
1391 /// specified value type.
1392 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1393   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1394   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1395   // load / store 4 to 8 consecutive D registers.
1396   if (Subtarget->hasNEON()) {
1397     if (VT == MVT::v4i64)
1398       return &ARM::QQPRRegClass;
1399     if (VT == MVT::v8i64)
1400       return &ARM::QQQQPRRegClass;
1401   }
1402   return TargetLowering::getRegClassFor(VT);
1403 }
1404 
1405 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1406 // source/dest is aligned and the copy size is large enough. We therefore want
1407 // to align such objects passed to memory intrinsics.
1408 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1409                                                unsigned &PrefAlign) const {
1410   if (!isa<MemIntrinsic>(CI))
1411     return false;
1412   MinSize = 8;
1413   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1414   // cycle faster than 4-byte aligned LDM.
1415   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1416   return true;
1417 }
1418 
1419 // Create a fast isel object.
1420 FastISel *
1421 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1422                                   const TargetLibraryInfo *libInfo) const {
1423   return ARM::createFastISel(funcInfo, libInfo);
1424 }
1425 
1426 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1427   unsigned NumVals = N->getNumValues();
1428   if (!NumVals)
1429     return Sched::RegPressure;
1430 
1431   for (unsigned i = 0; i != NumVals; ++i) {
1432     EVT VT = N->getValueType(i);
1433     if (VT == MVT::Glue || VT == MVT::Other)
1434       continue;
1435     if (VT.isFloatingPoint() || VT.isVector())
1436       return Sched::ILP;
1437   }
1438 
1439   if (!N->isMachineOpcode())
1440     return Sched::RegPressure;
1441 
1442   // Load are scheduled for latency even if there instruction itinerary
1443   // is not available.
1444   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1445   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1446 
1447   if (MCID.getNumDefs() == 0)
1448     return Sched::RegPressure;
1449   if (!Itins->isEmpty() &&
1450       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1451     return Sched::ILP;
1452 
1453   return Sched::RegPressure;
1454 }
1455 
1456 //===----------------------------------------------------------------------===//
1457 // Lowering Code
1458 //===----------------------------------------------------------------------===//
1459 
1460 static bool isSRL16(const SDValue &Op) {
1461   if (Op.getOpcode() != ISD::SRL)
1462     return false;
1463   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1464     return Const->getZExtValue() == 16;
1465   return false;
1466 }
1467 
1468 static bool isSRA16(const SDValue &Op) {
1469   if (Op.getOpcode() != ISD::SRA)
1470     return false;
1471   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1472     return Const->getZExtValue() == 16;
1473   return false;
1474 }
1475 
1476 static bool isSHL16(const SDValue &Op) {
1477   if (Op.getOpcode() != ISD::SHL)
1478     return false;
1479   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1480     return Const->getZExtValue() == 16;
1481   return false;
1482 }
1483 
1484 // Check for a signed 16-bit value. We special case SRA because it makes it
1485 // more simple when also looking for SRAs that aren't sign extending a
1486 // smaller value. Without the check, we'd need to take extra care with
1487 // checking order for some operations.
1488 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1489   if (isSRA16(Op))
1490     return isSHL16(Op.getOperand(0));
1491   return DAG.ComputeNumSignBits(Op) == 17;
1492 }
1493 
1494 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1495 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1496   switch (CC) {
1497   default: llvm_unreachable("Unknown condition code!");
1498   case ISD::SETNE:  return ARMCC::NE;
1499   case ISD::SETEQ:  return ARMCC::EQ;
1500   case ISD::SETGT:  return ARMCC::GT;
1501   case ISD::SETGE:  return ARMCC::GE;
1502   case ISD::SETLT:  return ARMCC::LT;
1503   case ISD::SETLE:  return ARMCC::LE;
1504   case ISD::SETUGT: return ARMCC::HI;
1505   case ISD::SETUGE: return ARMCC::HS;
1506   case ISD::SETULT: return ARMCC::LO;
1507   case ISD::SETULE: return ARMCC::LS;
1508   }
1509 }
1510 
1511 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1512 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1513                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1514   CondCode2 = ARMCC::AL;
1515   InvalidOnQNaN = true;
1516   switch (CC) {
1517   default: llvm_unreachable("Unknown FP condition!");
1518   case ISD::SETEQ:
1519   case ISD::SETOEQ:
1520     CondCode = ARMCC::EQ;
1521     InvalidOnQNaN = false;
1522     break;
1523   case ISD::SETGT:
1524   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1525   case ISD::SETGE:
1526   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1527   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1528   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1529   case ISD::SETONE:
1530     CondCode = ARMCC::MI;
1531     CondCode2 = ARMCC::GT;
1532     InvalidOnQNaN = false;
1533     break;
1534   case ISD::SETO:   CondCode = ARMCC::VC; break;
1535   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1536   case ISD::SETUEQ:
1537     CondCode = ARMCC::EQ;
1538     CondCode2 = ARMCC::VS;
1539     InvalidOnQNaN = false;
1540     break;
1541   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1542   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1543   case ISD::SETLT:
1544   case ISD::SETULT: CondCode = ARMCC::LT; break;
1545   case ISD::SETLE:
1546   case ISD::SETULE: CondCode = ARMCC::LE; break;
1547   case ISD::SETNE:
1548   case ISD::SETUNE:
1549     CondCode = ARMCC::NE;
1550     InvalidOnQNaN = false;
1551     break;
1552   }
1553 }
1554 
1555 //===----------------------------------------------------------------------===//
1556 //                      Calling Convention Implementation
1557 //===----------------------------------------------------------------------===//
1558 
1559 #include "ARMGenCallingConv.inc"
1560 
1561 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1562 /// account presence of floating point hardware and calling convention
1563 /// limitations, such as support for variadic functions.
1564 CallingConv::ID
1565 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1566                                            bool isVarArg) const {
1567   switch (CC) {
1568   default:
1569     report_fatal_error("Unsupported calling convention");
1570   case CallingConv::ARM_AAPCS:
1571   case CallingConv::ARM_APCS:
1572   case CallingConv::GHC:
1573     return CC;
1574   case CallingConv::PreserveMost:
1575     return CallingConv::PreserveMost;
1576   case CallingConv::ARM_AAPCS_VFP:
1577   case CallingConv::Swift:
1578     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1579   case CallingConv::C:
1580     if (!Subtarget->isAAPCS_ABI())
1581       return CallingConv::ARM_APCS;
1582     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1583              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1584              !isVarArg)
1585       return CallingConv::ARM_AAPCS_VFP;
1586     else
1587       return CallingConv::ARM_AAPCS;
1588   case CallingConv::Fast:
1589   case CallingConv::CXX_FAST_TLS:
1590     if (!Subtarget->isAAPCS_ABI()) {
1591       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1592         return CallingConv::Fast;
1593       return CallingConv::ARM_APCS;
1594     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1595       return CallingConv::ARM_AAPCS_VFP;
1596     else
1597       return CallingConv::ARM_AAPCS;
1598   }
1599 }
1600 
1601 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1602                                                  bool isVarArg) const {
1603   return CCAssignFnForNode(CC, false, isVarArg);
1604 }
1605 
1606 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1607                                                    bool isVarArg) const {
1608   return CCAssignFnForNode(CC, true, isVarArg);
1609 }
1610 
1611 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1612 /// CallingConvention.
1613 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1614                                                  bool Return,
1615                                                  bool isVarArg) const {
1616   switch (getEffectiveCallingConv(CC, isVarArg)) {
1617   default:
1618     report_fatal_error("Unsupported calling convention");
1619   case CallingConv::ARM_APCS:
1620     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1621   case CallingConv::ARM_AAPCS:
1622     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1623   case CallingConv::ARM_AAPCS_VFP:
1624     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1625   case CallingConv::Fast:
1626     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1627   case CallingConv::GHC:
1628     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1629   case CallingConv::PreserveMost:
1630     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1631   }
1632 }
1633 
1634 /// LowerCallResult - Lower the result values of a call into the
1635 /// appropriate copies out of appropriate physical registers.
1636 SDValue ARMTargetLowering::LowerCallResult(
1637     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1638     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1639     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1640     SDValue ThisVal) const {
1641 
1642   // Assign locations to each value returned by this call.
1643   SmallVector<CCValAssign, 16> RVLocs;
1644   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1645                  *DAG.getContext());
1646   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1647 
1648   // Copy all of the result registers out of their specified physreg.
1649   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1650     CCValAssign VA = RVLocs[i];
1651 
1652     // Pass 'this' value directly from the argument to return value, to avoid
1653     // reg unit interference
1654     if (i == 0 && isThisReturn) {
1655       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1656              "unexpected return calling convention register assignment");
1657       InVals.push_back(ThisVal);
1658       continue;
1659     }
1660 
1661     SDValue Val;
1662     if (VA.needsCustom()) {
1663       // Handle f64 or half of a v2f64.
1664       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1665                                       InFlag);
1666       Chain = Lo.getValue(1);
1667       InFlag = Lo.getValue(2);
1668       VA = RVLocs[++i]; // skip ahead to next loc
1669       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1670                                       InFlag);
1671       Chain = Hi.getValue(1);
1672       InFlag = Hi.getValue(2);
1673       if (!Subtarget->isLittle())
1674         std::swap (Lo, Hi);
1675       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1676 
1677       if (VA.getLocVT() == MVT::v2f64) {
1678         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1679         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1680                           DAG.getConstant(0, dl, MVT::i32));
1681 
1682         VA = RVLocs[++i]; // skip ahead to next loc
1683         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1684         Chain = Lo.getValue(1);
1685         InFlag = Lo.getValue(2);
1686         VA = RVLocs[++i]; // skip ahead to next loc
1687         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1688         Chain = Hi.getValue(1);
1689         InFlag = Hi.getValue(2);
1690         if (!Subtarget->isLittle())
1691           std::swap (Lo, Hi);
1692         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1693         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1694                           DAG.getConstant(1, dl, MVT::i32));
1695       }
1696     } else {
1697       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1698                                InFlag);
1699       Chain = Val.getValue(1);
1700       InFlag = Val.getValue(2);
1701     }
1702 
1703     switch (VA.getLocInfo()) {
1704     default: llvm_unreachable("Unknown loc info!");
1705     case CCValAssign::Full: break;
1706     case CCValAssign::BCvt:
1707       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1708       break;
1709     }
1710 
1711     InVals.push_back(Val);
1712   }
1713 
1714   return Chain;
1715 }
1716 
1717 /// LowerMemOpCallTo - Store the argument to the stack.
1718 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1719                                             SDValue Arg, const SDLoc &dl,
1720                                             SelectionDAG &DAG,
1721                                             const CCValAssign &VA,
1722                                             ISD::ArgFlagsTy Flags) const {
1723   unsigned LocMemOffset = VA.getLocMemOffset();
1724   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1725   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1726                        StackPtr, PtrOff);
1727   return DAG.getStore(
1728       Chain, dl, Arg, PtrOff,
1729       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1730 }
1731 
1732 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1733                                          SDValue Chain, SDValue &Arg,
1734                                          RegsToPassVector &RegsToPass,
1735                                          CCValAssign &VA, CCValAssign &NextVA,
1736                                          SDValue &StackPtr,
1737                                          SmallVectorImpl<SDValue> &MemOpChains,
1738                                          ISD::ArgFlagsTy Flags) const {
1739 
1740   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1741                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1742   unsigned id = Subtarget->isLittle() ? 0 : 1;
1743   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1744 
1745   if (NextVA.isRegLoc())
1746     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1747   else {
1748     assert(NextVA.isMemLoc());
1749     if (!StackPtr.getNode())
1750       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1751                                     getPointerTy(DAG.getDataLayout()));
1752 
1753     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1754                                            dl, DAG, NextVA,
1755                                            Flags));
1756   }
1757 }
1758 
1759 /// LowerCall - Lowering a call into a callseq_start <-
1760 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1761 /// nodes.
1762 SDValue
1763 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1764                              SmallVectorImpl<SDValue> &InVals) const {
1765   SelectionDAG &DAG                     = CLI.DAG;
1766   SDLoc &dl                             = CLI.DL;
1767   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1768   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1769   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1770   SDValue Chain                         = CLI.Chain;
1771   SDValue Callee                        = CLI.Callee;
1772   bool &isTailCall                      = CLI.IsTailCall;
1773   CallingConv::ID CallConv              = CLI.CallConv;
1774   bool doesNotRet                       = CLI.DoesNotReturn;
1775   bool isVarArg                         = CLI.IsVarArg;
1776 
1777   MachineFunction &MF = DAG.getMachineFunction();
1778   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1779   bool isThisReturn   = false;
1780   bool isSibCall      = false;
1781   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1782 
1783   // Disable tail calls if they're not supported.
1784   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1785     isTailCall = false;
1786 
1787   if (isTailCall) {
1788     // Check if it's really possible to do a tail call.
1789     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1790                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1791                                                    Outs, OutVals, Ins, DAG);
1792     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1793       report_fatal_error("failed to perform tail call elimination on a call "
1794                          "site marked musttail");
1795     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1796     // detected sibcalls.
1797     if (isTailCall) {
1798       ++NumTailCalls;
1799       isSibCall = true;
1800     }
1801   }
1802 
1803   // Analyze operands of the call, assigning locations to each operand.
1804   SmallVector<CCValAssign, 16> ArgLocs;
1805   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1806                  *DAG.getContext());
1807   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1808 
1809   // Get a count of how many bytes are to be pushed on the stack.
1810   unsigned NumBytes = CCInfo.getNextStackOffset();
1811 
1812   // For tail calls, memory operands are available in our caller's stack.
1813   if (isSibCall)
1814     NumBytes = 0;
1815 
1816   // Adjust the stack pointer for the new arguments...
1817   // These operations are automatically eliminated by the prolog/epilog pass
1818   if (!isSibCall)
1819     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1820 
1821   SDValue StackPtr =
1822       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1823 
1824   RegsToPassVector RegsToPass;
1825   SmallVector<SDValue, 8> MemOpChains;
1826 
1827   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1828   // of tail call optimization, arguments are handled later.
1829   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1830        i != e;
1831        ++i, ++realArgIdx) {
1832     CCValAssign &VA = ArgLocs[i];
1833     SDValue Arg = OutVals[realArgIdx];
1834     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1835     bool isByVal = Flags.isByVal();
1836 
1837     // Promote the value if needed.
1838     switch (VA.getLocInfo()) {
1839     default: llvm_unreachable("Unknown loc info!");
1840     case CCValAssign::Full: break;
1841     case CCValAssign::SExt:
1842       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1843       break;
1844     case CCValAssign::ZExt:
1845       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1846       break;
1847     case CCValAssign::AExt:
1848       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1849       break;
1850     case CCValAssign::BCvt:
1851       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1852       break;
1853     }
1854 
1855     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1856     if (VA.needsCustom()) {
1857       if (VA.getLocVT() == MVT::v2f64) {
1858         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1859                                   DAG.getConstant(0, dl, MVT::i32));
1860         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1861                                   DAG.getConstant(1, dl, MVT::i32));
1862 
1863         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1864                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1865 
1866         VA = ArgLocs[++i]; // skip ahead to next loc
1867         if (VA.isRegLoc()) {
1868           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1869                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1870         } else {
1871           assert(VA.isMemLoc());
1872 
1873           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1874                                                  dl, DAG, VA, Flags));
1875         }
1876       } else {
1877         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1878                          StackPtr, MemOpChains, Flags);
1879       }
1880     } else if (VA.isRegLoc()) {
1881       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1882           Outs[0].VT == MVT::i32) {
1883         assert(VA.getLocVT() == MVT::i32 &&
1884                "unexpected calling convention register assignment");
1885         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1886                "unexpected use of 'returned'");
1887         isThisReturn = true;
1888       }
1889       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1890     } else if (isByVal) {
1891       assert(VA.isMemLoc());
1892       unsigned offset = 0;
1893 
1894       // True if this byval aggregate will be split between registers
1895       // and memory.
1896       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1897       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1898 
1899       if (CurByValIdx < ByValArgsCount) {
1900 
1901         unsigned RegBegin, RegEnd;
1902         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1903 
1904         EVT PtrVT =
1905             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1906         unsigned int i, j;
1907         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1908           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1909           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1910           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1911                                      MachinePointerInfo(),
1912                                      DAG.InferPtrAlignment(AddArg));
1913           MemOpChains.push_back(Load.getValue(1));
1914           RegsToPass.push_back(std::make_pair(j, Load));
1915         }
1916 
1917         // If parameter size outsides register area, "offset" value
1918         // helps us to calculate stack slot for remained part properly.
1919         offset = RegEnd - RegBegin;
1920 
1921         CCInfo.nextInRegsParam();
1922       }
1923 
1924       if (Flags.getByValSize() > 4*offset) {
1925         auto PtrVT = getPointerTy(DAG.getDataLayout());
1926         unsigned LocMemOffset = VA.getLocMemOffset();
1927         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1928         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1929         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1930         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1931         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1932                                            MVT::i32);
1933         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1934                                             MVT::i32);
1935 
1936         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1937         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1938         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1939                                           Ops));
1940       }
1941     } else if (!isSibCall) {
1942       assert(VA.isMemLoc());
1943 
1944       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1945                                              dl, DAG, VA, Flags));
1946     }
1947   }
1948 
1949   if (!MemOpChains.empty())
1950     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1951 
1952   // Build a sequence of copy-to-reg nodes chained together with token chain
1953   // and flag operands which copy the outgoing args into the appropriate regs.
1954   SDValue InFlag;
1955   // Tail call byval lowering might overwrite argument registers so in case of
1956   // tail call optimization the copies to registers are lowered later.
1957   if (!isTailCall)
1958     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1959       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1960                                RegsToPass[i].second, InFlag);
1961       InFlag = Chain.getValue(1);
1962     }
1963 
1964   // For tail calls lower the arguments to the 'real' stack slot.
1965   if (isTailCall) {
1966     // Force all the incoming stack arguments to be loaded from the stack
1967     // before any new outgoing arguments are stored to the stack, because the
1968     // outgoing stack slots may alias the incoming argument stack slots, and
1969     // the alias isn't otherwise explicit. This is slightly more conservative
1970     // than necessary, because it means that each store effectively depends
1971     // on every argument instead of just those arguments it would clobber.
1972 
1973     // Do not flag preceding copytoreg stuff together with the following stuff.
1974     InFlag = SDValue();
1975     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1976       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1977                                RegsToPass[i].second, InFlag);
1978       InFlag = Chain.getValue(1);
1979     }
1980     InFlag = SDValue();
1981   }
1982 
1983   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1984   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1985   // node so that legalize doesn't hack it.
1986   bool isDirect = false;
1987 
1988   const TargetMachine &TM = getTargetMachine();
1989   const Module *Mod = MF.getFunction()->getParent();
1990   const GlobalValue *GV = nullptr;
1991   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1992     GV = G->getGlobal();
1993   bool isStub =
1994       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1995 
1996   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1997   bool isLocalARMFunc = false;
1998   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1999   auto PtrVt = getPointerTy(DAG.getDataLayout());
2000 
2001   if (Subtarget->genLongCalls()) {
2002     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2003            "long-calls codegen is not position independent!");
2004     // Handle a global address or an external symbol. If it's not one of
2005     // those, the target's already in a register, so we don't need to do
2006     // anything extra.
2007     if (isa<GlobalAddressSDNode>(Callee)) {
2008       // Create a constant pool entry for the callee address
2009       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2010       ARMConstantPoolValue *CPV =
2011         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2012 
2013       // Get the address of the callee into a register
2014       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2015       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2016       Callee = DAG.getLoad(
2017           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2018           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2019     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2020       const char *Sym = S->getSymbol();
2021 
2022       // Create a constant pool entry for the callee address
2023       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2024       ARMConstantPoolValue *CPV =
2025         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2026                                       ARMPCLabelIndex, 0);
2027       // Get the address of the callee into a register
2028       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2029       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2030       Callee = DAG.getLoad(
2031           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2032           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2033     }
2034   } else if (isa<GlobalAddressSDNode>(Callee)) {
2035     // If we're optimizing for minimum size and the function is called three or
2036     // more times in this block, we can improve codesize by calling indirectly
2037     // as BLXr has a 16-bit encoding.
2038     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2039     auto *BB = CLI.CS.getParent();
2040     bool PreferIndirect =
2041         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2042         count_if(GV->users(), [&BB](const User *U) {
2043           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2044         }) > 2;
2045 
2046     if (!PreferIndirect) {
2047       isDirect = true;
2048       bool isDef = GV->isStrongDefinitionForLinker();
2049 
2050       // ARM call to a local ARM function is predicable.
2051       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2052       // tBX takes a register source operand.
2053       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2054         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2055         Callee = DAG.getNode(
2056             ARMISD::WrapperPIC, dl, PtrVt,
2057             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2058         Callee = DAG.getLoad(
2059             PtrVt, dl, DAG.getEntryNode(), Callee,
2060             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2061             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2062                                      MachineMemOperand::MOInvariant);
2063       } else if (Subtarget->isTargetCOFF()) {
2064         assert(Subtarget->isTargetWindows() &&
2065                "Windows is the only supported COFF target");
2066         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2067                                    ? ARMII::MO_DLLIMPORT
2068                                    : ARMII::MO_NO_FLAG;
2069         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2070                                             TargetFlags);
2071         if (GV->hasDLLImportStorageClass())
2072           Callee =
2073               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2074                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2075                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2076       } else {
2077         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2078       }
2079     }
2080   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2081     isDirect = true;
2082     // tBX takes a register source operand.
2083     const char *Sym = S->getSymbol();
2084     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2085       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2086       ARMConstantPoolValue *CPV =
2087         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2088                                       ARMPCLabelIndex, 4);
2089       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2090       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2091       Callee = DAG.getLoad(
2092           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2093           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2094       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2095       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2096     } else {
2097       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2098     }
2099   }
2100 
2101   // FIXME: handle tail calls differently.
2102   unsigned CallOpc;
2103   if (Subtarget->isThumb()) {
2104     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2105       CallOpc = ARMISD::CALL_NOLINK;
2106     else
2107       CallOpc = ARMISD::CALL;
2108   } else {
2109     if (!isDirect && !Subtarget->hasV5TOps())
2110       CallOpc = ARMISD::CALL_NOLINK;
2111     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2112              // Emit regular call when code size is the priority
2113              !MF.getFunction()->optForMinSize())
2114       // "mov lr, pc; b _foo" to avoid confusing the RSP
2115       CallOpc = ARMISD::CALL_NOLINK;
2116     else
2117       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2118   }
2119 
2120   std::vector<SDValue> Ops;
2121   Ops.push_back(Chain);
2122   Ops.push_back(Callee);
2123 
2124   // Add argument registers to the end of the list so that they are known live
2125   // into the call.
2126   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2127     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2128                                   RegsToPass[i].second.getValueType()));
2129 
2130   // Add a register mask operand representing the call-preserved registers.
2131   if (!isTailCall) {
2132     const uint32_t *Mask;
2133     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2134     if (isThisReturn) {
2135       // For 'this' returns, use the R0-preserving mask if applicable
2136       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2137       if (!Mask) {
2138         // Set isThisReturn to false if the calling convention is not one that
2139         // allows 'returned' to be modeled in this way, so LowerCallResult does
2140         // not try to pass 'this' straight through
2141         isThisReturn = false;
2142         Mask = ARI->getCallPreservedMask(MF, CallConv);
2143       }
2144     } else
2145       Mask = ARI->getCallPreservedMask(MF, CallConv);
2146 
2147     assert(Mask && "Missing call preserved mask for calling convention");
2148     Ops.push_back(DAG.getRegisterMask(Mask));
2149   }
2150 
2151   if (InFlag.getNode())
2152     Ops.push_back(InFlag);
2153 
2154   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2155   if (isTailCall) {
2156     MF.getFrameInfo().setHasTailCall();
2157     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2158   }
2159 
2160   // Returns a chain and a flag for retval copy to use.
2161   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2162   InFlag = Chain.getValue(1);
2163 
2164   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2165                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2166   if (!Ins.empty())
2167     InFlag = Chain.getValue(1);
2168 
2169   // Handle result values, copying them out of physregs into vregs that we
2170   // return.
2171   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2172                          InVals, isThisReturn,
2173                          isThisReturn ? OutVals[0] : SDValue());
2174 }
2175 
2176 /// HandleByVal - Every parameter *after* a byval parameter is passed
2177 /// on the stack.  Remember the next parameter register to allocate,
2178 /// and then confiscate the rest of the parameter registers to insure
2179 /// this.
2180 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2181                                     unsigned Align) const {
2182   // Byval (as with any stack) slots are always at least 4 byte aligned.
2183   Align = std::max(Align, 4U);
2184 
2185   unsigned Reg = State->AllocateReg(GPRArgRegs);
2186   if (!Reg)
2187     return;
2188 
2189   unsigned AlignInRegs = Align / 4;
2190   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2191   for (unsigned i = 0; i < Waste; ++i)
2192     Reg = State->AllocateReg(GPRArgRegs);
2193 
2194   if (!Reg)
2195     return;
2196 
2197   unsigned Excess = 4 * (ARM::R4 - Reg);
2198 
2199   // Special case when NSAA != SP and parameter size greater than size of
2200   // all remained GPR regs. In that case we can't split parameter, we must
2201   // send it to stack. We also must set NCRN to R4, so waste all
2202   // remained registers.
2203   const unsigned NSAAOffset = State->getNextStackOffset();
2204   if (NSAAOffset != 0 && Size > Excess) {
2205     while (State->AllocateReg(GPRArgRegs))
2206       ;
2207     return;
2208   }
2209 
2210   // First register for byval parameter is the first register that wasn't
2211   // allocated before this method call, so it would be "reg".
2212   // If parameter is small enough to be saved in range [reg, r4), then
2213   // the end (first after last) register would be reg + param-size-in-regs,
2214   // else parameter would be splitted between registers and stack,
2215   // end register would be r4 in this case.
2216   unsigned ByValRegBegin = Reg;
2217   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2218   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2219   // Note, first register is allocated in the beginning of function already,
2220   // allocate remained amount of registers we need.
2221   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2222     State->AllocateReg(GPRArgRegs);
2223   // A byval parameter that is split between registers and memory needs its
2224   // size truncated here.
2225   // In the case where the entire structure fits in registers, we set the
2226   // size in memory to zero.
2227   Size = std::max<int>(Size - Excess, 0);
2228 }
2229 
2230 /// MatchingStackOffset - Return true if the given stack call argument is
2231 /// already available in the same position (relatively) of the caller's
2232 /// incoming argument stack.
2233 static
2234 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2235                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2236                          const TargetInstrInfo *TII) {
2237   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2238   int FI = std::numeric_limits<int>::max();
2239   if (Arg.getOpcode() == ISD::CopyFromReg) {
2240     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2241     if (!TargetRegisterInfo::isVirtualRegister(VR))
2242       return false;
2243     MachineInstr *Def = MRI->getVRegDef(VR);
2244     if (!Def)
2245       return false;
2246     if (!Flags.isByVal()) {
2247       if (!TII->isLoadFromStackSlot(*Def, FI))
2248         return false;
2249     } else {
2250       return false;
2251     }
2252   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2253     if (Flags.isByVal())
2254       // ByVal argument is passed in as a pointer but it's now being
2255       // dereferenced. e.g.
2256       // define @foo(%struct.X* %A) {
2257       //   tail call @bar(%struct.X* byval %A)
2258       // }
2259       return false;
2260     SDValue Ptr = Ld->getBasePtr();
2261     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2262     if (!FINode)
2263       return false;
2264     FI = FINode->getIndex();
2265   } else
2266     return false;
2267 
2268   assert(FI != std::numeric_limits<int>::max());
2269   if (!MFI.isFixedObjectIndex(FI))
2270     return false;
2271   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2272 }
2273 
2274 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2275 /// for tail call optimization. Targets which want to do tail call
2276 /// optimization should implement this function.
2277 bool
2278 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2279                                                      CallingConv::ID CalleeCC,
2280                                                      bool isVarArg,
2281                                                      bool isCalleeStructRet,
2282                                                      bool isCallerStructRet,
2283                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2284                                     const SmallVectorImpl<SDValue> &OutVals,
2285                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2286                                                      SelectionDAG& DAG) const {
2287   MachineFunction &MF = DAG.getMachineFunction();
2288   const Function *CallerF = MF.getFunction();
2289   CallingConv::ID CallerCC = CallerF->getCallingConv();
2290 
2291   assert(Subtarget->supportsTailCall());
2292 
2293   // Look for obvious safe cases to perform tail call optimization that do not
2294   // require ABI changes. This is what gcc calls sibcall.
2295 
2296   // Exception-handling functions need a special set of instructions to indicate
2297   // a return to the hardware. Tail-calling another function would probably
2298   // break this.
2299   if (CallerF->hasFnAttribute("interrupt"))
2300     return false;
2301 
2302   // Also avoid sibcall optimization if either caller or callee uses struct
2303   // return semantics.
2304   if (isCalleeStructRet || isCallerStructRet)
2305     return false;
2306 
2307   // Externally-defined functions with weak linkage should not be
2308   // tail-called on ARM when the OS does not support dynamic
2309   // pre-emption of symbols, as the AAELF spec requires normal calls
2310   // to undefined weak functions to be replaced with a NOP or jump to the
2311   // next instruction. The behaviour of branch instructions in this
2312   // situation (as used for tail calls) is implementation-defined, so we
2313   // cannot rely on the linker replacing the tail call with a return.
2314   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2315     const GlobalValue *GV = G->getGlobal();
2316     const Triple &TT = getTargetMachine().getTargetTriple();
2317     if (GV->hasExternalWeakLinkage() &&
2318         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2319       return false;
2320   }
2321 
2322   // Check that the call results are passed in the same way.
2323   LLVMContext &C = *DAG.getContext();
2324   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2325                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2326                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2327     return false;
2328   // The callee has to preserve all registers the caller needs to preserve.
2329   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2330   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2331   if (CalleeCC != CallerCC) {
2332     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2333     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2334       return false;
2335   }
2336 
2337   // If Caller's vararg or byval argument has been split between registers and
2338   // stack, do not perform tail call, since part of the argument is in caller's
2339   // local frame.
2340   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2341   if (AFI_Caller->getArgRegsSaveSize())
2342     return false;
2343 
2344   // If the callee takes no arguments then go on to check the results of the
2345   // call.
2346   if (!Outs.empty()) {
2347     // Check if stack adjustment is needed. For now, do not do this if any
2348     // argument is passed on the stack.
2349     SmallVector<CCValAssign, 16> ArgLocs;
2350     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2351     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2352     if (CCInfo.getNextStackOffset()) {
2353       // Check if the arguments are already laid out in the right way as
2354       // the caller's fixed stack objects.
2355       MachineFrameInfo &MFI = MF.getFrameInfo();
2356       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2357       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2358       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2359            i != e;
2360            ++i, ++realArgIdx) {
2361         CCValAssign &VA = ArgLocs[i];
2362         EVT RegVT = VA.getLocVT();
2363         SDValue Arg = OutVals[realArgIdx];
2364         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2365         if (VA.getLocInfo() == CCValAssign::Indirect)
2366           return false;
2367         if (VA.needsCustom()) {
2368           // f64 and vector types are split into multiple registers or
2369           // register/stack-slot combinations.  The types will not match
2370           // the registers; give up on memory f64 refs until we figure
2371           // out what to do about this.
2372           if (!VA.isRegLoc())
2373             return false;
2374           if (!ArgLocs[++i].isRegLoc())
2375             return false;
2376           if (RegVT == MVT::v2f64) {
2377             if (!ArgLocs[++i].isRegLoc())
2378               return false;
2379             if (!ArgLocs[++i].isRegLoc())
2380               return false;
2381           }
2382         } else if (!VA.isRegLoc()) {
2383           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2384                                    MFI, MRI, TII))
2385             return false;
2386         }
2387       }
2388     }
2389 
2390     const MachineRegisterInfo &MRI = MF.getRegInfo();
2391     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2392       return false;
2393   }
2394 
2395   return true;
2396 }
2397 
2398 bool
2399 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2400                                   MachineFunction &MF, bool isVarArg,
2401                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2402                                   LLVMContext &Context) const {
2403   SmallVector<CCValAssign, 16> RVLocs;
2404   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2405   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2406 }
2407 
2408 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2409                                     const SDLoc &DL, SelectionDAG &DAG) {
2410   const MachineFunction &MF = DAG.getMachineFunction();
2411   const Function *F = MF.getFunction();
2412 
2413   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2414 
2415   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2416   // version of the "preferred return address". These offsets affect the return
2417   // instruction if this is a return from PL1 without hypervisor extensions.
2418   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2419   //    SWI:     0      "subs pc, lr, #0"
2420   //    ABORT:   +4     "subs pc, lr, #4"
2421   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2422   // UNDEF varies depending on where the exception came from ARM or Thumb
2423   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2424 
2425   int64_t LROffset;
2426   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2427       IntKind == "ABORT")
2428     LROffset = 4;
2429   else if (IntKind == "SWI" || IntKind == "UNDEF")
2430     LROffset = 0;
2431   else
2432     report_fatal_error("Unsupported interrupt attribute. If present, value "
2433                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2434 
2435   RetOps.insert(RetOps.begin() + 1,
2436                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2437 
2438   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2439 }
2440 
2441 SDValue
2442 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2443                                bool isVarArg,
2444                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2445                                const SmallVectorImpl<SDValue> &OutVals,
2446                                const SDLoc &dl, SelectionDAG &DAG) const {
2447 
2448   // CCValAssign - represent the assignment of the return value to a location.
2449   SmallVector<CCValAssign, 16> RVLocs;
2450 
2451   // CCState - Info about the registers and stack slots.
2452   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2453                  *DAG.getContext());
2454 
2455   // Analyze outgoing return values.
2456   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2457 
2458   SDValue Flag;
2459   SmallVector<SDValue, 4> RetOps;
2460   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2461   bool isLittleEndian = Subtarget->isLittle();
2462 
2463   MachineFunction &MF = DAG.getMachineFunction();
2464   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2465   AFI->setReturnRegsCount(RVLocs.size());
2466 
2467   // Copy the result values into the output registers.
2468   for (unsigned i = 0, realRVLocIdx = 0;
2469        i != RVLocs.size();
2470        ++i, ++realRVLocIdx) {
2471     CCValAssign &VA = RVLocs[i];
2472     assert(VA.isRegLoc() && "Can only return in registers!");
2473 
2474     SDValue Arg = OutVals[realRVLocIdx];
2475 
2476     switch (VA.getLocInfo()) {
2477     default: llvm_unreachable("Unknown loc info!");
2478     case CCValAssign::Full: break;
2479     case CCValAssign::BCvt:
2480       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2481       break;
2482     }
2483 
2484     if (VA.needsCustom()) {
2485       if (VA.getLocVT() == MVT::v2f64) {
2486         // Extract the first half and return it in two registers.
2487         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2488                                    DAG.getConstant(0, dl, MVT::i32));
2489         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2490                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2491 
2492         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2493                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2494                                  Flag);
2495         Flag = Chain.getValue(1);
2496         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2497         VA = RVLocs[++i]; // skip ahead to next loc
2498         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2499                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2500                                  Flag);
2501         Flag = Chain.getValue(1);
2502         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2503         VA = RVLocs[++i]; // skip ahead to next loc
2504 
2505         // Extract the 2nd half and fall through to handle it as an f64 value.
2506         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2507                           DAG.getConstant(1, dl, MVT::i32));
2508       }
2509       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2510       // available.
2511       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2512                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2513       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2514                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2515                                Flag);
2516       Flag = Chain.getValue(1);
2517       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2518       VA = RVLocs[++i]; // skip ahead to next loc
2519       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2520                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2521                                Flag);
2522     } else
2523       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2524 
2525     // Guarantee that all emitted copies are
2526     // stuck together, avoiding something bad.
2527     Flag = Chain.getValue(1);
2528     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2529   }
2530   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2531   const MCPhysReg *I =
2532       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2533   if (I) {
2534     for (; *I; ++I) {
2535       if (ARM::GPRRegClass.contains(*I))
2536         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2537       else if (ARM::DPRRegClass.contains(*I))
2538         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2539       else
2540         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2541     }
2542   }
2543 
2544   // Update chain and glue.
2545   RetOps[0] = Chain;
2546   if (Flag.getNode())
2547     RetOps.push_back(Flag);
2548 
2549   // CPUs which aren't M-class use a special sequence to return from
2550   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2551   // though we use "subs pc, lr, #N").
2552   //
2553   // M-class CPUs actually use a normal return sequence with a special
2554   // (hardware-provided) value in LR, so the normal code path works.
2555   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2556       !Subtarget->isMClass()) {
2557     if (Subtarget->isThumb1Only())
2558       report_fatal_error("interrupt attribute is not supported in Thumb1");
2559     return LowerInterruptReturn(RetOps, dl, DAG);
2560   }
2561 
2562   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2563 }
2564 
2565 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2566   if (N->getNumValues() != 1)
2567     return false;
2568   if (!N->hasNUsesOfValue(1, 0))
2569     return false;
2570 
2571   SDValue TCChain = Chain;
2572   SDNode *Copy = *N->use_begin();
2573   if (Copy->getOpcode() == ISD::CopyToReg) {
2574     // If the copy has a glue operand, we conservatively assume it isn't safe to
2575     // perform a tail call.
2576     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2577       return false;
2578     TCChain = Copy->getOperand(0);
2579   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2580     SDNode *VMov = Copy;
2581     // f64 returned in a pair of GPRs.
2582     SmallPtrSet<SDNode*, 2> Copies;
2583     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2584          UI != UE; ++UI) {
2585       if (UI->getOpcode() != ISD::CopyToReg)
2586         return false;
2587       Copies.insert(*UI);
2588     }
2589     if (Copies.size() > 2)
2590       return false;
2591 
2592     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2593          UI != UE; ++UI) {
2594       SDValue UseChain = UI->getOperand(0);
2595       if (Copies.count(UseChain.getNode()))
2596         // Second CopyToReg
2597         Copy = *UI;
2598       else {
2599         // We are at the top of this chain.
2600         // If the copy has a glue operand, we conservatively assume it
2601         // isn't safe to perform a tail call.
2602         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2603           return false;
2604         // First CopyToReg
2605         TCChain = UseChain;
2606       }
2607     }
2608   } else if (Copy->getOpcode() == ISD::BITCAST) {
2609     // f32 returned in a single GPR.
2610     if (!Copy->hasOneUse())
2611       return false;
2612     Copy = *Copy->use_begin();
2613     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2614       return false;
2615     // If the copy has a glue operand, we conservatively assume it isn't safe to
2616     // perform a tail call.
2617     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2618       return false;
2619     TCChain = Copy->getOperand(0);
2620   } else {
2621     return false;
2622   }
2623 
2624   bool HasRet = false;
2625   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2626        UI != UE; ++UI) {
2627     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2628         UI->getOpcode() != ARMISD::INTRET_FLAG)
2629       return false;
2630     HasRet = true;
2631   }
2632 
2633   if (!HasRet)
2634     return false;
2635 
2636   Chain = TCChain;
2637   return true;
2638 }
2639 
2640 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2641   if (!Subtarget->supportsTailCall())
2642     return false;
2643 
2644   auto Attr =
2645       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2646   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2647     return false;
2648 
2649   return true;
2650 }
2651 
2652 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2653 // and pass the lower and high parts through.
2654 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2655   SDLoc DL(Op);
2656   SDValue WriteValue = Op->getOperand(2);
2657 
2658   // This function is only supposed to be called for i64 type argument.
2659   assert(WriteValue.getValueType() == MVT::i64
2660           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2661 
2662   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2663                            DAG.getConstant(0, DL, MVT::i32));
2664   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2665                            DAG.getConstant(1, DL, MVT::i32));
2666   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2667   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2668 }
2669 
2670 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2671 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2672 // one of the above mentioned nodes. It has to be wrapped because otherwise
2673 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2674 // be used to form addressing mode. These wrapped nodes will be selected
2675 // into MOVi.
2676 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2677                                              SelectionDAG &DAG) const {
2678   EVT PtrVT = Op.getValueType();
2679   // FIXME there is no actual debug info here
2680   SDLoc dl(Op);
2681   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2682   SDValue Res;
2683 
2684   // When generating execute-only code Constant Pools must be promoted to the
2685   // global data section. It's a bit ugly that we can't share them across basic
2686   // blocks, but this way we guarantee that execute-only behaves correct with
2687   // position-independent addressing modes.
2688   if (Subtarget->genExecuteOnly()) {
2689     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2690     auto T = const_cast<Type*>(CP->getType());
2691     auto C = const_cast<Constant*>(CP->getConstVal());
2692     auto M = const_cast<Module*>(DAG.getMachineFunction().
2693                                  getFunction()->getParent());
2694     auto GV = new GlobalVariable(
2695                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2696                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2697                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2698                     Twine(AFI->createPICLabelUId())
2699                   );
2700     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2701                                             dl, PtrVT);
2702     return LowerGlobalAddress(GA, DAG);
2703   }
2704 
2705   if (CP->isMachineConstantPoolEntry())
2706     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2707                                     CP->getAlignment());
2708   else
2709     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2710                                     CP->getAlignment());
2711   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2712 }
2713 
2714 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2715   return MachineJumpTableInfo::EK_Inline;
2716 }
2717 
2718 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2719                                              SelectionDAG &DAG) const {
2720   MachineFunction &MF = DAG.getMachineFunction();
2721   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2722   unsigned ARMPCLabelIndex = 0;
2723   SDLoc DL(Op);
2724   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2725   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2726   SDValue CPAddr;
2727   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2728   if (!IsPositionIndependent) {
2729     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2730   } else {
2731     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2732     ARMPCLabelIndex = AFI->createPICLabelUId();
2733     ARMConstantPoolValue *CPV =
2734       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2735                                       ARMCP::CPBlockAddress, PCAdj);
2736     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2737   }
2738   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2739   SDValue Result = DAG.getLoad(
2740       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2741       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2742   if (!IsPositionIndependent)
2743     return Result;
2744   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2745   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2746 }
2747 
2748 /// \brief Convert a TLS address reference into the correct sequence of loads
2749 /// and calls to compute the variable's address for Darwin, and return an
2750 /// SDValue containing the final node.
2751 
2752 /// Darwin only has one TLS scheme which must be capable of dealing with the
2753 /// fully general situation, in the worst case. This means:
2754 ///     + "extern __thread" declaration.
2755 ///     + Defined in a possibly unknown dynamic library.
2756 ///
2757 /// The general system is that each __thread variable has a [3 x i32] descriptor
2758 /// which contains information used by the runtime to calculate the address. The
2759 /// only part of this the compiler needs to know about is the first word, which
2760 /// contains a function pointer that must be called with the address of the
2761 /// entire descriptor in "r0".
2762 ///
2763 /// Since this descriptor may be in a different unit, in general access must
2764 /// proceed along the usual ARM rules. A common sequence to produce is:
2765 ///
2766 ///     movw rT1, :lower16:_var$non_lazy_ptr
2767 ///     movt rT1, :upper16:_var$non_lazy_ptr
2768 ///     ldr r0, [rT1]
2769 ///     ldr rT2, [r0]
2770 ///     blx rT2
2771 ///     [...address now in r0...]
2772 SDValue
2773 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2774                                                SelectionDAG &DAG) const {
2775   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2776   SDLoc DL(Op);
2777 
2778   // First step is to get the address of the actua global symbol. This is where
2779   // the TLS descriptor lives.
2780   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2781 
2782   // The first entry in the descriptor is a function pointer that we must call
2783   // to obtain the address of the variable.
2784   SDValue Chain = DAG.getEntryNode();
2785   SDValue FuncTLVGet = DAG.getLoad(
2786       MVT::i32, DL, Chain, DescAddr,
2787       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2788       /* Alignment = */ 4,
2789       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2790           MachineMemOperand::MOInvariant);
2791   Chain = FuncTLVGet.getValue(1);
2792 
2793   MachineFunction &F = DAG.getMachineFunction();
2794   MachineFrameInfo &MFI = F.getFrameInfo();
2795   MFI.setAdjustsStack(true);
2796 
2797   // TLS calls preserve all registers except those that absolutely must be
2798   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2799   // silly).
2800   auto TRI =
2801       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2802   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2803   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2804 
2805   // Finally, we can make the call. This is just a degenerate version of a
2806   // normal AArch64 call node: r0 takes the address of the descriptor, and
2807   // returns the address of the variable in this thread.
2808   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2809   Chain =
2810       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2811                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2812                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2813   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2814 }
2815 
2816 SDValue
2817 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2818                                                 SelectionDAG &DAG) const {
2819   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2820 
2821   SDValue Chain = DAG.getEntryNode();
2822   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2823   SDLoc DL(Op);
2824 
2825   // Load the current TEB (thread environment block)
2826   SDValue Ops[] = {Chain,
2827                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2828                    DAG.getConstant(15, DL, MVT::i32),
2829                    DAG.getConstant(0, DL, MVT::i32),
2830                    DAG.getConstant(13, DL, MVT::i32),
2831                    DAG.getConstant(0, DL, MVT::i32),
2832                    DAG.getConstant(2, DL, MVT::i32)};
2833   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2834                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2835 
2836   SDValue TEB = CurrentTEB.getValue(0);
2837   Chain = CurrentTEB.getValue(1);
2838 
2839   // Load the ThreadLocalStoragePointer from the TEB
2840   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2841   SDValue TLSArray =
2842       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2843   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2844 
2845   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2846   // offset into the TLSArray.
2847 
2848   // Load the TLS index from the C runtime
2849   SDValue TLSIndex =
2850       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2851   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2852   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2853 
2854   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2855                               DAG.getConstant(2, DL, MVT::i32));
2856   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2857                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2858                             MachinePointerInfo());
2859 
2860   // Get the offset of the start of the .tls section (section base)
2861   const auto *GA = cast<GlobalAddressSDNode>(Op);
2862   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2863   SDValue Offset = DAG.getLoad(
2864       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2865                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2866       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2867 
2868   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2869 }
2870 
2871 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2872 SDValue
2873 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2874                                                  SelectionDAG &DAG) const {
2875   SDLoc dl(GA);
2876   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2877   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2878   MachineFunction &MF = DAG.getMachineFunction();
2879   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2880   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2881   ARMConstantPoolValue *CPV =
2882     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2883                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2884   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2885   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2886   Argument = DAG.getLoad(
2887       PtrVT, dl, DAG.getEntryNode(), Argument,
2888       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2889   SDValue Chain = Argument.getValue(1);
2890 
2891   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2892   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2893 
2894   // call __tls_get_addr.
2895   ArgListTy Args;
2896   ArgListEntry Entry;
2897   Entry.Node = Argument;
2898   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2899   Args.push_back(Entry);
2900 
2901   // FIXME: is there useful debug info available here?
2902   TargetLowering::CallLoweringInfo CLI(DAG);
2903   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2904       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2905       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2906 
2907   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2908   return CallResult.first;
2909 }
2910 
2911 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2912 // "local exec" model.
2913 SDValue
2914 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2915                                         SelectionDAG &DAG,
2916                                         TLSModel::Model model) const {
2917   const GlobalValue *GV = GA->getGlobal();
2918   SDLoc dl(GA);
2919   SDValue Offset;
2920   SDValue Chain = DAG.getEntryNode();
2921   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2922   // Get the Thread Pointer
2923   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2924 
2925   if (model == TLSModel::InitialExec) {
2926     MachineFunction &MF = DAG.getMachineFunction();
2927     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2929     // Initial exec model.
2930     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2931     ARMConstantPoolValue *CPV =
2932       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2933                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2934                                       true);
2935     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2936     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2937     Offset = DAG.getLoad(
2938         PtrVT, dl, Chain, Offset,
2939         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2940     Chain = Offset.getValue(1);
2941 
2942     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2943     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2944 
2945     Offset = DAG.getLoad(
2946         PtrVT, dl, Chain, Offset,
2947         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2948   } else {
2949     // local exec model
2950     assert(model == TLSModel::LocalExec);
2951     ARMConstantPoolValue *CPV =
2952       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2953     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2954     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2955     Offset = DAG.getLoad(
2956         PtrVT, dl, Chain, Offset,
2957         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2958   }
2959 
2960   // The address of the thread local variable is the add of the thread
2961   // pointer with the offset of the variable.
2962   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2963 }
2964 
2965 SDValue
2966 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2967   if (Subtarget->isTargetDarwin())
2968     return LowerGlobalTLSAddressDarwin(Op, DAG);
2969 
2970   if (Subtarget->isTargetWindows())
2971     return LowerGlobalTLSAddressWindows(Op, DAG);
2972 
2973   // TODO: implement the "local dynamic" model
2974   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2975   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2976   if (DAG.getTarget().Options.EmulatedTLS)
2977     return LowerToTLSEmulatedModel(GA, DAG);
2978 
2979   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2980 
2981   switch (model) {
2982     case TLSModel::GeneralDynamic:
2983     case TLSModel::LocalDynamic:
2984       return LowerToTLSGeneralDynamicModel(GA, DAG);
2985     case TLSModel::InitialExec:
2986     case TLSModel::LocalExec:
2987       return LowerToTLSExecModels(GA, DAG, model);
2988   }
2989   llvm_unreachable("bogus TLS model");
2990 }
2991 
2992 /// Return true if all users of V are within function F, looking through
2993 /// ConstantExprs.
2994 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2995   SmallVector<const User*,4> Worklist;
2996   for (auto *U : V->users())
2997     Worklist.push_back(U);
2998   while (!Worklist.empty()) {
2999     auto *U = Worklist.pop_back_val();
3000     if (isa<ConstantExpr>(U)) {
3001       for (auto *UU : U->users())
3002         Worklist.push_back(UU);
3003       continue;
3004     }
3005 
3006     auto *I = dyn_cast<Instruction>(U);
3007     if (!I || I->getParent()->getParent() != F)
3008       return false;
3009   }
3010   return true;
3011 }
3012 
3013 /// Return true if all users of V are within some (any) function, looking through
3014 /// ConstantExprs. In other words, are there any global constant users?
3015 static bool allUsersAreInFunctions(const Value *V) {
3016   SmallVector<const User*,4> Worklist;
3017   for (auto *U : V->users())
3018     Worklist.push_back(U);
3019   while (!Worklist.empty()) {
3020     auto *U = Worklist.pop_back_val();
3021     if (isa<ConstantExpr>(U)) {
3022       for (auto *UU : U->users())
3023         Worklist.push_back(UU);
3024       continue;
3025     }
3026 
3027     if (!isa<Instruction>(U))
3028       return false;
3029   }
3030   return true;
3031 }
3032 
3033 // Return true if T is an integer, float or an array/vector of either.
3034 static bool isSimpleType(Type *T) {
3035   if (T->isIntegerTy() || T->isFloatingPointTy())
3036     return true;
3037   Type *SubT = nullptr;
3038   if (T->isArrayTy())
3039     SubT = T->getArrayElementType();
3040   else if (T->isVectorTy())
3041     SubT = T->getVectorElementType();
3042   else
3043     return false;
3044   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3045 }
3046 
3047 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3048                                      EVT PtrVT, const SDLoc &dl) {
3049   // If we're creating a pool entry for a constant global with unnamed address,
3050   // and the global is small enough, we can emit it inline into the constant pool
3051   // to save ourselves an indirection.
3052   //
3053   // This is a win if the constant is only used in one function (so it doesn't
3054   // need to be duplicated) or duplicating the constant wouldn't increase code
3055   // size (implying the constant is no larger than 4 bytes).
3056   const Function *F = DAG.getMachineFunction().getFunction();
3057 
3058   // We rely on this decision to inline being idemopotent and unrelated to the
3059   // use-site. We know that if we inline a variable at one use site, we'll
3060   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3061   // doesn't know about this optimization, so bail out if it's enabled else
3062   // we could decide to inline here (and thus never emit the GV) but require
3063   // the GV from fast-isel generated code.
3064   if (!EnableConstpoolPromotion ||
3065       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3066       return SDValue();
3067 
3068   auto *GVar = dyn_cast<GlobalVariable>(GV);
3069   if (!GVar || !GVar->hasInitializer() ||
3070       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3071       !GVar->hasLocalLinkage())
3072     return SDValue();
3073 
3074   // Ensure that we don't try and inline any type that contains pointers. If
3075   // we inline a value that contains relocations, we move the relocations from
3076   // .data to .text which is not ideal.
3077   auto *Init = GVar->getInitializer();
3078   if (!isSimpleType(Init->getType()))
3079     return SDValue();
3080 
3081   // The constant islands pass can only really deal with alignment requests
3082   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3083   // any type wanting greater alignment requirements than 4 bytes. We also
3084   // can only promote constants that are multiples of 4 bytes in size or
3085   // are paddable to a multiple of 4. Currently we only try and pad constants
3086   // that are strings for simplicity.
3087   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3088   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3089   unsigned Align = GVar->getAlignment();
3090   unsigned RequiredPadding = 4 - (Size % 4);
3091   bool PaddingPossible =
3092     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3093   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3094       Size == 0)
3095     return SDValue();
3096 
3097   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3098   MachineFunction &MF = DAG.getMachineFunction();
3099   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3100 
3101   // We can't bloat the constant pool too much, else the ConstantIslands pass
3102   // may fail to converge. If we haven't promoted this global yet (it may have
3103   // multiple uses), and promoting it would increase the constant pool size (Sz
3104   // > 4), ensure we have space to do so up to MaxTotal.
3105   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3106     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3107         ConstpoolPromotionMaxTotal)
3108       return SDValue();
3109 
3110   // This is only valid if all users are in a single function OR it has users
3111   // in multiple functions but it no larger than a pointer. We also check if
3112   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3113   // address taken.
3114   if (!allUsersAreInFunction(GVar, F) &&
3115       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3116     return SDValue();
3117 
3118   // We're going to inline this global. Pad it out if needed.
3119   if (RequiredPadding != 4) {
3120     StringRef S = CDAInit->getAsString();
3121 
3122     SmallVector<uint8_t,16> V(S.size());
3123     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3124     while (RequiredPadding--)
3125       V.push_back(0);
3126     Init = ConstantDataArray::get(*DAG.getContext(), V);
3127   }
3128 
3129   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3130   SDValue CPAddr =
3131     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3132   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3133     AFI->markGlobalAsPromotedToConstantPool(GVar);
3134     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3135                                       PaddedSize - 4);
3136   }
3137   ++NumConstpoolPromoted;
3138   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3139 }
3140 
3141 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3142   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3143     GV = GA->getBaseObject();
3144   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3145          isa<Function>(GV);
3146 }
3147 
3148 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3149                                               SelectionDAG &DAG) const {
3150   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3151   default: llvm_unreachable("unknown object format");
3152   case Triple::COFF:
3153     return LowerGlobalAddressWindows(Op, DAG);
3154   case Triple::ELF:
3155     return LowerGlobalAddressELF(Op, DAG);
3156   case Triple::MachO:
3157     return LowerGlobalAddressDarwin(Op, DAG);
3158   }
3159 }
3160 
3161 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3162                                                  SelectionDAG &DAG) const {
3163   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3164   SDLoc dl(Op);
3165   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3166   const TargetMachine &TM = getTargetMachine();
3167   bool IsRO = isReadOnly(GV);
3168 
3169   // promoteToConstantPool only if not generating XO text section
3170   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3171     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3172       return V;
3173 
3174   if (isPositionIndependent()) {
3175     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3176 
3177     MachineFunction &MF = DAG.getMachineFunction();
3178     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3179     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3180     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3181     SDLoc dl(Op);
3182     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3183     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3184         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3185         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3186         /*AddCurrentAddress=*/UseGOT_PREL);
3187     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3188     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3189     SDValue Result = DAG.getLoad(
3190         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3191         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3192     SDValue Chain = Result.getValue(1);
3193     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3194     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3195     if (UseGOT_PREL)
3196       Result =
3197           DAG.getLoad(PtrVT, dl, Chain, Result,
3198                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3199     return Result;
3200   } else if (Subtarget->isROPI() && IsRO) {
3201     // PC-relative.
3202     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3203     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3204     return Result;
3205   } else if (Subtarget->isRWPI() && !IsRO) {
3206     // SB-relative.
3207     SDValue RelAddr;
3208     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3209       ++NumMovwMovt;
3210       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3211       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3212     } else { // use literal pool for address constant
3213       ARMConstantPoolValue *CPV =
3214         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3215       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3216       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3217       RelAddr = DAG.getLoad(
3218           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3219           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3220     }
3221     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3222     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3223     return Result;
3224   }
3225 
3226   // If we have T2 ops, we can materialize the address directly via movt/movw
3227   // pair. This is always cheaper.
3228   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3229     ++NumMovwMovt;
3230     // FIXME: Once remat is capable of dealing with instructions with register
3231     // operands, expand this into two nodes.
3232     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3233                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3234   } else {
3235     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3236     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3237     return DAG.getLoad(
3238         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3239         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3240   }
3241 }
3242 
3243 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3244                                                     SelectionDAG &DAG) const {
3245   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3246          "ROPI/RWPI not currently supported for Darwin");
3247   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3248   SDLoc dl(Op);
3249   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3250 
3251   if (Subtarget->useMovt(DAG.getMachineFunction()))
3252     ++NumMovwMovt;
3253 
3254   // FIXME: Once remat is capable of dealing with instructions with register
3255   // operands, expand this into multiple nodes
3256   unsigned Wrapper =
3257       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3258 
3259   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3260   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3261 
3262   if (Subtarget->isGVIndirectSymbol(GV))
3263     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3264                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3265   return Result;
3266 }
3267 
3268 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3269                                                      SelectionDAG &DAG) const {
3270   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3271   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3272          "Windows on ARM expects to use movw/movt");
3273   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3274          "ROPI/RWPI not currently supported for Windows");
3275 
3276   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3277   const ARMII::TOF TargetFlags =
3278     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3279   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3280   SDValue Result;
3281   SDLoc DL(Op);
3282 
3283   ++NumMovwMovt;
3284 
3285   // FIXME: Once remat is capable of dealing with instructions with register
3286   // operands, expand this into two nodes.
3287   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3288                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3289                                                   TargetFlags));
3290   if (GV->hasDLLImportStorageClass())
3291     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3292                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3293   return Result;
3294 }
3295 
3296 SDValue
3297 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3298   SDLoc dl(Op);
3299   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3300   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3301                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3302                      Op.getOperand(1), Val);
3303 }
3304 
3305 SDValue
3306 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3307   SDLoc dl(Op);
3308   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3309                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3310 }
3311 
3312 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3313                                                       SelectionDAG &DAG) const {
3314   SDLoc dl(Op);
3315   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3316                      Op.getOperand(0));
3317 }
3318 
3319 SDValue
3320 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3321                                           const ARMSubtarget *Subtarget) const {
3322   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3323   SDLoc dl(Op);
3324   switch (IntNo) {
3325   default: return SDValue();    // Don't custom lower most intrinsics.
3326   case Intrinsic::thread_pointer: {
3327     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3328     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3329   }
3330   case Intrinsic::eh_sjlj_lsda: {
3331     MachineFunction &MF = DAG.getMachineFunction();
3332     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3333     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3334     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3335     SDValue CPAddr;
3336     bool IsPositionIndependent = isPositionIndependent();
3337     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3338     ARMConstantPoolValue *CPV =
3339       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3340                                       ARMCP::CPLSDA, PCAdj);
3341     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3342     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3343     SDValue Result = DAG.getLoad(
3344         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3345         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3346 
3347     if (IsPositionIndependent) {
3348       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3349       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3350     }
3351     return Result;
3352   }
3353   case Intrinsic::arm_neon_vabs:
3354     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3355                         Op.getOperand(1));
3356   case Intrinsic::arm_neon_vmulls:
3357   case Intrinsic::arm_neon_vmullu: {
3358     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3359       ? ARMISD::VMULLs : ARMISD::VMULLu;
3360     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3361                        Op.getOperand(1), Op.getOperand(2));
3362   }
3363   case Intrinsic::arm_neon_vminnm:
3364   case Intrinsic::arm_neon_vmaxnm: {
3365     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3366       ? ISD::FMINNUM : ISD::FMAXNUM;
3367     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3368                        Op.getOperand(1), Op.getOperand(2));
3369   }
3370   case Intrinsic::arm_neon_vminu:
3371   case Intrinsic::arm_neon_vmaxu: {
3372     if (Op.getValueType().isFloatingPoint())
3373       return SDValue();
3374     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3375       ? ISD::UMIN : ISD::UMAX;
3376     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3377                          Op.getOperand(1), Op.getOperand(2));
3378   }
3379   case Intrinsic::arm_neon_vmins:
3380   case Intrinsic::arm_neon_vmaxs: {
3381     // v{min,max}s is overloaded between signed integers and floats.
3382     if (!Op.getValueType().isFloatingPoint()) {
3383       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3384         ? ISD::SMIN : ISD::SMAX;
3385       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3386                          Op.getOperand(1), Op.getOperand(2));
3387     }
3388     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3389       ? ISD::FMINNAN : ISD::FMAXNAN;
3390     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3391                        Op.getOperand(1), Op.getOperand(2));
3392   }
3393   case Intrinsic::arm_neon_vtbl1:
3394     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3395                        Op.getOperand(1), Op.getOperand(2));
3396   case Intrinsic::arm_neon_vtbl2:
3397     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3398                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3399   }
3400 }
3401 
3402 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3403                                  const ARMSubtarget *Subtarget) {
3404   SDLoc dl(Op);
3405   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3406   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3407   if (SSID == SyncScope::SingleThread)
3408     return Op;
3409 
3410   if (!Subtarget->hasDataBarrier()) {
3411     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3412     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3413     // here.
3414     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3415            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3416     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3417                        DAG.getConstant(0, dl, MVT::i32));
3418   }
3419 
3420   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3421   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3422   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3423   if (Subtarget->isMClass()) {
3424     // Only a full system barrier exists in the M-class architectures.
3425     Domain = ARM_MB::SY;
3426   } else if (Subtarget->preferISHSTBarriers() &&
3427              Ord == AtomicOrdering::Release) {
3428     // Swift happens to implement ISHST barriers in a way that's compatible with
3429     // Release semantics but weaker than ISH so we'd be fools not to use
3430     // it. Beware: other processors probably don't!
3431     Domain = ARM_MB::ISHST;
3432   }
3433 
3434   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3435                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3436                      DAG.getConstant(Domain, dl, MVT::i32));
3437 }
3438 
3439 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3440                              const ARMSubtarget *Subtarget) {
3441   // ARM pre v5TE and Thumb1 does not have preload instructions.
3442   if (!(Subtarget->isThumb2() ||
3443         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3444     // Just preserve the chain.
3445     return Op.getOperand(0);
3446 
3447   SDLoc dl(Op);
3448   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3449   if (!isRead &&
3450       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3451     // ARMv7 with MP extension has PLDW.
3452     return Op.getOperand(0);
3453 
3454   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3455   if (Subtarget->isThumb()) {
3456     // Invert the bits.
3457     isRead = ~isRead & 1;
3458     isData = ~isData & 1;
3459   }
3460 
3461   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3462                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3463                      DAG.getConstant(isData, dl, MVT::i32));
3464 }
3465 
3466 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3467   MachineFunction &MF = DAG.getMachineFunction();
3468   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3469 
3470   // vastart just stores the address of the VarArgsFrameIndex slot into the
3471   // memory location argument.
3472   SDLoc dl(Op);
3473   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3474   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3475   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3476   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3477                       MachinePointerInfo(SV));
3478 }
3479 
3480 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3481                                                 CCValAssign &NextVA,
3482                                                 SDValue &Root,
3483                                                 SelectionDAG &DAG,
3484                                                 const SDLoc &dl) const {
3485   MachineFunction &MF = DAG.getMachineFunction();
3486   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3487 
3488   const TargetRegisterClass *RC;
3489   if (AFI->isThumb1OnlyFunction())
3490     RC = &ARM::tGPRRegClass;
3491   else
3492     RC = &ARM::GPRRegClass;
3493 
3494   // Transform the arguments stored in physical registers into virtual ones.
3495   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3496   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3497 
3498   SDValue ArgValue2;
3499   if (NextVA.isMemLoc()) {
3500     MachineFrameInfo &MFI = MF.getFrameInfo();
3501     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3502 
3503     // Create load node to retrieve arguments from the stack.
3504     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3505     ArgValue2 = DAG.getLoad(
3506         MVT::i32, dl, Root, FIN,
3507         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3508   } else {
3509     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3510     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3511   }
3512   if (!Subtarget->isLittle())
3513     std::swap (ArgValue, ArgValue2);
3514   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3515 }
3516 
3517 // The remaining GPRs hold either the beginning of variable-argument
3518 // data, or the beginning of an aggregate passed by value (usually
3519 // byval).  Either way, we allocate stack slots adjacent to the data
3520 // provided by our caller, and store the unallocated registers there.
3521 // If this is a variadic function, the va_list pointer will begin with
3522 // these values; otherwise, this reassembles a (byval) structure that
3523 // was split between registers and memory.
3524 // Return: The frame index registers were stored into.
3525 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3526                                       const SDLoc &dl, SDValue &Chain,
3527                                       const Value *OrigArg,
3528                                       unsigned InRegsParamRecordIdx,
3529                                       int ArgOffset, unsigned ArgSize) const {
3530   // Currently, two use-cases possible:
3531   // Case #1. Non-var-args function, and we meet first byval parameter.
3532   //          Setup first unallocated register as first byval register;
3533   //          eat all remained registers
3534   //          (these two actions are performed by HandleByVal method).
3535   //          Then, here, we initialize stack frame with
3536   //          "store-reg" instructions.
3537   // Case #2. Var-args function, that doesn't contain byval parameters.
3538   //          The same: eat all remained unallocated registers,
3539   //          initialize stack frame.
3540 
3541   MachineFunction &MF = DAG.getMachineFunction();
3542   MachineFrameInfo &MFI = MF.getFrameInfo();
3543   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3544   unsigned RBegin, REnd;
3545   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3546     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3547   } else {
3548     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3549     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3550     REnd = ARM::R4;
3551   }
3552 
3553   if (REnd != RBegin)
3554     ArgOffset = -4 * (ARM::R4 - RBegin);
3555 
3556   auto PtrVT = getPointerTy(DAG.getDataLayout());
3557   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3558   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3559 
3560   SmallVector<SDValue, 4> MemOps;
3561   const TargetRegisterClass *RC =
3562       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3563 
3564   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3565     unsigned VReg = MF.addLiveIn(Reg, RC);
3566     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3567     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3568                                  MachinePointerInfo(OrigArg, 4 * i));
3569     MemOps.push_back(Store);
3570     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3571   }
3572 
3573   if (!MemOps.empty())
3574     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3575   return FrameIndex;
3576 }
3577 
3578 // Setup stack frame, the va_list pointer will start from.
3579 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3580                                              const SDLoc &dl, SDValue &Chain,
3581                                              unsigned ArgOffset,
3582                                              unsigned TotalArgRegsSaveSize,
3583                                              bool ForceMutable) const {
3584   MachineFunction &MF = DAG.getMachineFunction();
3585   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3586 
3587   // Try to store any remaining integer argument regs
3588   // to their spots on the stack so that they may be loaded by dereferencing
3589   // the result of va_next.
3590   // If there is no regs to be stored, just point address after last
3591   // argument passed via stack.
3592   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3593                                   CCInfo.getInRegsParamsCount(),
3594                                   CCInfo.getNextStackOffset(), 4);
3595   AFI->setVarArgsFrameIndex(FrameIndex);
3596 }
3597 
3598 SDValue ARMTargetLowering::LowerFormalArguments(
3599     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3600     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3601     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3602   MachineFunction &MF = DAG.getMachineFunction();
3603   MachineFrameInfo &MFI = MF.getFrameInfo();
3604 
3605   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3606 
3607   // Assign locations to all of the incoming arguments.
3608   SmallVector<CCValAssign, 16> ArgLocs;
3609   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3610                  *DAG.getContext());
3611   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3612 
3613   SmallVector<SDValue, 16> ArgValues;
3614   SDValue ArgValue;
3615   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3616   unsigned CurArgIdx = 0;
3617 
3618   // Initially ArgRegsSaveSize is zero.
3619   // Then we increase this value each time we meet byval parameter.
3620   // We also increase this value in case of varargs function.
3621   AFI->setArgRegsSaveSize(0);
3622 
3623   // Calculate the amount of stack space that we need to allocate to store
3624   // byval and variadic arguments that are passed in registers.
3625   // We need to know this before we allocate the first byval or variadic
3626   // argument, as they will be allocated a stack slot below the CFA (Canonical
3627   // Frame Address, the stack pointer at entry to the function).
3628   unsigned ArgRegBegin = ARM::R4;
3629   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3630     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3631       break;
3632 
3633     CCValAssign &VA = ArgLocs[i];
3634     unsigned Index = VA.getValNo();
3635     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3636     if (!Flags.isByVal())
3637       continue;
3638 
3639     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3640     unsigned RBegin, REnd;
3641     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3642     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3643 
3644     CCInfo.nextInRegsParam();
3645   }
3646   CCInfo.rewindByValRegsInfo();
3647 
3648   int lastInsIndex = -1;
3649   if (isVarArg && MFI.hasVAStart()) {
3650     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3651     if (RegIdx != array_lengthof(GPRArgRegs))
3652       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3653   }
3654 
3655   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3656   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3657   auto PtrVT = getPointerTy(DAG.getDataLayout());
3658 
3659   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3660     CCValAssign &VA = ArgLocs[i];
3661     if (Ins[VA.getValNo()].isOrigArg()) {
3662       std::advance(CurOrigArg,
3663                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3664       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3665     }
3666     // Arguments stored in registers.
3667     if (VA.isRegLoc()) {
3668       EVT RegVT = VA.getLocVT();
3669 
3670       if (VA.needsCustom()) {
3671         // f64 and vector types are split up into multiple registers or
3672         // combinations of registers and stack slots.
3673         if (VA.getLocVT() == MVT::v2f64) {
3674           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3675                                                    Chain, DAG, dl);
3676           VA = ArgLocs[++i]; // skip ahead to next loc
3677           SDValue ArgValue2;
3678           if (VA.isMemLoc()) {
3679             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3680             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3681             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3682                                     MachinePointerInfo::getFixedStack(
3683                                         DAG.getMachineFunction(), FI));
3684           } else {
3685             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3686                                              Chain, DAG, dl);
3687           }
3688           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3689           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3690                                  ArgValue, ArgValue1,
3691                                  DAG.getIntPtrConstant(0, dl));
3692           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3693                                  ArgValue, ArgValue2,
3694                                  DAG.getIntPtrConstant(1, dl));
3695         } else
3696           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3697 
3698       } else {
3699         const TargetRegisterClass *RC;
3700 
3701         if (RegVT == MVT::f32)
3702           RC = &ARM::SPRRegClass;
3703         else if (RegVT == MVT::f64)
3704           RC = &ARM::DPRRegClass;
3705         else if (RegVT == MVT::v2f64)
3706           RC = &ARM::QPRRegClass;
3707         else if (RegVT == MVT::i32)
3708           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3709                                            : &ARM::GPRRegClass;
3710         else
3711           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3712 
3713         // Transform the arguments in physical registers into virtual ones.
3714         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3715         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3716       }
3717 
3718       // If this is an 8 or 16-bit value, it is really passed promoted
3719       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3720       // truncate to the right size.
3721       switch (VA.getLocInfo()) {
3722       default: llvm_unreachable("Unknown loc info!");
3723       case CCValAssign::Full: break;
3724       case CCValAssign::BCvt:
3725         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3726         break;
3727       case CCValAssign::SExt:
3728         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3729                                DAG.getValueType(VA.getValVT()));
3730         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3731         break;
3732       case CCValAssign::ZExt:
3733         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3734                                DAG.getValueType(VA.getValVT()));
3735         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3736         break;
3737       }
3738 
3739       InVals.push_back(ArgValue);
3740 
3741     } else { // VA.isRegLoc()
3742       // sanity check
3743       assert(VA.isMemLoc());
3744       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3745 
3746       int index = VA.getValNo();
3747 
3748       // Some Ins[] entries become multiple ArgLoc[] entries.
3749       // Process them only once.
3750       if (index != lastInsIndex)
3751         {
3752           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3753           // FIXME: For now, all byval parameter objects are marked mutable.
3754           // This can be changed with more analysis.
3755           // In case of tail call optimization mark all arguments mutable.
3756           // Since they could be overwritten by lowering of arguments in case of
3757           // a tail call.
3758           if (Flags.isByVal()) {
3759             assert(Ins[index].isOrigArg() &&
3760                    "Byval arguments cannot be implicit");
3761             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3762 
3763             int FrameIndex = StoreByValRegs(
3764                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3765                 VA.getLocMemOffset(), Flags.getByValSize());
3766             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3767             CCInfo.nextInRegsParam();
3768           } else {
3769             unsigned FIOffset = VA.getLocMemOffset();
3770             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3771                                            FIOffset, true);
3772 
3773             // Create load nodes to retrieve arguments from the stack.
3774             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3775             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3776                                          MachinePointerInfo::getFixedStack(
3777                                              DAG.getMachineFunction(), FI)));
3778           }
3779           lastInsIndex = index;
3780         }
3781     }
3782   }
3783 
3784   // varargs
3785   if (isVarArg && MFI.hasVAStart())
3786     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3787                          CCInfo.getNextStackOffset(),
3788                          TotalArgRegsSaveSize);
3789 
3790   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3791 
3792   return Chain;
3793 }
3794 
3795 /// isFloatingPointZero - Return true if this is +0.0.
3796 static bool isFloatingPointZero(SDValue Op) {
3797   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3798     return CFP->getValueAPF().isPosZero();
3799   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3800     // Maybe this has already been legalized into the constant pool?
3801     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3802       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3803       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3804         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3805           return CFP->getValueAPF().isPosZero();
3806     }
3807   } else if (Op->getOpcode() == ISD::BITCAST &&
3808              Op->getValueType(0) == MVT::f64) {
3809     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3810     // created by LowerConstantFP().
3811     SDValue BitcastOp = Op->getOperand(0);
3812     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3813         isNullConstant(BitcastOp->getOperand(0)))
3814       return true;
3815   }
3816   return false;
3817 }
3818 
3819 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3820 /// the given operands.
3821 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3822                                      SDValue &ARMcc, SelectionDAG &DAG,
3823                                      const SDLoc &dl) const {
3824   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3825     unsigned C = RHSC->getZExtValue();
3826     if (!isLegalICmpImmediate(C)) {
3827       // Constant does not fit, try adjusting it by one?
3828       switch (CC) {
3829       default: break;
3830       case ISD::SETLT:
3831       case ISD::SETGE:
3832         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3833           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3834           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3835         }
3836         break;
3837       case ISD::SETULT:
3838       case ISD::SETUGE:
3839         if (C != 0 && isLegalICmpImmediate(C-1)) {
3840           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3841           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3842         }
3843         break;
3844       case ISD::SETLE:
3845       case ISD::SETGT:
3846         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3847           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3848           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3849         }
3850         break;
3851       case ISD::SETULE:
3852       case ISD::SETUGT:
3853         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3854           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3855           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3856         }
3857         break;
3858       }
3859     }
3860   }
3861 
3862   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3863   ARMISD::NodeType CompareType;
3864   switch (CondCode) {
3865   default:
3866     CompareType = ARMISD::CMP;
3867     break;
3868   case ARMCC::EQ:
3869   case ARMCC::NE:
3870     // Uses only Z Flag
3871     CompareType = ARMISD::CMPZ;
3872     break;
3873   }
3874   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3875   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3876 }
3877 
3878 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3879 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3880                                      SelectionDAG &DAG, const SDLoc &dl,
3881                                      bool InvalidOnQNaN) const {
3882   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3883   SDValue Cmp;
3884   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3885   if (!isFloatingPointZero(RHS))
3886     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3887   else
3888     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3889   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3890 }
3891 
3892 /// duplicateCmp - Glue values can have only one use, so this function
3893 /// duplicates a comparison node.
3894 SDValue
3895 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3896   unsigned Opc = Cmp.getOpcode();
3897   SDLoc DL(Cmp);
3898   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3899     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3900 
3901   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3902   Cmp = Cmp.getOperand(0);
3903   Opc = Cmp.getOpcode();
3904   if (Opc == ARMISD::CMPFP)
3905     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3906                       Cmp.getOperand(1), Cmp.getOperand(2));
3907   else {
3908     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3909     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3910                       Cmp.getOperand(1));
3911   }
3912   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3913 }
3914 
3915 std::pair<SDValue, SDValue>
3916 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3917                                  SDValue &ARMcc) const {
3918   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3919 
3920   SDValue Value, OverflowCmp;
3921   SDValue LHS = Op.getOperand(0);
3922   SDValue RHS = Op.getOperand(1);
3923   SDLoc dl(Op);
3924 
3925   // FIXME: We are currently always generating CMPs because we don't support
3926   // generating CMN through the backend. This is not as good as the natural
3927   // CMP case because it causes a register dependency and cannot be folded
3928   // later.
3929 
3930   switch (Op.getOpcode()) {
3931   default:
3932     llvm_unreachable("Unknown overflow instruction!");
3933   case ISD::SADDO:
3934     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3935     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3936     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3937     break;
3938   case ISD::UADDO:
3939     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3940     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3941     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3942     break;
3943   case ISD::SSUBO:
3944     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3945     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3946     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3947     break;
3948   case ISD::USUBO:
3949     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3950     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3951     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3952     break;
3953   } // switch (...)
3954 
3955   return std::make_pair(Value, OverflowCmp);
3956 }
3957 
3958 SDValue
3959 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
3960   // Let legalize expand this if it isn't a legal type yet.
3961   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3962     return SDValue();
3963 
3964   SDValue Value, OverflowCmp;
3965   SDValue ARMcc;
3966   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3967   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3968   SDLoc dl(Op);
3969   // We use 0 and 1 as false and true values.
3970   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3971   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3972   EVT VT = Op.getValueType();
3973 
3974   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3975                                  ARMcc, CCR, OverflowCmp);
3976 
3977   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3978   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3979 }
3980 
3981 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
3982                                               SelectionDAG &DAG) {
3983   SDLoc DL(BoolCarry);
3984   EVT CarryVT = BoolCarry.getValueType();
3985 
3986   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
3987   // This converts the boolean value carry into the carry flag by doing
3988   // ARMISD::ADDC Carry, ~0
3989   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
3990                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
3991 }
3992 
3993 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
3994                                               SelectionDAG &DAG) {
3995   SDLoc DL(Flags);
3996 
3997   // Now convert the carry flag into a boolean carry. We do this
3998   // using ARMISD:ADDE 0, 0, Carry
3999   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4000                      DAG.getConstant(0, DL, MVT::i32),
4001                      DAG.getConstant(0, DL, MVT::i32), Flags);
4002 }
4003 
4004 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4005                                              SelectionDAG &DAG) const {
4006   // Let legalize expand this if it isn't a legal type yet.
4007   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4008     return SDValue();
4009 
4010   SDValue LHS = Op.getOperand(0);
4011   SDValue RHS = Op.getOperand(1);
4012   SDLoc dl(Op);
4013 
4014   EVT VT = Op.getValueType();
4015   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4016   SDValue Value;
4017   SDValue Overflow;
4018   switch (Op.getOpcode()) {
4019   default:
4020     llvm_unreachable("Unknown overflow instruction!");
4021   case ISD::UADDO:
4022     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4023     // Convert the carry flag into a boolean value.
4024     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4025     break;
4026   case ISD::USUBO: {
4027     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4028     // Convert the carry flag into a boolean value.
4029     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4030     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4031     // value. So compute 1 - C.
4032     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4033                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4034     break;
4035   }
4036   }
4037 
4038   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4039 }
4040 
4041 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4042   SDValue Cond = Op.getOperand(0);
4043   SDValue SelectTrue = Op.getOperand(1);
4044   SDValue SelectFalse = Op.getOperand(2);
4045   SDLoc dl(Op);
4046   unsigned Opc = Cond.getOpcode();
4047 
4048   if (Cond.getResNo() == 1 &&
4049       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4050        Opc == ISD::USUBO)) {
4051     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4052       return SDValue();
4053 
4054     SDValue Value, OverflowCmp;
4055     SDValue ARMcc;
4056     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4057     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4058     EVT VT = Op.getValueType();
4059 
4060     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4061                    OverflowCmp, DAG);
4062   }
4063 
4064   // Convert:
4065   //
4066   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4067   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4068   //
4069   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4070     const ConstantSDNode *CMOVTrue =
4071       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4072     const ConstantSDNode *CMOVFalse =
4073       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4074 
4075     if (CMOVTrue && CMOVFalse) {
4076       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4077       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4078 
4079       SDValue True;
4080       SDValue False;
4081       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4082         True = SelectTrue;
4083         False = SelectFalse;
4084       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4085         True = SelectFalse;
4086         False = SelectTrue;
4087       }
4088 
4089       if (True.getNode() && False.getNode()) {
4090         EVT VT = Op.getValueType();
4091         SDValue ARMcc = Cond.getOperand(2);
4092         SDValue CCR = Cond.getOperand(3);
4093         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4094         assert(True.getValueType() == VT);
4095         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4096       }
4097     }
4098   }
4099 
4100   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4101   // undefined bits before doing a full-word comparison with zero.
4102   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4103                      DAG.getConstant(1, dl, Cond.getValueType()));
4104 
4105   return DAG.getSelectCC(dl, Cond,
4106                          DAG.getConstant(0, dl, Cond.getValueType()),
4107                          SelectTrue, SelectFalse, ISD::SETNE);
4108 }
4109 
4110 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4111                                  bool &swpCmpOps, bool &swpVselOps) {
4112   // Start by selecting the GE condition code for opcodes that return true for
4113   // 'equality'
4114   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4115       CC == ISD::SETULE)
4116     CondCode = ARMCC::GE;
4117 
4118   // and GT for opcodes that return false for 'equality'.
4119   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4120            CC == ISD::SETULT)
4121     CondCode = ARMCC::GT;
4122 
4123   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4124   // to swap the compare operands.
4125   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4126       CC == ISD::SETULT)
4127     swpCmpOps = true;
4128 
4129   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4130   // If we have an unordered opcode, we need to swap the operands to the VSEL
4131   // instruction (effectively negating the condition).
4132   //
4133   // This also has the effect of swapping which one of 'less' or 'greater'
4134   // returns true, so we also swap the compare operands. It also switches
4135   // whether we return true for 'equality', so we compensate by picking the
4136   // opposite condition code to our original choice.
4137   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4138       CC == ISD::SETUGT) {
4139     swpCmpOps = !swpCmpOps;
4140     swpVselOps = !swpVselOps;
4141     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4142   }
4143 
4144   // 'ordered' is 'anything but unordered', so use the VS condition code and
4145   // swap the VSEL operands.
4146   if (CC == ISD::SETO) {
4147     CondCode = ARMCC::VS;
4148     swpVselOps = true;
4149   }
4150 
4151   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4152   // code and swap the VSEL operands.
4153   if (CC == ISD::SETUNE) {
4154     CondCode = ARMCC::EQ;
4155     swpVselOps = true;
4156   }
4157 }
4158 
4159 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4160                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4161                                    SDValue Cmp, SelectionDAG &DAG) const {
4162   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4163     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4164                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4165     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4166                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4167 
4168     SDValue TrueLow = TrueVal.getValue(0);
4169     SDValue TrueHigh = TrueVal.getValue(1);
4170     SDValue FalseLow = FalseVal.getValue(0);
4171     SDValue FalseHigh = FalseVal.getValue(1);
4172 
4173     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4174                               ARMcc, CCR, Cmp);
4175     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4176                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4177 
4178     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4179   } else {
4180     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4181                        Cmp);
4182   }
4183 }
4184 
4185 static bool isGTorGE(ISD::CondCode CC) {
4186   return CC == ISD::SETGT || CC == ISD::SETGE;
4187 }
4188 
4189 static bool isLTorLE(ISD::CondCode CC) {
4190   return CC == ISD::SETLT || CC == ISD::SETLE;
4191 }
4192 
4193 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4194 // All of these conditions (and their <= and >= counterparts) will do:
4195 //          x < k ? k : x
4196 //          x > k ? x : k
4197 //          k < x ? x : k
4198 //          k > x ? k : x
4199 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4200                             const SDValue TrueVal, const SDValue FalseVal,
4201                             const ISD::CondCode CC, const SDValue K) {
4202   return (isGTorGE(CC) &&
4203           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4204          (isLTorLE(CC) &&
4205           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4206 }
4207 
4208 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4209 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4210                             const SDValue TrueVal, const SDValue FalseVal,
4211                             const ISD::CondCode CC, const SDValue K) {
4212   return (isGTorGE(CC) &&
4213           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4214          (isLTorLE(CC) &&
4215           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4216 }
4217 
4218 // Check if two chained conditionals could be converted into SSAT.
4219 //
4220 // SSAT can replace a set of two conditional selectors that bound a number to an
4221 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4222 //
4223 //     x < -k ? -k : (x > k ? k : x)
4224 //     x < -k ? -k : (x < k ? x : k)
4225 //     x > -k ? (x > k ? k : x) : -k
4226 //     x < k ? (x < -k ? -k : x) : k
4227 //     etc.
4228 //
4229 // It returns true if the conversion can be done, false otherwise.
4230 // Additionally, the variable is returned in parameter V and the constant in K.
4231 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4232                                     uint64_t &K) {
4233   SDValue LHS1 = Op.getOperand(0);
4234   SDValue RHS1 = Op.getOperand(1);
4235   SDValue TrueVal1 = Op.getOperand(2);
4236   SDValue FalseVal1 = Op.getOperand(3);
4237   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4238 
4239   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4240   if (Op2.getOpcode() != ISD::SELECT_CC)
4241     return false;
4242 
4243   SDValue LHS2 = Op2.getOperand(0);
4244   SDValue RHS2 = Op2.getOperand(1);
4245   SDValue TrueVal2 = Op2.getOperand(2);
4246   SDValue FalseVal2 = Op2.getOperand(3);
4247   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4248 
4249   // Find out which are the constants and which are the variables
4250   // in each conditional
4251   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4252                                                         ? &RHS1
4253                                                         : nullptr;
4254   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4255                                                         ? &RHS2
4256                                                         : nullptr;
4257   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4258   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4259   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4260   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4261 
4262   // We must detect cases where the original operations worked with 16- or
4263   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4264   // must work with sign-extended values but the select operations return
4265   // the original non-extended value.
4266   SDValue V2TmpReg = V2Tmp;
4267   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4268     V2TmpReg = V2Tmp->getOperand(0);
4269 
4270   // Check that the registers and the constants have the correct values
4271   // in both conditionals
4272   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4273       V2TmpReg != V2)
4274     return false;
4275 
4276   // Figure out which conditional is saturating the lower/upper bound.
4277   const SDValue *LowerCheckOp =
4278       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4279           ? &Op
4280           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4281                 ? &Op2
4282                 : nullptr;
4283   const SDValue *UpperCheckOp =
4284       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4285           ? &Op
4286           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4287                 ? &Op2
4288                 : nullptr;
4289 
4290   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4291     return false;
4292 
4293   // Check that the constant in the lower-bound check is
4294   // the opposite of the constant in the upper-bound check
4295   // in 1's complement.
4296   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4297   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4298   int64_t PosVal = std::max(Val1, Val2);
4299 
4300   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4301        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4302       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4303 
4304     V = V2;
4305     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4306     return true;
4307   }
4308 
4309   return false;
4310 }
4311 
4312 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4313   EVT VT = Op.getValueType();
4314   SDLoc dl(Op);
4315 
4316   // Try to convert two saturating conditional selects into a single SSAT
4317   SDValue SatValue;
4318   uint64_t SatConstant;
4319   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4320       isSaturatingConditional(Op, SatValue, SatConstant))
4321     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4322                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4323 
4324   SDValue LHS = Op.getOperand(0);
4325   SDValue RHS = Op.getOperand(1);
4326   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4327   SDValue TrueVal = Op.getOperand(2);
4328   SDValue FalseVal = Op.getOperand(3);
4329 
4330   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4331     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4332                                                     dl);
4333 
4334     // If softenSetCCOperands only returned one value, we should compare it to
4335     // zero.
4336     if (!RHS.getNode()) {
4337       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4338       CC = ISD::SETNE;
4339     }
4340   }
4341 
4342   if (LHS.getValueType() == MVT::i32) {
4343     // Try to generate VSEL on ARMv8.
4344     // The VSEL instruction can't use all the usual ARM condition
4345     // codes: it only has two bits to select the condition code, so it's
4346     // constrained to use only GE, GT, VS and EQ.
4347     //
4348     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4349     // swap the operands of the previous compare instruction (effectively
4350     // inverting the compare condition, swapping 'less' and 'greater') and
4351     // sometimes need to swap the operands to the VSEL (which inverts the
4352     // condition in the sense of firing whenever the previous condition didn't)
4353     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4354                                     TrueVal.getValueType() == MVT::f64)) {
4355       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4356       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4357           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4358         CC = ISD::getSetCCInverse(CC, true);
4359         std::swap(TrueVal, FalseVal);
4360       }
4361     }
4362 
4363     SDValue ARMcc;
4364     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4365     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4366     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4367   }
4368 
4369   ARMCC::CondCodes CondCode, CondCode2;
4370   bool InvalidOnQNaN;
4371   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4372 
4373   // Try to generate VMAXNM/VMINNM on ARMv8.
4374   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4375                                   TrueVal.getValueType() == MVT::f64)) {
4376     bool swpCmpOps = false;
4377     bool swpVselOps = false;
4378     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4379 
4380     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4381         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4382       if (swpCmpOps)
4383         std::swap(LHS, RHS);
4384       if (swpVselOps)
4385         std::swap(TrueVal, FalseVal);
4386     }
4387   }
4388 
4389   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4390   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4391   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4392   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4393   if (CondCode2 != ARMCC::AL) {
4394     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4395     // FIXME: Needs another CMP because flag can have but one use.
4396     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4397     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4398   }
4399   return Result;
4400 }
4401 
4402 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4403 /// to morph to an integer compare sequence.
4404 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4405                            const ARMSubtarget *Subtarget) {
4406   SDNode *N = Op.getNode();
4407   if (!N->hasOneUse())
4408     // Otherwise it requires moving the value from fp to integer registers.
4409     return false;
4410   if (!N->getNumValues())
4411     return false;
4412   EVT VT = Op.getValueType();
4413   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4414     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4415     // vmrs are very slow, e.g. cortex-a8.
4416     return false;
4417 
4418   if (isFloatingPointZero(Op)) {
4419     SeenZero = true;
4420     return true;
4421   }
4422   return ISD::isNormalLoad(N);
4423 }
4424 
4425 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4426   if (isFloatingPointZero(Op))
4427     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4428 
4429   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4430     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4431                        Ld->getPointerInfo(), Ld->getAlignment(),
4432                        Ld->getMemOperand()->getFlags());
4433 
4434   llvm_unreachable("Unknown VFP cmp argument!");
4435 }
4436 
4437 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4438                            SDValue &RetVal1, SDValue &RetVal2) {
4439   SDLoc dl(Op);
4440 
4441   if (isFloatingPointZero(Op)) {
4442     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4443     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4444     return;
4445   }
4446 
4447   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4448     SDValue Ptr = Ld->getBasePtr();
4449     RetVal1 =
4450         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4451                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4452 
4453     EVT PtrType = Ptr.getValueType();
4454     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4455     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4456                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4457     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4458                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4459                           Ld->getMemOperand()->getFlags());
4460     return;
4461   }
4462 
4463   llvm_unreachable("Unknown VFP cmp argument!");
4464 }
4465 
4466 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4467 /// f32 and even f64 comparisons to integer ones.
4468 SDValue
4469 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4470   SDValue Chain = Op.getOperand(0);
4471   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4472   SDValue LHS = Op.getOperand(2);
4473   SDValue RHS = Op.getOperand(3);
4474   SDValue Dest = Op.getOperand(4);
4475   SDLoc dl(Op);
4476 
4477   bool LHSSeenZero = false;
4478   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4479   bool RHSSeenZero = false;
4480   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4481   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4482     // If unsafe fp math optimization is enabled and there are no other uses of
4483     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4484     // to an integer comparison.
4485     if (CC == ISD::SETOEQ)
4486       CC = ISD::SETEQ;
4487     else if (CC == ISD::SETUNE)
4488       CC = ISD::SETNE;
4489 
4490     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4491     SDValue ARMcc;
4492     if (LHS.getValueType() == MVT::f32) {
4493       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4494                         bitcastf32Toi32(LHS, DAG), Mask);
4495       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4496                         bitcastf32Toi32(RHS, DAG), Mask);
4497       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4498       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4499       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4500                          Chain, Dest, ARMcc, CCR, Cmp);
4501     }
4502 
4503     SDValue LHS1, LHS2;
4504     SDValue RHS1, RHS2;
4505     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4506     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4507     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4508     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4509     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4510     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4511     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4512     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4513     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4514   }
4515 
4516   return SDValue();
4517 }
4518 
4519 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4520   SDValue Chain = Op.getOperand(0);
4521   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4522   SDValue LHS = Op.getOperand(2);
4523   SDValue RHS = Op.getOperand(3);
4524   SDValue Dest = Op.getOperand(4);
4525   SDLoc dl(Op);
4526 
4527   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4528     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4529                                                     dl);
4530 
4531     // If softenSetCCOperands only returned one value, we should compare it to
4532     // zero.
4533     if (!RHS.getNode()) {
4534       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4535       CC = ISD::SETNE;
4536     }
4537   }
4538 
4539   if (LHS.getValueType() == MVT::i32) {
4540     SDValue ARMcc;
4541     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4542     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4543     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4544                        Chain, Dest, ARMcc, CCR, Cmp);
4545   }
4546 
4547   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4548 
4549   if (getTargetMachine().Options.UnsafeFPMath &&
4550       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4551        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4552     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4553       return Result;
4554   }
4555 
4556   ARMCC::CondCodes CondCode, CondCode2;
4557   bool InvalidOnQNaN;
4558   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4559 
4560   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4561   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4562   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4563   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4564   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4565   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4566   if (CondCode2 != ARMCC::AL) {
4567     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4568     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4569     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4570   }
4571   return Res;
4572 }
4573 
4574 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4575   SDValue Chain = Op.getOperand(0);
4576   SDValue Table = Op.getOperand(1);
4577   SDValue Index = Op.getOperand(2);
4578   SDLoc dl(Op);
4579 
4580   EVT PTy = getPointerTy(DAG.getDataLayout());
4581   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4582   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4583   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4584   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4585   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4586   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4587     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4588     // which does another jump to the destination. This also makes it easier
4589     // to translate it to TBB / TBH later (Thumb2 only).
4590     // FIXME: This might not work if the function is extremely large.
4591     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4592                        Addr, Op.getOperand(2), JTI);
4593   }
4594   if (isPositionIndependent() || Subtarget->isROPI()) {
4595     Addr =
4596         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4597                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4598     Chain = Addr.getValue(1);
4599     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4600     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4601   } else {
4602     Addr =
4603         DAG.getLoad(PTy, dl, Chain, Addr,
4604                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4605     Chain = Addr.getValue(1);
4606     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4607   }
4608 }
4609 
4610 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4611   EVT VT = Op.getValueType();
4612   SDLoc dl(Op);
4613 
4614   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4615     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4616       return Op;
4617     return DAG.UnrollVectorOp(Op.getNode());
4618   }
4619 
4620   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4621          "Invalid type for custom lowering!");
4622   if (VT != MVT::v4i16)
4623     return DAG.UnrollVectorOp(Op.getNode());
4624 
4625   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4626   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4627 }
4628 
4629 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4630   EVT VT = Op.getValueType();
4631   if (VT.isVector())
4632     return LowerVectorFP_TO_INT(Op, DAG);
4633   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4634     RTLIB::Libcall LC;
4635     if (Op.getOpcode() == ISD::FP_TO_SINT)
4636       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4637                               Op.getValueType());
4638     else
4639       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4640                               Op.getValueType());
4641     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4642                        /*isSigned*/ false, SDLoc(Op)).first;
4643   }
4644 
4645   return Op;
4646 }
4647 
4648 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4649   EVT VT = Op.getValueType();
4650   SDLoc dl(Op);
4651 
4652   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4653     if (VT.getVectorElementType() == MVT::f32)
4654       return Op;
4655     return DAG.UnrollVectorOp(Op.getNode());
4656   }
4657 
4658   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4659          "Invalid type for custom lowering!");
4660   if (VT != MVT::v4f32)
4661     return DAG.UnrollVectorOp(Op.getNode());
4662 
4663   unsigned CastOpc;
4664   unsigned Opc;
4665   switch (Op.getOpcode()) {
4666   default: llvm_unreachable("Invalid opcode!");
4667   case ISD::SINT_TO_FP:
4668     CastOpc = ISD::SIGN_EXTEND;
4669     Opc = ISD::SINT_TO_FP;
4670     break;
4671   case ISD::UINT_TO_FP:
4672     CastOpc = ISD::ZERO_EXTEND;
4673     Opc = ISD::UINT_TO_FP;
4674     break;
4675   }
4676 
4677   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4678   return DAG.getNode(Opc, dl, VT, Op);
4679 }
4680 
4681 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4682   EVT VT = Op.getValueType();
4683   if (VT.isVector())
4684     return LowerVectorINT_TO_FP(Op, DAG);
4685   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4686     RTLIB::Libcall LC;
4687     if (Op.getOpcode() == ISD::SINT_TO_FP)
4688       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4689                               Op.getValueType());
4690     else
4691       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4692                               Op.getValueType());
4693     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4694                        /*isSigned*/ false, SDLoc(Op)).first;
4695   }
4696 
4697   return Op;
4698 }
4699 
4700 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4701   // Implement fcopysign with a fabs and a conditional fneg.
4702   SDValue Tmp0 = Op.getOperand(0);
4703   SDValue Tmp1 = Op.getOperand(1);
4704   SDLoc dl(Op);
4705   EVT VT = Op.getValueType();
4706   EVT SrcVT = Tmp1.getValueType();
4707   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4708     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4709   bool UseNEON = !InGPR && Subtarget->hasNEON();
4710 
4711   if (UseNEON) {
4712     // Use VBSL to copy the sign bit.
4713     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4714     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4715                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4716     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4717     if (VT == MVT::f64)
4718       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4719                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4720                          DAG.getConstant(32, dl, MVT::i32));
4721     else /*if (VT == MVT::f32)*/
4722       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4723     if (SrcVT == MVT::f32) {
4724       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4725       if (VT == MVT::f64)
4726         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4727                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4728                            DAG.getConstant(32, dl, MVT::i32));
4729     } else if (VT == MVT::f32)
4730       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4731                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4732                          DAG.getConstant(32, dl, MVT::i32));
4733     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4734     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4735 
4736     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4737                                             dl, MVT::i32);
4738     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4739     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4740                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4741 
4742     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4743                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4744                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4745     if (VT == MVT::f32) {
4746       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4747       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4748                         DAG.getConstant(0, dl, MVT::i32));
4749     } else {
4750       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4751     }
4752 
4753     return Res;
4754   }
4755 
4756   // Bitcast operand 1 to i32.
4757   if (SrcVT == MVT::f64)
4758     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4759                        Tmp1).getValue(1);
4760   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4761 
4762   // Or in the signbit with integer operations.
4763   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4764   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4765   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4766   if (VT == MVT::f32) {
4767     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4768                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4769     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4770                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4771   }
4772 
4773   // f64: Or the high part with signbit and then combine two parts.
4774   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4775                      Tmp0);
4776   SDValue Lo = Tmp0.getValue(0);
4777   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4778   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4779   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4780 }
4781 
4782 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4783   MachineFunction &MF = DAG.getMachineFunction();
4784   MachineFrameInfo &MFI = MF.getFrameInfo();
4785   MFI.setReturnAddressIsTaken(true);
4786 
4787   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4788     return SDValue();
4789 
4790   EVT VT = Op.getValueType();
4791   SDLoc dl(Op);
4792   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4793   if (Depth) {
4794     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4795     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4796     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4797                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4798                        MachinePointerInfo());
4799   }
4800 
4801   // Return LR, which contains the return address. Mark it an implicit live-in.
4802   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4803   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4804 }
4805 
4806 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4807   const ARMBaseRegisterInfo &ARI =
4808     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4809   MachineFunction &MF = DAG.getMachineFunction();
4810   MachineFrameInfo &MFI = MF.getFrameInfo();
4811   MFI.setFrameAddressIsTaken(true);
4812 
4813   EVT VT = Op.getValueType();
4814   SDLoc dl(Op);  // FIXME probably not meaningful
4815   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4816   unsigned FrameReg = ARI.getFrameRegister(MF);
4817   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4818   while (Depth--)
4819     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4820                             MachinePointerInfo());
4821   return FrameAddr;
4822 }
4823 
4824 // FIXME? Maybe this could be a TableGen attribute on some registers and
4825 // this table could be generated automatically from RegInfo.
4826 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4827                                               SelectionDAG &DAG) const {
4828   unsigned Reg = StringSwitch<unsigned>(RegName)
4829                        .Case("sp", ARM::SP)
4830                        .Default(0);
4831   if (Reg)
4832     return Reg;
4833   report_fatal_error(Twine("Invalid register name \""
4834                               + StringRef(RegName)  + "\"."));
4835 }
4836 
4837 // Result is 64 bit value so split into two 32 bit values and return as a
4838 // pair of values.
4839 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4840                                 SelectionDAG &DAG) {
4841   SDLoc DL(N);
4842 
4843   // This function is only supposed to be called for i64 type destination.
4844   assert(N->getValueType(0) == MVT::i64
4845           && "ExpandREAD_REGISTER called for non-i64 type result.");
4846 
4847   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4848                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4849                              N->getOperand(0),
4850                              N->getOperand(1));
4851 
4852   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4853                     Read.getValue(1)));
4854   Results.push_back(Read.getOperand(0));
4855 }
4856 
4857 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4858 /// When \p DstVT, the destination type of \p BC, is on the vector
4859 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4860 /// it might be possible to combine them, such that everything stays on the
4861 /// vector register bank.
4862 /// \p return The node that would replace \p BT, if the combine
4863 /// is possible.
4864 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4865                                                 SelectionDAG &DAG) {
4866   SDValue Op = BC->getOperand(0);
4867   EVT DstVT = BC->getValueType(0);
4868 
4869   // The only vector instruction that can produce a scalar (remember,
4870   // since the bitcast was about to be turned into VMOVDRR, the source
4871   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4872   // Moreover, we can do this combine only if there is one use.
4873   // Finally, if the destination type is not a vector, there is not
4874   // much point on forcing everything on the vector bank.
4875   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4876       !Op.hasOneUse())
4877     return SDValue();
4878 
4879   // If the index is not constant, we will introduce an additional
4880   // multiply that will stick.
4881   // Give up in that case.
4882   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4883   if (!Index)
4884     return SDValue();
4885   unsigned DstNumElt = DstVT.getVectorNumElements();
4886 
4887   // Compute the new index.
4888   const APInt &APIntIndex = Index->getAPIntValue();
4889   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4890   NewIndex *= APIntIndex;
4891   // Check if the new constant index fits into i32.
4892   if (NewIndex.getBitWidth() > 32)
4893     return SDValue();
4894 
4895   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4896   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4897   SDLoc dl(Op);
4898   SDValue ExtractSrc = Op.getOperand(0);
4899   EVT VecVT = EVT::getVectorVT(
4900       *DAG.getContext(), DstVT.getScalarType(),
4901       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4902   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4903   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4904                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4905 }
4906 
4907 /// ExpandBITCAST - If the target supports VFP, this function is called to
4908 /// expand a bit convert where either the source or destination type is i64 to
4909 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4910 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4911 /// vectors), since the legalizer won't know what to do with that.
4912 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4914   SDLoc dl(N);
4915   SDValue Op = N->getOperand(0);
4916 
4917   // This function is only supposed to be called for i64 types, either as the
4918   // source or destination of the bit convert.
4919   EVT SrcVT = Op.getValueType();
4920   EVT DstVT = N->getValueType(0);
4921   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4922          "ExpandBITCAST called for non-i64 type");
4923 
4924   // Turn i64->f64 into VMOVDRR.
4925   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4926     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4927     // if we can combine the bitcast with its source.
4928     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4929       return Val;
4930 
4931     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4932                              DAG.getConstant(0, dl, MVT::i32));
4933     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4934                              DAG.getConstant(1, dl, MVT::i32));
4935     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4936                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4937   }
4938 
4939   // Turn f64->i64 into VMOVRRD.
4940   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4941     SDValue Cvt;
4942     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4943         SrcVT.getVectorNumElements() > 1)
4944       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4945                         DAG.getVTList(MVT::i32, MVT::i32),
4946                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4947     else
4948       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4949                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4950     // Merge the pieces into a single i64 value.
4951     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4952   }
4953 
4954   return SDValue();
4955 }
4956 
4957 /// getZeroVector - Returns a vector of specified type with all zero elements.
4958 /// Zero vectors are used to represent vector negation and in those cases
4959 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4960 /// not support i64 elements, so sometimes the zero vectors will need to be
4961 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4962 /// zero vector.
4963 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4964   assert(VT.isVector() && "Expected a vector type");
4965   // The canonical modified immediate encoding of a zero vector is....0!
4966   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4967   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4968   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4969   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4970 }
4971 
4972 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4973 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4974 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4975                                                 SelectionDAG &DAG) const {
4976   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4977   EVT VT = Op.getValueType();
4978   unsigned VTBits = VT.getSizeInBits();
4979   SDLoc dl(Op);
4980   SDValue ShOpLo = Op.getOperand(0);
4981   SDValue ShOpHi = Op.getOperand(1);
4982   SDValue ShAmt  = Op.getOperand(2);
4983   SDValue ARMcc;
4984   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4985   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4986 
4987   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4988 
4989   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4990                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4991   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4992   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4993                                    DAG.getConstant(VTBits, dl, MVT::i32));
4994   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4995   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4996   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4997   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4998                             ISD::SETGE, ARMcc, DAG, dl);
4999   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5000                            ARMcc, CCR, CmpLo);
5001 
5002 
5003   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5004   SDValue HiBigShift = Opc == ISD::SRA
5005                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5006                                          DAG.getConstant(VTBits - 1, dl, VT))
5007                            : DAG.getConstant(0, dl, VT);
5008   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5009                             ISD::SETGE, ARMcc, DAG, dl);
5010   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5011                            ARMcc, CCR, CmpHi);
5012 
5013   SDValue Ops[2] = { Lo, Hi };
5014   return DAG.getMergeValues(Ops, dl);
5015 }
5016 
5017 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5018 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5019 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5020                                                SelectionDAG &DAG) const {
5021   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5022   EVT VT = Op.getValueType();
5023   unsigned VTBits = VT.getSizeInBits();
5024   SDLoc dl(Op);
5025   SDValue ShOpLo = Op.getOperand(0);
5026   SDValue ShOpHi = Op.getOperand(1);
5027   SDValue ShAmt  = Op.getOperand(2);
5028   SDValue ARMcc;
5029   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5030 
5031   assert(Op.getOpcode() == ISD::SHL_PARTS);
5032   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5033                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5034   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5035   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5036   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5037 
5038   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5039                                    DAG.getConstant(VTBits, dl, MVT::i32));
5040   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5041   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5042                             ISD::SETGE, ARMcc, DAG, dl);
5043   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5044                            ARMcc, CCR, CmpHi);
5045 
5046   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5047                           ISD::SETGE, ARMcc, DAG, dl);
5048   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5049   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5050                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5051 
5052   SDValue Ops[2] = { Lo, Hi };
5053   return DAG.getMergeValues(Ops, dl);
5054 }
5055 
5056 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5057                                             SelectionDAG &DAG) const {
5058   // The rounding mode is in bits 23:22 of the FPSCR.
5059   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5060   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5061   // so that the shift + and get folded into a bitfield extract.
5062   SDLoc dl(Op);
5063   SDValue Ops[] = { DAG.getEntryNode(),
5064                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5065 
5066   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5067   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5068                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5069   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5070                               DAG.getConstant(22, dl, MVT::i32));
5071   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5072                      DAG.getConstant(3, dl, MVT::i32));
5073 }
5074 
5075 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5076                          const ARMSubtarget *ST) {
5077   SDLoc dl(N);
5078   EVT VT = N->getValueType(0);
5079   if (VT.isVector()) {
5080     assert(ST->hasNEON());
5081 
5082     // Compute the least significant set bit: LSB = X & -X
5083     SDValue X = N->getOperand(0);
5084     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5085     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5086 
5087     EVT ElemTy = VT.getVectorElementType();
5088 
5089     if (ElemTy == MVT::i8) {
5090       // Compute with: cttz(x) = ctpop(lsb - 1)
5091       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5092                                 DAG.getTargetConstant(1, dl, ElemTy));
5093       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5094       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5095     }
5096 
5097     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5098         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5099       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5100       unsigned NumBits = ElemTy.getSizeInBits();
5101       SDValue WidthMinus1 =
5102           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5103                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5104       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5105       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5106     }
5107 
5108     // Compute with: cttz(x) = ctpop(lsb - 1)
5109 
5110     // Since we can only compute the number of bits in a byte with vcnt.8, we
5111     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5112     // and i64.
5113 
5114     // Compute LSB - 1.
5115     SDValue Bits;
5116     if (ElemTy == MVT::i64) {
5117       // Load constant 0xffff'ffff'ffff'ffff to register.
5118       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5119                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5120       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5121     } else {
5122       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5123                                 DAG.getTargetConstant(1, dl, ElemTy));
5124       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5125     }
5126 
5127     // Count #bits with vcnt.8.
5128     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5129     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5130     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5131 
5132     // Gather the #bits with vpaddl (pairwise add.)
5133     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5134     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5135         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5136         Cnt8);
5137     if (ElemTy == MVT::i16)
5138       return Cnt16;
5139 
5140     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5141     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5142         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5143         Cnt16);
5144     if (ElemTy == MVT::i32)
5145       return Cnt32;
5146 
5147     assert(ElemTy == MVT::i64);
5148     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5149         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5150         Cnt32);
5151     return Cnt64;
5152   }
5153 
5154   if (!ST->hasV6T2Ops())
5155     return SDValue();
5156 
5157   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5158   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5159 }
5160 
5161 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5162 /// for each 16-bit element from operand, repeated.  The basic idea is to
5163 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5164 ///
5165 /// Trace for v4i16:
5166 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5167 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5168 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5169 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5170 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5171 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5172 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5173 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5174 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5175   EVT VT = N->getValueType(0);
5176   SDLoc DL(N);
5177 
5178   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5179   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5180   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5181   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5182   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5183   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5184 }
5185 
5186 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5187 /// bit-count for each 16-bit element from the operand.  We need slightly
5188 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5189 /// 64/128-bit registers.
5190 ///
5191 /// Trace for v4i16:
5192 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5193 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5194 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5195 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5196 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5197   EVT VT = N->getValueType(0);
5198   SDLoc DL(N);
5199 
5200   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5201   if (VT.is64BitVector()) {
5202     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5203     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5204                        DAG.getIntPtrConstant(0, DL));
5205   } else {
5206     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5207                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5208     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5209   }
5210 }
5211 
5212 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5213 /// bit-count for each 32-bit element from the operand.  The idea here is
5214 /// to split the vector into 16-bit elements, leverage the 16-bit count
5215 /// routine, and then combine the results.
5216 ///
5217 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5218 /// input    = [v0    v1    ] (vi: 32-bit elements)
5219 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5220 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5221 /// vrev: N0 = [k1 k0 k3 k2 ]
5222 ///            [k0 k1 k2 k3 ]
5223 ///       N1 =+[k1 k0 k3 k2 ]
5224 ///            [k0 k2 k1 k3 ]
5225 ///       N2 =+[k1 k3 k0 k2 ]
5226 ///            [k0    k2    k1    k3    ]
5227 /// Extended =+[k1    k3    k0    k2    ]
5228 ///            [k0    k2    ]
5229 /// Extracted=+[k1    k3    ]
5230 ///
5231 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5232   EVT VT = N->getValueType(0);
5233   SDLoc DL(N);
5234 
5235   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5236 
5237   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5238   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5239   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5240   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5241   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5242 
5243   if (VT.is64BitVector()) {
5244     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5245     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5246                        DAG.getIntPtrConstant(0, DL));
5247   } else {
5248     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5249                                     DAG.getIntPtrConstant(0, DL));
5250     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5251   }
5252 }
5253 
5254 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5255                           const ARMSubtarget *ST) {
5256   EVT VT = N->getValueType(0);
5257 
5258   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5259   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5260           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5261          "Unexpected type for custom ctpop lowering");
5262 
5263   if (VT.getVectorElementType() == MVT::i32)
5264     return lowerCTPOP32BitElements(N, DAG);
5265   else
5266     return lowerCTPOP16BitElements(N, DAG);
5267 }
5268 
5269 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5270                           const ARMSubtarget *ST) {
5271   EVT VT = N->getValueType(0);
5272   SDLoc dl(N);
5273 
5274   if (!VT.isVector())
5275     return SDValue();
5276 
5277   // Lower vector shifts on NEON to use VSHL.
5278   assert(ST->hasNEON() && "unexpected vector shift");
5279 
5280   // Left shifts translate directly to the vshiftu intrinsic.
5281   if (N->getOpcode() == ISD::SHL)
5282     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5283                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5284                                        MVT::i32),
5285                        N->getOperand(0), N->getOperand(1));
5286 
5287   assert((N->getOpcode() == ISD::SRA ||
5288           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5289 
5290   // NEON uses the same intrinsics for both left and right shifts.  For
5291   // right shifts, the shift amounts are negative, so negate the vector of
5292   // shift amounts.
5293   EVT ShiftVT = N->getOperand(1).getValueType();
5294   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5295                                      getZeroVector(ShiftVT, DAG, dl),
5296                                      N->getOperand(1));
5297   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5298                              Intrinsic::arm_neon_vshifts :
5299                              Intrinsic::arm_neon_vshiftu);
5300   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5301                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5302                      N->getOperand(0), NegatedCount);
5303 }
5304 
5305 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5306                                 const ARMSubtarget *ST) {
5307   EVT VT = N->getValueType(0);
5308   SDLoc dl(N);
5309 
5310   // We can get here for a node like i32 = ISD::SHL i32, i64
5311   if (VT != MVT::i64)
5312     return SDValue();
5313 
5314   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5315          "Unknown shift to lower!");
5316 
5317   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5318   if (!isOneConstant(N->getOperand(1)))
5319     return SDValue();
5320 
5321   // If we are in thumb mode, we don't have RRX.
5322   if (ST->isThumb1Only()) return SDValue();
5323 
5324   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5325   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5326                            DAG.getConstant(0, dl, MVT::i32));
5327   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5328                            DAG.getConstant(1, dl, MVT::i32));
5329 
5330   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5331   // captures the result into a carry flag.
5332   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5333   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5334 
5335   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5336   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5337 
5338   // Merge the pieces into a single i64 value.
5339  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5340 }
5341 
5342 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5343   SDValue TmpOp0, TmpOp1;
5344   bool Invert = false;
5345   bool Swap = false;
5346   unsigned Opc = 0;
5347 
5348   SDValue Op0 = Op.getOperand(0);
5349   SDValue Op1 = Op.getOperand(1);
5350   SDValue CC = Op.getOperand(2);
5351   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5352   EVT VT = Op.getValueType();
5353   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5354   SDLoc dl(Op);
5355 
5356   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5357       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5358     // Special-case integer 64-bit equality comparisons. They aren't legal,
5359     // but they can be lowered with a few vector instructions.
5360     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5361     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5362     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5363     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5364     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5365                               DAG.getCondCode(ISD::SETEQ));
5366     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5367     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5368     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5369     if (SetCCOpcode == ISD::SETNE)
5370       Merged = DAG.getNOT(dl, Merged, CmpVT);
5371     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5372     return Merged;
5373   }
5374 
5375   if (CmpVT.getVectorElementType() == MVT::i64)
5376     // 64-bit comparisons are not legal in general.
5377     return SDValue();
5378 
5379   if (Op1.getValueType().isFloatingPoint()) {
5380     switch (SetCCOpcode) {
5381     default: llvm_unreachable("Illegal FP comparison");
5382     case ISD::SETUNE:
5383     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5384     case ISD::SETOEQ:
5385     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5386     case ISD::SETOLT:
5387     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5388     case ISD::SETOGT:
5389     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5390     case ISD::SETOLE:
5391     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5392     case ISD::SETOGE:
5393     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5394     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5395     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5396     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5397     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5398     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5399     case ISD::SETONE:
5400       // Expand this to (OLT | OGT).
5401       TmpOp0 = Op0;
5402       TmpOp1 = Op1;
5403       Opc = ISD::OR;
5404       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5405       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5406       break;
5407     case ISD::SETUO:
5408       Invert = true;
5409       LLVM_FALLTHROUGH;
5410     case ISD::SETO:
5411       // Expand this to (OLT | OGE).
5412       TmpOp0 = Op0;
5413       TmpOp1 = Op1;
5414       Opc = ISD::OR;
5415       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5416       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5417       break;
5418     }
5419   } else {
5420     // Integer comparisons.
5421     switch (SetCCOpcode) {
5422     default: llvm_unreachable("Illegal integer comparison");
5423     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5424     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5425     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5426     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5427     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5428     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5429     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5430     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5431     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5432     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5433     }
5434 
5435     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5436     if (Opc == ARMISD::VCEQ) {
5437 
5438       SDValue AndOp;
5439       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5440         AndOp = Op0;
5441       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5442         AndOp = Op1;
5443 
5444       // Ignore bitconvert.
5445       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5446         AndOp = AndOp.getOperand(0);
5447 
5448       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5449         Opc = ARMISD::VTST;
5450         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5451         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5452         Invert = !Invert;
5453       }
5454     }
5455   }
5456 
5457   if (Swap)
5458     std::swap(Op0, Op1);
5459 
5460   // If one of the operands is a constant vector zero, attempt to fold the
5461   // comparison to a specialized compare-against-zero form.
5462   SDValue SingleOp;
5463   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5464     SingleOp = Op0;
5465   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5466     if (Opc == ARMISD::VCGE)
5467       Opc = ARMISD::VCLEZ;
5468     else if (Opc == ARMISD::VCGT)
5469       Opc = ARMISD::VCLTZ;
5470     SingleOp = Op1;
5471   }
5472 
5473   SDValue Result;
5474   if (SingleOp.getNode()) {
5475     switch (Opc) {
5476     case ARMISD::VCEQ:
5477       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5478     case ARMISD::VCGE:
5479       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5480     case ARMISD::VCLEZ:
5481       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5482     case ARMISD::VCGT:
5483       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5484     case ARMISD::VCLTZ:
5485       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5486     default:
5487       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5488     }
5489   } else {
5490      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5491   }
5492 
5493   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5494 
5495   if (Invert)
5496     Result = DAG.getNOT(dl, Result, VT);
5497 
5498   return Result;
5499 }
5500 
5501 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5502   SDValue LHS = Op.getOperand(0);
5503   SDValue RHS = Op.getOperand(1);
5504   SDValue Carry = Op.getOperand(2);
5505   SDValue Cond = Op.getOperand(3);
5506   SDLoc DL(Op);
5507 
5508   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5509 
5510   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5511   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5512   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5513 
5514   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5515   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5516   SDValue ARMcc = DAG.getConstant(
5517       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5518   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5519   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5520                                    Cmp.getValue(1), SDValue());
5521   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5522                      CCR, Chain.getValue(1));
5523 }
5524 
5525 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5526 /// valid vector constant for a NEON instruction with a "modified immediate"
5527 /// operand (e.g., VMOV).  If so, return the encoded value.
5528 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5529                                  unsigned SplatBitSize, SelectionDAG &DAG,
5530                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5531                                  NEONModImmType type) {
5532   unsigned OpCmode, Imm;
5533 
5534   // SplatBitSize is set to the smallest size that splats the vector, so a
5535   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5536   // immediate instructions others than VMOV do not support the 8-bit encoding
5537   // of a zero vector, and the default encoding of zero is supposed to be the
5538   // 32-bit version.
5539   if (SplatBits == 0)
5540     SplatBitSize = 32;
5541 
5542   switch (SplatBitSize) {
5543   case 8:
5544     if (type != VMOVModImm)
5545       return SDValue();
5546     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5547     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5548     OpCmode = 0xe;
5549     Imm = SplatBits;
5550     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5551     break;
5552 
5553   case 16:
5554     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5555     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5556     if ((SplatBits & ~0xff) == 0) {
5557       // Value = 0x00nn: Op=x, Cmode=100x.
5558       OpCmode = 0x8;
5559       Imm = SplatBits;
5560       break;
5561     }
5562     if ((SplatBits & ~0xff00) == 0) {
5563       // Value = 0xnn00: Op=x, Cmode=101x.
5564       OpCmode = 0xa;
5565       Imm = SplatBits >> 8;
5566       break;
5567     }
5568     return SDValue();
5569 
5570   case 32:
5571     // NEON's 32-bit VMOV supports splat values where:
5572     // * only one byte is nonzero, or
5573     // * the least significant byte is 0xff and the second byte is nonzero, or
5574     // * the least significant 2 bytes are 0xff and the third is nonzero.
5575     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5576     if ((SplatBits & ~0xff) == 0) {
5577       // Value = 0x000000nn: Op=x, Cmode=000x.
5578       OpCmode = 0;
5579       Imm = SplatBits;
5580       break;
5581     }
5582     if ((SplatBits & ~0xff00) == 0) {
5583       // Value = 0x0000nn00: Op=x, Cmode=001x.
5584       OpCmode = 0x2;
5585       Imm = SplatBits >> 8;
5586       break;
5587     }
5588     if ((SplatBits & ~0xff0000) == 0) {
5589       // Value = 0x00nn0000: Op=x, Cmode=010x.
5590       OpCmode = 0x4;
5591       Imm = SplatBits >> 16;
5592       break;
5593     }
5594     if ((SplatBits & ~0xff000000) == 0) {
5595       // Value = 0xnn000000: Op=x, Cmode=011x.
5596       OpCmode = 0x6;
5597       Imm = SplatBits >> 24;
5598       break;
5599     }
5600 
5601     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5602     if (type == OtherModImm) return SDValue();
5603 
5604     if ((SplatBits & ~0xffff) == 0 &&
5605         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5606       // Value = 0x0000nnff: Op=x, Cmode=1100.
5607       OpCmode = 0xc;
5608       Imm = SplatBits >> 8;
5609       break;
5610     }
5611 
5612     if ((SplatBits & ~0xffffff) == 0 &&
5613         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5614       // Value = 0x00nnffff: Op=x, Cmode=1101.
5615       OpCmode = 0xd;
5616       Imm = SplatBits >> 16;
5617       break;
5618     }
5619 
5620     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5621     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5622     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5623     // and fall through here to test for a valid 64-bit splat.  But, then the
5624     // caller would also need to check and handle the change in size.
5625     return SDValue();
5626 
5627   case 64: {
5628     if (type != VMOVModImm)
5629       return SDValue();
5630     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5631     uint64_t BitMask = 0xff;
5632     uint64_t Val = 0;
5633     unsigned ImmMask = 1;
5634     Imm = 0;
5635     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5636       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5637         Val |= BitMask;
5638         Imm |= ImmMask;
5639       } else if ((SplatBits & BitMask) != 0) {
5640         return SDValue();
5641       }
5642       BitMask <<= 8;
5643       ImmMask <<= 1;
5644     }
5645 
5646     if (DAG.getDataLayout().isBigEndian())
5647       // swap higher and lower 32 bit word
5648       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5649 
5650     // Op=1, Cmode=1110.
5651     OpCmode = 0x1e;
5652     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5653     break;
5654   }
5655 
5656   default:
5657     llvm_unreachable("unexpected size for isNEONModifiedImm");
5658   }
5659 
5660   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5661   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5662 }
5663 
5664 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5665                                            const ARMSubtarget *ST) const {
5666   bool IsDouble = Op.getValueType() == MVT::f64;
5667   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5668   const APFloat &FPVal = CFP->getValueAPF();
5669 
5670   // Prevent floating-point constants from using literal loads
5671   // when execute-only is enabled.
5672   if (ST->genExecuteOnly()) {
5673     APInt INTVal = FPVal.bitcastToAPInt();
5674     SDLoc DL(CFP);
5675     if (IsDouble) {
5676       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5677       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5678       if (!ST->isLittle())
5679         std::swap(Lo, Hi);
5680       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5681     } else {
5682       return DAG.getConstant(INTVal, DL, MVT::i32);
5683     }
5684   }
5685 
5686   if (!ST->hasVFP3())
5687     return SDValue();
5688 
5689   // Use the default (constant pool) lowering for double constants when we have
5690   // an SP-only FPU
5691   if (IsDouble && Subtarget->isFPOnlySP())
5692     return SDValue();
5693 
5694   // Try splatting with a VMOV.f32...
5695   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5696 
5697   if (ImmVal != -1) {
5698     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5699       // We have code in place to select a valid ConstantFP already, no need to
5700       // do any mangling.
5701       return Op;
5702     }
5703 
5704     // It's a float and we are trying to use NEON operations where
5705     // possible. Lower it to a splat followed by an extract.
5706     SDLoc DL(Op);
5707     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5708     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5709                                       NewVal);
5710     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5711                        DAG.getConstant(0, DL, MVT::i32));
5712   }
5713 
5714   // The rest of our options are NEON only, make sure that's allowed before
5715   // proceeding..
5716   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5717     return SDValue();
5718 
5719   EVT VMovVT;
5720   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5721 
5722   // It wouldn't really be worth bothering for doubles except for one very
5723   // important value, which does happen to match: 0.0. So make sure we don't do
5724   // anything stupid.
5725   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5726     return SDValue();
5727 
5728   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5729   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5730                                      VMovVT, false, VMOVModImm);
5731   if (NewVal != SDValue()) {
5732     SDLoc DL(Op);
5733     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5734                                       NewVal);
5735     if (IsDouble)
5736       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5737 
5738     // It's a float: cast and extract a vector element.
5739     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5740                                        VecConstant);
5741     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5742                        DAG.getConstant(0, DL, MVT::i32));
5743   }
5744 
5745   // Finally, try a VMVN.i32
5746   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5747                              false, VMVNModImm);
5748   if (NewVal != SDValue()) {
5749     SDLoc DL(Op);
5750     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5751 
5752     if (IsDouble)
5753       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5754 
5755     // It's a float: cast and extract a vector element.
5756     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5757                                        VecConstant);
5758     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5759                        DAG.getConstant(0, DL, MVT::i32));
5760   }
5761 
5762   return SDValue();
5763 }
5764 
5765 // check if an VEXT instruction can handle the shuffle mask when the
5766 // vector sources of the shuffle are the same.
5767 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5768   unsigned NumElts = VT.getVectorNumElements();
5769 
5770   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5771   if (M[0] < 0)
5772     return false;
5773 
5774   Imm = M[0];
5775 
5776   // If this is a VEXT shuffle, the immediate value is the index of the first
5777   // element.  The other shuffle indices must be the successive elements after
5778   // the first one.
5779   unsigned ExpectedElt = Imm;
5780   for (unsigned i = 1; i < NumElts; ++i) {
5781     // Increment the expected index.  If it wraps around, just follow it
5782     // back to index zero and keep going.
5783     ++ExpectedElt;
5784     if (ExpectedElt == NumElts)
5785       ExpectedElt = 0;
5786 
5787     if (M[i] < 0) continue; // ignore UNDEF indices
5788     if (ExpectedElt != static_cast<unsigned>(M[i]))
5789       return false;
5790   }
5791 
5792   return true;
5793 }
5794 
5795 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5796                        bool &ReverseVEXT, unsigned &Imm) {
5797   unsigned NumElts = VT.getVectorNumElements();
5798   ReverseVEXT = false;
5799 
5800   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5801   if (M[0] < 0)
5802     return false;
5803 
5804   Imm = M[0];
5805 
5806   // If this is a VEXT shuffle, the immediate value is the index of the first
5807   // element.  The other shuffle indices must be the successive elements after
5808   // the first one.
5809   unsigned ExpectedElt = Imm;
5810   for (unsigned i = 1; i < NumElts; ++i) {
5811     // Increment the expected index.  If it wraps around, it may still be
5812     // a VEXT but the source vectors must be swapped.
5813     ExpectedElt += 1;
5814     if (ExpectedElt == NumElts * 2) {
5815       ExpectedElt = 0;
5816       ReverseVEXT = true;
5817     }
5818 
5819     if (M[i] < 0) continue; // ignore UNDEF indices
5820     if (ExpectedElt != static_cast<unsigned>(M[i]))
5821       return false;
5822   }
5823 
5824   // Adjust the index value if the source operands will be swapped.
5825   if (ReverseVEXT)
5826     Imm -= NumElts;
5827 
5828   return true;
5829 }
5830 
5831 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5832 /// instruction with the specified blocksize.  (The order of the elements
5833 /// within each block of the vector is reversed.)
5834 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5835   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5836          "Only possible block sizes for VREV are: 16, 32, 64");
5837 
5838   unsigned EltSz = VT.getScalarSizeInBits();
5839   if (EltSz == 64)
5840     return false;
5841 
5842   unsigned NumElts = VT.getVectorNumElements();
5843   unsigned BlockElts = M[0] + 1;
5844   // If the first shuffle index is UNDEF, be optimistic.
5845   if (M[0] < 0)
5846     BlockElts = BlockSize / EltSz;
5847 
5848   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5849     return false;
5850 
5851   for (unsigned i = 0; i < NumElts; ++i) {
5852     if (M[i] < 0) continue; // ignore UNDEF indices
5853     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5854       return false;
5855   }
5856 
5857   return true;
5858 }
5859 
5860 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5861   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5862   // range, then 0 is placed into the resulting vector. So pretty much any mask
5863   // of 8 elements can work here.
5864   return VT == MVT::v8i8 && M.size() == 8;
5865 }
5866 
5867 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
5868                                unsigned Index) {
5869   if (Mask.size() == Elements * 2)
5870     return Index / Elements;
5871   return Mask[Index] == 0 ? 0 : 1;
5872 }
5873 
5874 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5875 // checking that pairs of elements in the shuffle mask represent the same index
5876 // in each vector, incrementing the expected index by 2 at each step.
5877 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5878 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5879 //  v2={e,f,g,h}
5880 // WhichResult gives the offset for each element in the mask based on which
5881 // of the two results it belongs to.
5882 //
5883 // The transpose can be represented either as:
5884 // result1 = shufflevector v1, v2, result1_shuffle_mask
5885 // result2 = shufflevector v1, v2, result2_shuffle_mask
5886 // where v1/v2 and the shuffle masks have the same number of elements
5887 // (here WhichResult (see below) indicates which result is being checked)
5888 //
5889 // or as:
5890 // results = shufflevector v1, v2, shuffle_mask
5891 // where both results are returned in one vector and the shuffle mask has twice
5892 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5893 // want to check the low half and high half of the shuffle mask as if it were
5894 // the other case
5895 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5896   unsigned EltSz = VT.getScalarSizeInBits();
5897   if (EltSz == 64)
5898     return false;
5899 
5900   unsigned NumElts = VT.getVectorNumElements();
5901   if (M.size() != NumElts && M.size() != NumElts*2)
5902     return false;
5903 
5904   // If the mask is twice as long as the input vector then we need to check the
5905   // upper and lower parts of the mask with a matching value for WhichResult
5906   // FIXME: A mask with only even values will be rejected in case the first
5907   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5908   // M[0] is used to determine WhichResult
5909   for (unsigned i = 0; i < M.size(); i += NumElts) {
5910     WhichResult = SelectPairHalf(NumElts, M, i);
5911     for (unsigned j = 0; j < NumElts; j += 2) {
5912       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5913           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5914         return false;
5915     }
5916   }
5917 
5918   if (M.size() == NumElts*2)
5919     WhichResult = 0;
5920 
5921   return true;
5922 }
5923 
5924 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5925 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5926 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5927 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5928   unsigned EltSz = VT.getScalarSizeInBits();
5929   if (EltSz == 64)
5930     return false;
5931 
5932   unsigned NumElts = VT.getVectorNumElements();
5933   if (M.size() != NumElts && M.size() != NumElts*2)
5934     return false;
5935 
5936   for (unsigned i = 0; i < M.size(); i += NumElts) {
5937     WhichResult = SelectPairHalf(NumElts, M, i);
5938     for (unsigned j = 0; j < NumElts; j += 2) {
5939       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5940           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5941         return false;
5942     }
5943   }
5944 
5945   if (M.size() == NumElts*2)
5946     WhichResult = 0;
5947 
5948   return true;
5949 }
5950 
5951 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5952 // that the mask elements are either all even and in steps of size 2 or all odd
5953 // and in steps of size 2.
5954 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5955 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5956 //  v2={e,f,g,h}
5957 // Requires similar checks to that of isVTRNMask with
5958 // respect the how results are returned.
5959 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5960   unsigned EltSz = VT.getScalarSizeInBits();
5961   if (EltSz == 64)
5962     return false;
5963 
5964   unsigned NumElts = VT.getVectorNumElements();
5965   if (M.size() != NumElts && M.size() != NumElts*2)
5966     return false;
5967 
5968   for (unsigned i = 0; i < M.size(); i += NumElts) {
5969     WhichResult = SelectPairHalf(NumElts, M, i);
5970     for (unsigned j = 0; j < NumElts; ++j) {
5971       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5972         return false;
5973     }
5974   }
5975 
5976   if (M.size() == NumElts*2)
5977     WhichResult = 0;
5978 
5979   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5980   if (VT.is64BitVector() && EltSz == 32)
5981     return false;
5982 
5983   return true;
5984 }
5985 
5986 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5987 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5988 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5989 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5990   unsigned EltSz = VT.getScalarSizeInBits();
5991   if (EltSz == 64)
5992     return false;
5993 
5994   unsigned NumElts = VT.getVectorNumElements();
5995   if (M.size() != NumElts && M.size() != NumElts*2)
5996     return false;
5997 
5998   unsigned Half = NumElts / 2;
5999   for (unsigned i = 0; i < M.size(); i += NumElts) {
6000     WhichResult = SelectPairHalf(NumElts, M, i);
6001     for (unsigned j = 0; j < NumElts; j += Half) {
6002       unsigned Idx = WhichResult;
6003       for (unsigned k = 0; k < Half; ++k) {
6004         int MIdx = M[i + j + k];
6005         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6006           return false;
6007         Idx += 2;
6008       }
6009     }
6010   }
6011 
6012   if (M.size() == NumElts*2)
6013     WhichResult = 0;
6014 
6015   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6016   if (VT.is64BitVector() && EltSz == 32)
6017     return false;
6018 
6019   return true;
6020 }
6021 
6022 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6023 // that pairs of elements of the shufflemask represent the same index in each
6024 // vector incrementing sequentially through the vectors.
6025 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6026 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6027 //  v2={e,f,g,h}
6028 // Requires similar checks to that of isVTRNMask with respect the how results
6029 // are returned.
6030 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6031   unsigned EltSz = VT.getScalarSizeInBits();
6032   if (EltSz == 64)
6033     return false;
6034 
6035   unsigned NumElts = VT.getVectorNumElements();
6036   if (M.size() != NumElts && M.size() != NumElts*2)
6037     return false;
6038 
6039   for (unsigned i = 0; i < M.size(); i += NumElts) {
6040     WhichResult = SelectPairHalf(NumElts, M, i);
6041     unsigned Idx = WhichResult * NumElts / 2;
6042     for (unsigned j = 0; j < NumElts; j += 2) {
6043       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6044           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6045         return false;
6046       Idx += 1;
6047     }
6048   }
6049 
6050   if (M.size() == NumElts*2)
6051     WhichResult = 0;
6052 
6053   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6054   if (VT.is64BitVector() && EltSz == 32)
6055     return false;
6056 
6057   return true;
6058 }
6059 
6060 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6061 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6062 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6063 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6064   unsigned EltSz = VT.getScalarSizeInBits();
6065   if (EltSz == 64)
6066     return false;
6067 
6068   unsigned NumElts = VT.getVectorNumElements();
6069   if (M.size() != NumElts && M.size() != NumElts*2)
6070     return false;
6071 
6072   for (unsigned i = 0; i < M.size(); i += NumElts) {
6073     WhichResult = SelectPairHalf(NumElts, M, i);
6074     unsigned Idx = WhichResult * NumElts / 2;
6075     for (unsigned j = 0; j < NumElts; j += 2) {
6076       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6077           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6078         return false;
6079       Idx += 1;
6080     }
6081   }
6082 
6083   if (M.size() == NumElts*2)
6084     WhichResult = 0;
6085 
6086   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6087   if (VT.is64BitVector() && EltSz == 32)
6088     return false;
6089 
6090   return true;
6091 }
6092 
6093 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6094 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6095 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6096                                            unsigned &WhichResult,
6097                                            bool &isV_UNDEF) {
6098   isV_UNDEF = false;
6099   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6100     return ARMISD::VTRN;
6101   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6102     return ARMISD::VUZP;
6103   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6104     return ARMISD::VZIP;
6105 
6106   isV_UNDEF = true;
6107   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6108     return ARMISD::VTRN;
6109   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6110     return ARMISD::VUZP;
6111   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6112     return ARMISD::VZIP;
6113 
6114   return 0;
6115 }
6116 
6117 /// \return true if this is a reverse operation on an vector.
6118 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6119   unsigned NumElts = VT.getVectorNumElements();
6120   // Make sure the mask has the right size.
6121   if (NumElts != M.size())
6122       return false;
6123 
6124   // Look for <15, ..., 3, -1, 1, 0>.
6125   for (unsigned i = 0; i != NumElts; ++i)
6126     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6127       return false;
6128 
6129   return true;
6130 }
6131 
6132 // If N is an integer constant that can be moved into a register in one
6133 // instruction, return an SDValue of such a constant (will become a MOV
6134 // instruction).  Otherwise return null.
6135 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6136                                      const ARMSubtarget *ST, const SDLoc &dl) {
6137   uint64_t Val;
6138   if (!isa<ConstantSDNode>(N))
6139     return SDValue();
6140   Val = cast<ConstantSDNode>(N)->getZExtValue();
6141 
6142   if (ST->isThumb1Only()) {
6143     if (Val <= 255 || ~Val <= 255)
6144       return DAG.getConstant(Val, dl, MVT::i32);
6145   } else {
6146     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6147       return DAG.getConstant(Val, dl, MVT::i32);
6148   }
6149   return SDValue();
6150 }
6151 
6152 // If this is a case we can't handle, return null and let the default
6153 // expansion code take care of it.
6154 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6155                                              const ARMSubtarget *ST) const {
6156   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6157   SDLoc dl(Op);
6158   EVT VT = Op.getValueType();
6159 
6160   APInt SplatBits, SplatUndef;
6161   unsigned SplatBitSize;
6162   bool HasAnyUndefs;
6163   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6164     if (SplatUndef.isAllOnesValue())
6165       return DAG.getUNDEF(VT);
6166 
6167     if (SplatBitSize <= 64) {
6168       // Check if an immediate VMOV works.
6169       EVT VmovVT;
6170       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6171                                       SplatUndef.getZExtValue(), SplatBitSize,
6172                                       DAG, dl, VmovVT, VT.is128BitVector(),
6173                                       VMOVModImm);
6174       if (Val.getNode()) {
6175         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6176         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6177       }
6178 
6179       // Try an immediate VMVN.
6180       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6181       Val = isNEONModifiedImm(NegatedImm,
6182                                       SplatUndef.getZExtValue(), SplatBitSize,
6183                                       DAG, dl, VmovVT, VT.is128BitVector(),
6184                                       VMVNModImm);
6185       if (Val.getNode()) {
6186         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6187         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6188       }
6189 
6190       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6191       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6192         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6193         if (ImmVal != -1) {
6194           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6195           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6196         }
6197       }
6198     }
6199   }
6200 
6201   // Scan through the operands to see if only one value is used.
6202   //
6203   // As an optimisation, even if more than one value is used it may be more
6204   // profitable to splat with one value then change some lanes.
6205   //
6206   // Heuristically we decide to do this if the vector has a "dominant" value,
6207   // defined as splatted to more than half of the lanes.
6208   unsigned NumElts = VT.getVectorNumElements();
6209   bool isOnlyLowElement = true;
6210   bool usesOnlyOneValue = true;
6211   bool hasDominantValue = false;
6212   bool isConstant = true;
6213 
6214   // Map of the number of times a particular SDValue appears in the
6215   // element list.
6216   DenseMap<SDValue, unsigned> ValueCounts;
6217   SDValue Value;
6218   for (unsigned i = 0; i < NumElts; ++i) {
6219     SDValue V = Op.getOperand(i);
6220     if (V.isUndef())
6221       continue;
6222     if (i > 0)
6223       isOnlyLowElement = false;
6224     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6225       isConstant = false;
6226 
6227     ValueCounts.insert(std::make_pair(V, 0));
6228     unsigned &Count = ValueCounts[V];
6229 
6230     // Is this value dominant? (takes up more than half of the lanes)
6231     if (++Count > (NumElts / 2)) {
6232       hasDominantValue = true;
6233       Value = V;
6234     }
6235   }
6236   if (ValueCounts.size() != 1)
6237     usesOnlyOneValue = false;
6238   if (!Value.getNode() && !ValueCounts.empty())
6239     Value = ValueCounts.begin()->first;
6240 
6241   if (ValueCounts.empty())
6242     return DAG.getUNDEF(VT);
6243 
6244   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6245   // Keep going if we are hitting this case.
6246   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6247     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6248 
6249   unsigned EltSize = VT.getScalarSizeInBits();
6250 
6251   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6252   // i32 and try again.
6253   if (hasDominantValue && EltSize <= 32) {
6254     if (!isConstant) {
6255       SDValue N;
6256 
6257       // If we are VDUPing a value that comes directly from a vector, that will
6258       // cause an unnecessary move to and from a GPR, where instead we could
6259       // just use VDUPLANE. We can only do this if the lane being extracted
6260       // is at a constant index, as the VDUP from lane instructions only have
6261       // constant-index forms.
6262       ConstantSDNode *constIndex;
6263       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6264           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6265         // We need to create a new undef vector to use for the VDUPLANE if the
6266         // size of the vector from which we get the value is different than the
6267         // size of the vector that we need to create. We will insert the element
6268         // such that the register coalescer will remove unnecessary copies.
6269         if (VT != Value->getOperand(0).getValueType()) {
6270           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6271                              VT.getVectorNumElements();
6272           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6273                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6274                         Value, DAG.getConstant(index, dl, MVT::i32)),
6275                            DAG.getConstant(index, dl, MVT::i32));
6276         } else
6277           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6278                         Value->getOperand(0), Value->getOperand(1));
6279       } else
6280         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6281 
6282       if (!usesOnlyOneValue) {
6283         // The dominant value was splatted as 'N', but we now have to insert
6284         // all differing elements.
6285         for (unsigned I = 0; I < NumElts; ++I) {
6286           if (Op.getOperand(I) == Value)
6287             continue;
6288           SmallVector<SDValue, 3> Ops;
6289           Ops.push_back(N);
6290           Ops.push_back(Op.getOperand(I));
6291           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6292           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6293         }
6294       }
6295       return N;
6296     }
6297     if (VT.getVectorElementType().isFloatingPoint()) {
6298       SmallVector<SDValue, 8> Ops;
6299       for (unsigned i = 0; i < NumElts; ++i)
6300         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6301                                   Op.getOperand(i)));
6302       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6303       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6304       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6305       if (Val.getNode())
6306         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6307     }
6308     if (usesOnlyOneValue) {
6309       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6310       if (isConstant && Val.getNode())
6311         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6312     }
6313   }
6314 
6315   // If all elements are constants and the case above didn't get hit, fall back
6316   // to the default expansion, which will generate a load from the constant
6317   // pool.
6318   if (isConstant)
6319     return SDValue();
6320 
6321   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6322   if (NumElts >= 4) {
6323     SDValue shuffle = ReconstructShuffle(Op, DAG);
6324     if (shuffle != SDValue())
6325       return shuffle;
6326   }
6327 
6328   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6329     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6330     // into two 64-bit vectors; we might discover a better way to lower it.
6331     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6332     EVT ExtVT = VT.getVectorElementType();
6333     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6334     SDValue Lower =
6335         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6336     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6337       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6338     SDValue Upper = DAG.getBuildVector(
6339         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6340     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6341       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6342     if (Lower && Upper)
6343       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6344   }
6345 
6346   // Vectors with 32- or 64-bit elements can be built by directly assigning
6347   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6348   // will be legalized.
6349   if (EltSize >= 32) {
6350     // Do the expansion with floating-point types, since that is what the VFP
6351     // registers are defined to use, and since i64 is not legal.
6352     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6353     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6354     SmallVector<SDValue, 8> Ops;
6355     for (unsigned i = 0; i < NumElts; ++i)
6356       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6357     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6358     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6359   }
6360 
6361   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6362   // know the default expansion would otherwise fall back on something even
6363   // worse. For a vector with one or two non-undef values, that's
6364   // scalar_to_vector for the elements followed by a shuffle (provided the
6365   // shuffle is valid for the target) and materialization element by element
6366   // on the stack followed by a load for everything else.
6367   if (!isConstant && !usesOnlyOneValue) {
6368     SDValue Vec = DAG.getUNDEF(VT);
6369     for (unsigned i = 0 ; i < NumElts; ++i) {
6370       SDValue V = Op.getOperand(i);
6371       if (V.isUndef())
6372         continue;
6373       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6374       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6375     }
6376     return Vec;
6377   }
6378 
6379   return SDValue();
6380 }
6381 
6382 // Gather data to see if the operation can be modelled as a
6383 // shuffle in combination with VEXTs.
6384 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6385                                               SelectionDAG &DAG) const {
6386   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6387   SDLoc dl(Op);
6388   EVT VT = Op.getValueType();
6389   unsigned NumElts = VT.getVectorNumElements();
6390 
6391   struct ShuffleSourceInfo {
6392     SDValue Vec;
6393     unsigned MinElt = std::numeric_limits<unsigned>::max();
6394     unsigned MaxElt = 0;
6395 
6396     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6397     // be compatible with the shuffle we intend to construct. As a result
6398     // ShuffleVec will be some sliding window into the original Vec.
6399     SDValue ShuffleVec;
6400 
6401     // Code should guarantee that element i in Vec starts at element "WindowBase
6402     // + i * WindowScale in ShuffleVec".
6403     int WindowBase = 0;
6404     int WindowScale = 1;
6405 
6406     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6407 
6408     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6409   };
6410 
6411   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6412   // node.
6413   SmallVector<ShuffleSourceInfo, 2> Sources;
6414   for (unsigned i = 0; i < NumElts; ++i) {
6415     SDValue V = Op.getOperand(i);
6416     if (V.isUndef())
6417       continue;
6418     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6419       // A shuffle can only come from building a vector from various
6420       // elements of other vectors.
6421       return SDValue();
6422     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6423       // Furthermore, shuffles require a constant mask, whereas extractelts
6424       // accept variable indices.
6425       return SDValue();
6426     }
6427 
6428     // Add this element source to the list if it's not already there.
6429     SDValue SourceVec = V.getOperand(0);
6430     auto Source = llvm::find(Sources, SourceVec);
6431     if (Source == Sources.end())
6432       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6433 
6434     // Update the minimum and maximum lane number seen.
6435     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6436     Source->MinElt = std::min(Source->MinElt, EltNo);
6437     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6438   }
6439 
6440   // Currently only do something sane when at most two source vectors
6441   // are involved.
6442   if (Sources.size() > 2)
6443     return SDValue();
6444 
6445   // Find out the smallest element size among result and two sources, and use
6446   // it as element size to build the shuffle_vector.
6447   EVT SmallestEltTy = VT.getVectorElementType();
6448   for (auto &Source : Sources) {
6449     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6450     if (SrcEltTy.bitsLT(SmallestEltTy))
6451       SmallestEltTy = SrcEltTy;
6452   }
6453   unsigned ResMultiplier =
6454       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6455   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6456   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6457 
6458   // If the source vector is too wide or too narrow, we may nevertheless be able
6459   // to construct a compatible shuffle either by concatenating it with UNDEF or
6460   // extracting a suitable range of elements.
6461   for (auto &Src : Sources) {
6462     EVT SrcVT = Src.ShuffleVec.getValueType();
6463 
6464     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6465       continue;
6466 
6467     // This stage of the search produces a source with the same element type as
6468     // the original, but with a total width matching the BUILD_VECTOR output.
6469     EVT EltVT = SrcVT.getVectorElementType();
6470     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6471     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6472 
6473     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6474       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6475         return SDValue();
6476       // We can pad out the smaller vector for free, so if it's part of a
6477       // shuffle...
6478       Src.ShuffleVec =
6479           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6480                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6481       continue;
6482     }
6483 
6484     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6485       return SDValue();
6486 
6487     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6488       // Span too large for a VEXT to cope
6489       return SDValue();
6490     }
6491 
6492     if (Src.MinElt >= NumSrcElts) {
6493       // The extraction can just take the second half
6494       Src.ShuffleVec =
6495           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6496                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6497       Src.WindowBase = -NumSrcElts;
6498     } else if (Src.MaxElt < NumSrcElts) {
6499       // The extraction can just take the first half
6500       Src.ShuffleVec =
6501           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6502                       DAG.getConstant(0, dl, MVT::i32));
6503     } else {
6504       // An actual VEXT is needed
6505       SDValue VEXTSrc1 =
6506           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6507                       DAG.getConstant(0, dl, MVT::i32));
6508       SDValue VEXTSrc2 =
6509           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6510                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6511 
6512       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6513                                    VEXTSrc2,
6514                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6515       Src.WindowBase = -Src.MinElt;
6516     }
6517   }
6518 
6519   // Another possible incompatibility occurs from the vector element types. We
6520   // can fix this by bitcasting the source vectors to the same type we intend
6521   // for the shuffle.
6522   for (auto &Src : Sources) {
6523     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6524     if (SrcEltTy == SmallestEltTy)
6525       continue;
6526     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6527     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6528     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6529     Src.WindowBase *= Src.WindowScale;
6530   }
6531 
6532   // Final sanity check before we try to actually produce a shuffle.
6533   DEBUG(
6534     for (auto Src : Sources)
6535       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6536   );
6537 
6538   // The stars all align, our next step is to produce the mask for the shuffle.
6539   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6540   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6541   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6542     SDValue Entry = Op.getOperand(i);
6543     if (Entry.isUndef())
6544       continue;
6545 
6546     auto Src = llvm::find(Sources, Entry.getOperand(0));
6547     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6548 
6549     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6550     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6551     // segment.
6552     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6553     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6554                                VT.getScalarSizeInBits());
6555     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6556 
6557     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6558     // starting at the appropriate offset.
6559     int *LaneMask = &Mask[i * ResMultiplier];
6560 
6561     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6562     ExtractBase += NumElts * (Src - Sources.begin());
6563     for (int j = 0; j < LanesDefined; ++j)
6564       LaneMask[j] = ExtractBase + j;
6565   }
6566 
6567   // Final check before we try to produce nonsense...
6568   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6569     return SDValue();
6570 
6571   // We can't handle more than two sources. This should have already
6572   // been checked before this point.
6573   assert(Sources.size() <= 2 && "Too many sources!");
6574 
6575   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6576   for (unsigned i = 0; i < Sources.size(); ++i)
6577     ShuffleOps[i] = Sources[i].ShuffleVec;
6578 
6579   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6580                                          ShuffleOps[1], Mask);
6581   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6582 }
6583 
6584 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6585 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6586 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6587 /// are assumed to be legal.
6588 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6589   if (VT.getVectorNumElements() == 4 &&
6590       (VT.is128BitVector() || VT.is64BitVector())) {
6591     unsigned PFIndexes[4];
6592     for (unsigned i = 0; i != 4; ++i) {
6593       if (M[i] < 0)
6594         PFIndexes[i] = 8;
6595       else
6596         PFIndexes[i] = M[i];
6597     }
6598 
6599     // Compute the index in the perfect shuffle table.
6600     unsigned PFTableIndex =
6601       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6602     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6603     unsigned Cost = (PFEntry >> 30);
6604 
6605     if (Cost <= 4)
6606       return true;
6607   }
6608 
6609   bool ReverseVEXT, isV_UNDEF;
6610   unsigned Imm, WhichResult;
6611 
6612   unsigned EltSize = VT.getScalarSizeInBits();
6613   return (EltSize >= 32 ||
6614           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6615           isVREVMask(M, VT, 64) ||
6616           isVREVMask(M, VT, 32) ||
6617           isVREVMask(M, VT, 16) ||
6618           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6619           isVTBLMask(M, VT) ||
6620           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6621           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6622 }
6623 
6624 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6625 /// the specified operations to build the shuffle.
6626 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6627                                       SDValue RHS, SelectionDAG &DAG,
6628                                       const SDLoc &dl) {
6629   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6630   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6631   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6632 
6633   enum {
6634     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6635     OP_VREV,
6636     OP_VDUP0,
6637     OP_VDUP1,
6638     OP_VDUP2,
6639     OP_VDUP3,
6640     OP_VEXT1,
6641     OP_VEXT2,
6642     OP_VEXT3,
6643     OP_VUZPL, // VUZP, left result
6644     OP_VUZPR, // VUZP, right result
6645     OP_VZIPL, // VZIP, left result
6646     OP_VZIPR, // VZIP, right result
6647     OP_VTRNL, // VTRN, left result
6648     OP_VTRNR  // VTRN, right result
6649   };
6650 
6651   if (OpNum == OP_COPY) {
6652     if (LHSID == (1*9+2)*9+3) return LHS;
6653     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6654     return RHS;
6655   }
6656 
6657   SDValue OpLHS, OpRHS;
6658   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6659   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6660   EVT VT = OpLHS.getValueType();
6661 
6662   switch (OpNum) {
6663   default: llvm_unreachable("Unknown shuffle opcode!");
6664   case OP_VREV:
6665     // VREV divides the vector in half and swaps within the half.
6666     if (VT.getVectorElementType() == MVT::i32 ||
6667         VT.getVectorElementType() == MVT::f32)
6668       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6669     // vrev <4 x i16> -> VREV32
6670     if (VT.getVectorElementType() == MVT::i16)
6671       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6672     // vrev <4 x i8> -> VREV16
6673     assert(VT.getVectorElementType() == MVT::i8);
6674     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6675   case OP_VDUP0:
6676   case OP_VDUP1:
6677   case OP_VDUP2:
6678   case OP_VDUP3:
6679     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6680                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6681   case OP_VEXT1:
6682   case OP_VEXT2:
6683   case OP_VEXT3:
6684     return DAG.getNode(ARMISD::VEXT, dl, VT,
6685                        OpLHS, OpRHS,
6686                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6687   case OP_VUZPL:
6688   case OP_VUZPR:
6689     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6690                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6691   case OP_VZIPL:
6692   case OP_VZIPR:
6693     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6694                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6695   case OP_VTRNL:
6696   case OP_VTRNR:
6697     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6698                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6699   }
6700 }
6701 
6702 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6703                                        ArrayRef<int> ShuffleMask,
6704                                        SelectionDAG &DAG) {
6705   // Check to see if we can use the VTBL instruction.
6706   SDValue V1 = Op.getOperand(0);
6707   SDValue V2 = Op.getOperand(1);
6708   SDLoc DL(Op);
6709 
6710   SmallVector<SDValue, 8> VTBLMask;
6711   for (ArrayRef<int>::iterator
6712          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6713     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6714 
6715   if (V2.getNode()->isUndef())
6716     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6717                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6718 
6719   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6720                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6721 }
6722 
6723 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6724                                                       SelectionDAG &DAG) {
6725   SDLoc DL(Op);
6726   SDValue OpLHS = Op.getOperand(0);
6727   EVT VT = OpLHS.getValueType();
6728 
6729   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6730          "Expect an v8i16/v16i8 type");
6731   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6732   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6733   // extract the first 8 bytes into the top double word and the last 8 bytes
6734   // into the bottom double word. The v8i16 case is similar.
6735   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6736   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6737                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6738 }
6739 
6740 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6741   SDValue V1 = Op.getOperand(0);
6742   SDValue V2 = Op.getOperand(1);
6743   SDLoc dl(Op);
6744   EVT VT = Op.getValueType();
6745   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6746 
6747   // Convert shuffles that are directly supported on NEON to target-specific
6748   // DAG nodes, instead of keeping them as shuffles and matching them again
6749   // during code selection.  This is more efficient and avoids the possibility
6750   // of inconsistencies between legalization and selection.
6751   // FIXME: floating-point vectors should be canonicalized to integer vectors
6752   // of the same time so that they get CSEd properly.
6753   ArrayRef<int> ShuffleMask = SVN->getMask();
6754 
6755   unsigned EltSize = VT.getScalarSizeInBits();
6756   if (EltSize <= 32) {
6757     if (SVN->isSplat()) {
6758       int Lane = SVN->getSplatIndex();
6759       // If this is undef splat, generate it via "just" vdup, if possible.
6760       if (Lane == -1) Lane = 0;
6761 
6762       // Test if V1 is a SCALAR_TO_VECTOR.
6763       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6764         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6765       }
6766       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6767       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6768       // reaches it).
6769       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6770           !isa<ConstantSDNode>(V1.getOperand(0))) {
6771         bool IsScalarToVector = true;
6772         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6773           if (!V1.getOperand(i).isUndef()) {
6774             IsScalarToVector = false;
6775             break;
6776           }
6777         if (IsScalarToVector)
6778           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6779       }
6780       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6781                          DAG.getConstant(Lane, dl, MVT::i32));
6782     }
6783 
6784     bool ReverseVEXT;
6785     unsigned Imm;
6786     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6787       if (ReverseVEXT)
6788         std::swap(V1, V2);
6789       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6790                          DAG.getConstant(Imm, dl, MVT::i32));
6791     }
6792 
6793     if (isVREVMask(ShuffleMask, VT, 64))
6794       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6795     if (isVREVMask(ShuffleMask, VT, 32))
6796       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6797     if (isVREVMask(ShuffleMask, VT, 16))
6798       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6799 
6800     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6801       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6802                          DAG.getConstant(Imm, dl, MVT::i32));
6803     }
6804 
6805     // Check for Neon shuffles that modify both input vectors in place.
6806     // If both results are used, i.e., if there are two shuffles with the same
6807     // source operands and with masks corresponding to both results of one of
6808     // these operations, DAG memoization will ensure that a single node is
6809     // used for both shuffles.
6810     unsigned WhichResult;
6811     bool isV_UNDEF;
6812     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6813             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6814       if (isV_UNDEF)
6815         V2 = V1;
6816       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6817           .getValue(WhichResult);
6818     }
6819 
6820     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6821     // shuffles that produce a result larger than their operands with:
6822     //   shuffle(concat(v1, undef), concat(v2, undef))
6823     // ->
6824     //   shuffle(concat(v1, v2), undef)
6825     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6826     //
6827     // This is useful in the general case, but there are special cases where
6828     // native shuffles produce larger results: the two-result ops.
6829     //
6830     // Look through the concat when lowering them:
6831     //   shuffle(concat(v1, v2), undef)
6832     // ->
6833     //   concat(VZIP(v1, v2):0, :1)
6834     //
6835     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6836       SDValue SubV1 = V1->getOperand(0);
6837       SDValue SubV2 = V1->getOperand(1);
6838       EVT SubVT = SubV1.getValueType();
6839 
6840       // We expect these to have been canonicalized to -1.
6841       assert(llvm::all_of(ShuffleMask, [&](int i) {
6842         return i < (int)VT.getVectorNumElements();
6843       }) && "Unexpected shuffle index into UNDEF operand!");
6844 
6845       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6846               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6847         if (isV_UNDEF)
6848           SubV2 = SubV1;
6849         assert((WhichResult == 0) &&
6850                "In-place shuffle of concat can only have one result!");
6851         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6852                                   SubV1, SubV2);
6853         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6854                            Res.getValue(1));
6855       }
6856     }
6857   }
6858 
6859   // If the shuffle is not directly supported and it has 4 elements, use
6860   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6861   unsigned NumElts = VT.getVectorNumElements();
6862   if (NumElts == 4) {
6863     unsigned PFIndexes[4];
6864     for (unsigned i = 0; i != 4; ++i) {
6865       if (ShuffleMask[i] < 0)
6866         PFIndexes[i] = 8;
6867       else
6868         PFIndexes[i] = ShuffleMask[i];
6869     }
6870 
6871     // Compute the index in the perfect shuffle table.
6872     unsigned PFTableIndex =
6873       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6874     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6875     unsigned Cost = (PFEntry >> 30);
6876 
6877     if (Cost <= 4)
6878       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6879   }
6880 
6881   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6882   if (EltSize >= 32) {
6883     // Do the expansion with floating-point types, since that is what the VFP
6884     // registers are defined to use, and since i64 is not legal.
6885     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6886     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6887     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6888     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6889     SmallVector<SDValue, 8> Ops;
6890     for (unsigned i = 0; i < NumElts; ++i) {
6891       if (ShuffleMask[i] < 0)
6892         Ops.push_back(DAG.getUNDEF(EltVT));
6893       else
6894         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6895                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6896                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6897                                                   dl, MVT::i32)));
6898     }
6899     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6900     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6901   }
6902 
6903   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6904     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6905 
6906   if (VT == MVT::v8i8)
6907     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6908       return NewOp;
6909 
6910   return SDValue();
6911 }
6912 
6913 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6914   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6915   SDValue Lane = Op.getOperand(2);
6916   if (!isa<ConstantSDNode>(Lane))
6917     return SDValue();
6918 
6919   return Op;
6920 }
6921 
6922 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6923   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6924   SDValue Lane = Op.getOperand(1);
6925   if (!isa<ConstantSDNode>(Lane))
6926     return SDValue();
6927 
6928   SDValue Vec = Op.getOperand(0);
6929   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6930     SDLoc dl(Op);
6931     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6932   }
6933 
6934   return Op;
6935 }
6936 
6937 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6938   // The only time a CONCAT_VECTORS operation can have legal types is when
6939   // two 64-bit vectors are concatenated to a 128-bit vector.
6940   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6941          "unexpected CONCAT_VECTORS");
6942   SDLoc dl(Op);
6943   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6944   SDValue Op0 = Op.getOperand(0);
6945   SDValue Op1 = Op.getOperand(1);
6946   if (!Op0.isUndef())
6947     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6948                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6949                       DAG.getIntPtrConstant(0, dl));
6950   if (!Op1.isUndef())
6951     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6952                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6953                       DAG.getIntPtrConstant(1, dl));
6954   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6955 }
6956 
6957 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6958 /// element has been zero/sign-extended, depending on the isSigned parameter,
6959 /// from an integer type half its size.
6960 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6961                                    bool isSigned) {
6962   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6963   EVT VT = N->getValueType(0);
6964   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6965     SDNode *BVN = N->getOperand(0).getNode();
6966     if (BVN->getValueType(0) != MVT::v4i32 ||
6967         BVN->getOpcode() != ISD::BUILD_VECTOR)
6968       return false;
6969     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6970     unsigned HiElt = 1 - LoElt;
6971     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6972     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6973     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6974     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6975     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6976       return false;
6977     if (isSigned) {
6978       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6979           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6980         return true;
6981     } else {
6982       if (Hi0->isNullValue() && Hi1->isNullValue())
6983         return true;
6984     }
6985     return false;
6986   }
6987 
6988   if (N->getOpcode() != ISD::BUILD_VECTOR)
6989     return false;
6990 
6991   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6992     SDNode *Elt = N->getOperand(i).getNode();
6993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6994       unsigned EltSize = VT.getScalarSizeInBits();
6995       unsigned HalfSize = EltSize / 2;
6996       if (isSigned) {
6997         if (!isIntN(HalfSize, C->getSExtValue()))
6998           return false;
6999       } else {
7000         if (!isUIntN(HalfSize, C->getZExtValue()))
7001           return false;
7002       }
7003       continue;
7004     }
7005     return false;
7006   }
7007 
7008   return true;
7009 }
7010 
7011 /// isSignExtended - Check if a node is a vector value that is sign-extended
7012 /// or a constant BUILD_VECTOR with sign-extended elements.
7013 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7014   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7015     return true;
7016   if (isExtendedBUILD_VECTOR(N, DAG, true))
7017     return true;
7018   return false;
7019 }
7020 
7021 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7022 /// or a constant BUILD_VECTOR with zero-extended elements.
7023 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7024   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7025     return true;
7026   if (isExtendedBUILD_VECTOR(N, DAG, false))
7027     return true;
7028   return false;
7029 }
7030 
7031 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7032   if (OrigVT.getSizeInBits() >= 64)
7033     return OrigVT;
7034 
7035   assert(OrigVT.isSimple() && "Expecting a simple value type");
7036 
7037   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7038   switch (OrigSimpleTy) {
7039   default: llvm_unreachable("Unexpected Vector Type");
7040   case MVT::v2i8:
7041   case MVT::v2i16:
7042      return MVT::v2i32;
7043   case MVT::v4i8:
7044     return  MVT::v4i16;
7045   }
7046 }
7047 
7048 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7049 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7050 /// We insert the required extension here to get the vector to fill a D register.
7051 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7052                                             const EVT &OrigTy,
7053                                             const EVT &ExtTy,
7054                                             unsigned ExtOpcode) {
7055   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7056   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7057   // 64-bits we need to insert a new extension so that it will be 64-bits.
7058   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7059   if (OrigTy.getSizeInBits() >= 64)
7060     return N;
7061 
7062   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7063   EVT NewVT = getExtensionTo64Bits(OrigTy);
7064 
7065   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7066 }
7067 
7068 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7069 /// does not do any sign/zero extension. If the original vector is less
7070 /// than 64 bits, an appropriate extension will be added after the load to
7071 /// reach a total size of 64 bits. We have to add the extension separately
7072 /// because ARM does not have a sign/zero extending load for vectors.
7073 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7074   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7075 
7076   // The load already has the right type.
7077   if (ExtendedTy == LD->getMemoryVT())
7078     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7079                        LD->getBasePtr(), LD->getPointerInfo(),
7080                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7081 
7082   // We need to create a zextload/sextload. We cannot just create a load
7083   // followed by a zext/zext node because LowerMUL is also run during normal
7084   // operation legalization where we can't create illegal types.
7085   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7086                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7087                         LD->getMemoryVT(), LD->getAlignment(),
7088                         LD->getMemOperand()->getFlags());
7089 }
7090 
7091 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7092 /// extending load, or BUILD_VECTOR with extended elements, return the
7093 /// unextended value. The unextended vector should be 64 bits so that it can
7094 /// be used as an operand to a VMULL instruction. If the original vector size
7095 /// before extension is less than 64 bits we add a an extension to resize
7096 /// the vector to 64 bits.
7097 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7098   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7099     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7100                                         N->getOperand(0)->getValueType(0),
7101                                         N->getValueType(0),
7102                                         N->getOpcode());
7103 
7104   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7105     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7106            "Expected extending load");
7107 
7108     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7109     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7110     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7111     SDValue extLoad =
7112         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7113     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7114 
7115     return newLoad;
7116   }
7117 
7118   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7119   // have been legalized as a BITCAST from v4i32.
7120   if (N->getOpcode() == ISD::BITCAST) {
7121     SDNode *BVN = N->getOperand(0).getNode();
7122     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7123            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7124     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7125     return DAG.getBuildVector(
7126         MVT::v2i32, SDLoc(N),
7127         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7128   }
7129   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7130   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7131   EVT VT = N->getValueType(0);
7132   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7133   unsigned NumElts = VT.getVectorNumElements();
7134   MVT TruncVT = MVT::getIntegerVT(EltSize);
7135   SmallVector<SDValue, 8> Ops;
7136   SDLoc dl(N);
7137   for (unsigned i = 0; i != NumElts; ++i) {
7138     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7139     const APInt &CInt = C->getAPIntValue();
7140     // Element types smaller than 32 bits are not legal, so use i32 elements.
7141     // The values are implicitly truncated so sext vs. zext doesn't matter.
7142     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7143   }
7144   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7145 }
7146 
7147 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7148   unsigned Opcode = N->getOpcode();
7149   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7150     SDNode *N0 = N->getOperand(0).getNode();
7151     SDNode *N1 = N->getOperand(1).getNode();
7152     return N0->hasOneUse() && N1->hasOneUse() &&
7153       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7154   }
7155   return false;
7156 }
7157 
7158 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7159   unsigned Opcode = N->getOpcode();
7160   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7161     SDNode *N0 = N->getOperand(0).getNode();
7162     SDNode *N1 = N->getOperand(1).getNode();
7163     return N0->hasOneUse() && N1->hasOneUse() &&
7164       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7165   }
7166   return false;
7167 }
7168 
7169 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7170   // Multiplications are only custom-lowered for 128-bit vectors so that
7171   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7172   EVT VT = Op.getValueType();
7173   assert(VT.is128BitVector() && VT.isInteger() &&
7174          "unexpected type for custom-lowering ISD::MUL");
7175   SDNode *N0 = Op.getOperand(0).getNode();
7176   SDNode *N1 = Op.getOperand(1).getNode();
7177   unsigned NewOpc = 0;
7178   bool isMLA = false;
7179   bool isN0SExt = isSignExtended(N0, DAG);
7180   bool isN1SExt = isSignExtended(N1, DAG);
7181   if (isN0SExt && isN1SExt)
7182     NewOpc = ARMISD::VMULLs;
7183   else {
7184     bool isN0ZExt = isZeroExtended(N0, DAG);
7185     bool isN1ZExt = isZeroExtended(N1, DAG);
7186     if (isN0ZExt && isN1ZExt)
7187       NewOpc = ARMISD::VMULLu;
7188     else if (isN1SExt || isN1ZExt) {
7189       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7190       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7191       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7192         NewOpc = ARMISD::VMULLs;
7193         isMLA = true;
7194       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7195         NewOpc = ARMISD::VMULLu;
7196         isMLA = true;
7197       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7198         std::swap(N0, N1);
7199         NewOpc = ARMISD::VMULLu;
7200         isMLA = true;
7201       }
7202     }
7203 
7204     if (!NewOpc) {
7205       if (VT == MVT::v2i64)
7206         // Fall through to expand this.  It is not legal.
7207         return SDValue();
7208       else
7209         // Other vector multiplications are legal.
7210         return Op;
7211     }
7212   }
7213 
7214   // Legalize to a VMULL instruction.
7215   SDLoc DL(Op);
7216   SDValue Op0;
7217   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7218   if (!isMLA) {
7219     Op0 = SkipExtensionForVMULL(N0, DAG);
7220     assert(Op0.getValueType().is64BitVector() &&
7221            Op1.getValueType().is64BitVector() &&
7222            "unexpected types for extended operands to VMULL");
7223     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7224   }
7225 
7226   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7227   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7228   //   vmull q0, d4, d6
7229   //   vmlal q0, d5, d6
7230   // is faster than
7231   //   vaddl q0, d4, d5
7232   //   vmovl q1, d6
7233   //   vmul  q0, q0, q1
7234   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7235   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7236   EVT Op1VT = Op1.getValueType();
7237   return DAG.getNode(N0->getOpcode(), DL, VT,
7238                      DAG.getNode(NewOpc, DL, VT,
7239                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7240                      DAG.getNode(NewOpc, DL, VT,
7241                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7242 }
7243 
7244 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7245                               SelectionDAG &DAG) {
7246   // TODO: Should this propagate fast-math-flags?
7247 
7248   // Convert to float
7249   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7250   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7251   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7252   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7253   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7254   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7255   // Get reciprocal estimate.
7256   // float4 recip = vrecpeq_f32(yf);
7257   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7258                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7259                    Y);
7260   // Because char has a smaller range than uchar, we can actually get away
7261   // without any newton steps.  This requires that we use a weird bias
7262   // of 0xb000, however (again, this has been exhaustively tested).
7263   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7264   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7265   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7266   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7267   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7268   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7269   // Convert back to short.
7270   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7271   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7272   return X;
7273 }
7274 
7275 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7276                                SelectionDAG &DAG) {
7277   // TODO: Should this propagate fast-math-flags?
7278 
7279   SDValue N2;
7280   // Convert to float.
7281   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7282   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7283   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7284   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7285   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7286   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7287 
7288   // Use reciprocal estimate and one refinement step.
7289   // float4 recip = vrecpeq_f32(yf);
7290   // recip *= vrecpsq_f32(yf, recip);
7291   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7292                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7293                    N1);
7294   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7295                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7296                    N1, N2);
7297   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7298   // Because short has a smaller range than ushort, we can actually get away
7299   // with only a single newton step.  This requires that we use a weird bias
7300   // of 89, however (again, this has been exhaustively tested).
7301   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7302   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7303   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7304   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7305   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7306   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7307   // Convert back to integer and return.
7308   // return vmovn_s32(vcvt_s32_f32(result));
7309   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7310   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7311   return N0;
7312 }
7313 
7314 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7315   EVT VT = Op.getValueType();
7316   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7317          "unexpected type for custom-lowering ISD::SDIV");
7318 
7319   SDLoc dl(Op);
7320   SDValue N0 = Op.getOperand(0);
7321   SDValue N1 = Op.getOperand(1);
7322   SDValue N2, N3;
7323 
7324   if (VT == MVT::v8i8) {
7325     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7326     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7327 
7328     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7329                      DAG.getIntPtrConstant(4, dl));
7330     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7331                      DAG.getIntPtrConstant(4, dl));
7332     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7333                      DAG.getIntPtrConstant(0, dl));
7334     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7335                      DAG.getIntPtrConstant(0, dl));
7336 
7337     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7338     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7339 
7340     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7341     N0 = LowerCONCAT_VECTORS(N0, DAG);
7342 
7343     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7344     return N0;
7345   }
7346   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7347 }
7348 
7349 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7350   // TODO: Should this propagate fast-math-flags?
7351   EVT VT = Op.getValueType();
7352   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7353          "unexpected type for custom-lowering ISD::UDIV");
7354 
7355   SDLoc dl(Op);
7356   SDValue N0 = Op.getOperand(0);
7357   SDValue N1 = Op.getOperand(1);
7358   SDValue N2, N3;
7359 
7360   if (VT == MVT::v8i8) {
7361     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7362     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7363 
7364     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7365                      DAG.getIntPtrConstant(4, dl));
7366     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7367                      DAG.getIntPtrConstant(4, dl));
7368     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7369                      DAG.getIntPtrConstant(0, dl));
7370     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7371                      DAG.getIntPtrConstant(0, dl));
7372 
7373     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7374     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7375 
7376     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7377     N0 = LowerCONCAT_VECTORS(N0, DAG);
7378 
7379     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7380                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7381                                      MVT::i32),
7382                      N0);
7383     return N0;
7384   }
7385 
7386   // v4i16 sdiv ... Convert to float.
7387   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7388   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7389   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7390   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7391   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7392   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7393 
7394   // Use reciprocal estimate and two refinement steps.
7395   // float4 recip = vrecpeq_f32(yf);
7396   // recip *= vrecpsq_f32(yf, recip);
7397   // recip *= vrecpsq_f32(yf, recip);
7398   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7399                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7400                    BN1);
7401   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7402                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7403                    BN1, N2);
7404   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7405   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7406                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7407                    BN1, N2);
7408   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7409   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7410   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7411   // and that it will never cause us to return an answer too large).
7412   // float4 result = as_float4(as_int4(xf*recip) + 2);
7413   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7414   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7415   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7416   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7417   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7418   // Convert back to integer and return.
7419   // return vmovn_u32(vcvt_s32_f32(result));
7420   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7421   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7422   return N0;
7423 }
7424 
7425 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7426   EVT VT = Op.getNode()->getValueType(0);
7427   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7428 
7429   unsigned Opc;
7430   bool ExtraOp = false;
7431   switch (Op.getOpcode()) {
7432   default: llvm_unreachable("Invalid code");
7433   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7434   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7435   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7436   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7437   }
7438 
7439   if (!ExtraOp)
7440     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7441                        Op.getOperand(1));
7442   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7443                      Op.getOperand(1), Op.getOperand(2));
7444 }
7445 
7446 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7447   SDNode *N = Op.getNode();
7448   EVT VT = N->getValueType(0);
7449   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7450 
7451   SDValue Carry = Op.getOperand(2);
7452   EVT CarryVT = Carry.getValueType();
7453 
7454   SDLoc DL(Op);
7455 
7456   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7457 
7458   SDValue Result;
7459   if (Op.getOpcode() == ISD::ADDCARRY) {
7460     // This converts the boolean value carry into the carry flag.
7461     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7462 
7463     // Do the addition proper using the carry flag we wanted.
7464     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7465                          Op.getOperand(1), Carry.getValue(1));
7466 
7467     // Now convert the carry flag into a boolean value.
7468     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7469   } else {
7470     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7471     // have to invert the carry first.
7472     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7473                         DAG.getConstant(1, DL, MVT::i32), Carry);
7474     // This converts the boolean value carry into the carry flag.
7475     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7476 
7477     // Do the subtraction proper using the carry flag we wanted.
7478     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7479                          Op.getOperand(1), Carry.getValue(1));
7480 
7481     // Now convert the carry flag into a boolean value.
7482     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7483     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7484     // by ISD::SUBCARRY, so compute 1 - C.
7485     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7486                         DAG.getConstant(1, DL, MVT::i32), Carry);
7487   }
7488 
7489   // Return both values.
7490   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7491 }
7492 
7493 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7494   assert(Subtarget->isTargetDarwin());
7495 
7496   // For iOS, we want to call an alternative entry point: __sincos_stret,
7497   // return values are passed via sret.
7498   SDLoc dl(Op);
7499   SDValue Arg = Op.getOperand(0);
7500   EVT ArgVT = Arg.getValueType();
7501   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7502   auto PtrVT = getPointerTy(DAG.getDataLayout());
7503 
7504   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7506 
7507   // Pair of floats / doubles used to pass the result.
7508   Type *RetTy = StructType::get(ArgTy, ArgTy);
7509   auto &DL = DAG.getDataLayout();
7510 
7511   ArgListTy Args;
7512   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7513   SDValue SRet;
7514   if (ShouldUseSRet) {
7515     // Create stack object for sret.
7516     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7517     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7518     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7519     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7520 
7521     ArgListEntry Entry;
7522     Entry.Node = SRet;
7523     Entry.Ty = RetTy->getPointerTo();
7524     Entry.IsSExt = false;
7525     Entry.IsZExt = false;
7526     Entry.IsSRet = true;
7527     Args.push_back(Entry);
7528     RetTy = Type::getVoidTy(*DAG.getContext());
7529   }
7530 
7531   ArgListEntry Entry;
7532   Entry.Node = Arg;
7533   Entry.Ty = ArgTy;
7534   Entry.IsSExt = false;
7535   Entry.IsZExt = false;
7536   Args.push_back(Entry);
7537 
7538   const char *LibcallName =
7539       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7540   RTLIB::Libcall LC =
7541       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7542   CallingConv::ID CC = getLibcallCallingConv(LC);
7543   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7544 
7545   TargetLowering::CallLoweringInfo CLI(DAG);
7546   CLI.setDebugLoc(dl)
7547       .setChain(DAG.getEntryNode())
7548       .setCallee(CC, RetTy, Callee, std::move(Args))
7549       .setDiscardResult(ShouldUseSRet);
7550   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7551 
7552   if (!ShouldUseSRet)
7553     return CallResult.first;
7554 
7555   SDValue LoadSin =
7556       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7557 
7558   // Address of cos field.
7559   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7560                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7561   SDValue LoadCos =
7562       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7563 
7564   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7565   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7566                      LoadSin.getValue(0), LoadCos.getValue(0));
7567 }
7568 
7569 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7570                                                   bool Signed,
7571                                                   SDValue &Chain) const {
7572   EVT VT = Op.getValueType();
7573   assert((VT == MVT::i32 || VT == MVT::i64) &&
7574          "unexpected type for custom lowering DIV");
7575   SDLoc dl(Op);
7576 
7577   const auto &DL = DAG.getDataLayout();
7578   const auto &TLI = DAG.getTargetLoweringInfo();
7579 
7580   const char *Name = nullptr;
7581   if (Signed)
7582     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7583   else
7584     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7585 
7586   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7587 
7588   ARMTargetLowering::ArgListTy Args;
7589 
7590   for (auto AI : {1, 0}) {
7591     ArgListEntry Arg;
7592     Arg.Node = Op.getOperand(AI);
7593     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7594     Args.push_back(Arg);
7595   }
7596 
7597   CallLoweringInfo CLI(DAG);
7598   CLI.setDebugLoc(dl)
7599     .setChain(Chain)
7600     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7601                ES, std::move(Args));
7602 
7603   return LowerCallTo(CLI).first;
7604 }
7605 
7606 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7607                                             bool Signed) const {
7608   assert(Op.getValueType() == MVT::i32 &&
7609          "unexpected type for custom lowering DIV");
7610   SDLoc dl(Op);
7611 
7612   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7613                                DAG.getEntryNode(), Op.getOperand(1));
7614 
7615   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7616 }
7617 
7618 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7619   SDLoc DL(N);
7620   SDValue Op = N->getOperand(1);
7621   if (N->getValueType(0) == MVT::i32)
7622     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7623   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7624                            DAG.getConstant(0, DL, MVT::i32));
7625   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7626                            DAG.getConstant(1, DL, MVT::i32));
7627   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7628                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7629 }
7630 
7631 void ARMTargetLowering::ExpandDIV_Windows(
7632     SDValue Op, SelectionDAG &DAG, bool Signed,
7633     SmallVectorImpl<SDValue> &Results) const {
7634   const auto &DL = DAG.getDataLayout();
7635   const auto &TLI = DAG.getTargetLoweringInfo();
7636 
7637   assert(Op.getValueType() == MVT::i64 &&
7638          "unexpected type for custom lowering DIV");
7639   SDLoc dl(Op);
7640 
7641   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7642 
7643   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7644 
7645   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7646   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7647                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7648   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7649 
7650   Results.push_back(Lower);
7651   Results.push_back(Upper);
7652 }
7653 
7654 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7655   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7656     // Acquire/Release load/store is not legal for targets without a dmb or
7657     // equivalent available.
7658     return SDValue();
7659 
7660   // Monotonic load/store is legal for all targets.
7661   return Op;
7662 }
7663 
7664 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7665                                     SmallVectorImpl<SDValue> &Results,
7666                                     SelectionDAG &DAG,
7667                                     const ARMSubtarget *Subtarget) {
7668   SDLoc DL(N);
7669   // Under Power Management extensions, the cycle-count is:
7670   //    mrc p15, #0, <Rt>, c9, c13, #0
7671   SDValue Ops[] = { N->getOperand(0), // Chain
7672                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7673                     DAG.getConstant(15, DL, MVT::i32),
7674                     DAG.getConstant(0, DL, MVT::i32),
7675                     DAG.getConstant(9, DL, MVT::i32),
7676                     DAG.getConstant(13, DL, MVT::i32),
7677                     DAG.getConstant(0, DL, MVT::i32)
7678   };
7679 
7680   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7681                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7682   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7683                                 DAG.getConstant(0, DL, MVT::i32)));
7684   Results.push_back(Cycles32.getValue(1));
7685 }
7686 
7687 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7688   SDLoc dl(V.getNode());
7689   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7690   SDValue VHi = DAG.getAnyExtOrTrunc(
7691       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7692       dl, MVT::i32);
7693   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7694   if (isBigEndian)
7695     std::swap (VLo, VHi);
7696   SDValue RegClass =
7697       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7698   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7699   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7700   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7701   return SDValue(
7702       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7703 }
7704 
7705 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7706                                        SmallVectorImpl<SDValue> & Results,
7707                                        SelectionDAG &DAG) {
7708   assert(N->getValueType(0) == MVT::i64 &&
7709          "AtomicCmpSwap on types less than 64 should be legal");
7710   SDValue Ops[] = {N->getOperand(1),
7711                    createGPRPairNode(DAG, N->getOperand(2)),
7712                    createGPRPairNode(DAG, N->getOperand(3)),
7713                    N->getOperand(0)};
7714   SDNode *CmpSwap = DAG.getMachineNode(
7715       ARM::CMP_SWAP_64, SDLoc(N),
7716       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7717 
7718   MachineFunction &MF = DAG.getMachineFunction();
7719   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7720   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7721   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7722 
7723   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7724 
7725   Results.push_back(
7726       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7727                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7728   Results.push_back(
7729       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7730                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7731   Results.push_back(SDValue(CmpSwap, 2));
7732 }
7733 
7734 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7735                           SelectionDAG &DAG) {
7736   const auto &TLI = DAG.getTargetLoweringInfo();
7737 
7738   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7739          "Custom lowering is MSVCRT specific!");
7740 
7741   SDLoc dl(Op);
7742   SDValue Val = Op.getOperand(0);
7743   MVT Ty = Val->getSimpleValueType(0);
7744   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7745   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7746                                          TLI.getPointerTy(DAG.getDataLayout()));
7747 
7748   TargetLowering::ArgListTy Args;
7749   TargetLowering::ArgListEntry Entry;
7750 
7751   Entry.Node = Val;
7752   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7753   Entry.IsZExt = true;
7754   Args.push_back(Entry);
7755 
7756   Entry.Node = Exponent;
7757   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7758   Entry.IsZExt = true;
7759   Args.push_back(Entry);
7760 
7761   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7762 
7763   // In the in-chain to the call is the entry node  If we are emitting a
7764   // tailcall, the chain will be mutated if the node has a non-entry input
7765   // chain.
7766   SDValue InChain = DAG.getEntryNode();
7767   SDValue TCChain = InChain;
7768 
7769   const auto *F = DAG.getMachineFunction().getFunction();
7770   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7771               F->getReturnType() == LCRTy;
7772   if (IsTC)
7773     InChain = TCChain;
7774 
7775   TargetLowering::CallLoweringInfo CLI(DAG);
7776   CLI.setDebugLoc(dl)
7777       .setChain(InChain)
7778       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7779       .setTailCall(IsTC);
7780   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7781 
7782   // Return the chain (the DAG root) if it is a tail call
7783   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7784 }
7785 
7786 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7787   switch (Op.getOpcode()) {
7788   default: llvm_unreachable("Don't know how to custom lower this!");
7789   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7790   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7791   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7792   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7793   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7794   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7795   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7796   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7797   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7798   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7799   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7800   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7801   case ISD::SINT_TO_FP:
7802   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7803   case ISD::FP_TO_SINT:
7804   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7805   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7806   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7807   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7808   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7809   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7810   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7811   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7812                                                                Subtarget);
7813   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7814   case ISD::SHL:
7815   case ISD::SRL:
7816   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7817   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7818   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7819   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7820   case ISD::SRL_PARTS:
7821   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7822   case ISD::CTTZ:
7823   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7824   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7825   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7826   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7827   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7828   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7829   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7830   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7831   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7832   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7833   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7834   case ISD::MUL:           return LowerMUL(Op, DAG);
7835   case ISD::SDIV:
7836     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7837       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7838     return LowerSDIV(Op, DAG);
7839   case ISD::UDIV:
7840     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7841       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7842     return LowerUDIV(Op, DAG);
7843   case ISD::ADDC:
7844   case ISD::ADDE:
7845   case ISD::SUBC:
7846   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7847   case ISD::ADDCARRY:
7848   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
7849   case ISD::SADDO:
7850   case ISD::SSUBO:
7851     return LowerSignedALUO(Op, DAG);
7852   case ISD::UADDO:
7853   case ISD::USUBO:
7854     return LowerUnsignedALUO(Op, DAG);
7855   case ISD::ATOMIC_LOAD:
7856   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7857   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7858   case ISD::SDIVREM:
7859   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7860   case ISD::DYNAMIC_STACKALLOC:
7861     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7862       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7863     llvm_unreachable("Don't know how to custom lower this!");
7864   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7865   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7866   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7867   case ARMISD::WIN__DBZCHK: return SDValue();
7868   }
7869 }
7870 
7871 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7872                                  SelectionDAG &DAG) {
7873   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7874   unsigned Opc = 0;
7875   if (IntNo == Intrinsic::arm_smlald)
7876     Opc = ARMISD::SMLALD;
7877   else if (IntNo == Intrinsic::arm_smlaldx)
7878     Opc = ARMISD::SMLALDX;
7879   else if (IntNo == Intrinsic::arm_smlsld)
7880     Opc = ARMISD::SMLSLD;
7881   else if (IntNo == Intrinsic::arm_smlsldx)
7882     Opc = ARMISD::SMLSLDX;
7883   else
7884     return;
7885 
7886   SDLoc dl(N);
7887   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7888                            N->getOperand(3),
7889                            DAG.getConstant(0, dl, MVT::i32));
7890   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7891                            N->getOperand(3),
7892                            DAG.getConstant(1, dl, MVT::i32));
7893 
7894   SDValue LongMul = DAG.getNode(Opc, dl,
7895                                 DAG.getVTList(MVT::i32, MVT::i32),
7896                                 N->getOperand(1), N->getOperand(2),
7897                                 Lo, Hi);
7898   Results.push_back(LongMul.getValue(0));
7899   Results.push_back(LongMul.getValue(1));
7900 }
7901 
7902 /// ReplaceNodeResults - Replace the results of node with an illegal result
7903 /// type with new values built out of custom code.
7904 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7905                                            SmallVectorImpl<SDValue> &Results,
7906                                            SelectionDAG &DAG) const {
7907   SDValue Res;
7908   switch (N->getOpcode()) {
7909   default:
7910     llvm_unreachable("Don't know how to custom expand this!");
7911   case ISD::READ_REGISTER:
7912     ExpandREAD_REGISTER(N, Results, DAG);
7913     break;
7914   case ISD::BITCAST:
7915     Res = ExpandBITCAST(N, DAG);
7916     break;
7917   case ISD::SRL:
7918   case ISD::SRA:
7919     Res = Expand64BitShift(N, DAG, Subtarget);
7920     break;
7921   case ISD::SREM:
7922   case ISD::UREM:
7923     Res = LowerREM(N, DAG);
7924     break;
7925   case ISD::SDIVREM:
7926   case ISD::UDIVREM:
7927     Res = LowerDivRem(SDValue(N, 0), DAG);
7928     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7929     Results.push_back(Res.getValue(0));
7930     Results.push_back(Res.getValue(1));
7931     return;
7932   case ISD::READCYCLECOUNTER:
7933     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7934     return;
7935   case ISD::UDIV:
7936   case ISD::SDIV:
7937     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7938     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7939                              Results);
7940   case ISD::ATOMIC_CMP_SWAP:
7941     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7942     return;
7943   case ISD::INTRINSIC_WO_CHAIN:
7944     return ReplaceLongIntrinsic(N, Results, DAG);
7945   }
7946   if (Res.getNode())
7947     Results.push_back(Res);
7948 }
7949 
7950 //===----------------------------------------------------------------------===//
7951 //                           ARM Scheduler Hooks
7952 //===----------------------------------------------------------------------===//
7953 
7954 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7955 /// registers the function context.
7956 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7957                                                MachineBasicBlock *MBB,
7958                                                MachineBasicBlock *DispatchBB,
7959                                                int FI) const {
7960   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7961          "ROPI/RWPI not currently supported with SjLj");
7962   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7963   DebugLoc dl = MI.getDebugLoc();
7964   MachineFunction *MF = MBB->getParent();
7965   MachineRegisterInfo *MRI = &MF->getRegInfo();
7966   MachineConstantPool *MCP = MF->getConstantPool();
7967   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7968   const Function *F = MF->getFunction();
7969 
7970   bool isThumb = Subtarget->isThumb();
7971   bool isThumb2 = Subtarget->isThumb2();
7972 
7973   unsigned PCLabelId = AFI->createPICLabelUId();
7974   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7975   ARMConstantPoolValue *CPV =
7976     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7977   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7978 
7979   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7980                                            : &ARM::GPRRegClass;
7981 
7982   // Grab constant pool and fixed stack memory operands.
7983   MachineMemOperand *CPMMO =
7984       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7985                                MachineMemOperand::MOLoad, 4, 4);
7986 
7987   MachineMemOperand *FIMMOSt =
7988       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7989                                MachineMemOperand::MOStore, 4, 4);
7990 
7991   // Load the address of the dispatch MBB into the jump buffer.
7992   if (isThumb2) {
7993     // Incoming value: jbuf
7994     //   ldr.n  r5, LCPI1_1
7995     //   orr    r5, r5, #1
7996     //   add    r5, pc
7997     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7998     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7999     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8000         .addConstantPoolIndex(CPI)
8001         .addMemOperand(CPMMO)
8002         .add(predOps(ARMCC::AL));
8003     // Set the low bit because of thumb mode.
8004     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8005     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8006         .addReg(NewVReg1, RegState::Kill)
8007         .addImm(0x01)
8008         .add(predOps(ARMCC::AL))
8009         .add(condCodeOp());
8010     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8011     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8012       .addReg(NewVReg2, RegState::Kill)
8013       .addImm(PCLabelId);
8014     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8015         .addReg(NewVReg3, RegState::Kill)
8016         .addFrameIndex(FI)
8017         .addImm(36) // &jbuf[1] :: pc
8018         .addMemOperand(FIMMOSt)
8019         .add(predOps(ARMCC::AL));
8020   } else if (isThumb) {
8021     // Incoming value: jbuf
8022     //   ldr.n  r1, LCPI1_4
8023     //   add    r1, pc
8024     //   mov    r2, #1
8025     //   orrs   r1, r2
8026     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8027     //   str    r1, [r2]
8028     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8029     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8030         .addConstantPoolIndex(CPI)
8031         .addMemOperand(CPMMO)
8032         .add(predOps(ARMCC::AL));
8033     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8034     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8035       .addReg(NewVReg1, RegState::Kill)
8036       .addImm(PCLabelId);
8037     // Set the low bit because of thumb mode.
8038     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8039     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8040         .addReg(ARM::CPSR, RegState::Define)
8041         .addImm(1)
8042         .add(predOps(ARMCC::AL));
8043     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8044     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8045         .addReg(ARM::CPSR, RegState::Define)
8046         .addReg(NewVReg2, RegState::Kill)
8047         .addReg(NewVReg3, RegState::Kill)
8048         .add(predOps(ARMCC::AL));
8049     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8050     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8051             .addFrameIndex(FI)
8052             .addImm(36); // &jbuf[1] :: pc
8053     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8054         .addReg(NewVReg4, RegState::Kill)
8055         .addReg(NewVReg5, RegState::Kill)
8056         .addImm(0)
8057         .addMemOperand(FIMMOSt)
8058         .add(predOps(ARMCC::AL));
8059   } else {
8060     // Incoming value: jbuf
8061     //   ldr  r1, LCPI1_1
8062     //   add  r1, pc, r1
8063     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8064     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8065     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8066         .addConstantPoolIndex(CPI)
8067         .addImm(0)
8068         .addMemOperand(CPMMO)
8069         .add(predOps(ARMCC::AL));
8070     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8071     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8072         .addReg(NewVReg1, RegState::Kill)
8073         .addImm(PCLabelId)
8074         .add(predOps(ARMCC::AL));
8075     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8076         .addReg(NewVReg2, RegState::Kill)
8077         .addFrameIndex(FI)
8078         .addImm(36) // &jbuf[1] :: pc
8079         .addMemOperand(FIMMOSt)
8080         .add(predOps(ARMCC::AL));
8081   }
8082 }
8083 
8084 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8085                                               MachineBasicBlock *MBB) const {
8086   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8087   DebugLoc dl = MI.getDebugLoc();
8088   MachineFunction *MF = MBB->getParent();
8089   MachineRegisterInfo *MRI = &MF->getRegInfo();
8090   MachineFrameInfo &MFI = MF->getFrameInfo();
8091   int FI = MFI.getFunctionContextIndex();
8092 
8093   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8094                                                         : &ARM::GPRnopcRegClass;
8095 
8096   // Get a mapping of the call site numbers to all of the landing pads they're
8097   // associated with.
8098   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8099   unsigned MaxCSNum = 0;
8100   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8101        ++BB) {
8102     if (!BB->isEHPad()) continue;
8103 
8104     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8105     // pad.
8106     for (MachineBasicBlock::iterator
8107            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8108       if (!II->isEHLabel()) continue;
8109 
8110       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8111       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8112 
8113       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8114       for (SmallVectorImpl<unsigned>::iterator
8115              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8116            CSI != CSE; ++CSI) {
8117         CallSiteNumToLPad[*CSI].push_back(&*BB);
8118         MaxCSNum = std::max(MaxCSNum, *CSI);
8119       }
8120       break;
8121     }
8122   }
8123 
8124   // Get an ordered list of the machine basic blocks for the jump table.
8125   std::vector<MachineBasicBlock*> LPadList;
8126   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8127   LPadList.reserve(CallSiteNumToLPad.size());
8128   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8129     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8130     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8131            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8132       LPadList.push_back(*II);
8133       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8134     }
8135   }
8136 
8137   assert(!LPadList.empty() &&
8138          "No landing pad destinations for the dispatch jump table!");
8139 
8140   // Create the jump table and associated information.
8141   MachineJumpTableInfo *JTI =
8142     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8143   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8144 
8145   // Create the MBBs for the dispatch code.
8146 
8147   // Shove the dispatch's address into the return slot in the function context.
8148   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8149   DispatchBB->setIsEHPad();
8150 
8151   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8152   unsigned trap_opcode;
8153   if (Subtarget->isThumb())
8154     trap_opcode = ARM::tTRAP;
8155   else
8156     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8157 
8158   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8159   DispatchBB->addSuccessor(TrapBB);
8160 
8161   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8162   DispatchBB->addSuccessor(DispContBB);
8163 
8164   // Insert and MBBs.
8165   MF->insert(MF->end(), DispatchBB);
8166   MF->insert(MF->end(), DispContBB);
8167   MF->insert(MF->end(), TrapBB);
8168 
8169   // Insert code into the entry block that creates and registers the function
8170   // context.
8171   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8172 
8173   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8174       MachinePointerInfo::getFixedStack(*MF, FI),
8175       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8176 
8177   MachineInstrBuilder MIB;
8178   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8179 
8180   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8181   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8182 
8183   // Add a register mask with no preserved registers.  This results in all
8184   // registers being marked as clobbered. This can't work if the dispatch block
8185   // is in a Thumb1 function and is linked with ARM code which uses the FP
8186   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8187   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8188 
8189   bool IsPositionIndependent = isPositionIndependent();
8190   unsigned NumLPads = LPadList.size();
8191   if (Subtarget->isThumb2()) {
8192     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8193     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8194         .addFrameIndex(FI)
8195         .addImm(4)
8196         .addMemOperand(FIMMOLd)
8197         .add(predOps(ARMCC::AL));
8198 
8199     if (NumLPads < 256) {
8200       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8201           .addReg(NewVReg1)
8202           .addImm(LPadList.size())
8203           .add(predOps(ARMCC::AL));
8204     } else {
8205       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8206       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8207           .addImm(NumLPads & 0xFFFF)
8208           .add(predOps(ARMCC::AL));
8209 
8210       unsigned VReg2 = VReg1;
8211       if ((NumLPads & 0xFFFF0000) != 0) {
8212         VReg2 = MRI->createVirtualRegister(TRC);
8213         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8214             .addReg(VReg1)
8215             .addImm(NumLPads >> 16)
8216             .add(predOps(ARMCC::AL));
8217       }
8218 
8219       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8220           .addReg(NewVReg1)
8221           .addReg(VReg2)
8222           .add(predOps(ARMCC::AL));
8223     }
8224 
8225     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8226       .addMBB(TrapBB)
8227       .addImm(ARMCC::HI)
8228       .addReg(ARM::CPSR);
8229 
8230     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8231     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8232         .addJumpTableIndex(MJTI)
8233         .add(predOps(ARMCC::AL));
8234 
8235     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8236     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8237         .addReg(NewVReg3, RegState::Kill)
8238         .addReg(NewVReg1)
8239         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8240         .add(predOps(ARMCC::AL))
8241         .add(condCodeOp());
8242 
8243     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8244       .addReg(NewVReg4, RegState::Kill)
8245       .addReg(NewVReg1)
8246       .addJumpTableIndex(MJTI);
8247   } else if (Subtarget->isThumb()) {
8248     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8249     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8250         .addFrameIndex(FI)
8251         .addImm(1)
8252         .addMemOperand(FIMMOLd)
8253         .add(predOps(ARMCC::AL));
8254 
8255     if (NumLPads < 256) {
8256       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8257           .addReg(NewVReg1)
8258           .addImm(NumLPads)
8259           .add(predOps(ARMCC::AL));
8260     } else {
8261       MachineConstantPool *ConstantPool = MF->getConstantPool();
8262       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8263       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8264 
8265       // MachineConstantPool wants an explicit alignment.
8266       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8267       if (Align == 0)
8268         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8269       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8270 
8271       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8272       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8273           .addReg(VReg1, RegState::Define)
8274           .addConstantPoolIndex(Idx)
8275           .add(predOps(ARMCC::AL));
8276       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8277           .addReg(NewVReg1)
8278           .addReg(VReg1)
8279           .add(predOps(ARMCC::AL));
8280     }
8281 
8282     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8283       .addMBB(TrapBB)
8284       .addImm(ARMCC::HI)
8285       .addReg(ARM::CPSR);
8286 
8287     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8288     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8289         .addReg(ARM::CPSR, RegState::Define)
8290         .addReg(NewVReg1)
8291         .addImm(2)
8292         .add(predOps(ARMCC::AL));
8293 
8294     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8295     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8296         .addJumpTableIndex(MJTI)
8297         .add(predOps(ARMCC::AL));
8298 
8299     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8300     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8301         .addReg(ARM::CPSR, RegState::Define)
8302         .addReg(NewVReg2, RegState::Kill)
8303         .addReg(NewVReg3)
8304         .add(predOps(ARMCC::AL));
8305 
8306     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8307         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8308 
8309     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8310     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8311         .addReg(NewVReg4, RegState::Kill)
8312         .addImm(0)
8313         .addMemOperand(JTMMOLd)
8314         .add(predOps(ARMCC::AL));
8315 
8316     unsigned NewVReg6 = NewVReg5;
8317     if (IsPositionIndependent) {
8318       NewVReg6 = MRI->createVirtualRegister(TRC);
8319       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8320           .addReg(ARM::CPSR, RegState::Define)
8321           .addReg(NewVReg5, RegState::Kill)
8322           .addReg(NewVReg3)
8323           .add(predOps(ARMCC::AL));
8324     }
8325 
8326     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8327       .addReg(NewVReg6, RegState::Kill)
8328       .addJumpTableIndex(MJTI);
8329   } else {
8330     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8331     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8332         .addFrameIndex(FI)
8333         .addImm(4)
8334         .addMemOperand(FIMMOLd)
8335         .add(predOps(ARMCC::AL));
8336 
8337     if (NumLPads < 256) {
8338       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8339           .addReg(NewVReg1)
8340           .addImm(NumLPads)
8341           .add(predOps(ARMCC::AL));
8342     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8343       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8344       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8345           .addImm(NumLPads & 0xFFFF)
8346           .add(predOps(ARMCC::AL));
8347 
8348       unsigned VReg2 = VReg1;
8349       if ((NumLPads & 0xFFFF0000) != 0) {
8350         VReg2 = MRI->createVirtualRegister(TRC);
8351         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8352             .addReg(VReg1)
8353             .addImm(NumLPads >> 16)
8354             .add(predOps(ARMCC::AL));
8355       }
8356 
8357       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8358           .addReg(NewVReg1)
8359           .addReg(VReg2)
8360           .add(predOps(ARMCC::AL));
8361     } else {
8362       MachineConstantPool *ConstantPool = MF->getConstantPool();
8363       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8364       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8365 
8366       // MachineConstantPool wants an explicit alignment.
8367       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8368       if (Align == 0)
8369         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8370       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8371 
8372       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8373       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8374           .addReg(VReg1, RegState::Define)
8375           .addConstantPoolIndex(Idx)
8376           .addImm(0)
8377           .add(predOps(ARMCC::AL));
8378       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8379           .addReg(NewVReg1)
8380           .addReg(VReg1, RegState::Kill)
8381           .add(predOps(ARMCC::AL));
8382     }
8383 
8384     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8385       .addMBB(TrapBB)
8386       .addImm(ARMCC::HI)
8387       .addReg(ARM::CPSR);
8388 
8389     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8390     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8391         .addReg(NewVReg1)
8392         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8393         .add(predOps(ARMCC::AL))
8394         .add(condCodeOp());
8395     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8396     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8397         .addJumpTableIndex(MJTI)
8398         .add(predOps(ARMCC::AL));
8399 
8400     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8401         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8402     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8403     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8404         .addReg(NewVReg3, RegState::Kill)
8405         .addReg(NewVReg4)
8406         .addImm(0)
8407         .addMemOperand(JTMMOLd)
8408         .add(predOps(ARMCC::AL));
8409 
8410     if (IsPositionIndependent) {
8411       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8412         .addReg(NewVReg5, RegState::Kill)
8413         .addReg(NewVReg4)
8414         .addJumpTableIndex(MJTI);
8415     } else {
8416       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8417         .addReg(NewVReg5, RegState::Kill)
8418         .addJumpTableIndex(MJTI);
8419     }
8420   }
8421 
8422   // Add the jump table entries as successors to the MBB.
8423   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8424   for (std::vector<MachineBasicBlock*>::iterator
8425          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8426     MachineBasicBlock *CurMBB = *I;
8427     if (SeenMBBs.insert(CurMBB).second)
8428       DispContBB->addSuccessor(CurMBB);
8429   }
8430 
8431   // N.B. the order the invoke BBs are processed in doesn't matter here.
8432   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8433   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8434   for (MachineBasicBlock *BB : InvokeBBs) {
8435 
8436     // Remove the landing pad successor from the invoke block and replace it
8437     // with the new dispatch block.
8438     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8439                                                   BB->succ_end());
8440     while (!Successors.empty()) {
8441       MachineBasicBlock *SMBB = Successors.pop_back_val();
8442       if (SMBB->isEHPad()) {
8443         BB->removeSuccessor(SMBB);
8444         MBBLPads.push_back(SMBB);
8445       }
8446     }
8447 
8448     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8449     BB->normalizeSuccProbs();
8450 
8451     // Find the invoke call and mark all of the callee-saved registers as
8452     // 'implicit defined' so that they're spilled. This prevents code from
8453     // moving instructions to before the EH block, where they will never be
8454     // executed.
8455     for (MachineBasicBlock::reverse_iterator
8456            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8457       if (!II->isCall()) continue;
8458 
8459       DenseMap<unsigned, bool> DefRegs;
8460       for (MachineInstr::mop_iterator
8461              OI = II->operands_begin(), OE = II->operands_end();
8462            OI != OE; ++OI) {
8463         if (!OI->isReg()) continue;
8464         DefRegs[OI->getReg()] = true;
8465       }
8466 
8467       MachineInstrBuilder MIB(*MF, &*II);
8468 
8469       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8470         unsigned Reg = SavedRegs[i];
8471         if (Subtarget->isThumb2() &&
8472             !ARM::tGPRRegClass.contains(Reg) &&
8473             !ARM::hGPRRegClass.contains(Reg))
8474           continue;
8475         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8476           continue;
8477         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8478           continue;
8479         if (!DefRegs[Reg])
8480           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8481       }
8482 
8483       break;
8484     }
8485   }
8486 
8487   // Mark all former landing pads as non-landing pads. The dispatch is the only
8488   // landing pad now.
8489   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8490          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8491     (*I)->setIsEHPad(false);
8492 
8493   // The instruction is gone now.
8494   MI.eraseFromParent();
8495 }
8496 
8497 static
8498 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8499   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8500        E = MBB->succ_end(); I != E; ++I)
8501     if (*I != Succ)
8502       return *I;
8503   llvm_unreachable("Expecting a BB with two successors!");
8504 }
8505 
8506 /// Return the load opcode for a given load size. If load size >= 8,
8507 /// neon opcode will be returned.
8508 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8509   if (LdSize >= 8)
8510     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8511                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8512   if (IsThumb1)
8513     return LdSize == 4 ? ARM::tLDRi
8514                        : LdSize == 2 ? ARM::tLDRHi
8515                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8516   if (IsThumb2)
8517     return LdSize == 4 ? ARM::t2LDR_POST
8518                        : LdSize == 2 ? ARM::t2LDRH_POST
8519                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8520   return LdSize == 4 ? ARM::LDR_POST_IMM
8521                      : LdSize == 2 ? ARM::LDRH_POST
8522                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8523 }
8524 
8525 /// Return the store opcode for a given store size. If store size >= 8,
8526 /// neon opcode will be returned.
8527 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8528   if (StSize >= 8)
8529     return StSize == 16 ? ARM::VST1q32wb_fixed
8530                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8531   if (IsThumb1)
8532     return StSize == 4 ? ARM::tSTRi
8533                        : StSize == 2 ? ARM::tSTRHi
8534                                      : StSize == 1 ? ARM::tSTRBi : 0;
8535   if (IsThumb2)
8536     return StSize == 4 ? ARM::t2STR_POST
8537                        : StSize == 2 ? ARM::t2STRH_POST
8538                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8539   return StSize == 4 ? ARM::STR_POST_IMM
8540                      : StSize == 2 ? ARM::STRH_POST
8541                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8542 }
8543 
8544 /// Emit a post-increment load operation with given size. The instructions
8545 /// will be added to BB at Pos.
8546 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8547                        const TargetInstrInfo *TII, const DebugLoc &dl,
8548                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8549                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8550   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8551   assert(LdOpc != 0 && "Should have a load opcode");
8552   if (LdSize >= 8) {
8553     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8554         .addReg(AddrOut, RegState::Define)
8555         .addReg(AddrIn)
8556         .addImm(0)
8557         .add(predOps(ARMCC::AL));
8558   } else if (IsThumb1) {
8559     // load + update AddrIn
8560     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8561         .addReg(AddrIn)
8562         .addImm(0)
8563         .add(predOps(ARMCC::AL));
8564     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8565         .add(t1CondCodeOp())
8566         .addReg(AddrIn)
8567         .addImm(LdSize)
8568         .add(predOps(ARMCC::AL));
8569   } else if (IsThumb2) {
8570     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8571         .addReg(AddrOut, RegState::Define)
8572         .addReg(AddrIn)
8573         .addImm(LdSize)
8574         .add(predOps(ARMCC::AL));
8575   } else { // arm
8576     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8577         .addReg(AddrOut, RegState::Define)
8578         .addReg(AddrIn)
8579         .addReg(0)
8580         .addImm(LdSize)
8581         .add(predOps(ARMCC::AL));
8582   }
8583 }
8584 
8585 /// Emit a post-increment store operation with given size. The instructions
8586 /// will be added to BB at Pos.
8587 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8588                        const TargetInstrInfo *TII, const DebugLoc &dl,
8589                        unsigned StSize, unsigned Data, unsigned AddrIn,
8590                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8591   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8592   assert(StOpc != 0 && "Should have a store opcode");
8593   if (StSize >= 8) {
8594     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8595         .addReg(AddrIn)
8596         .addImm(0)
8597         .addReg(Data)
8598         .add(predOps(ARMCC::AL));
8599   } else if (IsThumb1) {
8600     // store + update AddrIn
8601     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8602         .addReg(Data)
8603         .addReg(AddrIn)
8604         .addImm(0)
8605         .add(predOps(ARMCC::AL));
8606     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8607         .add(t1CondCodeOp())
8608         .addReg(AddrIn)
8609         .addImm(StSize)
8610         .add(predOps(ARMCC::AL));
8611   } else if (IsThumb2) {
8612     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8613         .addReg(Data)
8614         .addReg(AddrIn)
8615         .addImm(StSize)
8616         .add(predOps(ARMCC::AL));
8617   } else { // arm
8618     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8619         .addReg(Data)
8620         .addReg(AddrIn)
8621         .addReg(0)
8622         .addImm(StSize)
8623         .add(predOps(ARMCC::AL));
8624   }
8625 }
8626 
8627 MachineBasicBlock *
8628 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8629                                    MachineBasicBlock *BB) const {
8630   // This pseudo instruction has 3 operands: dst, src, size
8631   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8632   // Otherwise, we will generate unrolled scalar copies.
8633   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8634   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8635   MachineFunction::iterator It = ++BB->getIterator();
8636 
8637   unsigned dest = MI.getOperand(0).getReg();
8638   unsigned src = MI.getOperand(1).getReg();
8639   unsigned SizeVal = MI.getOperand(2).getImm();
8640   unsigned Align = MI.getOperand(3).getImm();
8641   DebugLoc dl = MI.getDebugLoc();
8642 
8643   MachineFunction *MF = BB->getParent();
8644   MachineRegisterInfo &MRI = MF->getRegInfo();
8645   unsigned UnitSize = 0;
8646   const TargetRegisterClass *TRC = nullptr;
8647   const TargetRegisterClass *VecTRC = nullptr;
8648 
8649   bool IsThumb1 = Subtarget->isThumb1Only();
8650   bool IsThumb2 = Subtarget->isThumb2();
8651   bool IsThumb = Subtarget->isThumb();
8652 
8653   if (Align & 1) {
8654     UnitSize = 1;
8655   } else if (Align & 2) {
8656     UnitSize = 2;
8657   } else {
8658     // Check whether we can use NEON instructions.
8659     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8660         Subtarget->hasNEON()) {
8661       if ((Align % 16 == 0) && SizeVal >= 16)
8662         UnitSize = 16;
8663       else if ((Align % 8 == 0) && SizeVal >= 8)
8664         UnitSize = 8;
8665     }
8666     // Can't use NEON instructions.
8667     if (UnitSize == 0)
8668       UnitSize = 4;
8669   }
8670 
8671   // Select the correct opcode and register class for unit size load/store
8672   bool IsNeon = UnitSize >= 8;
8673   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8674   if (IsNeon)
8675     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8676                             : UnitSize == 8 ? &ARM::DPRRegClass
8677                                             : nullptr;
8678 
8679   unsigned BytesLeft = SizeVal % UnitSize;
8680   unsigned LoopSize = SizeVal - BytesLeft;
8681 
8682   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8683     // Use LDR and STR to copy.
8684     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8685     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8686     unsigned srcIn = src;
8687     unsigned destIn = dest;
8688     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8689       unsigned srcOut = MRI.createVirtualRegister(TRC);
8690       unsigned destOut = MRI.createVirtualRegister(TRC);
8691       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8692       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8693                  IsThumb1, IsThumb2);
8694       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8695                  IsThumb1, IsThumb2);
8696       srcIn = srcOut;
8697       destIn = destOut;
8698     }
8699 
8700     // Handle the leftover bytes with LDRB and STRB.
8701     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8702     // [destOut] = STRB_POST(scratch, destIn, 1)
8703     for (unsigned i = 0; i < BytesLeft; i++) {
8704       unsigned srcOut = MRI.createVirtualRegister(TRC);
8705       unsigned destOut = MRI.createVirtualRegister(TRC);
8706       unsigned scratch = MRI.createVirtualRegister(TRC);
8707       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8708                  IsThumb1, IsThumb2);
8709       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8710                  IsThumb1, IsThumb2);
8711       srcIn = srcOut;
8712       destIn = destOut;
8713     }
8714     MI.eraseFromParent(); // The instruction is gone now.
8715     return BB;
8716   }
8717 
8718   // Expand the pseudo op to a loop.
8719   // thisMBB:
8720   //   ...
8721   //   movw varEnd, # --> with thumb2
8722   //   movt varEnd, #
8723   //   ldrcp varEnd, idx --> without thumb2
8724   //   fallthrough --> loopMBB
8725   // loopMBB:
8726   //   PHI varPhi, varEnd, varLoop
8727   //   PHI srcPhi, src, srcLoop
8728   //   PHI destPhi, dst, destLoop
8729   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8730   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8731   //   subs varLoop, varPhi, #UnitSize
8732   //   bne loopMBB
8733   //   fallthrough --> exitMBB
8734   // exitMBB:
8735   //   epilogue to handle left-over bytes
8736   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8737   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8738   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8739   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8740   MF->insert(It, loopMBB);
8741   MF->insert(It, exitMBB);
8742 
8743   // Transfer the remainder of BB and its successor edges to exitMBB.
8744   exitMBB->splice(exitMBB->begin(), BB,
8745                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8746   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8747 
8748   // Load an immediate to varEnd.
8749   unsigned varEnd = MRI.createVirtualRegister(TRC);
8750   if (Subtarget->useMovt(*MF)) {
8751     unsigned Vtmp = varEnd;
8752     if ((LoopSize & 0xFFFF0000) != 0)
8753       Vtmp = MRI.createVirtualRegister(TRC);
8754     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8755         .addImm(LoopSize & 0xFFFF)
8756         .add(predOps(ARMCC::AL));
8757 
8758     if ((LoopSize & 0xFFFF0000) != 0)
8759       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8760           .addReg(Vtmp)
8761           .addImm(LoopSize >> 16)
8762           .add(predOps(ARMCC::AL));
8763   } else {
8764     MachineConstantPool *ConstantPool = MF->getConstantPool();
8765     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8766     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8767 
8768     // MachineConstantPool wants an explicit alignment.
8769     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8770     if (Align == 0)
8771       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8772     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8773 
8774     if (IsThumb)
8775       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8776           .addReg(varEnd, RegState::Define)
8777           .addConstantPoolIndex(Idx)
8778           .add(predOps(ARMCC::AL));
8779     else
8780       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8781           .addReg(varEnd, RegState::Define)
8782           .addConstantPoolIndex(Idx)
8783           .addImm(0)
8784           .add(predOps(ARMCC::AL));
8785   }
8786   BB->addSuccessor(loopMBB);
8787 
8788   // Generate the loop body:
8789   //   varPhi = PHI(varLoop, varEnd)
8790   //   srcPhi = PHI(srcLoop, src)
8791   //   destPhi = PHI(destLoop, dst)
8792   MachineBasicBlock *entryBB = BB;
8793   BB = loopMBB;
8794   unsigned varLoop = MRI.createVirtualRegister(TRC);
8795   unsigned varPhi = MRI.createVirtualRegister(TRC);
8796   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8797   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8798   unsigned destLoop = MRI.createVirtualRegister(TRC);
8799   unsigned destPhi = MRI.createVirtualRegister(TRC);
8800 
8801   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8802     .addReg(varLoop).addMBB(loopMBB)
8803     .addReg(varEnd).addMBB(entryBB);
8804   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8805     .addReg(srcLoop).addMBB(loopMBB)
8806     .addReg(src).addMBB(entryBB);
8807   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8808     .addReg(destLoop).addMBB(loopMBB)
8809     .addReg(dest).addMBB(entryBB);
8810 
8811   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8812   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8813   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8814   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8815              IsThumb1, IsThumb2);
8816   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8817              IsThumb1, IsThumb2);
8818 
8819   // Decrement loop variable by UnitSize.
8820   if (IsThumb1) {
8821     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8822         .add(t1CondCodeOp())
8823         .addReg(varPhi)
8824         .addImm(UnitSize)
8825         .add(predOps(ARMCC::AL));
8826   } else {
8827     MachineInstrBuilder MIB =
8828         BuildMI(*BB, BB->end(), dl,
8829                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8830     MIB.addReg(varPhi)
8831         .addImm(UnitSize)
8832         .add(predOps(ARMCC::AL))
8833         .add(condCodeOp());
8834     MIB->getOperand(5).setReg(ARM::CPSR);
8835     MIB->getOperand(5).setIsDef(true);
8836   }
8837   BuildMI(*BB, BB->end(), dl,
8838           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8839       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8840 
8841   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8842   BB->addSuccessor(loopMBB);
8843   BB->addSuccessor(exitMBB);
8844 
8845   // Add epilogue to handle BytesLeft.
8846   BB = exitMBB;
8847   auto StartOfExit = exitMBB->begin();
8848 
8849   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8850   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8851   unsigned srcIn = srcLoop;
8852   unsigned destIn = destLoop;
8853   for (unsigned i = 0; i < BytesLeft; i++) {
8854     unsigned srcOut = MRI.createVirtualRegister(TRC);
8855     unsigned destOut = MRI.createVirtualRegister(TRC);
8856     unsigned scratch = MRI.createVirtualRegister(TRC);
8857     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8858                IsThumb1, IsThumb2);
8859     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8860                IsThumb1, IsThumb2);
8861     srcIn = srcOut;
8862     destIn = destOut;
8863   }
8864 
8865   MI.eraseFromParent(); // The instruction is gone now.
8866   return BB;
8867 }
8868 
8869 MachineBasicBlock *
8870 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8871                                        MachineBasicBlock *MBB) const {
8872   const TargetMachine &TM = getTargetMachine();
8873   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8874   DebugLoc DL = MI.getDebugLoc();
8875 
8876   assert(Subtarget->isTargetWindows() &&
8877          "__chkstk is only supported on Windows");
8878   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8879 
8880   // __chkstk takes the number of words to allocate on the stack in R4, and
8881   // returns the stack adjustment in number of bytes in R4.  This will not
8882   // clober any other registers (other than the obvious lr).
8883   //
8884   // Although, technically, IP should be considered a register which may be
8885   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8886   // thumb-2 environment, so there is no interworking required.  As a result, we
8887   // do not expect a veneer to be emitted by the linker, clobbering IP.
8888   //
8889   // Each module receives its own copy of __chkstk, so no import thunk is
8890   // required, again, ensuring that IP is not clobbered.
8891   //
8892   // Finally, although some linkers may theoretically provide a trampoline for
8893   // out of range calls (which is quite common due to a 32M range limitation of
8894   // branches for Thumb), we can generate the long-call version via
8895   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8896   // IP.
8897 
8898   switch (TM.getCodeModel()) {
8899   case CodeModel::Small:
8900   case CodeModel::Medium:
8901   case CodeModel::Kernel:
8902     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8903         .add(predOps(ARMCC::AL))
8904         .addExternalSymbol("__chkstk")
8905         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8906         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8907         .addReg(ARM::R12,
8908                 RegState::Implicit | RegState::Define | RegState::Dead)
8909         .addReg(ARM::CPSR,
8910                 RegState::Implicit | RegState::Define | RegState::Dead);
8911     break;
8912   case CodeModel::Large: {
8913     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8914     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8915 
8916     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8917       .addExternalSymbol("__chkstk");
8918     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8919         .add(predOps(ARMCC::AL))
8920         .addReg(Reg, RegState::Kill)
8921         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8922         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8923         .addReg(ARM::R12,
8924                 RegState::Implicit | RegState::Define | RegState::Dead)
8925         .addReg(ARM::CPSR,
8926                 RegState::Implicit | RegState::Define | RegState::Dead);
8927     break;
8928   }
8929   }
8930 
8931   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8932       .addReg(ARM::SP, RegState::Kill)
8933       .addReg(ARM::R4, RegState::Kill)
8934       .setMIFlags(MachineInstr::FrameSetup)
8935       .add(predOps(ARMCC::AL))
8936       .add(condCodeOp());
8937 
8938   MI.eraseFromParent();
8939   return MBB;
8940 }
8941 
8942 MachineBasicBlock *
8943 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8944                                        MachineBasicBlock *MBB) const {
8945   DebugLoc DL = MI.getDebugLoc();
8946   MachineFunction *MF = MBB->getParent();
8947   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8948 
8949   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8950   MF->insert(++MBB->getIterator(), ContBB);
8951   ContBB->splice(ContBB->begin(), MBB,
8952                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8953   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8954   MBB->addSuccessor(ContBB);
8955 
8956   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8957   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8958   MF->push_back(TrapBB);
8959   MBB->addSuccessor(TrapBB);
8960 
8961   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8962       .addReg(MI.getOperand(0).getReg())
8963       .addImm(0)
8964       .add(predOps(ARMCC::AL));
8965   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8966       .addMBB(TrapBB)
8967       .addImm(ARMCC::EQ)
8968       .addReg(ARM::CPSR);
8969 
8970   MI.eraseFromParent();
8971   return ContBB;
8972 }
8973 
8974 MachineBasicBlock *
8975 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8976                                                MachineBasicBlock *BB) const {
8977   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8978   DebugLoc dl = MI.getDebugLoc();
8979   bool isThumb2 = Subtarget->isThumb2();
8980   switch (MI.getOpcode()) {
8981   default: {
8982     MI.print(errs());
8983     llvm_unreachable("Unexpected instr type to insert");
8984   }
8985 
8986   // Thumb1 post-indexed loads are really just single-register LDMs.
8987   case ARM::tLDR_postidx: {
8988     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8989         .add(MI.getOperand(1))  // Rn_wb
8990         .add(MI.getOperand(2))  // Rn
8991         .add(MI.getOperand(3))  // PredImm
8992         .add(MI.getOperand(4))  // PredReg
8993         .add(MI.getOperand(0)); // Rt
8994     MI.eraseFromParent();
8995     return BB;
8996   }
8997 
8998   // The Thumb2 pre-indexed stores have the same MI operands, they just
8999   // define them differently in the .td files from the isel patterns, so
9000   // they need pseudos.
9001   case ARM::t2STR_preidx:
9002     MI.setDesc(TII->get(ARM::t2STR_PRE));
9003     return BB;
9004   case ARM::t2STRB_preidx:
9005     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9006     return BB;
9007   case ARM::t2STRH_preidx:
9008     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9009     return BB;
9010 
9011   case ARM::STRi_preidx:
9012   case ARM::STRBi_preidx: {
9013     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9014                                                          : ARM::STRB_PRE_IMM;
9015     // Decode the offset.
9016     unsigned Offset = MI.getOperand(4).getImm();
9017     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9018     Offset = ARM_AM::getAM2Offset(Offset);
9019     if (isSub)
9020       Offset = -Offset;
9021 
9022     MachineMemOperand *MMO = *MI.memoperands_begin();
9023     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9024         .add(MI.getOperand(0)) // Rn_wb
9025         .add(MI.getOperand(1)) // Rt
9026         .add(MI.getOperand(2)) // Rn
9027         .addImm(Offset)        // offset (skip GPR==zero_reg)
9028         .add(MI.getOperand(5)) // pred
9029         .add(MI.getOperand(6))
9030         .addMemOperand(MMO);
9031     MI.eraseFromParent();
9032     return BB;
9033   }
9034   case ARM::STRr_preidx:
9035   case ARM::STRBr_preidx:
9036   case ARM::STRH_preidx: {
9037     unsigned NewOpc;
9038     switch (MI.getOpcode()) {
9039     default: llvm_unreachable("unexpected opcode!");
9040     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9041     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9042     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9043     }
9044     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9045     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9046       MIB.add(MI.getOperand(i));
9047     MI.eraseFromParent();
9048     return BB;
9049   }
9050 
9051   case ARM::tMOVCCr_pseudo: {
9052     // To "insert" a SELECT_CC instruction, we actually have to insert the
9053     // diamond control-flow pattern.  The incoming instruction knows the
9054     // destination vreg to set, the condition code register to branch on, the
9055     // true/false values to select between, and a branch opcode to use.
9056     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9057     MachineFunction::iterator It = ++BB->getIterator();
9058 
9059     //  thisMBB:
9060     //  ...
9061     //   TrueVal = ...
9062     //   cmpTY ccX, r1, r2
9063     //   bCC copy1MBB
9064     //   fallthrough --> copy0MBB
9065     MachineBasicBlock *thisMBB  = BB;
9066     MachineFunction *F = BB->getParent();
9067     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9068     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9069     F->insert(It, copy0MBB);
9070     F->insert(It, sinkMBB);
9071 
9072     // Transfer the remainder of BB and its successor edges to sinkMBB.
9073     sinkMBB->splice(sinkMBB->begin(), BB,
9074                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9075     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9076 
9077     BB->addSuccessor(copy0MBB);
9078     BB->addSuccessor(sinkMBB);
9079 
9080     BuildMI(BB, dl, TII->get(ARM::tBcc))
9081         .addMBB(sinkMBB)
9082         .addImm(MI.getOperand(3).getImm())
9083         .addReg(MI.getOperand(4).getReg());
9084 
9085     //  copy0MBB:
9086     //   %FalseValue = ...
9087     //   # fallthrough to sinkMBB
9088     BB = copy0MBB;
9089 
9090     // Update machine-CFG edges
9091     BB->addSuccessor(sinkMBB);
9092 
9093     //  sinkMBB:
9094     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9095     //  ...
9096     BB = sinkMBB;
9097     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9098         .addReg(MI.getOperand(1).getReg())
9099         .addMBB(copy0MBB)
9100         .addReg(MI.getOperand(2).getReg())
9101         .addMBB(thisMBB);
9102 
9103     MI.eraseFromParent(); // The pseudo instruction is gone now.
9104     return BB;
9105   }
9106 
9107   case ARM::BCCi64:
9108   case ARM::BCCZi64: {
9109     // If there is an unconditional branch to the other successor, remove it.
9110     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9111 
9112     // Compare both parts that make up the double comparison separately for
9113     // equality.
9114     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9115 
9116     unsigned LHS1 = MI.getOperand(1).getReg();
9117     unsigned LHS2 = MI.getOperand(2).getReg();
9118     if (RHSisZero) {
9119       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9120           .addReg(LHS1)
9121           .addImm(0)
9122           .add(predOps(ARMCC::AL));
9123       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9124         .addReg(LHS2).addImm(0)
9125         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9126     } else {
9127       unsigned RHS1 = MI.getOperand(3).getReg();
9128       unsigned RHS2 = MI.getOperand(4).getReg();
9129       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9130           .addReg(LHS1)
9131           .addReg(RHS1)
9132           .add(predOps(ARMCC::AL));
9133       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9134         .addReg(LHS2).addReg(RHS2)
9135         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9136     }
9137 
9138     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9139     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9140     if (MI.getOperand(0).getImm() == ARMCC::NE)
9141       std::swap(destMBB, exitMBB);
9142 
9143     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9144       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9145     if (isThumb2)
9146       BuildMI(BB, dl, TII->get(ARM::t2B))
9147           .addMBB(exitMBB)
9148           .add(predOps(ARMCC::AL));
9149     else
9150       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9151 
9152     MI.eraseFromParent(); // The pseudo instruction is gone now.
9153     return BB;
9154   }
9155 
9156   case ARM::Int_eh_sjlj_setjmp:
9157   case ARM::Int_eh_sjlj_setjmp_nofp:
9158   case ARM::tInt_eh_sjlj_setjmp:
9159   case ARM::t2Int_eh_sjlj_setjmp:
9160   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9161     return BB;
9162 
9163   case ARM::Int_eh_sjlj_setup_dispatch:
9164     EmitSjLjDispatchBlock(MI, BB);
9165     return BB;
9166 
9167   case ARM::ABS:
9168   case ARM::t2ABS: {
9169     // To insert an ABS instruction, we have to insert the
9170     // diamond control-flow pattern.  The incoming instruction knows the
9171     // source vreg to test against 0, the destination vreg to set,
9172     // the condition code register to branch on, the
9173     // true/false values to select between, and a branch opcode to use.
9174     // It transforms
9175     //     V1 = ABS V0
9176     // into
9177     //     V2 = MOVS V0
9178     //     BCC                      (branch to SinkBB if V0 >= 0)
9179     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9180     //     SinkBB: V1 = PHI(V2, V3)
9181     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9182     MachineFunction::iterator BBI = ++BB->getIterator();
9183     MachineFunction *Fn = BB->getParent();
9184     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9185     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9186     Fn->insert(BBI, RSBBB);
9187     Fn->insert(BBI, SinkBB);
9188 
9189     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9190     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9191     bool ABSSrcKIll = MI.getOperand(1).isKill();
9192     bool isThumb2 = Subtarget->isThumb2();
9193     MachineRegisterInfo &MRI = Fn->getRegInfo();
9194     // In Thumb mode S must not be specified if source register is the SP or
9195     // PC and if destination register is the SP, so restrict register class
9196     unsigned NewRsbDstReg =
9197       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9198 
9199     // Transfer the remainder of BB and its successor edges to sinkMBB.
9200     SinkBB->splice(SinkBB->begin(), BB,
9201                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9202     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9203 
9204     BB->addSuccessor(RSBBB);
9205     BB->addSuccessor(SinkBB);
9206 
9207     // fall through to SinkMBB
9208     RSBBB->addSuccessor(SinkBB);
9209 
9210     // insert a cmp at the end of BB
9211     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9212         .addReg(ABSSrcReg)
9213         .addImm(0)
9214         .add(predOps(ARMCC::AL));
9215 
9216     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9217     BuildMI(BB, dl,
9218       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9219       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9220 
9221     // insert rsbri in RSBBB
9222     // Note: BCC and rsbri will be converted into predicated rsbmi
9223     // by if-conversion pass
9224     BuildMI(*RSBBB, RSBBB->begin(), dl,
9225             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9226         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9227         .addImm(0)
9228         .add(predOps(ARMCC::AL))
9229         .add(condCodeOp());
9230 
9231     // insert PHI in SinkBB,
9232     // reuse ABSDstReg to not change uses of ABS instruction
9233     BuildMI(*SinkBB, SinkBB->begin(), dl,
9234       TII->get(ARM::PHI), ABSDstReg)
9235       .addReg(NewRsbDstReg).addMBB(RSBBB)
9236       .addReg(ABSSrcReg).addMBB(BB);
9237 
9238     // remove ABS instruction
9239     MI.eraseFromParent();
9240 
9241     // return last added BB
9242     return SinkBB;
9243   }
9244   case ARM::COPY_STRUCT_BYVAL_I32:
9245     ++NumLoopByVals;
9246     return EmitStructByval(MI, BB);
9247   case ARM::WIN__CHKSTK:
9248     return EmitLowered__chkstk(MI, BB);
9249   case ARM::WIN__DBZCHK:
9250     return EmitLowered__dbzchk(MI, BB);
9251   }
9252 }
9253 
9254 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9255 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9256 /// instead of as a custom inserter because we need the use list from the SDNode.
9257 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9258                                     MachineInstr &MI, const SDNode *Node) {
9259   bool isThumb1 = Subtarget->isThumb1Only();
9260 
9261   DebugLoc DL = MI.getDebugLoc();
9262   MachineFunction *MF = MI.getParent()->getParent();
9263   MachineRegisterInfo &MRI = MF->getRegInfo();
9264   MachineInstrBuilder MIB(*MF, MI);
9265 
9266   // If the new dst/src is unused mark it as dead.
9267   if (!Node->hasAnyUseOfValue(0)) {
9268     MI.getOperand(0).setIsDead(true);
9269   }
9270   if (!Node->hasAnyUseOfValue(1)) {
9271     MI.getOperand(1).setIsDead(true);
9272   }
9273 
9274   // The MEMCPY both defines and kills the scratch registers.
9275   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9276     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9277                                                          : &ARM::GPRRegClass);
9278     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9279   }
9280 }
9281 
9282 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9283                                                       SDNode *Node) const {
9284   if (MI.getOpcode() == ARM::MEMCPY) {
9285     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9286     return;
9287   }
9288 
9289   const MCInstrDesc *MCID = &MI.getDesc();
9290   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9291   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9292   // operand is still set to noreg. If needed, set the optional operand's
9293   // register to CPSR, and remove the redundant implicit def.
9294   //
9295   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9296 
9297   // Rename pseudo opcodes.
9298   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9299   unsigned ccOutIdx;
9300   if (NewOpc) {
9301     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9302     MCID = &TII->get(NewOpc);
9303 
9304     assert(MCID->getNumOperands() ==
9305            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9306         && "converted opcode should be the same except for cc_out"
9307            " (and, on Thumb1, pred)");
9308 
9309     MI.setDesc(*MCID);
9310 
9311     // Add the optional cc_out operand
9312     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9313 
9314     // On Thumb1, move all input operands to the end, then add the predicate
9315     if (Subtarget->isThumb1Only()) {
9316       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9317         MI.addOperand(MI.getOperand(1));
9318         MI.RemoveOperand(1);
9319       }
9320 
9321       // Restore the ties
9322       for (unsigned i = MI.getNumOperands(); i--;) {
9323         const MachineOperand& op = MI.getOperand(i);
9324         if (op.isReg() && op.isUse()) {
9325           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9326           if (DefIdx != -1)
9327             MI.tieOperands(DefIdx, i);
9328         }
9329       }
9330 
9331       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9332       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9333       ccOutIdx = 1;
9334     } else
9335       ccOutIdx = MCID->getNumOperands() - 1;
9336   } else
9337     ccOutIdx = MCID->getNumOperands() - 1;
9338 
9339   // Any ARM instruction that sets the 's' bit should specify an optional
9340   // "cc_out" operand in the last operand position.
9341   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9342     assert(!NewOpc && "Optional cc_out operand required");
9343     return;
9344   }
9345   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9346   // since we already have an optional CPSR def.
9347   bool definesCPSR = false;
9348   bool deadCPSR = false;
9349   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9350        ++i) {
9351     const MachineOperand &MO = MI.getOperand(i);
9352     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9353       definesCPSR = true;
9354       if (MO.isDead())
9355         deadCPSR = true;
9356       MI.RemoveOperand(i);
9357       break;
9358     }
9359   }
9360   if (!definesCPSR) {
9361     assert(!NewOpc && "Optional cc_out operand required");
9362     return;
9363   }
9364   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9365   if (deadCPSR) {
9366     assert(!MI.getOperand(ccOutIdx).getReg() &&
9367            "expect uninitialized optional cc_out operand");
9368     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9369     if (!Subtarget->isThumb1Only())
9370       return;
9371   }
9372 
9373   // If this instruction was defined with an optional CPSR def and its dag node
9374   // had a live implicit CPSR def, then activate the optional CPSR def.
9375   MachineOperand &MO = MI.getOperand(ccOutIdx);
9376   MO.setReg(ARM::CPSR);
9377   MO.setIsDef(true);
9378 }
9379 
9380 //===----------------------------------------------------------------------===//
9381 //                           ARM Optimization Hooks
9382 //===----------------------------------------------------------------------===//
9383 
9384 // Helper function that checks if N is a null or all ones constant.
9385 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9386   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9387 }
9388 
9389 // Return true if N is conditionally 0 or all ones.
9390 // Detects these expressions where cc is an i1 value:
9391 //
9392 //   (select cc 0, y)   [AllOnes=0]
9393 //   (select cc y, 0)   [AllOnes=0]
9394 //   (zext cc)          [AllOnes=0]
9395 //   (sext cc)          [AllOnes=0/1]
9396 //   (select cc -1, y)  [AllOnes=1]
9397 //   (select cc y, -1)  [AllOnes=1]
9398 //
9399 // Invert is set when N is the null/all ones constant when CC is false.
9400 // OtherOp is set to the alternative value of N.
9401 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9402                                        SDValue &CC, bool &Invert,
9403                                        SDValue &OtherOp,
9404                                        SelectionDAG &DAG) {
9405   switch (N->getOpcode()) {
9406   default: return false;
9407   case ISD::SELECT: {
9408     CC = N->getOperand(0);
9409     SDValue N1 = N->getOperand(1);
9410     SDValue N2 = N->getOperand(2);
9411     if (isZeroOrAllOnes(N1, AllOnes)) {
9412       Invert = false;
9413       OtherOp = N2;
9414       return true;
9415     }
9416     if (isZeroOrAllOnes(N2, AllOnes)) {
9417       Invert = true;
9418       OtherOp = N1;
9419       return true;
9420     }
9421     return false;
9422   }
9423   case ISD::ZERO_EXTEND:
9424     // (zext cc) can never be the all ones value.
9425     if (AllOnes)
9426       return false;
9427     LLVM_FALLTHROUGH;
9428   case ISD::SIGN_EXTEND: {
9429     SDLoc dl(N);
9430     EVT VT = N->getValueType(0);
9431     CC = N->getOperand(0);
9432     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9433       return false;
9434     Invert = !AllOnes;
9435     if (AllOnes)
9436       // When looking for an AllOnes constant, N is an sext, and the 'other'
9437       // value is 0.
9438       OtherOp = DAG.getConstant(0, dl, VT);
9439     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9440       // When looking for a 0 constant, N can be zext or sext.
9441       OtherOp = DAG.getConstant(1, dl, VT);
9442     else
9443       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9444                                 VT);
9445     return true;
9446   }
9447   }
9448 }
9449 
9450 // Combine a constant select operand into its use:
9451 //
9452 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9453 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9454 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9455 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9456 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9457 //
9458 // The transform is rejected if the select doesn't have a constant operand that
9459 // is null, or all ones when AllOnes is set.
9460 //
9461 // Also recognize sext/zext from i1:
9462 //
9463 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9464 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9465 //
9466 // These transformations eventually create predicated instructions.
9467 //
9468 // @param N       The node to transform.
9469 // @param Slct    The N operand that is a select.
9470 // @param OtherOp The other N operand (x above).
9471 // @param DCI     Context.
9472 // @param AllOnes Require the select constant to be all ones instead of null.
9473 // @returns The new node, or SDValue() on failure.
9474 static
9475 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9476                             TargetLowering::DAGCombinerInfo &DCI,
9477                             bool AllOnes = false) {
9478   SelectionDAG &DAG = DCI.DAG;
9479   EVT VT = N->getValueType(0);
9480   SDValue NonConstantVal;
9481   SDValue CCOp;
9482   bool SwapSelectOps;
9483   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9484                                   NonConstantVal, DAG))
9485     return SDValue();
9486 
9487   // Slct is now know to be the desired identity constant when CC is true.
9488   SDValue TrueVal = OtherOp;
9489   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9490                                  OtherOp, NonConstantVal);
9491   // Unless SwapSelectOps says CC should be false.
9492   if (SwapSelectOps)
9493     std::swap(TrueVal, FalseVal);
9494 
9495   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9496                      CCOp, TrueVal, FalseVal);
9497 }
9498 
9499 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9500 static
9501 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9502                                        TargetLowering::DAGCombinerInfo &DCI) {
9503   SDValue N0 = N->getOperand(0);
9504   SDValue N1 = N->getOperand(1);
9505   if (N0.getNode()->hasOneUse())
9506     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9507       return Result;
9508   if (N1.getNode()->hasOneUse())
9509     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9510       return Result;
9511   return SDValue();
9512 }
9513 
9514 static bool IsVUZPShuffleNode(SDNode *N) {
9515   // VUZP shuffle node.
9516   if (N->getOpcode() == ARMISD::VUZP)
9517     return true;
9518 
9519   // "VUZP" on i32 is an alias for VTRN.
9520   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9521     return true;
9522 
9523   return false;
9524 }
9525 
9526 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9527                                  TargetLowering::DAGCombinerInfo &DCI,
9528                                  const ARMSubtarget *Subtarget) {
9529   // Look for ADD(VUZP.0, VUZP.1).
9530   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9531       N0 == N1)
9532    return SDValue();
9533 
9534   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9535   if (!N->getValueType(0).is64BitVector())
9536     return SDValue();
9537 
9538   // Generate vpadd.
9539   SelectionDAG &DAG = DCI.DAG;
9540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9541   SDLoc dl(N);
9542   SDNode *Unzip = N0.getNode();
9543   EVT VT = N->getValueType(0);
9544 
9545   SmallVector<SDValue, 8> Ops;
9546   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9547                                 TLI.getPointerTy(DAG.getDataLayout())));
9548   Ops.push_back(Unzip->getOperand(0));
9549   Ops.push_back(Unzip->getOperand(1));
9550 
9551   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9552 }
9553 
9554 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9555                                       TargetLowering::DAGCombinerInfo &DCI,
9556                                       const ARMSubtarget *Subtarget) {
9557   // Check for two extended operands.
9558   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9559         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9560       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9561         N1.getOpcode() == ISD::ZERO_EXTEND))
9562     return SDValue();
9563 
9564   SDValue N00 = N0.getOperand(0);
9565   SDValue N10 = N1.getOperand(0);
9566 
9567   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9568   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9569       N00 == N10)
9570     return SDValue();
9571 
9572   // We only recognize Q register paddl here; this can't be reached until
9573   // after type legalization.
9574   if (!N00.getValueType().is64BitVector() ||
9575       !N0.getValueType().is128BitVector())
9576     return SDValue();
9577 
9578   // Generate vpaddl.
9579   SelectionDAG &DAG = DCI.DAG;
9580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9581   SDLoc dl(N);
9582   EVT VT = N->getValueType(0);
9583 
9584   SmallVector<SDValue, 8> Ops;
9585   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9586   unsigned Opcode;
9587   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9588     Opcode = Intrinsic::arm_neon_vpaddls;
9589   else
9590     Opcode = Intrinsic::arm_neon_vpaddlu;
9591   Ops.push_back(DAG.getConstant(Opcode, dl,
9592                                 TLI.getPointerTy(DAG.getDataLayout())));
9593   EVT ElemTy = N00.getValueType().getVectorElementType();
9594   unsigned NumElts = VT.getVectorNumElements();
9595   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9596   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9597                                N00.getOperand(0), N00.getOperand(1));
9598   Ops.push_back(Concat);
9599 
9600   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9601 }
9602 
9603 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9604 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9605 // much easier to match.
9606 static SDValue
9607 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9608                                TargetLowering::DAGCombinerInfo &DCI,
9609                                const ARMSubtarget *Subtarget) {
9610   // Only perform optimization if after legalize, and if NEON is available. We
9611   // also expected both operands to be BUILD_VECTORs.
9612   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9613       || N0.getOpcode() != ISD::BUILD_VECTOR
9614       || N1.getOpcode() != ISD::BUILD_VECTOR)
9615     return SDValue();
9616 
9617   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9618   EVT VT = N->getValueType(0);
9619   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9620     return SDValue();
9621 
9622   // Check that the vector operands are of the right form.
9623   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9624   // operands, where N is the size of the formed vector.
9625   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9626   // index such that we have a pair wise add pattern.
9627 
9628   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9629   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9630     return SDValue();
9631   SDValue Vec = N0->getOperand(0)->getOperand(0);
9632   SDNode *V = Vec.getNode();
9633   unsigned nextIndex = 0;
9634 
9635   // For each operands to the ADD which are BUILD_VECTORs,
9636   // check to see if each of their operands are an EXTRACT_VECTOR with
9637   // the same vector and appropriate index.
9638   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9639     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9640         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9641 
9642       SDValue ExtVec0 = N0->getOperand(i);
9643       SDValue ExtVec1 = N1->getOperand(i);
9644 
9645       // First operand is the vector, verify its the same.
9646       if (V != ExtVec0->getOperand(0).getNode() ||
9647           V != ExtVec1->getOperand(0).getNode())
9648         return SDValue();
9649 
9650       // Second is the constant, verify its correct.
9651       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9652       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9653 
9654       // For the constant, we want to see all the even or all the odd.
9655       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9656           || C1->getZExtValue() != nextIndex+1)
9657         return SDValue();
9658 
9659       // Increment index.
9660       nextIndex+=2;
9661     } else
9662       return SDValue();
9663   }
9664 
9665   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9666   // we're using the entire input vector, otherwise there's a size/legality
9667   // mismatch somewhere.
9668   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9669       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9670     return SDValue();
9671 
9672   // Create VPADDL node.
9673   SelectionDAG &DAG = DCI.DAG;
9674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9675 
9676   SDLoc dl(N);
9677 
9678   // Build operand list.
9679   SmallVector<SDValue, 8> Ops;
9680   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9681                                 TLI.getPointerTy(DAG.getDataLayout())));
9682 
9683   // Input is the vector.
9684   Ops.push_back(Vec);
9685 
9686   // Get widened type and narrowed type.
9687   MVT widenType;
9688   unsigned numElem = VT.getVectorNumElements();
9689 
9690   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9691   switch (inputLaneType.getSimpleVT().SimpleTy) {
9692     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9693     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9694     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9695     default:
9696       llvm_unreachable("Invalid vector element type for padd optimization.");
9697   }
9698 
9699   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9700   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9701   return DAG.getNode(ExtOp, dl, VT, tmp);
9702 }
9703 
9704 static SDValue findMUL_LOHI(SDValue V) {
9705   if (V->getOpcode() == ISD::UMUL_LOHI ||
9706       V->getOpcode() == ISD::SMUL_LOHI)
9707     return V;
9708   return SDValue();
9709 }
9710 
9711 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9712                                         TargetLowering::DAGCombinerInfo &DCI,
9713                                         const ARMSubtarget *Subtarget) {
9714 
9715   if (Subtarget->isThumb()) {
9716     if (!Subtarget->hasDSP())
9717       return SDValue();
9718   } else if (!Subtarget->hasV5TEOps())
9719     return SDValue();
9720 
9721   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9722   // accumulates the product into a 64-bit value. The 16-bit values will
9723   // be sign extended somehow or SRA'd into 32-bit values
9724   // (addc (adde (mul 16bit, 16bit), lo), hi)
9725   SDValue Mul = AddcNode->getOperand(0);
9726   SDValue Lo = AddcNode->getOperand(1);
9727   if (Mul.getOpcode() != ISD::MUL) {
9728     Lo = AddcNode->getOperand(0);
9729     Mul = AddcNode->getOperand(1);
9730     if (Mul.getOpcode() != ISD::MUL)
9731       return SDValue();
9732   }
9733 
9734   SDValue SRA = AddeNode->getOperand(0);
9735   SDValue Hi = AddeNode->getOperand(1);
9736   if (SRA.getOpcode() != ISD::SRA) {
9737     SRA = AddeNode->getOperand(1);
9738     Hi = AddeNode->getOperand(0);
9739     if (SRA.getOpcode() != ISD::SRA)
9740       return SDValue();
9741   }
9742   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9743     if (Const->getZExtValue() != 31)
9744       return SDValue();
9745   } else
9746     return SDValue();
9747 
9748   if (SRA.getOperand(0) != Mul)
9749     return SDValue();
9750 
9751   SelectionDAG &DAG = DCI.DAG;
9752   SDLoc dl(AddcNode);
9753   unsigned Opcode = 0;
9754   SDValue Op0;
9755   SDValue Op1;
9756 
9757   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9758     Opcode = ARMISD::SMLALBB;
9759     Op0 = Mul.getOperand(0);
9760     Op1 = Mul.getOperand(1);
9761   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9762     Opcode = ARMISD::SMLALBT;
9763     Op0 = Mul.getOperand(0);
9764     Op1 = Mul.getOperand(1).getOperand(0);
9765   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9766     Opcode = ARMISD::SMLALTB;
9767     Op0 = Mul.getOperand(0).getOperand(0);
9768     Op1 = Mul.getOperand(1);
9769   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9770     Opcode = ARMISD::SMLALTT;
9771     Op0 = Mul->getOperand(0).getOperand(0);
9772     Op1 = Mul->getOperand(1).getOperand(0);
9773   }
9774 
9775   if (!Op0 || !Op1)
9776     return SDValue();
9777 
9778   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9779                               Op0, Op1, Lo, Hi);
9780   // Replace the ADDs' nodes uses by the MLA node's values.
9781   SDValue HiMLALResult(SMLAL.getNode(), 1);
9782   SDValue LoMLALResult(SMLAL.getNode(), 0);
9783 
9784   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9785   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9786 
9787   // Return original node to notify the driver to stop replacing.
9788   SDValue resNode(AddcNode, 0);
9789   return resNode;
9790 }
9791 
9792 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9793                                      TargetLowering::DAGCombinerInfo &DCI,
9794                                      const ARMSubtarget *Subtarget) {
9795   // Look for multiply add opportunities.
9796   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9797   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9798   // a glue link from the first add to the second add.
9799   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9800   // a S/UMLAL instruction.
9801   //                  UMUL_LOHI
9802   //                 / :lo    \ :hi
9803   //                V          \          [no multiline comment]
9804   //    loAdd ->  ADDC         |
9805   //                 \ :carry /
9806   //                  V      V
9807   //                    ADDE   <- hiAdd
9808   //
9809   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9810 
9811   assert(AddeNode->getNumOperands() == 3 &&
9812          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9813          "ADDE node has the wrong inputs");
9814 
9815   // Check that we are chained to the right ADDC node.
9816   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9817   if (AddcNode->getOpcode() != ARMISD::ADDC)
9818     return SDValue();
9819 
9820   SDValue AddcOp0 = AddcNode->getOperand(0);
9821   SDValue AddcOp1 = AddcNode->getOperand(1);
9822 
9823   // Check if the two operands are from the same mul_lohi node.
9824   if (AddcOp0.getNode() == AddcOp1.getNode())
9825     return SDValue();
9826 
9827   assert(AddcNode->getNumValues() == 2 &&
9828          AddcNode->getValueType(0) == MVT::i32 &&
9829          "Expect ADDC with two result values. First: i32");
9830 
9831   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9832   // maybe a SMLAL which multiplies two 16-bit values.
9833   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9834       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9835       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9836       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9837     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9838 
9839   // Check for the triangle shape.
9840   SDValue AddeOp0 = AddeNode->getOperand(0);
9841   SDValue AddeOp1 = AddeNode->getOperand(1);
9842 
9843   // Make sure that the ADDE operands are not coming from the same node.
9844   if (AddeOp0.getNode() == AddeOp1.getNode())
9845     return SDValue();
9846 
9847   // Find the MUL_LOHI node walking up ADDE's operands.
9848   bool IsLeftOperandMUL = false;
9849   SDValue MULOp = findMUL_LOHI(AddeOp0);
9850   if (MULOp == SDValue())
9851    MULOp = findMUL_LOHI(AddeOp1);
9852   else
9853     IsLeftOperandMUL = true;
9854   if (MULOp == SDValue())
9855     return SDValue();
9856 
9857   // Figure out the right opcode.
9858   unsigned Opc = MULOp->getOpcode();
9859   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9860 
9861   // Figure out the high and low input values to the MLAL node.
9862   SDValue* HiAdd = nullptr;
9863   SDValue* LoMul = nullptr;
9864   SDValue* LowAdd = nullptr;
9865 
9866   // Ensure that ADDE is from high result of ISD::xMUL_LOHI.
9867   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9868     return SDValue();
9869 
9870   if (IsLeftOperandMUL)
9871     HiAdd = &AddeOp1;
9872   else
9873     HiAdd = &AddeOp0;
9874 
9875 
9876   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9877   // whose low result is fed to the ADDC we are checking.
9878 
9879   if (AddcOp0 == MULOp.getValue(0)) {
9880     LoMul = &AddcOp0;
9881     LowAdd = &AddcOp1;
9882   }
9883   if (AddcOp1 == MULOp.getValue(0)) {
9884     LoMul = &AddcOp1;
9885     LowAdd = &AddcOp0;
9886   }
9887 
9888   if (!LoMul)
9889     return SDValue();
9890 
9891   // If HiAdd is the same node as ADDC or is a predecessor of ADDC the
9892   // replacement below will create a cycle.
9893   if (AddcNode == HiAdd->getNode() ||
9894       AddcNode->isPredecessorOf(HiAdd->getNode()))
9895     return SDValue();
9896 
9897   // Create the merged node.
9898   SelectionDAG &DAG = DCI.DAG;
9899 
9900   // Build operand list.
9901   SmallVector<SDValue, 8> Ops;
9902   Ops.push_back(LoMul->getOperand(0));
9903   Ops.push_back(LoMul->getOperand(1));
9904   Ops.push_back(*LowAdd);
9905   Ops.push_back(*HiAdd);
9906 
9907   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9908                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9909 
9910   // Replace the ADDs' nodes uses by the MLA node's values.
9911   SDValue HiMLALResult(MLALNode.getNode(), 1);
9912   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9913 
9914   SDValue LoMLALResult(MLALNode.getNode(), 0);
9915   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9916 
9917   // Return original node to notify the driver to stop replacing.
9918   return SDValue(AddeNode, 0);
9919 }
9920 
9921 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9922                                       TargetLowering::DAGCombinerInfo &DCI,
9923                                       const ARMSubtarget *Subtarget) {
9924   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9925   // While trying to combine for the other MLAL nodes, first search for the
9926   // chance to use UMAAL. Check if Addc uses a node which has already
9927   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9928   // as the addend, and it's handled in PerformUMLALCombine.
9929 
9930   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9931     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9932 
9933   // Check that we have a glued ADDC node.
9934   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9935   if (AddcNode->getOpcode() != ARMISD::ADDC)
9936     return SDValue();
9937 
9938   // Find the converted UMAAL or quit if it doesn't exist.
9939   SDNode *UmlalNode = nullptr;
9940   SDValue AddHi;
9941   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9942     UmlalNode = AddcNode->getOperand(0).getNode();
9943     AddHi = AddcNode->getOperand(1);
9944   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9945     UmlalNode = AddcNode->getOperand(1).getNode();
9946     AddHi = AddcNode->getOperand(0);
9947   } else {
9948     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9949   }
9950 
9951   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9952   // the ADDC as well as Zero.
9953   if (!isNullConstant(UmlalNode->getOperand(3)))
9954     return SDValue();
9955 
9956   if ((isNullConstant(AddeNode->getOperand(0)) &&
9957        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9958       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9959        isNullConstant(AddeNode->getOperand(1)))) {
9960 
9961     SelectionDAG &DAG = DCI.DAG;
9962     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9963                       UmlalNode->getOperand(2), AddHi };
9964     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9965                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9966 
9967     // Replace the ADDs' nodes uses by the UMAAL node's values.
9968     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9969     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9970 
9971     // Return original node to notify the driver to stop replacing.
9972     return SDValue(AddeNode, 0);
9973   }
9974   return SDValue();
9975 }
9976 
9977 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9978                                    const ARMSubtarget *Subtarget) {
9979   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9980     return SDValue();
9981 
9982   // Check that we have a pair of ADDC and ADDE as operands.
9983   // Both addends of the ADDE must be zero.
9984   SDNode* AddcNode = N->getOperand(2).getNode();
9985   SDNode* AddeNode = N->getOperand(3).getNode();
9986   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9987       (AddeNode->getOpcode() == ARMISD::ADDE) &&
9988       isNullConstant(AddeNode->getOperand(0)) &&
9989       isNullConstant(AddeNode->getOperand(1)) &&
9990       (AddeNode->getOperand(2).getNode() == AddcNode))
9991     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9992                        DAG.getVTList(MVT::i32, MVT::i32),
9993                        {N->getOperand(0), N->getOperand(1),
9994                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
9995   else
9996     return SDValue();
9997 }
9998 
9999 static SDValue PerformAddcSubcCombine(SDNode *N,
10000                                       TargetLowering::DAGCombinerInfo &DCI,
10001                                       const ARMSubtarget *Subtarget) {
10002   SelectionDAG &DAG(DCI.DAG);
10003 
10004   if (N->getOpcode() == ARMISD::ADDC) {
10005     // (ADDC (ADDE 0, 0, C), -1) -> C
10006     SDValue LHS = N->getOperand(0);
10007     SDValue RHS = N->getOperand(1);
10008     if (LHS->getOpcode() == ARMISD::ADDE &&
10009         isNullConstant(LHS->getOperand(0)) &&
10010         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10011       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10012     }
10013   }
10014 
10015   if (Subtarget->isThumb1Only()) {
10016     SDValue RHS = N->getOperand(1);
10017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10018       int32_t imm = C->getSExtValue();
10019       if (imm < 0 && imm > INT_MIN) {
10020         SDLoc DL(N);
10021         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10022         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10023                                                            : ARMISD::ADDC;
10024         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10025       }
10026     }
10027   }
10028   return SDValue();
10029 }
10030 
10031 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
10032                                       const ARMSubtarget *Subtarget) {
10033   if (Subtarget->isThumb1Only()) {
10034     SDValue RHS = N->getOperand(1);
10035     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10036       int64_t imm = C->getSExtValue();
10037       if (imm < 0) {
10038         SDLoc DL(N);
10039 
10040         // The with-carry-in form matches bitwise not instead of the negation.
10041         // Effectively, the inverse interpretation of the carry flag already
10042         // accounts for part of the negation.
10043         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10044 
10045         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10046                                                            : ARMISD::ADDE;
10047         return DAG.getNode(Opcode, DL, N->getVTList(),
10048                            N->getOperand(0), RHS, N->getOperand(2));
10049       }
10050     }
10051   }
10052   return SDValue();
10053 }
10054 
10055 /// PerformADDECombine - Target-specific dag combine transform from
10056 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10057 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10058 static SDValue PerformADDECombine(SDNode *N,
10059                                   TargetLowering::DAGCombinerInfo &DCI,
10060                                   const ARMSubtarget *Subtarget) {
10061   // Only ARM and Thumb2 support UMLAL/SMLAL.
10062   if (Subtarget->isThumb1Only())
10063     return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
10064 
10065   // Only perform the checks after legalize when the pattern is available.
10066   if (DCI.isBeforeLegalize()) return SDValue();
10067 
10068   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10069 }
10070 
10071 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10072 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10073 /// called with the default operands, and if that fails, with commuted
10074 /// operands.
10075 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10076                                           TargetLowering::DAGCombinerInfo &DCI,
10077                                           const ARMSubtarget *Subtarget){
10078   // Attempt to create vpadd for this add.
10079   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10080     return Result;
10081 
10082   // Attempt to create vpaddl for this add.
10083   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10084     return Result;
10085   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10086                                                       Subtarget))
10087     return Result;
10088 
10089   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10090   if (N0.getNode()->hasOneUse())
10091     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10092       return Result;
10093   return SDValue();
10094 }
10095 
10096 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10097 ///
10098 static SDValue PerformADDCombine(SDNode *N,
10099                                  TargetLowering::DAGCombinerInfo &DCI,
10100                                  const ARMSubtarget *Subtarget) {
10101   SDValue N0 = N->getOperand(0);
10102   SDValue N1 = N->getOperand(1);
10103 
10104   // First try with the default operand order.
10105   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10106     return Result;
10107 
10108   // If that didn't work, try again with the operands commuted.
10109   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10110 }
10111 
10112 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10113 ///
10114 static SDValue PerformSUBCombine(SDNode *N,
10115                                  TargetLowering::DAGCombinerInfo &DCI) {
10116   SDValue N0 = N->getOperand(0);
10117   SDValue N1 = N->getOperand(1);
10118 
10119   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10120   if (N1.getNode()->hasOneUse())
10121     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10122       return Result;
10123 
10124   return SDValue();
10125 }
10126 
10127 /// PerformVMULCombine
10128 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10129 /// special multiplier accumulator forwarding.
10130 ///   vmul d3, d0, d2
10131 ///   vmla d3, d1, d2
10132 /// is faster than
10133 ///   vadd d3, d0, d1
10134 ///   vmul d3, d3, d2
10135 //  However, for (A + B) * (A + B),
10136 //    vadd d2, d0, d1
10137 //    vmul d3, d0, d2
10138 //    vmla d3, d1, d2
10139 //  is slower than
10140 //    vadd d2, d0, d1
10141 //    vmul d3, d2, d2
10142 static SDValue PerformVMULCombine(SDNode *N,
10143                                   TargetLowering::DAGCombinerInfo &DCI,
10144                                   const ARMSubtarget *Subtarget) {
10145   if (!Subtarget->hasVMLxForwarding())
10146     return SDValue();
10147 
10148   SelectionDAG &DAG = DCI.DAG;
10149   SDValue N0 = N->getOperand(0);
10150   SDValue N1 = N->getOperand(1);
10151   unsigned Opcode = N0.getOpcode();
10152   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10153       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10154     Opcode = N1.getOpcode();
10155     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10156         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10157       return SDValue();
10158     std::swap(N0, N1);
10159   }
10160 
10161   if (N0 == N1)
10162     return SDValue();
10163 
10164   EVT VT = N->getValueType(0);
10165   SDLoc DL(N);
10166   SDValue N00 = N0->getOperand(0);
10167   SDValue N01 = N0->getOperand(1);
10168   return DAG.getNode(Opcode, DL, VT,
10169                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10170                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10171 }
10172 
10173 static SDValue PerformMULCombine(SDNode *N,
10174                                  TargetLowering::DAGCombinerInfo &DCI,
10175                                  const ARMSubtarget *Subtarget) {
10176   SelectionDAG &DAG = DCI.DAG;
10177 
10178   if (Subtarget->isThumb1Only())
10179     return SDValue();
10180 
10181   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10182     return SDValue();
10183 
10184   EVT VT = N->getValueType(0);
10185   if (VT.is64BitVector() || VT.is128BitVector())
10186     return PerformVMULCombine(N, DCI, Subtarget);
10187   if (VT != MVT::i32)
10188     return SDValue();
10189 
10190   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10191   if (!C)
10192     return SDValue();
10193 
10194   int64_t MulAmt = C->getSExtValue();
10195   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10196 
10197   ShiftAmt = ShiftAmt & (32 - 1);
10198   SDValue V = N->getOperand(0);
10199   SDLoc DL(N);
10200 
10201   SDValue Res;
10202   MulAmt >>= ShiftAmt;
10203 
10204   if (MulAmt >= 0) {
10205     if (isPowerOf2_32(MulAmt - 1)) {
10206       // (mul x, 2^N + 1) => (add (shl x, N), x)
10207       Res = DAG.getNode(ISD::ADD, DL, VT,
10208                         V,
10209                         DAG.getNode(ISD::SHL, DL, VT,
10210                                     V,
10211                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10212                                                     MVT::i32)));
10213     } else if (isPowerOf2_32(MulAmt + 1)) {
10214       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10215       Res = DAG.getNode(ISD::SUB, DL, VT,
10216                         DAG.getNode(ISD::SHL, DL, VT,
10217                                     V,
10218                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10219                                                     MVT::i32)),
10220                         V);
10221     } else
10222       return SDValue();
10223   } else {
10224     uint64_t MulAmtAbs = -MulAmt;
10225     if (isPowerOf2_32(MulAmtAbs + 1)) {
10226       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10227       Res = DAG.getNode(ISD::SUB, DL, VT,
10228                         V,
10229                         DAG.getNode(ISD::SHL, DL, VT,
10230                                     V,
10231                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10232                                                     MVT::i32)));
10233     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10234       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10235       Res = DAG.getNode(ISD::ADD, DL, VT,
10236                         V,
10237                         DAG.getNode(ISD::SHL, DL, VT,
10238                                     V,
10239                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10240                                                     MVT::i32)));
10241       Res = DAG.getNode(ISD::SUB, DL, VT,
10242                         DAG.getConstant(0, DL, MVT::i32), Res);
10243 
10244     } else
10245       return SDValue();
10246   }
10247 
10248   if (ShiftAmt != 0)
10249     Res = DAG.getNode(ISD::SHL, DL, VT,
10250                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10251 
10252   // Do not add new nodes to DAG combiner worklist.
10253   DCI.CombineTo(N, Res, false);
10254   return SDValue();
10255 }
10256 
10257 static SDValue PerformANDCombine(SDNode *N,
10258                                  TargetLowering::DAGCombinerInfo &DCI,
10259                                  const ARMSubtarget *Subtarget) {
10260   // Attempt to use immediate-form VBIC
10261   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10262   SDLoc dl(N);
10263   EVT VT = N->getValueType(0);
10264   SelectionDAG &DAG = DCI.DAG;
10265 
10266   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10267     return SDValue();
10268 
10269   APInt SplatBits, SplatUndef;
10270   unsigned SplatBitSize;
10271   bool HasAnyUndefs;
10272   if (BVN &&
10273       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10274     if (SplatBitSize <= 64) {
10275       EVT VbicVT;
10276       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10277                                       SplatUndef.getZExtValue(), SplatBitSize,
10278                                       DAG, dl, VbicVT, VT.is128BitVector(),
10279                                       OtherModImm);
10280       if (Val.getNode()) {
10281         SDValue Input =
10282           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10283         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10284         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10285       }
10286     }
10287   }
10288 
10289   if (!Subtarget->isThumb1Only()) {
10290     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10291     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10292       return Result;
10293   }
10294 
10295   return SDValue();
10296 }
10297 
10298 // Try combining OR nodes to SMULWB, SMULWT.
10299 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10300                                          TargetLowering::DAGCombinerInfo &DCI,
10301                                          const ARMSubtarget *Subtarget) {
10302   if (!Subtarget->hasV6Ops() ||
10303       (Subtarget->isThumb() &&
10304        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10305     return SDValue();
10306 
10307   SDValue SRL = OR->getOperand(0);
10308   SDValue SHL = OR->getOperand(1);
10309 
10310   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10311     SRL = OR->getOperand(1);
10312     SHL = OR->getOperand(0);
10313   }
10314   if (!isSRL16(SRL) || !isSHL16(SHL))
10315     return SDValue();
10316 
10317   // The first operands to the shifts need to be the two results from the
10318   // same smul_lohi node.
10319   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10320        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10321     return SDValue();
10322 
10323   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10324   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10325       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10326     return SDValue();
10327 
10328   // Now we have:
10329   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10330   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10331   // For SMUWB the 16-bit value will signed extended somehow.
10332   // For SMULWT only the SRA is required.
10333   // Check both sides of SMUL_LOHI
10334   SDValue OpS16 = SMULLOHI->getOperand(0);
10335   SDValue OpS32 = SMULLOHI->getOperand(1);
10336 
10337   SelectionDAG &DAG = DCI.DAG;
10338   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10339     OpS16 = OpS32;
10340     OpS32 = SMULLOHI->getOperand(0);
10341   }
10342 
10343   SDLoc dl(OR);
10344   unsigned Opcode = 0;
10345   if (isS16(OpS16, DAG))
10346     Opcode = ARMISD::SMULWB;
10347   else if (isSRA16(OpS16)) {
10348     Opcode = ARMISD::SMULWT;
10349     OpS16 = OpS16->getOperand(0);
10350   }
10351   else
10352     return SDValue();
10353 
10354   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10355   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10356   return SDValue(OR, 0);
10357 }
10358 
10359 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10360 static SDValue PerformORCombine(SDNode *N,
10361                                 TargetLowering::DAGCombinerInfo &DCI,
10362                                 const ARMSubtarget *Subtarget) {
10363   // Attempt to use immediate-form VORR
10364   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10365   SDLoc dl(N);
10366   EVT VT = N->getValueType(0);
10367   SelectionDAG &DAG = DCI.DAG;
10368 
10369   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10370     return SDValue();
10371 
10372   APInt SplatBits, SplatUndef;
10373   unsigned SplatBitSize;
10374   bool HasAnyUndefs;
10375   if (BVN && Subtarget->hasNEON() &&
10376       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10377     if (SplatBitSize <= 64) {
10378       EVT VorrVT;
10379       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10380                                       SplatUndef.getZExtValue(), SplatBitSize,
10381                                       DAG, dl, VorrVT, VT.is128BitVector(),
10382                                       OtherModImm);
10383       if (Val.getNode()) {
10384         SDValue Input =
10385           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10386         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10387         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10388       }
10389     }
10390   }
10391 
10392   if (!Subtarget->isThumb1Only()) {
10393     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10394     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10395       return Result;
10396     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10397       return Result;
10398   }
10399 
10400   // The code below optimizes (or (and X, Y), Z).
10401   // The AND operand needs to have a single user to make these optimizations
10402   // profitable.
10403   SDValue N0 = N->getOperand(0);
10404   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10405     return SDValue();
10406   SDValue N1 = N->getOperand(1);
10407 
10408   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10409   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10410       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10411     APInt SplatUndef;
10412     unsigned SplatBitSize;
10413     bool HasAnyUndefs;
10414 
10415     APInt SplatBits0, SplatBits1;
10416     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10417     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10418     // Ensure that the second operand of both ands are constants
10419     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10420                                       HasAnyUndefs) && !HasAnyUndefs) {
10421         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10422                                           HasAnyUndefs) && !HasAnyUndefs) {
10423             // Ensure that the bit width of the constants are the same and that
10424             // the splat arguments are logical inverses as per the pattern we
10425             // are trying to simplify.
10426             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10427                 SplatBits0 == ~SplatBits1) {
10428                 // Canonicalize the vector type to make instruction selection
10429                 // simpler.
10430                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10431                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10432                                              N0->getOperand(1),
10433                                              N0->getOperand(0),
10434                                              N1->getOperand(0));
10435                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10436             }
10437         }
10438     }
10439   }
10440 
10441   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10442   // reasonable.
10443 
10444   // BFI is only available on V6T2+
10445   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10446     return SDValue();
10447 
10448   SDLoc DL(N);
10449   // 1) or (and A, mask), val => ARMbfi A, val, mask
10450   //      iff (val & mask) == val
10451   //
10452   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10453   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10454   //          && mask == ~mask2
10455   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10456   //          && ~mask == mask2
10457   //  (i.e., copy a bitfield value into another bitfield of the same width)
10458 
10459   if (VT != MVT::i32)
10460     return SDValue();
10461 
10462   SDValue N00 = N0.getOperand(0);
10463 
10464   // The value and the mask need to be constants so we can verify this is
10465   // actually a bitfield set. If the mask is 0xffff, we can do better
10466   // via a movt instruction, so don't use BFI in that case.
10467   SDValue MaskOp = N0.getOperand(1);
10468   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10469   if (!MaskC)
10470     return SDValue();
10471   unsigned Mask = MaskC->getZExtValue();
10472   if (Mask == 0xffff)
10473     return SDValue();
10474   SDValue Res;
10475   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10476   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10477   if (N1C) {
10478     unsigned Val = N1C->getZExtValue();
10479     if ((Val & ~Mask) != Val)
10480       return SDValue();
10481 
10482     if (ARM::isBitFieldInvertedMask(Mask)) {
10483       Val >>= countTrailingZeros(~Mask);
10484 
10485       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10486                         DAG.getConstant(Val, DL, MVT::i32),
10487                         DAG.getConstant(Mask, DL, MVT::i32));
10488 
10489       // Do not add new nodes to DAG combiner worklist.
10490       DCI.CombineTo(N, Res, false);
10491       return SDValue();
10492     }
10493   } else if (N1.getOpcode() == ISD::AND) {
10494     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10495     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10496     if (!N11C)
10497       return SDValue();
10498     unsigned Mask2 = N11C->getZExtValue();
10499 
10500     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10501     // as is to match.
10502     if (ARM::isBitFieldInvertedMask(Mask) &&
10503         (Mask == ~Mask2)) {
10504       // The pack halfword instruction works better for masks that fit it,
10505       // so use that when it's available.
10506       if (Subtarget->hasDSP() &&
10507           (Mask == 0xffff || Mask == 0xffff0000))
10508         return SDValue();
10509       // 2a
10510       unsigned amt = countTrailingZeros(Mask2);
10511       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10512                         DAG.getConstant(amt, DL, MVT::i32));
10513       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10514                         DAG.getConstant(Mask, DL, MVT::i32));
10515       // Do not add new nodes to DAG combiner worklist.
10516       DCI.CombineTo(N, Res, false);
10517       return SDValue();
10518     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10519                (~Mask == Mask2)) {
10520       // The pack halfword instruction works better for masks that fit it,
10521       // so use that when it's available.
10522       if (Subtarget->hasDSP() &&
10523           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10524         return SDValue();
10525       // 2b
10526       unsigned lsb = countTrailingZeros(Mask);
10527       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10528                         DAG.getConstant(lsb, DL, MVT::i32));
10529       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10530                         DAG.getConstant(Mask2, DL, MVT::i32));
10531       // Do not add new nodes to DAG combiner worklist.
10532       DCI.CombineTo(N, Res, false);
10533       return SDValue();
10534     }
10535   }
10536 
10537   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10538       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10539       ARM::isBitFieldInvertedMask(~Mask)) {
10540     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10541     // where lsb(mask) == #shamt and masked bits of B are known zero.
10542     SDValue ShAmt = N00.getOperand(1);
10543     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10544     unsigned LSB = countTrailingZeros(Mask);
10545     if (ShAmtC != LSB)
10546       return SDValue();
10547 
10548     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10549                       DAG.getConstant(~Mask, DL, MVT::i32));
10550 
10551     // Do not add new nodes to DAG combiner worklist.
10552     DCI.CombineTo(N, Res, false);
10553   }
10554 
10555   return SDValue();
10556 }
10557 
10558 static SDValue PerformXORCombine(SDNode *N,
10559                                  TargetLowering::DAGCombinerInfo &DCI,
10560                                  const ARMSubtarget *Subtarget) {
10561   EVT VT = N->getValueType(0);
10562   SelectionDAG &DAG = DCI.DAG;
10563 
10564   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10565     return SDValue();
10566 
10567   if (!Subtarget->isThumb1Only()) {
10568     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10569     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10570       return Result;
10571   }
10572 
10573   return SDValue();
10574 }
10575 
10576 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10577 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10578 // their position in "to" (Rd).
10579 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10580   assert(N->getOpcode() == ARMISD::BFI);
10581 
10582   SDValue From = N->getOperand(1);
10583   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10584   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10585 
10586   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10587   // #C in the base of the SHR.
10588   if (From->getOpcode() == ISD::SRL &&
10589       isa<ConstantSDNode>(From->getOperand(1))) {
10590     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10591     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10592     FromMask <<= Shift.getLimitedValue(31);
10593     From = From->getOperand(0);
10594   }
10595 
10596   return From;
10597 }
10598 
10599 // If A and B contain one contiguous set of bits, does A | B == A . B?
10600 //
10601 // Neither A nor B must be zero.
10602 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10603   unsigned LastActiveBitInA =  A.countTrailingZeros();
10604   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10605   return LastActiveBitInA - 1 == FirstActiveBitInB;
10606 }
10607 
10608 static SDValue FindBFIToCombineWith(SDNode *N) {
10609   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10610   // if one exists.
10611   APInt ToMask, FromMask;
10612   SDValue From = ParseBFI(N, ToMask, FromMask);
10613   SDValue To = N->getOperand(0);
10614 
10615   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10616   // aren't compatible, but not if they set the same bit in their destination as
10617   // we do (or that of any BFI we're going to combine with).
10618   SDValue V = To;
10619   APInt CombinedToMask = ToMask;
10620   while (V.getOpcode() == ARMISD::BFI) {
10621     APInt NewToMask, NewFromMask;
10622     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10623     if (NewFrom != From) {
10624       // This BFI has a different base. Keep going.
10625       CombinedToMask |= NewToMask;
10626       V = V.getOperand(0);
10627       continue;
10628     }
10629 
10630     // Do the written bits conflict with any we've seen so far?
10631     if ((NewToMask & CombinedToMask).getBoolValue())
10632       // Conflicting bits - bail out because going further is unsafe.
10633       return SDValue();
10634 
10635     // Are the new bits contiguous when combined with the old bits?
10636     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10637         BitsProperlyConcatenate(FromMask, NewFromMask))
10638       return V;
10639     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10640         BitsProperlyConcatenate(NewFromMask, FromMask))
10641       return V;
10642 
10643     // We've seen a write to some bits, so track it.
10644     CombinedToMask |= NewToMask;
10645     // Keep going...
10646     V = V.getOperand(0);
10647   }
10648 
10649   return SDValue();
10650 }
10651 
10652 static SDValue PerformBFICombine(SDNode *N,
10653                                  TargetLowering::DAGCombinerInfo &DCI) {
10654   SDValue N1 = N->getOperand(1);
10655   if (N1.getOpcode() == ISD::AND) {
10656     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10657     // the bits being cleared by the AND are not demanded by the BFI.
10658     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10659     if (!N11C)
10660       return SDValue();
10661     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10662     unsigned LSB = countTrailingZeros(~InvMask);
10663     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10664     assert(Width <
10665                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10666            "undefined behavior");
10667     unsigned Mask = (1u << Width) - 1;
10668     unsigned Mask2 = N11C->getZExtValue();
10669     if ((Mask & (~Mask2)) == 0)
10670       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10671                              N->getOperand(0), N1.getOperand(0),
10672                              N->getOperand(2));
10673   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10674     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10675     // Keep track of any consecutive bits set that all come from the same base
10676     // value. We can combine these together into a single BFI.
10677     SDValue CombineBFI = FindBFIToCombineWith(N);
10678     if (CombineBFI == SDValue())
10679       return SDValue();
10680 
10681     // We've found a BFI.
10682     APInt ToMask1, FromMask1;
10683     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10684 
10685     APInt ToMask2, FromMask2;
10686     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10687     assert(From1 == From2);
10688     (void)From2;
10689 
10690     // First, unlink CombineBFI.
10691     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10692     // Then create a new BFI, combining the two together.
10693     APInt NewFromMask = FromMask1 | FromMask2;
10694     APInt NewToMask = ToMask1 | ToMask2;
10695 
10696     EVT VT = N->getValueType(0);
10697     SDLoc dl(N);
10698 
10699     if (NewFromMask[0] == 0)
10700       From1 = DCI.DAG.getNode(
10701         ISD::SRL, dl, VT, From1,
10702         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10703     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10704                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10705   }
10706   return SDValue();
10707 }
10708 
10709 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10710 /// ARMISD::VMOVRRD.
10711 static SDValue PerformVMOVRRDCombine(SDNode *N,
10712                                      TargetLowering::DAGCombinerInfo &DCI,
10713                                      const ARMSubtarget *Subtarget) {
10714   // vmovrrd(vmovdrr x, y) -> x,y
10715   SDValue InDouble = N->getOperand(0);
10716   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10717     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10718 
10719   // vmovrrd(load f64) -> (load i32), (load i32)
10720   SDNode *InNode = InDouble.getNode();
10721   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10722       InNode->getValueType(0) == MVT::f64 &&
10723       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10724       !cast<LoadSDNode>(InNode)->isVolatile()) {
10725     // TODO: Should this be done for non-FrameIndex operands?
10726     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10727 
10728     SelectionDAG &DAG = DCI.DAG;
10729     SDLoc DL(LD);
10730     SDValue BasePtr = LD->getBasePtr();
10731     SDValue NewLD1 =
10732         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10733                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10734 
10735     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10736                                     DAG.getConstant(4, DL, MVT::i32));
10737     SDValue NewLD2 = DAG.getLoad(
10738         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10739         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10740 
10741     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10742     if (DCI.DAG.getDataLayout().isBigEndian())
10743       std::swap (NewLD1, NewLD2);
10744     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10745     return Result;
10746   }
10747 
10748   return SDValue();
10749 }
10750 
10751 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10752 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10753 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10754   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10755   SDValue Op0 = N->getOperand(0);
10756   SDValue Op1 = N->getOperand(1);
10757   if (Op0.getOpcode() == ISD::BITCAST)
10758     Op0 = Op0.getOperand(0);
10759   if (Op1.getOpcode() == ISD::BITCAST)
10760     Op1 = Op1.getOperand(0);
10761   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10762       Op0.getNode() == Op1.getNode() &&
10763       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10764     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10765                        N->getValueType(0), Op0.getOperand(0));
10766   return SDValue();
10767 }
10768 
10769 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10770 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10771 /// i64 vector to have f64 elements, since the value can then be loaded
10772 /// directly into a VFP register.
10773 static bool hasNormalLoadOperand(SDNode *N) {
10774   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10775   for (unsigned i = 0; i < NumElts; ++i) {
10776     SDNode *Elt = N->getOperand(i).getNode();
10777     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10778       return true;
10779   }
10780   return false;
10781 }
10782 
10783 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10784 /// ISD::BUILD_VECTOR.
10785 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10786                                           TargetLowering::DAGCombinerInfo &DCI,
10787                                           const ARMSubtarget *Subtarget) {
10788   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10789   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10790   // into a pair of GPRs, which is fine when the value is used as a scalar,
10791   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10792   SelectionDAG &DAG = DCI.DAG;
10793   if (N->getNumOperands() == 2)
10794     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10795       return RV;
10796 
10797   // Load i64 elements as f64 values so that type legalization does not split
10798   // them up into i32 values.
10799   EVT VT = N->getValueType(0);
10800   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10801     return SDValue();
10802   SDLoc dl(N);
10803   SmallVector<SDValue, 8> Ops;
10804   unsigned NumElts = VT.getVectorNumElements();
10805   for (unsigned i = 0; i < NumElts; ++i) {
10806     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10807     Ops.push_back(V);
10808     // Make the DAGCombiner fold the bitcast.
10809     DCI.AddToWorklist(V.getNode());
10810   }
10811   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10812   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10813   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10814 }
10815 
10816 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10817 static SDValue
10818 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10819   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10820   // At that time, we may have inserted bitcasts from integer to float.
10821   // If these bitcasts have survived DAGCombine, change the lowering of this
10822   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10823   // force to use floating point types.
10824 
10825   // Make sure we can change the type of the vector.
10826   // This is possible iff:
10827   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10828   //    1.1. Vector is used only once.
10829   //    1.2. Use is a bit convert to an integer type.
10830   // 2. The size of its operands are 32-bits (64-bits are not legal).
10831   EVT VT = N->getValueType(0);
10832   EVT EltVT = VT.getVectorElementType();
10833 
10834   // Check 1.1. and 2.
10835   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10836     return SDValue();
10837 
10838   // By construction, the input type must be float.
10839   assert(EltVT == MVT::f32 && "Unexpected type!");
10840 
10841   // Check 1.2.
10842   SDNode *Use = *N->use_begin();
10843   if (Use->getOpcode() != ISD::BITCAST ||
10844       Use->getValueType(0).isFloatingPoint())
10845     return SDValue();
10846 
10847   // Check profitability.
10848   // Model is, if more than half of the relevant operands are bitcast from
10849   // i32, turn the build_vector into a sequence of insert_vector_elt.
10850   // Relevant operands are everything that is not statically
10851   // (i.e., at compile time) bitcasted.
10852   unsigned NumOfBitCastedElts = 0;
10853   unsigned NumElts = VT.getVectorNumElements();
10854   unsigned NumOfRelevantElts = NumElts;
10855   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10856     SDValue Elt = N->getOperand(Idx);
10857     if (Elt->getOpcode() == ISD::BITCAST) {
10858       // Assume only bit cast to i32 will go away.
10859       if (Elt->getOperand(0).getValueType() == MVT::i32)
10860         ++NumOfBitCastedElts;
10861     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10862       // Constants are statically casted, thus do not count them as
10863       // relevant operands.
10864       --NumOfRelevantElts;
10865   }
10866 
10867   // Check if more than half of the elements require a non-free bitcast.
10868   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10869     return SDValue();
10870 
10871   SelectionDAG &DAG = DCI.DAG;
10872   // Create the new vector type.
10873   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10874   // Check if the type is legal.
10875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10876   if (!TLI.isTypeLegal(VecVT))
10877     return SDValue();
10878 
10879   // Combine:
10880   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10881   // => BITCAST INSERT_VECTOR_ELT
10882   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10883   //                      (BITCAST EN), N.
10884   SDValue Vec = DAG.getUNDEF(VecVT);
10885   SDLoc dl(N);
10886   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10887     SDValue V = N->getOperand(Idx);
10888     if (V.isUndef())
10889       continue;
10890     if (V.getOpcode() == ISD::BITCAST &&
10891         V->getOperand(0).getValueType() == MVT::i32)
10892       // Fold obvious case.
10893       V = V.getOperand(0);
10894     else {
10895       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10896       // Make the DAGCombiner fold the bitcasts.
10897       DCI.AddToWorklist(V.getNode());
10898     }
10899     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10900     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10901   }
10902   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10903   // Make the DAGCombiner fold the bitcasts.
10904   DCI.AddToWorklist(Vec.getNode());
10905   return Vec;
10906 }
10907 
10908 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10909 /// ISD::INSERT_VECTOR_ELT.
10910 static SDValue PerformInsertEltCombine(SDNode *N,
10911                                        TargetLowering::DAGCombinerInfo &DCI) {
10912   // Bitcast an i64 load inserted into a vector to f64.
10913   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10914   EVT VT = N->getValueType(0);
10915   SDNode *Elt = N->getOperand(1).getNode();
10916   if (VT.getVectorElementType() != MVT::i64 ||
10917       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10918     return SDValue();
10919 
10920   SelectionDAG &DAG = DCI.DAG;
10921   SDLoc dl(N);
10922   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10923                                  VT.getVectorNumElements());
10924   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10925   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10926   // Make the DAGCombiner fold the bitcasts.
10927   DCI.AddToWorklist(Vec.getNode());
10928   DCI.AddToWorklist(V.getNode());
10929   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10930                                Vec, V, N->getOperand(2));
10931   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10932 }
10933 
10934 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10935 /// ISD::VECTOR_SHUFFLE.
10936 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10937   // The LLVM shufflevector instruction does not require the shuffle mask
10938   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10939   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10940   // operands do not match the mask length, they are extended by concatenating
10941   // them with undef vectors.  That is probably the right thing for other
10942   // targets, but for NEON it is better to concatenate two double-register
10943   // size vector operands into a single quad-register size vector.  Do that
10944   // transformation here:
10945   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10946   //   shuffle(concat(v1, v2), undef)
10947   SDValue Op0 = N->getOperand(0);
10948   SDValue Op1 = N->getOperand(1);
10949   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10950       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10951       Op0.getNumOperands() != 2 ||
10952       Op1.getNumOperands() != 2)
10953     return SDValue();
10954   SDValue Concat0Op1 = Op0.getOperand(1);
10955   SDValue Concat1Op1 = Op1.getOperand(1);
10956   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10957     return SDValue();
10958   // Skip the transformation if any of the types are illegal.
10959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10960   EVT VT = N->getValueType(0);
10961   if (!TLI.isTypeLegal(VT) ||
10962       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10963       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10964     return SDValue();
10965 
10966   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10967                                   Op0.getOperand(0), Op1.getOperand(0));
10968   // Translate the shuffle mask.
10969   SmallVector<int, 16> NewMask;
10970   unsigned NumElts = VT.getVectorNumElements();
10971   unsigned HalfElts = NumElts/2;
10972   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10973   for (unsigned n = 0; n < NumElts; ++n) {
10974     int MaskElt = SVN->getMaskElt(n);
10975     int NewElt = -1;
10976     if (MaskElt < (int)HalfElts)
10977       NewElt = MaskElt;
10978     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10979       NewElt = HalfElts + MaskElt - NumElts;
10980     NewMask.push_back(NewElt);
10981   }
10982   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10983                               DAG.getUNDEF(VT), NewMask);
10984 }
10985 
10986 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10987 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10988 /// base address updates.
10989 /// For generic load/stores, the memory type is assumed to be a vector.
10990 /// The caller is assumed to have checked legality.
10991 static SDValue CombineBaseUpdate(SDNode *N,
10992                                  TargetLowering::DAGCombinerInfo &DCI) {
10993   SelectionDAG &DAG = DCI.DAG;
10994   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10995                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10996   const bool isStore = N->getOpcode() == ISD::STORE;
10997   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10998   SDValue Addr = N->getOperand(AddrOpIdx);
10999   MemSDNode *MemN = cast<MemSDNode>(N);
11000   SDLoc dl(N);
11001 
11002   // Search for a use of the address operand that is an increment.
11003   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11004          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11005     SDNode *User = *UI;
11006     if (User->getOpcode() != ISD::ADD ||
11007         UI.getUse().getResNo() != Addr.getResNo())
11008       continue;
11009 
11010     // Check that the add is independent of the load/store.  Otherwise, folding
11011     // it would create a cycle.
11012     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11013       continue;
11014 
11015     // Find the new opcode for the updating load/store.
11016     bool isLoadOp = true;
11017     bool isLaneOp = false;
11018     unsigned NewOpc = 0;
11019     unsigned NumVecs = 0;
11020     if (isIntrinsic) {
11021       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11022       switch (IntNo) {
11023       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11024       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11025         NumVecs = 1; break;
11026       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11027         NumVecs = 2; break;
11028       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11029         NumVecs = 3; break;
11030       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11031         NumVecs = 4; break;
11032       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11033         NumVecs = 2; isLaneOp = true; break;
11034       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11035         NumVecs = 3; isLaneOp = true; break;
11036       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11037         NumVecs = 4; isLaneOp = true; break;
11038       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11039         NumVecs = 1; isLoadOp = false; break;
11040       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11041         NumVecs = 2; isLoadOp = false; break;
11042       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11043         NumVecs = 3; isLoadOp = false; break;
11044       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11045         NumVecs = 4; isLoadOp = false; break;
11046       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11047         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11048       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11049         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11050       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11051         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11052       }
11053     } else {
11054       isLaneOp = true;
11055       switch (N->getOpcode()) {
11056       default: llvm_unreachable("unexpected opcode for Neon base update");
11057       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11058       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11059       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11060       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11061       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11062         NumVecs = 1; isLaneOp = false; break;
11063       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11064         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11065       }
11066     }
11067 
11068     // Find the size of memory referenced by the load/store.
11069     EVT VecTy;
11070     if (isLoadOp) {
11071       VecTy = N->getValueType(0);
11072     } else if (isIntrinsic) {
11073       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11074     } else {
11075       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11076       VecTy = N->getOperand(1).getValueType();
11077     }
11078 
11079     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11080     if (isLaneOp)
11081       NumBytes /= VecTy.getVectorNumElements();
11082 
11083     // If the increment is a constant, it must match the memory ref size.
11084     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11085     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11086     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11087       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11088       // separate instructions that make it harder to use a non-constant update.
11089       continue;
11090     }
11091 
11092     // OK, we found an ADD we can fold into the base update.
11093     // Now, create a _UPD node, taking care of not breaking alignment.
11094 
11095     EVT AlignedVecTy = VecTy;
11096     unsigned Alignment = MemN->getAlignment();
11097 
11098     // If this is a less-than-standard-aligned load/store, change the type to
11099     // match the standard alignment.
11100     // The alignment is overlooked when selecting _UPD variants; and it's
11101     // easier to introduce bitcasts here than fix that.
11102     // There are 3 ways to get to this base-update combine:
11103     // - intrinsics: they are assumed to be properly aligned (to the standard
11104     //   alignment of the memory type), so we don't need to do anything.
11105     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11106     //   intrinsics, so, likewise, there's nothing to do.
11107     // - generic load/store instructions: the alignment is specified as an
11108     //   explicit operand, rather than implicitly as the standard alignment
11109     //   of the memory type (like the intrisics).  We need to change the
11110     //   memory type to match the explicit alignment.  That way, we don't
11111     //   generate non-standard-aligned ARMISD::VLDx nodes.
11112     if (isa<LSBaseSDNode>(N)) {
11113       if (Alignment == 0)
11114         Alignment = 1;
11115       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11116         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11117         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11118         assert(!isLaneOp && "Unexpected generic load/store lane.");
11119         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11120         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11121       }
11122       // Don't set an explicit alignment on regular load/stores that we want
11123       // to transform to VLD/VST 1_UPD nodes.
11124       // This matches the behavior of regular load/stores, which only get an
11125       // explicit alignment if the MMO alignment is larger than the standard
11126       // alignment of the memory type.
11127       // Intrinsics, however, always get an explicit alignment, set to the
11128       // alignment of the MMO.
11129       Alignment = 1;
11130     }
11131 
11132     // Create the new updating load/store node.
11133     // First, create an SDVTList for the new updating node's results.
11134     EVT Tys[6];
11135     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11136     unsigned n;
11137     for (n = 0; n < NumResultVecs; ++n)
11138       Tys[n] = AlignedVecTy;
11139     Tys[n++] = MVT::i32;
11140     Tys[n] = MVT::Other;
11141     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11142 
11143     // Then, gather the new node's operands.
11144     SmallVector<SDValue, 8> Ops;
11145     Ops.push_back(N->getOperand(0)); // incoming chain
11146     Ops.push_back(N->getOperand(AddrOpIdx));
11147     Ops.push_back(Inc);
11148 
11149     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11150       // Try to match the intrinsic's signature
11151       Ops.push_back(StN->getValue());
11152     } else {
11153       // Loads (and of course intrinsics) match the intrinsics' signature,
11154       // so just add all but the alignment operand.
11155       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11156         Ops.push_back(N->getOperand(i));
11157     }
11158 
11159     // For all node types, the alignment operand is always the last one.
11160     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11161 
11162     // If this is a non-standard-aligned STORE, the penultimate operand is the
11163     // stored value.  Bitcast it to the aligned type.
11164     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11165       SDValue &StVal = Ops[Ops.size()-2];
11166       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11167     }
11168 
11169     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11170     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11171                                            MemN->getMemOperand());
11172 
11173     // Update the uses.
11174     SmallVector<SDValue, 5> NewResults;
11175     for (unsigned i = 0; i < NumResultVecs; ++i)
11176       NewResults.push_back(SDValue(UpdN.getNode(), i));
11177 
11178     // If this is an non-standard-aligned LOAD, the first result is the loaded
11179     // value.  Bitcast it to the expected result type.
11180     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11181       SDValue &LdVal = NewResults[0];
11182       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11183     }
11184 
11185     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11186     DCI.CombineTo(N, NewResults);
11187     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11188 
11189     break;
11190   }
11191   return SDValue();
11192 }
11193 
11194 static SDValue PerformVLDCombine(SDNode *N,
11195                                  TargetLowering::DAGCombinerInfo &DCI) {
11196   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11197     return SDValue();
11198 
11199   return CombineBaseUpdate(N, DCI);
11200 }
11201 
11202 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11203 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11204 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11205 /// return true.
11206 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11207   SelectionDAG &DAG = DCI.DAG;
11208   EVT VT = N->getValueType(0);
11209   // vldN-dup instructions only support 64-bit vectors for N > 1.
11210   if (!VT.is64BitVector())
11211     return false;
11212 
11213   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11214   SDNode *VLD = N->getOperand(0).getNode();
11215   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11216     return false;
11217   unsigned NumVecs = 0;
11218   unsigned NewOpc = 0;
11219   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11220   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11221     NumVecs = 2;
11222     NewOpc = ARMISD::VLD2DUP;
11223   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11224     NumVecs = 3;
11225     NewOpc = ARMISD::VLD3DUP;
11226   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11227     NumVecs = 4;
11228     NewOpc = ARMISD::VLD4DUP;
11229   } else {
11230     return false;
11231   }
11232 
11233   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11234   // numbers match the load.
11235   unsigned VLDLaneNo =
11236     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11237   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11238        UI != UE; ++UI) {
11239     // Ignore uses of the chain result.
11240     if (UI.getUse().getResNo() == NumVecs)
11241       continue;
11242     SDNode *User = *UI;
11243     if (User->getOpcode() != ARMISD::VDUPLANE ||
11244         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11245       return false;
11246   }
11247 
11248   // Create the vldN-dup node.
11249   EVT Tys[5];
11250   unsigned n;
11251   for (n = 0; n < NumVecs; ++n)
11252     Tys[n] = VT;
11253   Tys[n] = MVT::Other;
11254   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11255   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11256   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11257   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11258                                            Ops, VLDMemInt->getMemoryVT(),
11259                                            VLDMemInt->getMemOperand());
11260 
11261   // Update the uses.
11262   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11263        UI != UE; ++UI) {
11264     unsigned ResNo = UI.getUse().getResNo();
11265     // Ignore uses of the chain result.
11266     if (ResNo == NumVecs)
11267       continue;
11268     SDNode *User = *UI;
11269     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11270   }
11271 
11272   // Now the vldN-lane intrinsic is dead except for its chain result.
11273   // Update uses of the chain.
11274   std::vector<SDValue> VLDDupResults;
11275   for (unsigned n = 0; n < NumVecs; ++n)
11276     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11277   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11278   DCI.CombineTo(VLD, VLDDupResults);
11279 
11280   return true;
11281 }
11282 
11283 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11284 /// ARMISD::VDUPLANE.
11285 static SDValue PerformVDUPLANECombine(SDNode *N,
11286                                       TargetLowering::DAGCombinerInfo &DCI) {
11287   SDValue Op = N->getOperand(0);
11288 
11289   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11290   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11291   if (CombineVLDDUP(N, DCI))
11292     return SDValue(N, 0);
11293 
11294   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11295   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11296   while (Op.getOpcode() == ISD::BITCAST)
11297     Op = Op.getOperand(0);
11298   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11299     return SDValue();
11300 
11301   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11302   unsigned EltSize = Op.getScalarValueSizeInBits();
11303   // The canonical VMOV for a zero vector uses a 32-bit element size.
11304   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11305   unsigned EltBits;
11306   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11307     EltSize = 8;
11308   EVT VT = N->getValueType(0);
11309   if (EltSize > VT.getScalarSizeInBits())
11310     return SDValue();
11311 
11312   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11313 }
11314 
11315 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11316 static SDValue PerformVDUPCombine(SDNode *N,
11317                                   TargetLowering::DAGCombinerInfo &DCI) {
11318   SelectionDAG &DAG = DCI.DAG;
11319   SDValue Op = N->getOperand(0);
11320 
11321   // Match VDUP(LOAD) -> VLD1DUP.
11322   // We match this pattern here rather than waiting for isel because the
11323   // transform is only legal for unindexed loads.
11324   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11325   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11326       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11327     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11328                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11329     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11330     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11331                                              Ops, LD->getMemoryVT(),
11332                                              LD->getMemOperand());
11333     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11334     return VLDDup;
11335   }
11336 
11337   return SDValue();
11338 }
11339 
11340 static SDValue PerformLOADCombine(SDNode *N,
11341                                   TargetLowering::DAGCombinerInfo &DCI) {
11342   EVT VT = N->getValueType(0);
11343 
11344   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11345   if (ISD::isNormalLoad(N) && VT.isVector() &&
11346       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11347     return CombineBaseUpdate(N, DCI);
11348 
11349   return SDValue();
11350 }
11351 
11352 /// PerformSTORECombine - Target-specific dag combine xforms for
11353 /// ISD::STORE.
11354 static SDValue PerformSTORECombine(SDNode *N,
11355                                    TargetLowering::DAGCombinerInfo &DCI) {
11356   StoreSDNode *St = cast<StoreSDNode>(N);
11357   if (St->isVolatile())
11358     return SDValue();
11359 
11360   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11361   // pack all of the elements in one place.  Next, store to memory in fewer
11362   // chunks.
11363   SDValue StVal = St->getValue();
11364   EVT VT = StVal.getValueType();
11365   if (St->isTruncatingStore() && VT.isVector()) {
11366     SelectionDAG &DAG = DCI.DAG;
11367     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11368     EVT StVT = St->getMemoryVT();
11369     unsigned NumElems = VT.getVectorNumElements();
11370     assert(StVT != VT && "Cannot truncate to the same type");
11371     unsigned FromEltSz = VT.getScalarSizeInBits();
11372     unsigned ToEltSz = StVT.getScalarSizeInBits();
11373 
11374     // From, To sizes and ElemCount must be pow of two
11375     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11376 
11377     // We are going to use the original vector elt for storing.
11378     // Accumulated smaller vector elements must be a multiple of the store size.
11379     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11380 
11381     unsigned SizeRatio  = FromEltSz / ToEltSz;
11382     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11383 
11384     // Create a type on which we perform the shuffle.
11385     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11386                                      NumElems*SizeRatio);
11387     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11388 
11389     SDLoc DL(St);
11390     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11391     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11392     for (unsigned i = 0; i < NumElems; ++i)
11393       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11394                           ? (i + 1) * SizeRatio - 1
11395                           : i * SizeRatio;
11396 
11397     // Can't shuffle using an illegal type.
11398     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11399 
11400     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11401                                 DAG.getUNDEF(WideVec.getValueType()),
11402                                 ShuffleVec);
11403     // At this point all of the data is stored at the bottom of the
11404     // register. We now need to save it to mem.
11405 
11406     // Find the largest store unit
11407     MVT StoreType = MVT::i8;
11408     for (MVT Tp : MVT::integer_valuetypes()) {
11409       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11410         StoreType = Tp;
11411     }
11412     // Didn't find a legal store type.
11413     if (!TLI.isTypeLegal(StoreType))
11414       return SDValue();
11415 
11416     // Bitcast the original vector into a vector of store-size units
11417     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11418             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11419     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11420     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11421     SmallVector<SDValue, 8> Chains;
11422     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11423                                         TLI.getPointerTy(DAG.getDataLayout()));
11424     SDValue BasePtr = St->getBasePtr();
11425 
11426     // Perform one or more big stores into memory.
11427     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11428     for (unsigned I = 0; I < E; I++) {
11429       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11430                                    StoreType, ShuffWide,
11431                                    DAG.getIntPtrConstant(I, DL));
11432       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11433                                 St->getPointerInfo(), St->getAlignment(),
11434                                 St->getMemOperand()->getFlags());
11435       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11436                             Increment);
11437       Chains.push_back(Ch);
11438     }
11439     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11440   }
11441 
11442   if (!ISD::isNormalStore(St))
11443     return SDValue();
11444 
11445   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11446   // ARM stores of arguments in the same cache line.
11447   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11448       StVal.getNode()->hasOneUse()) {
11449     SelectionDAG  &DAG = DCI.DAG;
11450     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11451     SDLoc DL(St);
11452     SDValue BasePtr = St->getBasePtr();
11453     SDValue NewST1 = DAG.getStore(
11454         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11455         BasePtr, St->getPointerInfo(), St->getAlignment(),
11456         St->getMemOperand()->getFlags());
11457 
11458     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11459                                     DAG.getConstant(4, DL, MVT::i32));
11460     return DAG.getStore(NewST1.getValue(0), DL,
11461                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11462                         OffsetPtr, St->getPointerInfo(),
11463                         std::min(4U, St->getAlignment() / 2),
11464                         St->getMemOperand()->getFlags());
11465   }
11466 
11467   if (StVal.getValueType() == MVT::i64 &&
11468       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11469 
11470     // Bitcast an i64 store extracted from a vector to f64.
11471     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11472     SelectionDAG &DAG = DCI.DAG;
11473     SDLoc dl(StVal);
11474     SDValue IntVec = StVal.getOperand(0);
11475     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11476                                    IntVec.getValueType().getVectorNumElements());
11477     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11478     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11479                                  Vec, StVal.getOperand(1));
11480     dl = SDLoc(N);
11481     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11482     // Make the DAGCombiner fold the bitcasts.
11483     DCI.AddToWorklist(Vec.getNode());
11484     DCI.AddToWorklist(ExtElt.getNode());
11485     DCI.AddToWorklist(V.getNode());
11486     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11487                         St->getPointerInfo(), St->getAlignment(),
11488                         St->getMemOperand()->getFlags(), St->getAAInfo());
11489   }
11490 
11491   // If this is a legal vector store, try to combine it into a VST1_UPD.
11492   if (ISD::isNormalStore(N) && VT.isVector() &&
11493       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11494     return CombineBaseUpdate(N, DCI);
11495 
11496   return SDValue();
11497 }
11498 
11499 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11500 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11501 /// when the VMUL has a constant operand that is a power of 2.
11502 ///
11503 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11504 ///  vmul.f32        d16, d17, d16
11505 ///  vcvt.s32.f32    d16, d16
11506 /// becomes:
11507 ///  vcvt.s32.f32    d16, d16, #3
11508 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11509                                   const ARMSubtarget *Subtarget) {
11510   if (!Subtarget->hasNEON())
11511     return SDValue();
11512 
11513   SDValue Op = N->getOperand(0);
11514   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11515       Op.getOpcode() != ISD::FMUL)
11516     return SDValue();
11517 
11518   SDValue ConstVec = Op->getOperand(1);
11519   if (!isa<BuildVectorSDNode>(ConstVec))
11520     return SDValue();
11521 
11522   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11523   uint32_t FloatBits = FloatTy.getSizeInBits();
11524   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11525   uint32_t IntBits = IntTy.getSizeInBits();
11526   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11527   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11528     // These instructions only exist converting from f32 to i32. We can handle
11529     // smaller integers by generating an extra truncate, but larger ones would
11530     // be lossy. We also can't handle more then 4 lanes, since these intructions
11531     // only support v2i32/v4i32 types.
11532     return SDValue();
11533   }
11534 
11535   BitVector UndefElements;
11536   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11537   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11538   if (C == -1 || C == 0 || C > 32)
11539     return SDValue();
11540 
11541   SDLoc dl(N);
11542   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11543   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11544     Intrinsic::arm_neon_vcvtfp2fxu;
11545   SDValue FixConv = DAG.getNode(
11546       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11547       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11548       DAG.getConstant(C, dl, MVT::i32));
11549 
11550   if (IntBits < FloatBits)
11551     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11552 
11553   return FixConv;
11554 }
11555 
11556 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11557 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11558 /// when the VDIV has a constant operand that is a power of 2.
11559 ///
11560 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11561 ///  vcvt.f32.s32    d16, d16
11562 ///  vdiv.f32        d16, d17, d16
11563 /// becomes:
11564 ///  vcvt.f32.s32    d16, d16, #3
11565 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11566                                   const ARMSubtarget *Subtarget) {
11567   if (!Subtarget->hasNEON())
11568     return SDValue();
11569 
11570   SDValue Op = N->getOperand(0);
11571   unsigned OpOpcode = Op.getNode()->getOpcode();
11572   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11573       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11574     return SDValue();
11575 
11576   SDValue ConstVec = N->getOperand(1);
11577   if (!isa<BuildVectorSDNode>(ConstVec))
11578     return SDValue();
11579 
11580   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11581   uint32_t FloatBits = FloatTy.getSizeInBits();
11582   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11583   uint32_t IntBits = IntTy.getSizeInBits();
11584   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11585   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11586     // These instructions only exist converting from i32 to f32. We can handle
11587     // smaller integers by generating an extra extend, but larger ones would
11588     // be lossy. We also can't handle more then 4 lanes, since these intructions
11589     // only support v2i32/v4i32 types.
11590     return SDValue();
11591   }
11592 
11593   BitVector UndefElements;
11594   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11595   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11596   if (C == -1 || C == 0 || C > 32)
11597     return SDValue();
11598 
11599   SDLoc dl(N);
11600   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11601   SDValue ConvInput = Op.getOperand(0);
11602   if (IntBits < FloatBits)
11603     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11604                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11605                             ConvInput);
11606 
11607   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11608     Intrinsic::arm_neon_vcvtfxu2fp;
11609   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11610                      Op.getValueType(),
11611                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11612                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11613 }
11614 
11615 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11616 /// operand of a vector shift operation, where all the elements of the
11617 /// build_vector must have the same constant integer value.
11618 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11619   // Ignore bit_converts.
11620   while (Op.getOpcode() == ISD::BITCAST)
11621     Op = Op.getOperand(0);
11622   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11623   APInt SplatBits, SplatUndef;
11624   unsigned SplatBitSize;
11625   bool HasAnyUndefs;
11626   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11627                                       HasAnyUndefs, ElementBits) ||
11628       SplatBitSize > ElementBits)
11629     return false;
11630   Cnt = SplatBits.getSExtValue();
11631   return true;
11632 }
11633 
11634 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11635 /// operand of a vector shift left operation.  That value must be in the range:
11636 ///   0 <= Value < ElementBits for a left shift; or
11637 ///   0 <= Value <= ElementBits for a long left shift.
11638 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11639   assert(VT.isVector() && "vector shift count is not a vector type");
11640   int64_t ElementBits = VT.getScalarSizeInBits();
11641   if (! getVShiftImm(Op, ElementBits, Cnt))
11642     return false;
11643   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11644 }
11645 
11646 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11647 /// operand of a vector shift right operation.  For a shift opcode, the value
11648 /// is positive, but for an intrinsic the value count must be negative. The
11649 /// absolute value must be in the range:
11650 ///   1 <= |Value| <= ElementBits for a right shift; or
11651 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11652 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11653                          int64_t &Cnt) {
11654   assert(VT.isVector() && "vector shift count is not a vector type");
11655   int64_t ElementBits = VT.getScalarSizeInBits();
11656   if (! getVShiftImm(Op, ElementBits, Cnt))
11657     return false;
11658   if (!isIntrinsic)
11659     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11660   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11661     Cnt = -Cnt;
11662     return true;
11663   }
11664   return false;
11665 }
11666 
11667 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11668 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11669   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11670   switch (IntNo) {
11671   default:
11672     // Don't do anything for most intrinsics.
11673     break;
11674 
11675   // Vector shifts: check for immediate versions and lower them.
11676   // Note: This is done during DAG combining instead of DAG legalizing because
11677   // the build_vectors for 64-bit vector element shift counts are generally
11678   // not legal, and it is hard to see their values after they get legalized to
11679   // loads from a constant pool.
11680   case Intrinsic::arm_neon_vshifts:
11681   case Intrinsic::arm_neon_vshiftu:
11682   case Intrinsic::arm_neon_vrshifts:
11683   case Intrinsic::arm_neon_vrshiftu:
11684   case Intrinsic::arm_neon_vrshiftn:
11685   case Intrinsic::arm_neon_vqshifts:
11686   case Intrinsic::arm_neon_vqshiftu:
11687   case Intrinsic::arm_neon_vqshiftsu:
11688   case Intrinsic::arm_neon_vqshiftns:
11689   case Intrinsic::arm_neon_vqshiftnu:
11690   case Intrinsic::arm_neon_vqshiftnsu:
11691   case Intrinsic::arm_neon_vqrshiftns:
11692   case Intrinsic::arm_neon_vqrshiftnu:
11693   case Intrinsic::arm_neon_vqrshiftnsu: {
11694     EVT VT = N->getOperand(1).getValueType();
11695     int64_t Cnt;
11696     unsigned VShiftOpc = 0;
11697 
11698     switch (IntNo) {
11699     case Intrinsic::arm_neon_vshifts:
11700     case Intrinsic::arm_neon_vshiftu:
11701       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11702         VShiftOpc = ARMISD::VSHL;
11703         break;
11704       }
11705       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11706         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11707                      ARMISD::VSHRs : ARMISD::VSHRu);
11708         break;
11709       }
11710       return SDValue();
11711 
11712     case Intrinsic::arm_neon_vrshifts:
11713     case Intrinsic::arm_neon_vrshiftu:
11714       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11715         break;
11716       return SDValue();
11717 
11718     case Intrinsic::arm_neon_vqshifts:
11719     case Intrinsic::arm_neon_vqshiftu:
11720       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11721         break;
11722       return SDValue();
11723 
11724     case Intrinsic::arm_neon_vqshiftsu:
11725       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11726         break;
11727       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11728 
11729     case Intrinsic::arm_neon_vrshiftn:
11730     case Intrinsic::arm_neon_vqshiftns:
11731     case Intrinsic::arm_neon_vqshiftnu:
11732     case Intrinsic::arm_neon_vqshiftnsu:
11733     case Intrinsic::arm_neon_vqrshiftns:
11734     case Intrinsic::arm_neon_vqrshiftnu:
11735     case Intrinsic::arm_neon_vqrshiftnsu:
11736       // Narrowing shifts require an immediate right shift.
11737       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11738         break;
11739       llvm_unreachable("invalid shift count for narrowing vector shift "
11740                        "intrinsic");
11741 
11742     default:
11743       llvm_unreachable("unhandled vector shift");
11744     }
11745 
11746     switch (IntNo) {
11747     case Intrinsic::arm_neon_vshifts:
11748     case Intrinsic::arm_neon_vshiftu:
11749       // Opcode already set above.
11750       break;
11751     case Intrinsic::arm_neon_vrshifts:
11752       VShiftOpc = ARMISD::VRSHRs; break;
11753     case Intrinsic::arm_neon_vrshiftu:
11754       VShiftOpc = ARMISD::VRSHRu; break;
11755     case Intrinsic::arm_neon_vrshiftn:
11756       VShiftOpc = ARMISD::VRSHRN; break;
11757     case Intrinsic::arm_neon_vqshifts:
11758       VShiftOpc = ARMISD::VQSHLs; break;
11759     case Intrinsic::arm_neon_vqshiftu:
11760       VShiftOpc = ARMISD::VQSHLu; break;
11761     case Intrinsic::arm_neon_vqshiftsu:
11762       VShiftOpc = ARMISD::VQSHLsu; break;
11763     case Intrinsic::arm_neon_vqshiftns:
11764       VShiftOpc = ARMISD::VQSHRNs; break;
11765     case Intrinsic::arm_neon_vqshiftnu:
11766       VShiftOpc = ARMISD::VQSHRNu; break;
11767     case Intrinsic::arm_neon_vqshiftnsu:
11768       VShiftOpc = ARMISD::VQSHRNsu; break;
11769     case Intrinsic::arm_neon_vqrshiftns:
11770       VShiftOpc = ARMISD::VQRSHRNs; break;
11771     case Intrinsic::arm_neon_vqrshiftnu:
11772       VShiftOpc = ARMISD::VQRSHRNu; break;
11773     case Intrinsic::arm_neon_vqrshiftnsu:
11774       VShiftOpc = ARMISD::VQRSHRNsu; break;
11775     }
11776 
11777     SDLoc dl(N);
11778     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11779                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11780   }
11781 
11782   case Intrinsic::arm_neon_vshiftins: {
11783     EVT VT = N->getOperand(1).getValueType();
11784     int64_t Cnt;
11785     unsigned VShiftOpc = 0;
11786 
11787     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11788       VShiftOpc = ARMISD::VSLI;
11789     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11790       VShiftOpc = ARMISD::VSRI;
11791     else {
11792       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11793     }
11794 
11795     SDLoc dl(N);
11796     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11797                        N->getOperand(1), N->getOperand(2),
11798                        DAG.getConstant(Cnt, dl, MVT::i32));
11799   }
11800 
11801   case Intrinsic::arm_neon_vqrshifts:
11802   case Intrinsic::arm_neon_vqrshiftu:
11803     // No immediate versions of these to check for.
11804     break;
11805   }
11806 
11807   return SDValue();
11808 }
11809 
11810 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11811 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11812 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11813 /// vector element shift counts are generally not legal, and it is hard to see
11814 /// their values after they get legalized to loads from a constant pool.
11815 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11816                                    const ARMSubtarget *ST) {
11817   EVT VT = N->getValueType(0);
11818   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11819     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11820     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11821     SDValue N1 = N->getOperand(1);
11822     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11823       SDValue N0 = N->getOperand(0);
11824       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11825           DAG.MaskedValueIsZero(N0.getOperand(0),
11826                                 APInt::getHighBitsSet(32, 16)))
11827         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11828     }
11829   }
11830 
11831   // Nothing to be done for scalar shifts.
11832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11833   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11834     return SDValue();
11835 
11836   assert(ST->hasNEON() && "unexpected vector shift");
11837   int64_t Cnt;
11838 
11839   switch (N->getOpcode()) {
11840   default: llvm_unreachable("unexpected shift opcode");
11841 
11842   case ISD::SHL:
11843     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11844       SDLoc dl(N);
11845       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11846                          DAG.getConstant(Cnt, dl, MVT::i32));
11847     }
11848     break;
11849 
11850   case ISD::SRA:
11851   case ISD::SRL:
11852     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11853       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11854                             ARMISD::VSHRs : ARMISD::VSHRu);
11855       SDLoc dl(N);
11856       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11857                          DAG.getConstant(Cnt, dl, MVT::i32));
11858     }
11859   }
11860   return SDValue();
11861 }
11862 
11863 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11864 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11865 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11866                                     const ARMSubtarget *ST) {
11867   SDValue N0 = N->getOperand(0);
11868 
11869   // Check for sign- and zero-extensions of vector extract operations of 8-
11870   // and 16-bit vector elements.  NEON supports these directly.  They are
11871   // handled during DAG combining because type legalization will promote them
11872   // to 32-bit types and it is messy to recognize the operations after that.
11873   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11874     SDValue Vec = N0.getOperand(0);
11875     SDValue Lane = N0.getOperand(1);
11876     EVT VT = N->getValueType(0);
11877     EVT EltVT = N0.getValueType();
11878     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11879 
11880     if (VT == MVT::i32 &&
11881         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11882         TLI.isTypeLegal(Vec.getValueType()) &&
11883         isa<ConstantSDNode>(Lane)) {
11884 
11885       unsigned Opc = 0;
11886       switch (N->getOpcode()) {
11887       default: llvm_unreachable("unexpected opcode");
11888       case ISD::SIGN_EXTEND:
11889         Opc = ARMISD::VGETLANEs;
11890         break;
11891       case ISD::ZERO_EXTEND:
11892       case ISD::ANY_EXTEND:
11893         Opc = ARMISD::VGETLANEu;
11894         break;
11895       }
11896       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11897     }
11898   }
11899 
11900   return SDValue();
11901 }
11902 
11903 static const APInt *isPowerOf2Constant(SDValue V) {
11904   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11905   if (!C)
11906     return nullptr;
11907   const APInt *CV = &C->getAPIntValue();
11908   return CV->isPowerOf2() ? CV : nullptr;
11909 }
11910 
11911 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11912   // If we have a CMOV, OR and AND combination such as:
11913   //   if (x & CN)
11914   //     y |= CM;
11915   //
11916   // And:
11917   //   * CN is a single bit;
11918   //   * All bits covered by CM are known zero in y
11919   //
11920   // Then we can convert this into a sequence of BFI instructions. This will
11921   // always be a win if CM is a single bit, will always be no worse than the
11922   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11923   // three bits (due to the extra IT instruction).
11924 
11925   SDValue Op0 = CMOV->getOperand(0);
11926   SDValue Op1 = CMOV->getOperand(1);
11927   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11928   auto CC = CCNode->getAPIntValue().getLimitedValue();
11929   SDValue CmpZ = CMOV->getOperand(4);
11930 
11931   // The compare must be against zero.
11932   if (!isNullConstant(CmpZ->getOperand(1)))
11933     return SDValue();
11934 
11935   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11936   SDValue And = CmpZ->getOperand(0);
11937   if (And->getOpcode() != ISD::AND)
11938     return SDValue();
11939   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
11940   if (!AndC)
11941     return SDValue();
11942   SDValue X = And->getOperand(0);
11943 
11944   if (CC == ARMCC::EQ) {
11945     // We're performing an "equal to zero" compare. Swap the operands so we
11946     // canonicalize on a "not equal to zero" compare.
11947     std::swap(Op0, Op1);
11948   } else {
11949     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11950   }
11951 
11952   if (Op1->getOpcode() != ISD::OR)
11953     return SDValue();
11954 
11955   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11956   if (!OrC)
11957     return SDValue();
11958   SDValue Y = Op1->getOperand(0);
11959 
11960   if (Op0 != Y)
11961     return SDValue();
11962 
11963   // Now, is it profitable to continue?
11964   APInt OrCI = OrC->getAPIntValue();
11965   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11966   if (OrCI.countPopulation() > Heuristic)
11967     return SDValue();
11968 
11969   // Lastly, can we determine that the bits defined by OrCI
11970   // are zero in Y?
11971   KnownBits Known;
11972   DAG.computeKnownBits(Y, Known);
11973   if ((OrCI & Known.Zero) != OrCI)
11974     return SDValue();
11975 
11976   // OK, we can do the combine.
11977   SDValue V = Y;
11978   SDLoc dl(X);
11979   EVT VT = X.getValueType();
11980   unsigned BitInX = AndC->logBase2();
11981 
11982   if (BitInX != 0) {
11983     // We must shift X first.
11984     X = DAG.getNode(ISD::SRL, dl, VT, X,
11985                     DAG.getConstant(BitInX, dl, VT));
11986   }
11987 
11988   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11989        BitInY < NumActiveBits; ++BitInY) {
11990     if (OrCI[BitInY] == 0)
11991       continue;
11992     APInt Mask(VT.getSizeInBits(), 0);
11993     Mask.setBit(BitInY);
11994     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11995                     // Confusingly, the operand is an *inverted* mask.
11996                     DAG.getConstant(~Mask, dl, VT));
11997   }
11998 
11999   return V;
12000 }
12001 
12002 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12003 SDValue
12004 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12005   SDValue Cmp = N->getOperand(4);
12006   if (Cmp.getOpcode() != ARMISD::CMPZ)
12007     // Only looking at NE cases.
12008     return SDValue();
12009 
12010   EVT VT = N->getValueType(0);
12011   SDLoc dl(N);
12012   SDValue LHS = Cmp.getOperand(0);
12013   SDValue RHS = Cmp.getOperand(1);
12014   SDValue Chain = N->getOperand(0);
12015   SDValue BB = N->getOperand(1);
12016   SDValue ARMcc = N->getOperand(2);
12017   ARMCC::CondCodes CC =
12018     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12019 
12020   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12021   // -> (brcond Chain BB CC CPSR Cmp)
12022   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12023       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12024       LHS->getOperand(0)->hasOneUse()) {
12025     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12026     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12027     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12028     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12029     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12030         (LHS01C && LHS01C->getZExtValue() == 1) &&
12031         (LHS1C && LHS1C->getZExtValue() == 1) &&
12032         (RHSC && RHSC->getZExtValue() == 0)) {
12033       return DAG.getNode(
12034           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12035           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12036     }
12037   }
12038 
12039   return SDValue();
12040 }
12041 
12042 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12043 SDValue
12044 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12045   SDValue Cmp = N->getOperand(4);
12046   if (Cmp.getOpcode() != ARMISD::CMPZ)
12047     // Only looking at EQ and NE cases.
12048     return SDValue();
12049 
12050   EVT VT = N->getValueType(0);
12051   SDLoc dl(N);
12052   SDValue LHS = Cmp.getOperand(0);
12053   SDValue RHS = Cmp.getOperand(1);
12054   SDValue FalseVal = N->getOperand(0);
12055   SDValue TrueVal = N->getOperand(1);
12056   SDValue ARMcc = N->getOperand(2);
12057   ARMCC::CondCodes CC =
12058     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12059 
12060   // BFI is only available on V6T2+.
12061   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12062     SDValue R = PerformCMOVToBFICombine(N, DAG);
12063     if (R)
12064       return R;
12065   }
12066 
12067   // Simplify
12068   //   mov     r1, r0
12069   //   cmp     r1, x
12070   //   mov     r0, y
12071   //   moveq   r0, x
12072   // to
12073   //   cmp     r0, x
12074   //   movne   r0, y
12075   //
12076   //   mov     r1, r0
12077   //   cmp     r1, x
12078   //   mov     r0, x
12079   //   movne   r0, y
12080   // to
12081   //   cmp     r0, x
12082   //   movne   r0, y
12083   /// FIXME: Turn this into a target neutral optimization?
12084   SDValue Res;
12085   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12086     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12087                       N->getOperand(3), Cmp);
12088   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12089     SDValue ARMcc;
12090     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12091     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12092                       N->getOperand(3), NewCmp);
12093   }
12094 
12095   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12096   // -> (cmov F T CC CPSR Cmp)
12097   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12098     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12099     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12100     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12101     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12102         (LHS1C && LHS1C->getZExtValue() == 1) &&
12103         (RHSC && RHSC->getZExtValue() == 0)) {
12104       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12105                          LHS->getOperand(2), LHS->getOperand(3),
12106                          LHS->getOperand(4));
12107     }
12108   }
12109 
12110   if (Res.getNode()) {
12111     KnownBits Known;
12112     DAG.computeKnownBits(SDValue(N,0), Known);
12113     // Capture demanded bits information that would be otherwise lost.
12114     if (Known.Zero == 0xfffffffe)
12115       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12116                         DAG.getValueType(MVT::i1));
12117     else if (Known.Zero == 0xffffff00)
12118       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12119                         DAG.getValueType(MVT::i8));
12120     else if (Known.Zero == 0xffff0000)
12121       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12122                         DAG.getValueType(MVT::i16));
12123   }
12124 
12125   return Res;
12126 }
12127 
12128 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12129                                              DAGCombinerInfo &DCI) const {
12130   switch (N->getOpcode()) {
12131   default: break;
12132   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12133   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12134   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12135   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12136   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12137   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12138   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12139   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12140   case ARMISD::ADDC:
12141   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12142   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
12143   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12144   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12145   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12146   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12147   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12148   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12149   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12150   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12151   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12152   case ISD::FP_TO_SINT:
12153   case ISD::FP_TO_UINT:
12154     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12155   case ISD::FDIV:
12156     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12157   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12158   case ISD::SHL:
12159   case ISD::SRA:
12160   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12161   case ISD::SIGN_EXTEND:
12162   case ISD::ZERO_EXTEND:
12163   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12164   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12165   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12166   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12167   case ARMISD::VLD1DUP:
12168   case ARMISD::VLD2DUP:
12169   case ARMISD::VLD3DUP:
12170   case ARMISD::VLD4DUP:
12171     return PerformVLDCombine(N, DCI);
12172   case ARMISD::BUILD_VECTOR:
12173     return PerformARMBUILD_VECTORCombine(N, DCI);
12174   case ARMISD::SMULWB: {
12175     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12176     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12177     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12178       return SDValue();
12179     break;
12180   }
12181   case ARMISD::SMULWT: {
12182     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12183     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12184     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12185       return SDValue();
12186     break;
12187   }
12188   case ARMISD::SMLALBB: {
12189     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12190     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12191     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12192         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12193       return SDValue();
12194     break;
12195   }
12196   case ARMISD::SMLALBT: {
12197     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12198     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12199     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12200     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12201     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12202         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12203       return SDValue();
12204     break;
12205   }
12206   case ARMISD::SMLALTB: {
12207     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12208     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12209     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12210     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12211     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12212         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12213       return SDValue();
12214     break;
12215   }
12216   case ARMISD::SMLALTT: {
12217     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12218     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12219     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12220         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12221       return SDValue();
12222     break;
12223   }
12224   case ISD::INTRINSIC_VOID:
12225   case ISD::INTRINSIC_W_CHAIN:
12226     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12227     case Intrinsic::arm_neon_vld1:
12228     case Intrinsic::arm_neon_vld2:
12229     case Intrinsic::arm_neon_vld3:
12230     case Intrinsic::arm_neon_vld4:
12231     case Intrinsic::arm_neon_vld2lane:
12232     case Intrinsic::arm_neon_vld3lane:
12233     case Intrinsic::arm_neon_vld4lane:
12234     case Intrinsic::arm_neon_vst1:
12235     case Intrinsic::arm_neon_vst2:
12236     case Intrinsic::arm_neon_vst3:
12237     case Intrinsic::arm_neon_vst4:
12238     case Intrinsic::arm_neon_vst2lane:
12239     case Intrinsic::arm_neon_vst3lane:
12240     case Intrinsic::arm_neon_vst4lane:
12241       return PerformVLDCombine(N, DCI);
12242     default: break;
12243     }
12244     break;
12245   }
12246   return SDValue();
12247 }
12248 
12249 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12250                                                           EVT VT) const {
12251   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12252 }
12253 
12254 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12255                                                        unsigned,
12256                                                        unsigned,
12257                                                        bool *Fast) const {
12258   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12259   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12260 
12261   switch (VT.getSimpleVT().SimpleTy) {
12262   default:
12263     return false;
12264   case MVT::i8:
12265   case MVT::i16:
12266   case MVT::i32: {
12267     // Unaligned access can use (for example) LRDB, LRDH, LDR
12268     if (AllowsUnaligned) {
12269       if (Fast)
12270         *Fast = Subtarget->hasV7Ops();
12271       return true;
12272     }
12273     return false;
12274   }
12275   case MVT::f64:
12276   case MVT::v2f64: {
12277     // For any little-endian targets with neon, we can support unaligned ld/st
12278     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12279     // A big-endian target may also explicitly support unaligned accesses
12280     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12281       if (Fast)
12282         *Fast = true;
12283       return true;
12284     }
12285     return false;
12286   }
12287   }
12288 }
12289 
12290 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12291                        unsigned AlignCheck) {
12292   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12293           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12294 }
12295 
12296 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12297                                            unsigned DstAlign, unsigned SrcAlign,
12298                                            bool IsMemset, bool ZeroMemset,
12299                                            bool MemcpyStrSrc,
12300                                            MachineFunction &MF) const {
12301   const Function *F = MF.getFunction();
12302 
12303   // See if we can use NEON instructions for this...
12304   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12305       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12306     bool Fast;
12307     if (Size >= 16 &&
12308         (memOpAlign(SrcAlign, DstAlign, 16) ||
12309          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12310       return MVT::v2f64;
12311     } else if (Size >= 8 &&
12312                (memOpAlign(SrcAlign, DstAlign, 8) ||
12313                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12314                  Fast))) {
12315       return MVT::f64;
12316     }
12317   }
12318 
12319   // Let the target-independent logic figure it out.
12320   return MVT::Other;
12321 }
12322 
12323 // 64-bit integers are split into their high and low parts and held in two
12324 // different registers, so the trunc is free since the low register can just
12325 // be used.
12326 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12327   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12328     return false;
12329   unsigned NumBits1 = SrcTy->getPrimitiveSizeInBits();
12330   unsigned NumBits2 = DstTy->getPrimitiveSizeInBits();
12331   return NumBits1 > NumBits2;
12332 }
12333 
12334 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12335   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12336       !DstVT.isInteger())
12337     return false;
12338   unsigned NumBits1 = SrcVT.getSizeInBits();
12339   unsigned NumBits2 = DstVT.getSizeInBits();
12340   return NumBits1 > NumBits2;
12341 }
12342 
12343 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12344   if (Val.getOpcode() != ISD::LOAD)
12345     return false;
12346 
12347   EVT VT1 = Val.getValueType();
12348   if (!VT1.isSimple() || !VT1.isInteger() ||
12349       !VT2.isSimple() || !VT2.isInteger())
12350     return false;
12351 
12352   switch (VT1.getSimpleVT().SimpleTy) {
12353   default: break;
12354   case MVT::i1:
12355   case MVT::i8:
12356   case MVT::i16:
12357     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12358     return true;
12359   }
12360 
12361   return false;
12362 }
12363 
12364 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12365   EVT VT = ExtVal.getValueType();
12366 
12367   if (!isTypeLegal(VT))
12368     return false;
12369 
12370   // Don't create a loadext if we can fold the extension into a wide/long
12371   // instruction.
12372   // If there's more than one user instruction, the loadext is desirable no
12373   // matter what.  There can be two uses by the same instruction.
12374   if (ExtVal->use_empty() ||
12375       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12376     return true;
12377 
12378   SDNode *U = *ExtVal->use_begin();
12379   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12380        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12381     return false;
12382 
12383   return true;
12384 }
12385 
12386 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12387   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12388     return false;
12389 
12390   if (!isTypeLegal(EVT::getEVT(Ty1)))
12391     return false;
12392 
12393   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12394 
12395   // Assuming the caller doesn't have a zeroext or signext return parameter,
12396   // truncation all the way down to i1 is valid.
12397   return true;
12398 }
12399 
12400 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12401                                                 const AddrMode &AM, Type *Ty,
12402                                                 unsigned AS) const {
12403   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12404     if (Subtarget->hasFPAO())
12405       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12406     return 0;
12407   }
12408   return -1;
12409 }
12410 
12411 
12412 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12413   if (V < 0)
12414     return false;
12415 
12416   unsigned Scale = 1;
12417   switch (VT.getSimpleVT().SimpleTy) {
12418   default: return false;
12419   case MVT::i1:
12420   case MVT::i8:
12421     // Scale == 1;
12422     break;
12423   case MVT::i16:
12424     // Scale == 2;
12425     Scale = 2;
12426     break;
12427   case MVT::i32:
12428     // Scale == 4;
12429     Scale = 4;
12430     break;
12431   }
12432 
12433   if ((V & (Scale - 1)) != 0)
12434     return false;
12435   V /= Scale;
12436   return V == (V & ((1LL << 5) - 1));
12437 }
12438 
12439 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12440                                       const ARMSubtarget *Subtarget) {
12441   bool isNeg = false;
12442   if (V < 0) {
12443     isNeg = true;
12444     V = - V;
12445   }
12446 
12447   switch (VT.getSimpleVT().SimpleTy) {
12448   default: return false;
12449   case MVT::i1:
12450   case MVT::i8:
12451   case MVT::i16:
12452   case MVT::i32:
12453     // + imm12 or - imm8
12454     if (isNeg)
12455       return V == (V & ((1LL << 8) - 1));
12456     return V == (V & ((1LL << 12) - 1));
12457   case MVT::f32:
12458   case MVT::f64:
12459     // Same as ARM mode. FIXME: NEON?
12460     if (!Subtarget->hasVFP2())
12461       return false;
12462     if ((V & 3) != 0)
12463       return false;
12464     V >>= 2;
12465     return V == (V & ((1LL << 8) - 1));
12466   }
12467 }
12468 
12469 /// isLegalAddressImmediate - Return true if the integer value can be used
12470 /// as the offset of the target addressing mode for load / store of the
12471 /// given type.
12472 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12473                                     const ARMSubtarget *Subtarget) {
12474   if (V == 0)
12475     return true;
12476 
12477   if (!VT.isSimple())
12478     return false;
12479 
12480   if (Subtarget->isThumb1Only())
12481     return isLegalT1AddressImmediate(V, VT);
12482   else if (Subtarget->isThumb2())
12483     return isLegalT2AddressImmediate(V, VT, Subtarget);
12484 
12485   // ARM mode.
12486   if (V < 0)
12487     V = - V;
12488   switch (VT.getSimpleVT().SimpleTy) {
12489   default: return false;
12490   case MVT::i1:
12491   case MVT::i8:
12492   case MVT::i32:
12493     // +- imm12
12494     return V == (V & ((1LL << 12) - 1));
12495   case MVT::i16:
12496     // +- imm8
12497     return V == (V & ((1LL << 8) - 1));
12498   case MVT::f32:
12499   case MVT::f64:
12500     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12501       return false;
12502     if ((V & 3) != 0)
12503       return false;
12504     V >>= 2;
12505     return V == (V & ((1LL << 8) - 1));
12506   }
12507 }
12508 
12509 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12510                                                       EVT VT) const {
12511   int Scale = AM.Scale;
12512   if (Scale < 0)
12513     return false;
12514 
12515   switch (VT.getSimpleVT().SimpleTy) {
12516   default: return false;
12517   case MVT::i1:
12518   case MVT::i8:
12519   case MVT::i16:
12520   case MVT::i32:
12521     if (Scale == 1)
12522       return true;
12523     // r + r << imm
12524     Scale = Scale & ~1;
12525     return Scale == 2 || Scale == 4 || Scale == 8;
12526   case MVT::i64:
12527     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12528     // version in Thumb mode.
12529     // r + r
12530     if (Scale == 1)
12531       return true;
12532     // r * 2 (this can be lowered to r + r).
12533     if (!AM.HasBaseReg && Scale == 2)
12534       return true;
12535     return false;
12536   case MVT::isVoid:
12537     // Note, we allow "void" uses (basically, uses that aren't loads or
12538     // stores), because arm allows folding a scale into many arithmetic
12539     // operations.  This should be made more precise and revisited later.
12540 
12541     // Allow r << imm, but the imm has to be a multiple of two.
12542     if (Scale & 1) return false;
12543     return isPowerOf2_32(Scale);
12544   }
12545 }
12546 
12547 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12548                                                       EVT VT) const {
12549   const int Scale = AM.Scale;
12550 
12551   // Negative scales are not supported in Thumb1.
12552   if (Scale < 0)
12553     return false;
12554 
12555   // Thumb1 addressing modes do not support register scaling excepting the
12556   // following cases:
12557   // 1. Scale == 1 means no scaling.
12558   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12559   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12560 }
12561 
12562 /// isLegalAddressingMode - Return true if the addressing mode represented
12563 /// by AM is legal for this target, for a load/store of the specified type.
12564 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12565                                               const AddrMode &AM, Type *Ty,
12566                                               unsigned AS, Instruction *I) const {
12567   EVT VT = getValueType(DL, Ty, true);
12568   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12569     return false;
12570 
12571   // Can never fold addr of global into load/store.
12572   if (AM.BaseGV)
12573     return false;
12574 
12575   switch (AM.Scale) {
12576   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12577     break;
12578   default:
12579     // ARM doesn't support any R+R*scale+imm addr modes.
12580     if (AM.BaseOffs)
12581       return false;
12582 
12583     if (!VT.isSimple())
12584       return false;
12585 
12586     if (Subtarget->isThumb1Only())
12587       return isLegalT1ScaledAddressingMode(AM, VT);
12588 
12589     if (Subtarget->isThumb2())
12590       return isLegalT2ScaledAddressingMode(AM, VT);
12591 
12592     int Scale = AM.Scale;
12593     switch (VT.getSimpleVT().SimpleTy) {
12594     default: return false;
12595     case MVT::i1:
12596     case MVT::i8:
12597     case MVT::i32:
12598       if (Scale < 0) Scale = -Scale;
12599       if (Scale == 1)
12600         return true;
12601       // r + r << imm
12602       return isPowerOf2_32(Scale & ~1);
12603     case MVT::i16:
12604     case MVT::i64:
12605       // r +/- r
12606       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
12607         return true;
12608       // r * 2 (this can be lowered to r + r).
12609       if (!AM.HasBaseReg && Scale == 2)
12610         return true;
12611       return false;
12612 
12613     case MVT::isVoid:
12614       // Note, we allow "void" uses (basically, uses that aren't loads or
12615       // stores), because arm allows folding a scale into many arithmetic
12616       // operations.  This should be made more precise and revisited later.
12617 
12618       // Allow r << imm, but the imm has to be a multiple of two.
12619       if (Scale & 1) return false;
12620       return isPowerOf2_32(Scale);
12621     }
12622   }
12623   return true;
12624 }
12625 
12626 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12627 /// icmp immediate, that is the target has icmp instructions which can compare
12628 /// a register against the immediate without having to materialize the
12629 /// immediate into a register.
12630 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12631   // Thumb2 and ARM modes can use cmn for negative immediates.
12632   if (!Subtarget->isThumb())
12633     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12634   if (Subtarget->isThumb2())
12635     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12636   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12637   return Imm >= 0 && Imm <= 255;
12638 }
12639 
12640 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12641 /// *or sub* immediate, that is the target has add or sub instructions which can
12642 /// add a register with the immediate without having to materialize the
12643 /// immediate into a register.
12644 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12645   // Same encoding for add/sub, just flip the sign.
12646   int64_t AbsImm = std::abs(Imm);
12647   if (!Subtarget->isThumb())
12648     return ARM_AM::getSOImmVal(AbsImm) != -1;
12649   if (Subtarget->isThumb2())
12650     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12651   // Thumb1 only has 8-bit unsigned immediate.
12652   return AbsImm >= 0 && AbsImm <= 255;
12653 }
12654 
12655 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12656                                       bool isSEXTLoad, SDValue &Base,
12657                                       SDValue &Offset, bool &isInc,
12658                                       SelectionDAG &DAG) {
12659   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12660     return false;
12661 
12662   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12663     // AddressingMode 3
12664     Base = Ptr->getOperand(0);
12665     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12666       int RHSC = (int)RHS->getZExtValue();
12667       if (RHSC < 0 && RHSC > -256) {
12668         assert(Ptr->getOpcode() == ISD::ADD);
12669         isInc = false;
12670         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12671         return true;
12672       }
12673     }
12674     isInc = (Ptr->getOpcode() == ISD::ADD);
12675     Offset = Ptr->getOperand(1);
12676     return true;
12677   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12678     // AddressingMode 2
12679     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12680       int RHSC = (int)RHS->getZExtValue();
12681       if (RHSC < 0 && RHSC > -0x1000) {
12682         assert(Ptr->getOpcode() == ISD::ADD);
12683         isInc = false;
12684         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12685         Base = Ptr->getOperand(0);
12686         return true;
12687       }
12688     }
12689 
12690     if (Ptr->getOpcode() == ISD::ADD) {
12691       isInc = true;
12692       ARM_AM::ShiftOpc ShOpcVal=
12693         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12694       if (ShOpcVal != ARM_AM::no_shift) {
12695         Base = Ptr->getOperand(1);
12696         Offset = Ptr->getOperand(0);
12697       } else {
12698         Base = Ptr->getOperand(0);
12699         Offset = Ptr->getOperand(1);
12700       }
12701       return true;
12702     }
12703 
12704     isInc = (Ptr->getOpcode() == ISD::ADD);
12705     Base = Ptr->getOperand(0);
12706     Offset = Ptr->getOperand(1);
12707     return true;
12708   }
12709 
12710   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12711   return false;
12712 }
12713 
12714 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12715                                      bool isSEXTLoad, SDValue &Base,
12716                                      SDValue &Offset, bool &isInc,
12717                                      SelectionDAG &DAG) {
12718   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12719     return false;
12720 
12721   Base = Ptr->getOperand(0);
12722   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12723     int RHSC = (int)RHS->getZExtValue();
12724     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12725       assert(Ptr->getOpcode() == ISD::ADD);
12726       isInc = false;
12727       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12728       return true;
12729     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12730       isInc = Ptr->getOpcode() == ISD::ADD;
12731       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12732       return true;
12733     }
12734   }
12735 
12736   return false;
12737 }
12738 
12739 /// getPreIndexedAddressParts - returns true by value, base pointer and
12740 /// offset pointer and addressing mode by reference if the node's address
12741 /// can be legally represented as pre-indexed load / store address.
12742 bool
12743 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12744                                              SDValue &Offset,
12745                                              ISD::MemIndexedMode &AM,
12746                                              SelectionDAG &DAG) const {
12747   if (Subtarget->isThumb1Only())
12748     return false;
12749 
12750   EVT VT;
12751   SDValue Ptr;
12752   bool isSEXTLoad = false;
12753   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12754     Ptr = LD->getBasePtr();
12755     VT  = LD->getMemoryVT();
12756     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12757   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12758     Ptr = ST->getBasePtr();
12759     VT  = ST->getMemoryVT();
12760   } else
12761     return false;
12762 
12763   bool isInc;
12764   bool isLegal = false;
12765   if (Subtarget->isThumb2())
12766     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12767                                        Offset, isInc, DAG);
12768   else
12769     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12770                                         Offset, isInc, DAG);
12771   if (!isLegal)
12772     return false;
12773 
12774   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12775   return true;
12776 }
12777 
12778 /// getPostIndexedAddressParts - returns true by value, base pointer and
12779 /// offset pointer and addressing mode by reference if this node can be
12780 /// combined with a load / store to form a post-indexed load / store.
12781 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12782                                                    SDValue &Base,
12783                                                    SDValue &Offset,
12784                                                    ISD::MemIndexedMode &AM,
12785                                                    SelectionDAG &DAG) const {
12786   EVT VT;
12787   SDValue Ptr;
12788   bool isSEXTLoad = false, isNonExt;
12789   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12790     VT  = LD->getMemoryVT();
12791     Ptr = LD->getBasePtr();
12792     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12793     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12794   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12795     VT  = ST->getMemoryVT();
12796     Ptr = ST->getBasePtr();
12797     isNonExt = !ST->isTruncatingStore();
12798   } else
12799     return false;
12800 
12801   if (Subtarget->isThumb1Only()) {
12802     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12803     // must be non-extending/truncating, i32, with an offset of 4.
12804     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12805     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12806       return false;
12807     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12808     if (!RHS || RHS->getZExtValue() != 4)
12809       return false;
12810 
12811     Offset = Op->getOperand(1);
12812     Base = Op->getOperand(0);
12813     AM = ISD::POST_INC;
12814     return true;
12815   }
12816 
12817   bool isInc;
12818   bool isLegal = false;
12819   if (Subtarget->isThumb2())
12820     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12821                                        isInc, DAG);
12822   else
12823     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12824                                         isInc, DAG);
12825   if (!isLegal)
12826     return false;
12827 
12828   if (Ptr != Base) {
12829     // Swap base ptr and offset to catch more post-index load / store when
12830     // it's legal. In Thumb2 mode, offset must be an immediate.
12831     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12832         !Subtarget->isThumb2())
12833       std::swap(Base, Offset);
12834 
12835     // Post-indexed load / store update the base pointer.
12836     if (Ptr != Base)
12837       return false;
12838   }
12839 
12840   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12841   return true;
12842 }
12843 
12844 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12845                                                       KnownBits &Known,
12846                                                       const APInt &DemandedElts,
12847                                                       const SelectionDAG &DAG,
12848                                                       unsigned Depth) const {
12849   unsigned BitWidth = Known.getBitWidth();
12850   Known.resetAll();
12851   switch (Op.getOpcode()) {
12852   default: break;
12853   case ARMISD::ADDC:
12854   case ARMISD::ADDE:
12855   case ARMISD::SUBC:
12856   case ARMISD::SUBE:
12857     // Special cases when we convert a carry to a boolean.
12858     if (Op.getResNo() == 0) {
12859       SDValue LHS = Op.getOperand(0);
12860       SDValue RHS = Op.getOperand(1);
12861       // (ADDE 0, 0, C) will give us a single bit.
12862       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
12863           isNullConstant(RHS)) {
12864         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12865         return;
12866       }
12867     }
12868     break;
12869   case ARMISD::CMOV: {
12870     // Bits are known zero/one if known on the LHS and RHS.
12871     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
12872     if (Known.isUnknown())
12873       return;
12874 
12875     KnownBits KnownRHS;
12876     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
12877     Known.Zero &= KnownRHS.Zero;
12878     Known.One  &= KnownRHS.One;
12879     return;
12880   }
12881   case ISD::INTRINSIC_W_CHAIN: {
12882     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12883     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12884     switch (IntID) {
12885     default: return;
12886     case Intrinsic::arm_ldaex:
12887     case Intrinsic::arm_ldrex: {
12888       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12889       unsigned MemBits = VT.getScalarSizeInBits();
12890       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12891       return;
12892     }
12893     }
12894   }
12895   case ARMISD::BFI: {
12896     // Conservatively, we can recurse down the first operand
12897     // and just mask out all affected bits.
12898     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
12899 
12900     // The operand to BFI is already a mask suitable for removing the bits it
12901     // sets.
12902     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
12903     const APInt &Mask = CI->getAPIntValue();
12904     Known.Zero &= Mask;
12905     Known.One &= Mask;
12906     return;
12907   }
12908   }
12909 }
12910 
12911 //===----------------------------------------------------------------------===//
12912 //                           ARM Inline Assembly Support
12913 //===----------------------------------------------------------------------===//
12914 
12915 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12916   // Looking for "rev" which is V6+.
12917   if (!Subtarget->hasV6Ops())
12918     return false;
12919 
12920   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12921   std::string AsmStr = IA->getAsmString();
12922   SmallVector<StringRef, 4> AsmPieces;
12923   SplitString(AsmStr, AsmPieces, ";\n");
12924 
12925   switch (AsmPieces.size()) {
12926   default: return false;
12927   case 1:
12928     AsmStr = AsmPieces[0];
12929     AsmPieces.clear();
12930     SplitString(AsmStr, AsmPieces, " \t,");
12931 
12932     // rev $0, $1
12933     if (AsmPieces.size() == 3 &&
12934         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12935         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12936       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12937       if (Ty && Ty->getBitWidth() == 32)
12938         return IntrinsicLowering::LowerToByteSwap(CI);
12939     }
12940     break;
12941   }
12942 
12943   return false;
12944 }
12945 
12946 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12947   // At this point, we have to lower this constraint to something else, so we
12948   // lower it to an "r" or "w". However, by doing this we will force the result
12949   // to be in register, while the X constraint is much more permissive.
12950   //
12951   // Although we are correct (we are free to emit anything, without
12952   // constraints), we might break use cases that would expect us to be more
12953   // efficient and emit something else.
12954   if (!Subtarget->hasVFP2())
12955     return "r";
12956   if (ConstraintVT.isFloatingPoint())
12957     return "w";
12958   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12959      (ConstraintVT.getSizeInBits() == 64 ||
12960       ConstraintVT.getSizeInBits() == 128))
12961     return "w";
12962 
12963   return "r";
12964 }
12965 
12966 /// getConstraintType - Given a constraint letter, return the type of
12967 /// constraint it is for this target.
12968 ARMTargetLowering::ConstraintType
12969 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12970   if (Constraint.size() == 1) {
12971     switch (Constraint[0]) {
12972     default:  break;
12973     case 'l': return C_RegisterClass;
12974     case 'w': return C_RegisterClass;
12975     case 'h': return C_RegisterClass;
12976     case 'x': return C_RegisterClass;
12977     case 't': return C_RegisterClass;
12978     case 'j': return C_Other; // Constant for movw.
12979       // An address with a single base register. Due to the way we
12980       // currently handle addresses it is the same as an 'r' memory constraint.
12981     case 'Q': return C_Memory;
12982     }
12983   } else if (Constraint.size() == 2) {
12984     switch (Constraint[0]) {
12985     default: break;
12986     // All 'U+' constraints are addresses.
12987     case 'U': return C_Memory;
12988     }
12989   }
12990   return TargetLowering::getConstraintType(Constraint);
12991 }
12992 
12993 /// Examine constraint type and operand type and determine a weight value.
12994 /// This object must already have been set up with the operand type
12995 /// and the current alternative constraint selected.
12996 TargetLowering::ConstraintWeight
12997 ARMTargetLowering::getSingleConstraintMatchWeight(
12998     AsmOperandInfo &info, const char *constraint) const {
12999   ConstraintWeight weight = CW_Invalid;
13000   Value *CallOperandVal = info.CallOperandVal;
13001     // If we don't have a value, we can't do a match,
13002     // but allow it at the lowest weight.
13003   if (!CallOperandVal)
13004     return CW_Default;
13005   Type *type = CallOperandVal->getType();
13006   // Look at the constraint type.
13007   switch (*constraint) {
13008   default:
13009     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13010     break;
13011   case 'l':
13012     if (type->isIntegerTy()) {
13013       if (Subtarget->isThumb())
13014         weight = CW_SpecificReg;
13015       else
13016         weight = CW_Register;
13017     }
13018     break;
13019   case 'w':
13020     if (type->isFloatingPointTy())
13021       weight = CW_Register;
13022     break;
13023   }
13024   return weight;
13025 }
13026 
13027 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
13028 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13029     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13030   if (Constraint.size() == 1) {
13031     // GCC ARM Constraint Letters
13032     switch (Constraint[0]) {
13033     case 'l': // Low regs or general regs.
13034       if (Subtarget->isThumb())
13035         return RCPair(0U, &ARM::tGPRRegClass);
13036       return RCPair(0U, &ARM::GPRRegClass);
13037     case 'h': // High regs or no regs.
13038       if (Subtarget->isThumb())
13039         return RCPair(0U, &ARM::hGPRRegClass);
13040       break;
13041     case 'r':
13042       if (Subtarget->isThumb1Only())
13043         return RCPair(0U, &ARM::tGPRRegClass);
13044       return RCPair(0U, &ARM::GPRRegClass);
13045     case 'w':
13046       if (VT == MVT::Other)
13047         break;
13048       if (VT == MVT::f32)
13049         return RCPair(0U, &ARM::SPRRegClass);
13050       if (VT.getSizeInBits() == 64)
13051         return RCPair(0U, &ARM::DPRRegClass);
13052       if (VT.getSizeInBits() == 128)
13053         return RCPair(0U, &ARM::QPRRegClass);
13054       break;
13055     case 'x':
13056       if (VT == MVT::Other)
13057         break;
13058       if (VT == MVT::f32)
13059         return RCPair(0U, &ARM::SPR_8RegClass);
13060       if (VT.getSizeInBits() == 64)
13061         return RCPair(0U, &ARM::DPR_8RegClass);
13062       if (VT.getSizeInBits() == 128)
13063         return RCPair(0U, &ARM::QPR_8RegClass);
13064       break;
13065     case 't':
13066       if (VT == MVT::f32)
13067         return RCPair(0U, &ARM::SPRRegClass);
13068       break;
13069     }
13070   }
13071   if (StringRef("{cc}").equals_lower(Constraint))
13072     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13073 
13074   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13075 }
13076 
13077 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13078 /// vector.  If it is invalid, don't add anything to Ops.
13079 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13080                                                      std::string &Constraint,
13081                                                      std::vector<SDValue>&Ops,
13082                                                      SelectionDAG &DAG) const {
13083   SDValue Result;
13084 
13085   // Currently only support length 1 constraints.
13086   if (Constraint.length() != 1) return;
13087 
13088   char ConstraintLetter = Constraint[0];
13089   switch (ConstraintLetter) {
13090   default: break;
13091   case 'j':
13092   case 'I': case 'J': case 'K': case 'L':
13093   case 'M': case 'N': case 'O':
13094     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13095     if (!C)
13096       return;
13097 
13098     int64_t CVal64 = C->getSExtValue();
13099     int CVal = (int) CVal64;
13100     // None of these constraints allow values larger than 32 bits.  Check
13101     // that the value fits in an int.
13102     if (CVal != CVal64)
13103       return;
13104 
13105     switch (ConstraintLetter) {
13106       case 'j':
13107         // Constant suitable for movw, must be between 0 and
13108         // 65535.
13109         if (Subtarget->hasV6T2Ops())
13110           if (CVal >= 0 && CVal <= 65535)
13111             break;
13112         return;
13113       case 'I':
13114         if (Subtarget->isThumb1Only()) {
13115           // This must be a constant between 0 and 255, for ADD
13116           // immediates.
13117           if (CVal >= 0 && CVal <= 255)
13118             break;
13119         } else if (Subtarget->isThumb2()) {
13120           // A constant that can be used as an immediate value in a
13121           // data-processing instruction.
13122           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13123             break;
13124         } else {
13125           // A constant that can be used as an immediate value in a
13126           // data-processing instruction.
13127           if (ARM_AM::getSOImmVal(CVal) != -1)
13128             break;
13129         }
13130         return;
13131 
13132       case 'J':
13133         if (Subtarget->isThumb1Only()) {
13134           // This must be a constant between -255 and -1, for negated ADD
13135           // immediates. This can be used in GCC with an "n" modifier that
13136           // prints the negated value, for use with SUB instructions. It is
13137           // not useful otherwise but is implemented for compatibility.
13138           if (CVal >= -255 && CVal <= -1)
13139             break;
13140         } else {
13141           // This must be a constant between -4095 and 4095. It is not clear
13142           // what this constraint is intended for. Implemented for
13143           // compatibility with GCC.
13144           if (CVal >= -4095 && CVal <= 4095)
13145             break;
13146         }
13147         return;
13148 
13149       case 'K':
13150         if (Subtarget->isThumb1Only()) {
13151           // A 32-bit value where only one byte has a nonzero value. Exclude
13152           // zero to match GCC. This constraint is used by GCC internally for
13153           // constants that can be loaded with a move/shift combination.
13154           // It is not useful otherwise but is implemented for compatibility.
13155           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13156             break;
13157         } else if (Subtarget->isThumb2()) {
13158           // A constant whose bitwise inverse can be used as an immediate
13159           // value in a data-processing instruction. This can be used in GCC
13160           // with a "B" modifier that prints the inverted value, for use with
13161           // BIC and MVN instructions. It is not useful otherwise but is
13162           // implemented for compatibility.
13163           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13164             break;
13165         } else {
13166           // A constant whose bitwise inverse can be used as an immediate
13167           // value in a data-processing instruction. This can be used in GCC
13168           // with a "B" modifier that prints the inverted value, for use with
13169           // BIC and MVN instructions. It is not useful otherwise but is
13170           // implemented for compatibility.
13171           if (ARM_AM::getSOImmVal(~CVal) != -1)
13172             break;
13173         }
13174         return;
13175 
13176       case 'L':
13177         if (Subtarget->isThumb1Only()) {
13178           // This must be a constant between -7 and 7,
13179           // for 3-operand ADD/SUB immediate instructions.
13180           if (CVal >= -7 && CVal < 7)
13181             break;
13182         } else if (Subtarget->isThumb2()) {
13183           // A constant whose negation can be used as an immediate value in a
13184           // data-processing instruction. This can be used in GCC with an "n"
13185           // modifier that prints the negated value, for use with SUB
13186           // instructions. It is not useful otherwise but is implemented for
13187           // compatibility.
13188           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13189             break;
13190         } else {
13191           // A constant whose negation can be used as an immediate value in a
13192           // data-processing instruction. This can be used in GCC with an "n"
13193           // modifier that prints the negated value, for use with SUB
13194           // instructions. It is not useful otherwise but is implemented for
13195           // compatibility.
13196           if (ARM_AM::getSOImmVal(-CVal) != -1)
13197             break;
13198         }
13199         return;
13200 
13201       case 'M':
13202         if (Subtarget->isThumb1Only()) {
13203           // This must be a multiple of 4 between 0 and 1020, for
13204           // ADD sp + immediate.
13205           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13206             break;
13207         } else {
13208           // A power of two or a constant between 0 and 32.  This is used in
13209           // GCC for the shift amount on shifted register operands, but it is
13210           // useful in general for any shift amounts.
13211           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13212             break;
13213         }
13214         return;
13215 
13216       case 'N':
13217         if (Subtarget->isThumb()) {  // FIXME thumb2
13218           // This must be a constant between 0 and 31, for shift amounts.
13219           if (CVal >= 0 && CVal <= 31)
13220             break;
13221         }
13222         return;
13223 
13224       case 'O':
13225         if (Subtarget->isThumb()) {  // FIXME thumb2
13226           // This must be a multiple of 4 between -508 and 508, for
13227           // ADD/SUB sp = sp + immediate.
13228           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13229             break;
13230         }
13231         return;
13232     }
13233     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13234     break;
13235   }
13236 
13237   if (Result.getNode()) {
13238     Ops.push_back(Result);
13239     return;
13240   }
13241   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13242 }
13243 
13244 static RTLIB::Libcall getDivRemLibcall(
13245     const SDNode *N, MVT::SimpleValueType SVT) {
13246   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13247           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13248          "Unhandled Opcode in getDivRemLibcall");
13249   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13250                   N->getOpcode() == ISD::SREM;
13251   RTLIB::Libcall LC;
13252   switch (SVT) {
13253   default: llvm_unreachable("Unexpected request for libcall!");
13254   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13255   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13256   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13257   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13258   }
13259   return LC;
13260 }
13261 
13262 static TargetLowering::ArgListTy getDivRemArgList(
13263     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13264   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13265           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13266          "Unhandled Opcode in getDivRemArgList");
13267   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13268                   N->getOpcode() == ISD::SREM;
13269   TargetLowering::ArgListTy Args;
13270   TargetLowering::ArgListEntry Entry;
13271   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13272     EVT ArgVT = N->getOperand(i).getValueType();
13273     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13274     Entry.Node = N->getOperand(i);
13275     Entry.Ty = ArgTy;
13276     Entry.IsSExt = isSigned;
13277     Entry.IsZExt = !isSigned;
13278     Args.push_back(Entry);
13279   }
13280   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13281     std::swap(Args[0], Args[1]);
13282   return Args;
13283 }
13284 
13285 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13286   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13287           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13288           Subtarget->isTargetWindows()) &&
13289          "Register-based DivRem lowering only");
13290   unsigned Opcode = Op->getOpcode();
13291   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13292          "Invalid opcode for Div/Rem lowering");
13293   bool isSigned = (Opcode == ISD::SDIVREM);
13294   EVT VT = Op->getValueType(0);
13295   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13296   SDLoc dl(Op);
13297 
13298   // If the target has hardware divide, use divide + multiply + subtract:
13299   //     div = a / b
13300   //     rem = a - b * div
13301   //     return {div, rem}
13302   // This should be lowered into UDIV/SDIV + MLS later on.
13303   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13304                                         : Subtarget->hasDivideInARMMode();
13305   if (hasDivide && Op->getValueType(0).isSimple() &&
13306       Op->getSimpleValueType(0) == MVT::i32) {
13307     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13308     const SDValue Dividend = Op->getOperand(0);
13309     const SDValue Divisor = Op->getOperand(1);
13310     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13311     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13312     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13313 
13314     SDValue Values[2] = {Div, Rem};
13315     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13316   }
13317 
13318   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13319                                        VT.getSimpleVT().SimpleTy);
13320   SDValue InChain = DAG.getEntryNode();
13321 
13322   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13323                                                     DAG.getContext(),
13324                                                     Subtarget);
13325 
13326   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13327                                          getPointerTy(DAG.getDataLayout()));
13328 
13329   Type *RetTy = StructType::get(Ty, Ty);
13330 
13331   if (Subtarget->isTargetWindows())
13332     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13333 
13334   TargetLowering::CallLoweringInfo CLI(DAG);
13335   CLI.setDebugLoc(dl).setChain(InChain)
13336     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13337     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13338 
13339   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13340   return CallInfo.first;
13341 }
13342 
13343 // Lowers REM using divmod helpers
13344 // see RTABI section 4.2/4.3
13345 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13346   // Build return types (div and rem)
13347   std::vector<Type*> RetTyParams;
13348   Type *RetTyElement;
13349 
13350   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13351   default: llvm_unreachable("Unexpected request for libcall!");
13352   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13353   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13354   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13355   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13356   }
13357 
13358   RetTyParams.push_back(RetTyElement);
13359   RetTyParams.push_back(RetTyElement);
13360   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13361   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13362 
13363   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13364                                                              SimpleTy);
13365   SDValue InChain = DAG.getEntryNode();
13366   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13367                                                     Subtarget);
13368   bool isSigned = N->getOpcode() == ISD::SREM;
13369   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13370                                          getPointerTy(DAG.getDataLayout()));
13371 
13372   if (Subtarget->isTargetWindows())
13373     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13374 
13375   // Lower call
13376   CallLoweringInfo CLI(DAG);
13377   CLI.setChain(InChain)
13378      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13379      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13380   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13381 
13382   // Return second (rem) result operand (first contains div)
13383   SDNode *ResNode = CallResult.first.getNode();
13384   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13385   return ResNode->getOperand(1);
13386 }
13387 
13388 SDValue
13389 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13390   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13391   SDLoc DL(Op);
13392 
13393   // Get the inputs.
13394   SDValue Chain = Op.getOperand(0);
13395   SDValue Size  = Op.getOperand(1);
13396 
13397   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13398                               DAG.getConstant(2, DL, MVT::i32));
13399 
13400   SDValue Flag;
13401   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13402   Flag = Chain.getValue(1);
13403 
13404   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13405   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13406 
13407   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13408   Chain = NewSP.getValue(1);
13409 
13410   SDValue Ops[2] = { NewSP, Chain };
13411   return DAG.getMergeValues(Ops, DL);
13412 }
13413 
13414 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13415   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13416          "Unexpected type for custom-lowering FP_EXTEND");
13417 
13418   RTLIB::Libcall LC;
13419   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13420 
13421   SDValue SrcVal = Op.getOperand(0);
13422   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13423                      SDLoc(Op)).first;
13424 }
13425 
13426 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13427   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13428          Subtarget->isFPOnlySP() &&
13429          "Unexpected type for custom-lowering FP_ROUND");
13430 
13431   RTLIB::Libcall LC;
13432   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13433 
13434   SDValue SrcVal = Op.getOperand(0);
13435   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13436                      SDLoc(Op)).first;
13437 }
13438 
13439 bool
13440 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13441   // The ARM target isn't yet aware of offsets.
13442   return false;
13443 }
13444 
13445 bool ARM::isBitFieldInvertedMask(unsigned v) {
13446   if (v == 0xffffffff)
13447     return false;
13448 
13449   // there can be 1's on either or both "outsides", all the "inside"
13450   // bits must be 0's
13451   return isShiftedMask_32(~v);
13452 }
13453 
13454 /// isFPImmLegal - Returns true if the target can instruction select the
13455 /// specified FP immediate natively. If false, the legalizer will
13456 /// materialize the FP immediate as a load from a constant pool.
13457 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13458   if (!Subtarget->hasVFP3())
13459     return false;
13460   if (VT == MVT::f32)
13461     return ARM_AM::getFP32Imm(Imm) != -1;
13462   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13463     return ARM_AM::getFP64Imm(Imm) != -1;
13464   return false;
13465 }
13466 
13467 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13468 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13469 /// specified in the intrinsic calls.
13470 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13471                                            const CallInst &I,
13472                                            unsigned Intrinsic) const {
13473   switch (Intrinsic) {
13474   case Intrinsic::arm_neon_vld1:
13475   case Intrinsic::arm_neon_vld2:
13476   case Intrinsic::arm_neon_vld3:
13477   case Intrinsic::arm_neon_vld4:
13478   case Intrinsic::arm_neon_vld2lane:
13479   case Intrinsic::arm_neon_vld3lane:
13480   case Intrinsic::arm_neon_vld4lane: {
13481     Info.opc = ISD::INTRINSIC_W_CHAIN;
13482     // Conservatively set memVT to the entire set of vectors loaded.
13483     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13484     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13485     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13486     Info.ptrVal = I.getArgOperand(0);
13487     Info.offset = 0;
13488     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13489     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13490     Info.vol = false; // volatile loads with NEON intrinsics not supported
13491     Info.readMem = true;
13492     Info.writeMem = false;
13493     return true;
13494   }
13495   case Intrinsic::arm_neon_vst1:
13496   case Intrinsic::arm_neon_vst2:
13497   case Intrinsic::arm_neon_vst3:
13498   case Intrinsic::arm_neon_vst4:
13499   case Intrinsic::arm_neon_vst2lane:
13500   case Intrinsic::arm_neon_vst3lane:
13501   case Intrinsic::arm_neon_vst4lane: {
13502     Info.opc = ISD::INTRINSIC_VOID;
13503     // Conservatively set memVT to the entire set of vectors stored.
13504     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13505     unsigned NumElts = 0;
13506     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13507       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13508       if (!ArgTy->isVectorTy())
13509         break;
13510       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13511     }
13512     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13513     Info.ptrVal = I.getArgOperand(0);
13514     Info.offset = 0;
13515     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13516     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13517     Info.vol = false; // volatile stores with NEON intrinsics not supported
13518     Info.readMem = false;
13519     Info.writeMem = true;
13520     return true;
13521   }
13522   case Intrinsic::arm_ldaex:
13523   case Intrinsic::arm_ldrex: {
13524     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13525     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13526     Info.opc = ISD::INTRINSIC_W_CHAIN;
13527     Info.memVT = MVT::getVT(PtrTy->getElementType());
13528     Info.ptrVal = I.getArgOperand(0);
13529     Info.offset = 0;
13530     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13531     Info.vol = true;
13532     Info.readMem = true;
13533     Info.writeMem = false;
13534     return true;
13535   }
13536   case Intrinsic::arm_stlex:
13537   case Intrinsic::arm_strex: {
13538     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13539     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13540     Info.opc = ISD::INTRINSIC_W_CHAIN;
13541     Info.memVT = MVT::getVT(PtrTy->getElementType());
13542     Info.ptrVal = I.getArgOperand(1);
13543     Info.offset = 0;
13544     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13545     Info.vol = true;
13546     Info.readMem = false;
13547     Info.writeMem = true;
13548     return true;
13549   }
13550   case Intrinsic::arm_stlexd:
13551   case Intrinsic::arm_strexd:
13552     Info.opc = ISD::INTRINSIC_W_CHAIN;
13553     Info.memVT = MVT::i64;
13554     Info.ptrVal = I.getArgOperand(2);
13555     Info.offset = 0;
13556     Info.align = 8;
13557     Info.vol = true;
13558     Info.readMem = false;
13559     Info.writeMem = true;
13560     return true;
13561 
13562   case Intrinsic::arm_ldaexd:
13563   case Intrinsic::arm_ldrexd:
13564     Info.opc = ISD::INTRINSIC_W_CHAIN;
13565     Info.memVT = MVT::i64;
13566     Info.ptrVal = I.getArgOperand(0);
13567     Info.offset = 0;
13568     Info.align = 8;
13569     Info.vol = true;
13570     Info.readMem = true;
13571     Info.writeMem = false;
13572     return true;
13573 
13574   default:
13575     break;
13576   }
13577 
13578   return false;
13579 }
13580 
13581 /// \brief Returns true if it is beneficial to convert a load of a constant
13582 /// to just the constant itself.
13583 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13584                                                           Type *Ty) const {
13585   assert(Ty->isIntegerTy());
13586 
13587   unsigned Bits = Ty->getPrimitiveSizeInBits();
13588   if (Bits == 0 || Bits > 32)
13589     return false;
13590   return true;
13591 }
13592 
13593 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13594                                                 unsigned Index) const {
13595   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13596     return false;
13597 
13598   return (Index == 0 || Index == ResVT.getVectorNumElements());
13599 }
13600 
13601 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13602                                         ARM_MB::MemBOpt Domain) const {
13603   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13604 
13605   // First, if the target has no DMB, see what fallback we can use.
13606   if (!Subtarget->hasDataBarrier()) {
13607     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13608     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13609     // here.
13610     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13611       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13612       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13613                         Builder.getInt32(0), Builder.getInt32(7),
13614                         Builder.getInt32(10), Builder.getInt32(5)};
13615       return Builder.CreateCall(MCR, args);
13616     } else {
13617       // Instead of using barriers, atomic accesses on these subtargets use
13618       // libcalls.
13619       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13620     }
13621   } else {
13622     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13623     // Only a full system barrier exists in the M-class architectures.
13624     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13625     Constant *CDomain = Builder.getInt32(Domain);
13626     return Builder.CreateCall(DMB, CDomain);
13627   }
13628 }
13629 
13630 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13631 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13632                                                  Instruction *Inst,
13633                                                  AtomicOrdering Ord) const {
13634   switch (Ord) {
13635   case AtomicOrdering::NotAtomic:
13636   case AtomicOrdering::Unordered:
13637     llvm_unreachable("Invalid fence: unordered/non-atomic");
13638   case AtomicOrdering::Monotonic:
13639   case AtomicOrdering::Acquire:
13640     return nullptr; // Nothing to do
13641   case AtomicOrdering::SequentiallyConsistent:
13642     if (!Inst->hasAtomicStore())
13643       return nullptr; // Nothing to do
13644     /*FALLTHROUGH*/
13645   case AtomicOrdering::Release:
13646   case AtomicOrdering::AcquireRelease:
13647     if (Subtarget->preferISHSTBarriers())
13648       return makeDMB(Builder, ARM_MB::ISHST);
13649     // FIXME: add a comment with a link to documentation justifying this.
13650     else
13651       return makeDMB(Builder, ARM_MB::ISH);
13652   }
13653   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13654 }
13655 
13656 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13657                                                   Instruction *Inst,
13658                                                   AtomicOrdering Ord) const {
13659   switch (Ord) {
13660   case AtomicOrdering::NotAtomic:
13661   case AtomicOrdering::Unordered:
13662     llvm_unreachable("Invalid fence: unordered/not-atomic");
13663   case AtomicOrdering::Monotonic:
13664   case AtomicOrdering::Release:
13665     return nullptr; // Nothing to do
13666   case AtomicOrdering::Acquire:
13667   case AtomicOrdering::AcquireRelease:
13668   case AtomicOrdering::SequentiallyConsistent:
13669     return makeDMB(Builder, ARM_MB::ISH);
13670   }
13671   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13672 }
13673 
13674 // Loads and stores less than 64-bits are already atomic; ones above that
13675 // are doomed anyway, so defer to the default libcall and blame the OS when
13676 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13677 // anything for those.
13678 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13679   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13680   return (Size == 64) && !Subtarget->isMClass();
13681 }
13682 
13683 // Loads and stores less than 64-bits are already atomic; ones above that
13684 // are doomed anyway, so defer to the default libcall and blame the OS when
13685 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13686 // anything for those.
13687 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13688 // guarantee, see DDI0406C ARM architecture reference manual,
13689 // sections A8.8.72-74 LDRD)
13690 TargetLowering::AtomicExpansionKind
13691 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13692   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13693   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13694                                                   : AtomicExpansionKind::None;
13695 }
13696 
13697 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13698 // and up to 64 bits on the non-M profiles
13699 TargetLowering::AtomicExpansionKind
13700 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13701   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13702   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13703   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13704              ? AtomicExpansionKind::LLSC
13705              : AtomicExpansionKind::None;
13706 }
13707 
13708 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13709     AtomicCmpXchgInst *AI) const {
13710   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13711   // implement cmpxchg without spilling. If the address being exchanged is also
13712   // on the stack and close enough to the spill slot, this can lead to a
13713   // situation where the monitor always gets cleared and the atomic operation
13714   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13715   bool hasAtomicCmpXchg =
13716       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13717   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13718 }
13719 
13720 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13721     const Instruction *I) const {
13722   return InsertFencesForAtomic;
13723 }
13724 
13725 // This has so far only been implemented for MachO.
13726 bool ARMTargetLowering::useLoadStackGuardNode() const {
13727   return Subtarget->isTargetMachO();
13728 }
13729 
13730 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13731                                                   unsigned &Cost) const {
13732   // If we do not have NEON, vector types are not natively supported.
13733   if (!Subtarget->hasNEON())
13734     return false;
13735 
13736   // Floating point values and vector values map to the same register file.
13737   // Therefore, although we could do a store extract of a vector type, this is
13738   // better to leave at float as we have more freedom in the addressing mode for
13739   // those.
13740   if (VectorTy->isFPOrFPVectorTy())
13741     return false;
13742 
13743   // If the index is unknown at compile time, this is very expensive to lower
13744   // and it is not possible to combine the store with the extract.
13745   if (!isa<ConstantInt>(Idx))
13746     return false;
13747 
13748   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13749   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13750   // We can do a store + vector extract on any vector that fits perfectly in a D
13751   // or Q register.
13752   if (BitWidth == 64 || BitWidth == 128) {
13753     Cost = 0;
13754     return true;
13755   }
13756   return false;
13757 }
13758 
13759 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13760   return Subtarget->hasV6T2Ops();
13761 }
13762 
13763 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13764   return Subtarget->hasV6T2Ops();
13765 }
13766 
13767 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13768                                          AtomicOrdering Ord) const {
13769   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13770   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13771   bool IsAcquire = isAcquireOrStronger(Ord);
13772 
13773   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13774   // intrinsic must return {i32, i32} and we have to recombine them into a
13775   // single i64 here.
13776   if (ValTy->getPrimitiveSizeInBits() == 64) {
13777     Intrinsic::ID Int =
13778         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13779     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13780 
13781     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13782     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13783 
13784     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13785     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13786     if (!Subtarget->isLittle())
13787       std::swap (Lo, Hi);
13788     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13789     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13790     return Builder.CreateOr(
13791         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13792   }
13793 
13794   Type *Tys[] = { Addr->getType() };
13795   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13796   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13797 
13798   return Builder.CreateTruncOrBitCast(
13799       Builder.CreateCall(Ldrex, Addr),
13800       cast<PointerType>(Addr->getType())->getElementType());
13801 }
13802 
13803 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13804     IRBuilder<> &Builder) const {
13805   if (!Subtarget->hasV7Ops())
13806     return;
13807   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13808   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13809 }
13810 
13811 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13812                                                Value *Addr,
13813                                                AtomicOrdering Ord) const {
13814   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13815   bool IsRelease = isReleaseOrStronger(Ord);
13816 
13817   // Since the intrinsics must have legal type, the i64 intrinsics take two
13818   // parameters: "i32, i32". We must marshal Val into the appropriate form
13819   // before the call.
13820   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13821     Intrinsic::ID Int =
13822         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13823     Function *Strex = Intrinsic::getDeclaration(M, Int);
13824     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13825 
13826     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13827     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13828     if (!Subtarget->isLittle())
13829       std::swap (Lo, Hi);
13830     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13831     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13832   }
13833 
13834   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13835   Type *Tys[] = { Addr->getType() };
13836   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13837 
13838   return Builder.CreateCall(
13839       Strex, {Builder.CreateZExtOrBitCast(
13840                   Val, Strex->getFunctionType()->getParamType(0)),
13841               Addr});
13842 }
13843 
13844 /// A helper function for determining the number of interleaved accesses we
13845 /// will generate when lowering accesses of the given type.
13846 unsigned
13847 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13848                                              const DataLayout &DL) const {
13849   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13850 }
13851 
13852 bool ARMTargetLowering::isLegalInterleavedAccessType(
13853     VectorType *VecTy, const DataLayout &DL) const {
13854 
13855   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13856   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13857 
13858   // Ensure the vector doesn't have f16 elements. Even though we could do an
13859   // i16 vldN, we can't hold the f16 vectors and will end up converting via
13860   // f32.
13861   if (VecTy->getElementType()->isHalfTy())
13862     return false;
13863 
13864   // Ensure the number of vector elements is greater than 1.
13865   if (VecTy->getNumElements() < 2)
13866     return false;
13867 
13868   // Ensure the element type is legal.
13869   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13870     return false;
13871 
13872   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13873   // 128 will be split into multiple interleaved accesses.
13874   return VecSize == 64 || VecSize % 128 == 0;
13875 }
13876 
13877 /// \brief Lower an interleaved load into a vldN intrinsic.
13878 ///
13879 /// E.g. Lower an interleaved load (Factor = 2):
13880 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13881 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13882 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13883 ///
13884 ///      Into:
13885 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13886 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13887 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13888 bool ARMTargetLowering::lowerInterleavedLoad(
13889     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13890     ArrayRef<unsigned> Indices, unsigned Factor) const {
13891   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13892          "Invalid interleave factor");
13893   assert(!Shuffles.empty() && "Empty shufflevector input");
13894   assert(Shuffles.size() == Indices.size() &&
13895          "Unmatched number of shufflevectors and indices");
13896 
13897   VectorType *VecTy = Shuffles[0]->getType();
13898   Type *EltTy = VecTy->getVectorElementType();
13899 
13900   const DataLayout &DL = LI->getModule()->getDataLayout();
13901 
13902   // Skip if we do not have NEON and skip illegal vector types. We can
13903   // "legalize" wide vector types into multiple interleaved accesses as long as
13904   // the vector types are divisible by 128.
13905   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13906     return false;
13907 
13908   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13909 
13910   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13911   // load integer vectors first and then convert to pointer vectors.
13912   if (EltTy->isPointerTy())
13913     VecTy =
13914         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13915 
13916   IRBuilder<> Builder(LI);
13917 
13918   // The base address of the load.
13919   Value *BaseAddr = LI->getPointerOperand();
13920 
13921   if (NumLoads > 1) {
13922     // If we're going to generate more than one load, reset the sub-vector type
13923     // to something legal.
13924     VecTy = VectorType::get(VecTy->getVectorElementType(),
13925                             VecTy->getVectorNumElements() / NumLoads);
13926 
13927     // We will compute the pointer operand of each load from the original base
13928     // address using GEPs. Cast the base address to a pointer to the scalar
13929     // element type.
13930     BaseAddr = Builder.CreateBitCast(
13931         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13932                       LI->getPointerAddressSpace()));
13933   }
13934 
13935   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13936 
13937   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13938   Type *Tys[] = {VecTy, Int8Ptr};
13939   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13940                                             Intrinsic::arm_neon_vld3,
13941                                             Intrinsic::arm_neon_vld4};
13942   Function *VldnFunc =
13943       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13944 
13945   // Holds sub-vectors extracted from the load intrinsic return values. The
13946   // sub-vectors are associated with the shufflevector instructions they will
13947   // replace.
13948   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13949 
13950   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13951 
13952     // If we're generating more than one load, compute the base address of
13953     // subsequent loads as an offset from the previous.
13954     if (LoadCount > 0)
13955       BaseAddr = Builder.CreateConstGEP1_32(
13956           BaseAddr, VecTy->getVectorNumElements() * Factor);
13957 
13958     SmallVector<Value *, 2> Ops;
13959     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13960     Ops.push_back(Builder.getInt32(LI->getAlignment()));
13961 
13962     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13963 
13964     // Replace uses of each shufflevector with the corresponding vector loaded
13965     // by ldN.
13966     for (unsigned i = 0; i < Shuffles.size(); i++) {
13967       ShuffleVectorInst *SV = Shuffles[i];
13968       unsigned Index = Indices[i];
13969 
13970       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13971 
13972       // Convert the integer vector to pointer vector if the element is pointer.
13973       if (EltTy->isPointerTy())
13974         SubVec = Builder.CreateIntToPtr(
13975             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
13976                                     VecTy->getVectorNumElements()));
13977 
13978       SubVecs[SV].push_back(SubVec);
13979     }
13980   }
13981 
13982   // Replace uses of the shufflevector instructions with the sub-vectors
13983   // returned by the load intrinsic. If a shufflevector instruction is
13984   // associated with more than one sub-vector, those sub-vectors will be
13985   // concatenated into a single wide vector.
13986   for (ShuffleVectorInst *SVI : Shuffles) {
13987     auto &SubVec = SubVecs[SVI];
13988     auto *WideVec =
13989         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13990     SVI->replaceAllUsesWith(WideVec);
13991   }
13992 
13993   return true;
13994 }
13995 
13996 /// \brief Lower an interleaved store into a vstN intrinsic.
13997 ///
13998 /// E.g. Lower an interleaved store (Factor = 3):
13999 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14000 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14001 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14002 ///
14003 ///      Into:
14004 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14005 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14006 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14007 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14008 ///
14009 /// Note that the new shufflevectors will be removed and we'll only generate one
14010 /// vst3 instruction in CodeGen.
14011 ///
14012 /// Example for a more general valid mask (Factor 3). Lower:
14013 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14014 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14015 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14016 ///
14017 ///      Into:
14018 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14019 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14020 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14021 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14022 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14023                                               ShuffleVectorInst *SVI,
14024                                               unsigned Factor) const {
14025   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14026          "Invalid interleave factor");
14027 
14028   VectorType *VecTy = SVI->getType();
14029   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14030          "Invalid interleaved store");
14031 
14032   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14033   Type *EltTy = VecTy->getVectorElementType();
14034   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14035 
14036   const DataLayout &DL = SI->getModule()->getDataLayout();
14037 
14038   // Skip if we do not have NEON and skip illegal vector types. We can
14039   // "legalize" wide vector types into multiple interleaved accesses as long as
14040   // the vector types are divisible by 128.
14041   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14042     return false;
14043 
14044   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14045 
14046   Value *Op0 = SVI->getOperand(0);
14047   Value *Op1 = SVI->getOperand(1);
14048   IRBuilder<> Builder(SI);
14049 
14050   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14051   // vectors to integer vectors.
14052   if (EltTy->isPointerTy()) {
14053     Type *IntTy = DL.getIntPtrType(EltTy);
14054 
14055     // Convert to the corresponding integer vector.
14056     Type *IntVecTy =
14057         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14058     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14059     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14060 
14061     SubVecTy = VectorType::get(IntTy, LaneLen);
14062   }
14063 
14064   // The base address of the store.
14065   Value *BaseAddr = SI->getPointerOperand();
14066 
14067   if (NumStores > 1) {
14068     // If we're going to generate more than one store, reset the lane length
14069     // and sub-vector type to something legal.
14070     LaneLen /= NumStores;
14071     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14072 
14073     // We will compute the pointer operand of each store from the original base
14074     // address using GEPs. Cast the base address to a pointer to the scalar
14075     // element type.
14076     BaseAddr = Builder.CreateBitCast(
14077         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14078                       SI->getPointerAddressSpace()));
14079   }
14080 
14081   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14082 
14083   auto Mask = SVI->getShuffleMask();
14084 
14085   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14086   Type *Tys[] = {Int8Ptr, SubVecTy};
14087   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14088                                              Intrinsic::arm_neon_vst3,
14089                                              Intrinsic::arm_neon_vst4};
14090 
14091   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14092 
14093     // If we generating more than one store, we compute the base address of
14094     // subsequent stores as an offset from the previous.
14095     if (StoreCount > 0)
14096       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14097 
14098     SmallVector<Value *, 6> Ops;
14099     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14100 
14101     Function *VstNFunc =
14102         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14103 
14104     // Split the shufflevector operands into sub vectors for the new vstN call.
14105     for (unsigned i = 0; i < Factor; i++) {
14106       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14107       if (Mask[IdxI] >= 0) {
14108         Ops.push_back(Builder.CreateShuffleVector(
14109             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14110       } else {
14111         unsigned StartMask = 0;
14112         for (unsigned j = 1; j < LaneLen; j++) {
14113           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14114           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14115             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14116             break;
14117           }
14118         }
14119         // Note: If all elements in a chunk are undefs, StartMask=0!
14120         // Note: Filling undef gaps with random elements is ok, since
14121         // those elements were being written anyway (with undefs).
14122         // In the case of all undefs we're defaulting to using elems from 0
14123         // Note: StartMask cannot be negative, it's checked in
14124         // isReInterleaveMask
14125         Ops.push_back(Builder.CreateShuffleVector(
14126             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14127       }
14128     }
14129 
14130     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14131     Builder.CreateCall(VstNFunc, Ops);
14132   }
14133   return true;
14134 }
14135 
14136 enum HABaseType {
14137   HA_UNKNOWN = 0,
14138   HA_FLOAT,
14139   HA_DOUBLE,
14140   HA_VECT64,
14141   HA_VECT128
14142 };
14143 
14144 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14145                                    uint64_t &Members) {
14146   if (auto *ST = dyn_cast<StructType>(Ty)) {
14147     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14148       uint64_t SubMembers = 0;
14149       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14150         return false;
14151       Members += SubMembers;
14152     }
14153   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14154     uint64_t SubMembers = 0;
14155     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14156       return false;
14157     Members += SubMembers * AT->getNumElements();
14158   } else if (Ty->isFloatTy()) {
14159     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14160       return false;
14161     Members = 1;
14162     Base = HA_FLOAT;
14163   } else if (Ty->isDoubleTy()) {
14164     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14165       return false;
14166     Members = 1;
14167     Base = HA_DOUBLE;
14168   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14169     Members = 1;
14170     switch (Base) {
14171     case HA_FLOAT:
14172     case HA_DOUBLE:
14173       return false;
14174     case HA_VECT64:
14175       return VT->getBitWidth() == 64;
14176     case HA_VECT128:
14177       return VT->getBitWidth() == 128;
14178     case HA_UNKNOWN:
14179       switch (VT->getBitWidth()) {
14180       case 64:
14181         Base = HA_VECT64;
14182         return true;
14183       case 128:
14184         Base = HA_VECT128;
14185         return true;
14186       default:
14187         return false;
14188       }
14189     }
14190   }
14191 
14192   return (Members > 0 && Members <= 4);
14193 }
14194 
14195 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14196 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14197 /// passing according to AAPCS rules.
14198 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14199     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14200   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14201       CallingConv::ARM_AAPCS_VFP)
14202     return false;
14203 
14204   HABaseType Base = HA_UNKNOWN;
14205   uint64_t Members = 0;
14206   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14207   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14208 
14209   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14210   return IsHA || IsIntArray;
14211 }
14212 
14213 unsigned ARMTargetLowering::getExceptionPointerRegister(
14214     const Constant *PersonalityFn) const {
14215   // Platforms which do not use SjLj EH may return values in these registers
14216   // via the personality function.
14217   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14218 }
14219 
14220 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14221     const Constant *PersonalityFn) const {
14222   // Platforms which do not use SjLj EH may return values in these registers
14223   // via the personality function.
14224   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14225 }
14226 
14227 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14228   // Update IsSplitCSR in ARMFunctionInfo.
14229   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14230   AFI->setIsSplitCSR(true);
14231 }
14232 
14233 void ARMTargetLowering::insertCopiesSplitCSR(
14234     MachineBasicBlock *Entry,
14235     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14236   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14237   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14238   if (!IStart)
14239     return;
14240 
14241   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14242   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14243   MachineBasicBlock::iterator MBBI = Entry->begin();
14244   for (const MCPhysReg *I = IStart; *I; ++I) {
14245     const TargetRegisterClass *RC = nullptr;
14246     if (ARM::GPRRegClass.contains(*I))
14247       RC = &ARM::GPRRegClass;
14248     else if (ARM::DPRRegClass.contains(*I))
14249       RC = &ARM::DPRRegClass;
14250     else
14251       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14252 
14253     unsigned NewVR = MRI->createVirtualRegister(RC);
14254     // Create copy from CSR to a virtual register.
14255     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14256     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14257     // nounwind. If we want to generalize this later, we may need to emit
14258     // CFI pseudo-instructions.
14259     assert(Entry->getParent()->getFunction()->hasFnAttribute(
14260                Attribute::NoUnwind) &&
14261            "Function should be nounwind in insertCopiesSplitCSR!");
14262     Entry->addLiveIn(*I);
14263     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14264         .addReg(*I);
14265 
14266     // Insert the copy-back instructions right before the terminator.
14267     for (auto *Exit : Exits)
14268       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14269               TII->get(TargetOpcode::COPY), *I)
14270           .addReg(NewVR);
14271   }
14272 }
14273 
14274 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14275   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14276   TargetLoweringBase::finalizeLowering(MF);
14277 }
14278