1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/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/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
117 
118 #define DEBUG_TYPE "arm-isel"
119 
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124   "Number of constants with their storage promoted into constant pools");
125 
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128   cl::desc("Enable / disable ARM interworking (for debugging only)"),
129   cl::init(true));
130 
131 static cl::opt<bool> EnableConstpoolPromotion(
132     "arm-promote-constant", cl::Hidden,
133     cl::desc("Enable / disable promotion of unnamed_addr constants into "
134              "constant pools"),
135     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
136 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137     "arm-promote-constant-max-size", cl::Hidden,
138     cl::desc("Maximum size of constant to promote into a constant pool"),
139     cl::init(64));
140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141     "arm-promote-constant-max-total", cl::Hidden,
142     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143     cl::init(128));
144 
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147   ARM::R0, ARM::R1, ARM::R2, ARM::R3
148 };
149 
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151                                        MVT PromotedBitwiseVT) {
152   if (VT != PromotedLdStVT) {
153     setOperationAction(ISD::LOAD, VT, Promote);
154     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
155 
156     setOperationAction(ISD::STORE, VT, Promote);
157     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
158   }
159 
160   MVT ElemTy = VT.getVectorElementType();
161   if (ElemTy != MVT::f64)
162     setOperationAction(ISD::SETCC, VT, Custom);
163   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165   if (ElemTy == MVT::i32) {
166     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170   } else {
171     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
175   }
176   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
177   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
178   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
179   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180   setOperationAction(ISD::SELECT,            VT, Expand);
181   setOperationAction(ISD::SELECT_CC,         VT, Expand);
182   setOperationAction(ISD::VSELECT,           VT, Expand);
183   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184   if (VT.isInteger()) {
185     setOperationAction(ISD::SHL, VT, Custom);
186     setOperationAction(ISD::SRA, VT, Custom);
187     setOperationAction(ISD::SRL, VT, Custom);
188   }
189 
190   // Promote all bit-wise operations.
191   if (VT.isInteger() && VT != PromotedBitwiseVT) {
192     setOperationAction(ISD::AND, VT, Promote);
193     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194     setOperationAction(ISD::OR,  VT, Promote);
195     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
196     setOperationAction(ISD::XOR, VT, Promote);
197     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
198   }
199 
200   // Neon does not support vector divide/remainder operations.
201   setOperationAction(ISD::SDIV, VT, Expand);
202   setOperationAction(ISD::UDIV, VT, Expand);
203   setOperationAction(ISD::FDIV, VT, Expand);
204   setOperationAction(ISD::SREM, VT, Expand);
205   setOperationAction(ISD::UREM, VT, Expand);
206   setOperationAction(ISD::FREM, VT, Expand);
207 
208   if (!VT.isFloatingPoint() &&
209       VT != MVT::v2i64 && VT != MVT::v1i64)
210     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211       setOperationAction(Opcode, VT, Legal);
212 }
213 
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215   addRegisterClass(VT, &ARM::DPRRegClass);
216   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
217 }
218 
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220   addRegisterClass(VT, &ARM::DPairRegClass);
221   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
222 }
223 
224 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
225                                      const ARMSubtarget &STI)
226     : TargetLowering(TM), Subtarget(&STI) {
227   RegInfo = Subtarget->getRegisterInfo();
228   Itins = Subtarget->getInstrItineraryData();
229 
230   setBooleanContents(ZeroOrOneBooleanContent);
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232 
233   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
234       !Subtarget->isTargetWatchOS()) {
235     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
236     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
237       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
238                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
239                                        : CallingConv::ARM_AAPCS);
240   }
241 
242   if (Subtarget->isTargetMachO()) {
243     // Uses VFP for Thumb libfuncs if available.
244     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
245         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
246       static const struct {
247         const RTLIB::Libcall Op;
248         const char * const Name;
249         const ISD::CondCode Cond;
250       } LibraryCalls[] = {
251         // Single-precision floating-point arithmetic.
252         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
253         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
254         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
255         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
256 
257         // Double-precision floating-point arithmetic.
258         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
259         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
262 
263         // Single-precision comparisons.
264         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
265         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
266         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
267         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
268         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
269         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
270         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
271         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
272 
273         // Double-precision comparisons.
274         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
275         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
276         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
277         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
278         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
279         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
280         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
281         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
282 
283         // Floating-point to integer conversions.
284         // i64 conversions are done via library routines even when generating VFP
285         // instructions, so use the same ones.
286         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
287         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
288         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
289         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
290 
291         // Conversions between floating types.
292         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
293         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
294 
295         // Integer to floating-point conversions.
296         // i64 conversions are done via library routines even when generating VFP
297         // instructions, so use the same ones.
298         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
299         // e.g., __floatunsidf vs. __floatunssidfvfp.
300         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
301         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
302         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
303         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
304       };
305 
306       for (const auto &LC : LibraryCalls) {
307         setLibcallName(LC.Op, LC.Name);
308         if (LC.Cond != ISD::SETCC_INVALID)
309           setCmpLibcallCC(LC.Op, LC.Cond);
310       }
311     }
312   }
313 
314   // These libcalls are not available in 32-bit.
315   setLibcallName(RTLIB::SHL_I128, nullptr);
316   setLibcallName(RTLIB::SRL_I128, nullptr);
317   setLibcallName(RTLIB::SRA_I128, nullptr);
318 
319   // RTLIB
320   if (Subtarget->isAAPCS_ABI() &&
321       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
322        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
323     static const struct {
324       const RTLIB::Libcall Op;
325       const char * const Name;
326       const CallingConv::ID CC;
327       const ISD::CondCode Cond;
328     } LibraryCalls[] = {
329       // Double-precision floating-point arithmetic helper functions
330       // RTABI chapter 4.1.2, Table 2
331       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 
336       // Double-precision floating-point comparison helper functions
337       // RTABI chapter 4.1.2, Table 3
338       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
339       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
340       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
341       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
342       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
343       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
344       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
345       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
346 
347       // Single-precision floating-point arithmetic helper functions
348       // RTABI chapter 4.1.2, Table 4
349       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353 
354       // Single-precision floating-point comparison helper functions
355       // RTABI chapter 4.1.2, Table 5
356       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
357       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
358       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
359       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
360       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
361       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
362       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
363       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
364 
365       // Floating-point to integer conversions.
366       // RTABI chapter 4.1.2, Table 6
367       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
369       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375 
376       // Conversions between floating types.
377       // RTABI chapter 4.1.2, Table 7
378       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 
382       // Integer to floating-point conversions.
383       // RTABI chapter 4.1.2, Table 8
384       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392 
393       // Long long helper functions
394       // RTABI chapter 4.2, Table 9
395       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399 
400       // Integer division functions
401       // RTABI chapter 4.3.1
402       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410     };
411 
412     for (const auto &LC : LibraryCalls) {
413       setLibcallName(LC.Op, LC.Name);
414       setLibcallCallingConv(LC.Op, LC.CC);
415       if (LC.Cond != ISD::SETCC_INVALID)
416         setCmpLibcallCC(LC.Op, LC.Cond);
417     }
418 
419     // EABI dependent RTLIB
420     if (TM.Options.EABIVersion == EABI::EABI4 ||
421         TM.Options.EABIVersion == EABI::EABI5) {
422       static const struct {
423         const RTLIB::Libcall Op;
424         const char *const Name;
425         const CallingConv::ID CC;
426         const ISD::CondCode Cond;
427       } MemOpsLibraryCalls[] = {
428         // Memory operations
429         // RTABI chapter 4.3.4
430         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
431         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
432         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
433       };
434 
435       for (const auto &LC : MemOpsLibraryCalls) {
436         setLibcallName(LC.Op, LC.Name);
437         setLibcallCallingConv(LC.Op, LC.CC);
438         if (LC.Cond != ISD::SETCC_INVALID)
439           setCmpLibcallCC(LC.Op, LC.Cond);
440       }
441     }
442   }
443 
444   if (Subtarget->isTargetWindows()) {
445     static const struct {
446       const RTLIB::Libcall Op;
447       const char * const Name;
448       const CallingConv::ID CC;
449     } LibraryCalls[] = {
450       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
451       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
452       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
453       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
454       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
455       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
456       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
457       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
458     };
459 
460     for (const auto &LC : LibraryCalls) {
461       setLibcallName(LC.Op, LC.Name);
462       setLibcallCallingConv(LC.Op, LC.CC);
463     }
464   }
465 
466   // Use divmod compiler-rt calls for iOS 5.0 and later.
467   if (Subtarget->isTargetMachO() &&
468       !(Subtarget->isTargetIOS() &&
469         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
470     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
471     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
472   }
473 
474   // The half <-> float conversion functions are always soft-float on
475   // non-watchos platforms, but are needed for some targets which use a
476   // hard-float calling convention by default.
477   if (!Subtarget->isTargetWatchABI()) {
478     if (Subtarget->isAAPCS_ABI()) {
479       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
480       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
481       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
482     } else {
483       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
484       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
485       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
486     }
487   }
488 
489   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
490   // a __gnu_ prefix (which is the default).
491   if (Subtarget->isTargetAEABI()) {
492     static const struct {
493       const RTLIB::Libcall Op;
494       const char * const Name;
495       const CallingConv::ID CC;
496     } LibraryCalls[] = {
497       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
498       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
499       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
500     };
501 
502     for (const auto &LC : LibraryCalls) {
503       setLibcallName(LC.Op, LC.Name);
504       setLibcallCallingConv(LC.Op, LC.CC);
505     }
506   }
507 
508   if (Subtarget->isThumb1Only())
509     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
510   else
511     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
512 
513   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
514       !Subtarget->isThumb1Only()) {
515     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
516     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
517   }
518 
519   if (Subtarget->hasFullFP16()) {
520     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
521     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
522     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
523     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
524 
525     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
526     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
527   }
528 
529   for (MVT VT : MVT::vector_valuetypes()) {
530     for (MVT InnerVT : MVT::vector_valuetypes()) {
531       setTruncStoreAction(VT, InnerVT, Expand);
532       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
533       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
534       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
535     }
536 
537     setOperationAction(ISD::MULHS, VT, Expand);
538     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
539     setOperationAction(ISD::MULHU, VT, Expand);
540     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
541 
542     setOperationAction(ISD::BSWAP, VT, Expand);
543   }
544 
545   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
546   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
547 
548   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
549   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
550 
551   if (Subtarget->hasNEON()) {
552     addDRTypeForNEON(MVT::v2f32);
553     addDRTypeForNEON(MVT::v8i8);
554     addDRTypeForNEON(MVT::v4i16);
555     addDRTypeForNEON(MVT::v2i32);
556     addDRTypeForNEON(MVT::v1i64);
557 
558     addQRTypeForNEON(MVT::v4f32);
559     addQRTypeForNEON(MVT::v2f64);
560     addQRTypeForNEON(MVT::v16i8);
561     addQRTypeForNEON(MVT::v8i16);
562     addQRTypeForNEON(MVT::v4i32);
563     addQRTypeForNEON(MVT::v2i64);
564 
565     if (Subtarget->hasFullFP16()) {
566       addQRTypeForNEON(MVT::v8f16);
567       addDRTypeForNEON(MVT::v4f16);
568     }
569 
570     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
571     // neither Neon nor VFP support any arithmetic operations on it.
572     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
573     // supported for v4f32.
574     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
575     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
576     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
577     // FIXME: Code duplication: FDIV and FREM are expanded always, see
578     // ARMTargetLowering::addTypeForNEON method for details.
579     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
580     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
581     // FIXME: Create unittest.
582     // In another words, find a way when "copysign" appears in DAG with vector
583     // operands.
584     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
585     // FIXME: Code duplication: SETCC has custom operation action, see
586     // ARMTargetLowering::addTypeForNEON method for details.
587     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
588     // FIXME: Create unittest for FNEG and for FABS.
589     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
590     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
591     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
592     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
593     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
594     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
595     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
596     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
597     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
598     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
599     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
600     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
601     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
602     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
603     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
604     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
605     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
606     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
607 
608     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
609     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
610     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
611     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
612     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
613     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
614     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
615     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
616     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
617     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
618     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
619     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
620     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
621     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
622 
623     // Mark v2f32 intrinsics.
624     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
625     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
626     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
627     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
628     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
629     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
630     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
631     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
632     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
633     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
634     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
635     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
636     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
637     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
638 
639     // Neon does not support some operations on v1i64 and v2i64 types.
640     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
641     // Custom handling for some quad-vector types to detect VMULL.
642     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
643     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
644     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
645     // Custom handling for some vector types to avoid expensive expansions
646     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
647     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
648     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
649     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
650     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
651     // a destination type that is wider than the source, and nor does
652     // it have a FP_TO_[SU]INT instruction with a narrower destination than
653     // source.
654     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
655     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
656     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
657     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
658     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
659     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
661     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
662 
663     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
664     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
665 
666     // NEON does not have single instruction CTPOP for vectors with element
667     // types wider than 8-bits.  However, custom lowering can leverage the
668     // v8i8/v16i8 vcnt instruction.
669     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
670     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
671     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
672     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
673     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
674     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
675 
676     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
677     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
678 
679     // NEON does not have single instruction CTTZ for vectors.
680     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
681     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
682     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
683     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
684 
685     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
686     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
687     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
688     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
689 
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
691     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
692     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
693     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
694 
695     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
696     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
697     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
698     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
699 
700     // NEON only has FMA instructions as of VFP4.
701     if (!Subtarget->hasVFP4()) {
702       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
703       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
704     }
705 
706     setTargetDAGCombine(ISD::INTRINSIC_VOID);
707     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
708     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
709     setTargetDAGCombine(ISD::SHL);
710     setTargetDAGCombine(ISD::SRL);
711     setTargetDAGCombine(ISD::SRA);
712     setTargetDAGCombine(ISD::SIGN_EXTEND);
713     setTargetDAGCombine(ISD::ZERO_EXTEND);
714     setTargetDAGCombine(ISD::ANY_EXTEND);
715     setTargetDAGCombine(ISD::BUILD_VECTOR);
716     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
717     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
718     setTargetDAGCombine(ISD::STORE);
719     setTargetDAGCombine(ISD::FP_TO_SINT);
720     setTargetDAGCombine(ISD::FP_TO_UINT);
721     setTargetDAGCombine(ISD::FDIV);
722     setTargetDAGCombine(ISD::LOAD);
723 
724     // It is legal to extload from v4i8 to v4i16 or v4i32.
725     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
726                    MVT::v2i32}) {
727       for (MVT VT : MVT::integer_vector_valuetypes()) {
728         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
729         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
730         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
731       }
732     }
733   }
734 
735   if (Subtarget->isFPOnlySP()) {
736     // When targeting a floating-point unit with only single-precision
737     // operations, f64 is legal for the few double-precision instructions which
738     // are present However, no double-precision operations other than moves,
739     // loads and stores are provided by the hardware.
740     setOperationAction(ISD::FADD,       MVT::f64, Expand);
741     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
742     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
743     setOperationAction(ISD::FMA,        MVT::f64, Expand);
744     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
745     setOperationAction(ISD::FREM,       MVT::f64, Expand);
746     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
747     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
748     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
749     setOperationAction(ISD::FABS,       MVT::f64, Expand);
750     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
751     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
752     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
753     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
754     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
755     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
756     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
757     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
758     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
759     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
760     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
761     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
762     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
763     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
764     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
765     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
766     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
767     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
768     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
769     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
770     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
771     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
772   }
773 
774   computeRegisterProperties(Subtarget->getRegisterInfo());
775 
776   // ARM does not have floating-point extending loads.
777   for (MVT VT : MVT::fp_valuetypes()) {
778     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
779     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
780   }
781 
782   // ... or truncating stores
783   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
784   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
785   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
786 
787   // ARM does not have i1 sign extending load.
788   for (MVT VT : MVT::integer_valuetypes())
789     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
790 
791   // ARM supports all 4 flavors of integer indexed load / store.
792   if (!Subtarget->isThumb1Only()) {
793     for (unsigned im = (unsigned)ISD::PRE_INC;
794          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
795       setIndexedLoadAction(im,  MVT::i1,  Legal);
796       setIndexedLoadAction(im,  MVT::i8,  Legal);
797       setIndexedLoadAction(im,  MVT::i16, Legal);
798       setIndexedLoadAction(im,  MVT::i32, Legal);
799       setIndexedStoreAction(im, MVT::i1,  Legal);
800       setIndexedStoreAction(im, MVT::i8,  Legal);
801       setIndexedStoreAction(im, MVT::i16, Legal);
802       setIndexedStoreAction(im, MVT::i32, Legal);
803     }
804   } else {
805     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
806     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
807     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
808   }
809 
810   setOperationAction(ISD::SADDO, MVT::i32, Custom);
811   setOperationAction(ISD::UADDO, MVT::i32, Custom);
812   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
813   setOperationAction(ISD::USUBO, MVT::i32, Custom);
814 
815   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
816   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
817 
818   // i64 operation support.
819   setOperationAction(ISD::MUL,     MVT::i64, Expand);
820   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
821   if (Subtarget->isThumb1Only()) {
822     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
823     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
824   }
825   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
826       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
827     setOperationAction(ISD::MULHS, MVT::i32, Expand);
828 
829   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
830   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
831   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
832   setOperationAction(ISD::SRL,       MVT::i64, Custom);
833   setOperationAction(ISD::SRA,       MVT::i64, Custom);
834   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
835 
836   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
837   if (Subtarget->isThumb1Only()) {
838     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
839     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
840     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
841   }
842 
843   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
844     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
845 
846   // ARM does not have ROTL.
847   setOperationAction(ISD::ROTL, MVT::i32, Expand);
848   for (MVT VT : MVT::vector_valuetypes()) {
849     setOperationAction(ISD::ROTL, VT, Expand);
850     setOperationAction(ISD::ROTR, VT, Expand);
851   }
852   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
853   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
854   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
855     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
856     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
857   }
858 
859   // @llvm.readcyclecounter requires the Performance Monitors extension.
860   // Default to the 0 expansion on unsupported platforms.
861   // FIXME: Technically there are older ARM CPUs that have
862   // implementation-specific ways of obtaining this information.
863   if (Subtarget->hasPerfMon())
864     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
865 
866   // Only ARMv6 has BSWAP.
867   if (!Subtarget->hasV6Ops())
868     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
869 
870   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
871                                         : Subtarget->hasDivideInARMMode();
872   if (!hasDivide) {
873     // These are expanded into libcalls if the cpu doesn't have HW divider.
874     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
875     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
876   }
877 
878   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
879     setOperationAction(ISD::SDIV, MVT::i32, Custom);
880     setOperationAction(ISD::UDIV, MVT::i32, Custom);
881 
882     setOperationAction(ISD::SDIV, MVT::i64, Custom);
883     setOperationAction(ISD::UDIV, MVT::i64, Custom);
884   }
885 
886   setOperationAction(ISD::SREM,  MVT::i32, Expand);
887   setOperationAction(ISD::UREM,  MVT::i32, Expand);
888 
889   // Register based DivRem for AEABI (RTABI 4.2)
890   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
891       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
892       Subtarget->isTargetWindows()) {
893     setOperationAction(ISD::SREM, MVT::i64, Custom);
894     setOperationAction(ISD::UREM, MVT::i64, Custom);
895     HasStandaloneRem = false;
896 
897     if (Subtarget->isTargetWindows()) {
898       const struct {
899         const RTLIB::Libcall Op;
900         const char * const Name;
901         const CallingConv::ID CC;
902       } LibraryCalls[] = {
903         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
904         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
905         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
906         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
907 
908         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
909         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
910         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
911         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
912       };
913 
914       for (const auto &LC : LibraryCalls) {
915         setLibcallName(LC.Op, LC.Name);
916         setLibcallCallingConv(LC.Op, LC.CC);
917       }
918     } else {
919       const struct {
920         const RTLIB::Libcall Op;
921         const char * const Name;
922         const CallingConv::ID CC;
923       } LibraryCalls[] = {
924         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
925         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
926         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
927         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
928 
929         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
930         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
931         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
932         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
933       };
934 
935       for (const auto &LC : LibraryCalls) {
936         setLibcallName(LC.Op, LC.Name);
937         setLibcallCallingConv(LC.Op, LC.CC);
938       }
939     }
940 
941     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
942     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
943     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
944     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
945   } else {
946     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
947     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
948   }
949 
950   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
951     for (auto &VT : {MVT::f32, MVT::f64})
952       setOperationAction(ISD::FPOWI, VT, Custom);
953 
954   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
955   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
956   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
957   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
958 
959   setOperationAction(ISD::TRAP, MVT::Other, Legal);
960   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
961 
962   // Use the default implementation.
963   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
964   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
965   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
966   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
967   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
968   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
969 
970   if (Subtarget->isTargetWindows())
971     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
972   else
973     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
974 
975   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
976   // the default expansion.
977   InsertFencesForAtomic = false;
978   if (Subtarget->hasAnyDataBarrier() &&
979       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
980     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
981     // to ldrex/strex loops already.
982     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
983     if (!Subtarget->isThumb() || !Subtarget->isMClass())
984       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
985 
986     // On v8, we have particularly efficient implementations of atomic fences
987     // if they can be combined with nearby atomic loads and stores.
988     if (!Subtarget->hasAcquireRelease() ||
989         getTargetMachine().getOptLevel() == 0) {
990       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
991       InsertFencesForAtomic = true;
992     }
993   } else {
994     // If there's anything we can use as a barrier, go through custom lowering
995     // for ATOMIC_FENCE.
996     // If target has DMB in thumb, Fences can be inserted.
997     if (Subtarget->hasDataBarrier())
998       InsertFencesForAtomic = true;
999 
1000     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1001                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1002 
1003     // Set them all for expansion, which will force libcalls.
1004     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1005     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1006     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1007     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1008     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1009     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1010     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1011     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1012     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1013     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1014     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1015     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1016     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1017     // Unordered/Monotonic case.
1018     if (!InsertFencesForAtomic) {
1019       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1020       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1021     }
1022   }
1023 
1024   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1025 
1026   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1027   if (!Subtarget->hasV6Ops()) {
1028     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1029     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1030   }
1031   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1032 
1033   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1034       !Subtarget->isThumb1Only()) {
1035     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1036     // iff target supports vfp2.
1037     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1038     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1039   }
1040 
1041   // We want to custom lower some of our intrinsics.
1042   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1043   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1044   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1045   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1046   if (Subtarget->useSjLjEH())
1047     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1048 
1049   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1050   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1051   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1052   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1053   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1054   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1055   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1056   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1057   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1058   if (Subtarget->hasFullFP16()) {
1059     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1060     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1061     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1062   }
1063 
1064   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1065 
1066   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1067   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1068   if (Subtarget->hasFullFP16())
1069       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1070   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1071   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1072   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1073 
1074   // We don't support sin/cos/fmod/copysign/pow
1075   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1076   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1077   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1078   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1079   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1080   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1081   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1082   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1083   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1084       !Subtarget->isThumb1Only()) {
1085     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1086     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1087   }
1088   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1089   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1090 
1091   if (!Subtarget->hasVFP4()) {
1092     setOperationAction(ISD::FMA, MVT::f64, Expand);
1093     setOperationAction(ISD::FMA, MVT::f32, Expand);
1094   }
1095 
1096   // Various VFP goodness
1097   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1098     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1099     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1100       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1101       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1102     }
1103 
1104     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1105     if (!Subtarget->hasFP16()) {
1106       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1107       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1108     }
1109   }
1110 
1111   // Use __sincos_stret if available.
1112   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1113       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1114     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1115     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1116   }
1117 
1118   // FP-ARMv8 implements a lot of rounding-like FP operations.
1119   if (Subtarget->hasFPARMv8()) {
1120     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1121     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1122     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1123     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1124     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1125     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1126     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1127     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1128     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1129     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1130     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1131     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1132 
1133     if (!Subtarget->isFPOnlySP()) {
1134       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1135       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1136       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1137       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1138       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1139       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1140       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1141       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1142     }
1143   }
1144 
1145   if (Subtarget->hasNEON()) {
1146     // vmin and vmax aren't available in a scalar form, so we use
1147     // a NEON instruction with an undef lane instead.
1148     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1149     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1150     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1151     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1152     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1153     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1154     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1155     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1156 
1157     if (Subtarget->hasFullFP16()) {
1158       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1159       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1160       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1161       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1162 
1163       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1164       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1165       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1166       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1167     }
1168   }
1169 
1170   // We have target-specific dag combine patterns for the following nodes:
1171   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1172   setTargetDAGCombine(ISD::ADD);
1173   setTargetDAGCombine(ISD::SUB);
1174   setTargetDAGCombine(ISD::MUL);
1175   setTargetDAGCombine(ISD::AND);
1176   setTargetDAGCombine(ISD::OR);
1177   setTargetDAGCombine(ISD::XOR);
1178 
1179   if (Subtarget->hasV6Ops())
1180     setTargetDAGCombine(ISD::SRL);
1181   if (Subtarget->isThumb1Only())
1182     setTargetDAGCombine(ISD::SHL);
1183 
1184   setStackPointerRegisterToSaveRestore(ARM::SP);
1185 
1186   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1187       !Subtarget->hasVFP2())
1188     setSchedulingPreference(Sched::RegPressure);
1189   else
1190     setSchedulingPreference(Sched::Hybrid);
1191 
1192   //// temporary - rewrite interface to use type
1193   MaxStoresPerMemset = 8;
1194   MaxStoresPerMemsetOptSize = 4;
1195   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1196   MaxStoresPerMemcpyOptSize = 2;
1197   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1198   MaxStoresPerMemmoveOptSize = 2;
1199 
1200   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1201   // are at least 4 bytes aligned.
1202   setMinStackArgumentAlignment(4);
1203 
1204   // Prefer likely predicted branches to selects on out-of-order cores.
1205   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1206 
1207   setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1208 
1209   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1210 }
1211 
1212 bool ARMTargetLowering::useSoftFloat() const {
1213   return Subtarget->useSoftFloat();
1214 }
1215 
1216 // FIXME: It might make sense to define the representative register class as the
1217 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1218 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1219 // SPR's representative would be DPR_VFP2. This should work well if register
1220 // pressure tracking were modified such that a register use would increment the
1221 // pressure of the register class's representative and all of it's super
1222 // classes' representatives transitively. We have not implemented this because
1223 // of the difficulty prior to coalescing of modeling operand register classes
1224 // due to the common occurrence of cross class copies and subregister insertions
1225 // and extractions.
1226 std::pair<const TargetRegisterClass *, uint8_t>
1227 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1228                                            MVT VT) const {
1229   const TargetRegisterClass *RRC = nullptr;
1230   uint8_t Cost = 1;
1231   switch (VT.SimpleTy) {
1232   default:
1233     return TargetLowering::findRepresentativeClass(TRI, VT);
1234   // Use DPR as representative register class for all floating point
1235   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1236   // the cost is 1 for both f32 and f64.
1237   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1238   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1239     RRC = &ARM::DPRRegClass;
1240     // When NEON is used for SP, only half of the register file is available
1241     // because operations that define both SP and DP results will be constrained
1242     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1243     // coalescing by double-counting the SP regs. See the FIXME above.
1244     if (Subtarget->useNEONForSinglePrecisionFP())
1245       Cost = 2;
1246     break;
1247   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1248   case MVT::v4f32: case MVT::v2f64:
1249     RRC = &ARM::DPRRegClass;
1250     Cost = 2;
1251     break;
1252   case MVT::v4i64:
1253     RRC = &ARM::DPRRegClass;
1254     Cost = 4;
1255     break;
1256   case MVT::v8i64:
1257     RRC = &ARM::DPRRegClass;
1258     Cost = 8;
1259     break;
1260   }
1261   return std::make_pair(RRC, Cost);
1262 }
1263 
1264 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1265   switch ((ARMISD::NodeType)Opcode) {
1266   case ARMISD::FIRST_NUMBER:  break;
1267   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1268   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1269   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1270   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1271   case ARMISD::CALL:          return "ARMISD::CALL";
1272   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1273   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1274   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1275   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1276   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1277   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1278   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1279   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1280   case ARMISD::CMP:           return "ARMISD::CMP";
1281   case ARMISD::CMN:           return "ARMISD::CMN";
1282   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1283   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1284   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1285   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1286   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1287 
1288   case ARMISD::CMOV:          return "ARMISD::CMOV";
1289   case ARMISD::SUBS:          return "ARMISD::SUBS";
1290 
1291   case ARMISD::SSAT:          return "ARMISD::SSAT";
1292   case ARMISD::USAT:          return "ARMISD::USAT";
1293 
1294   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1295   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1296   case ARMISD::RRX:           return "ARMISD::RRX";
1297 
1298   case ARMISD::ADDC:          return "ARMISD::ADDC";
1299   case ARMISD::ADDE:          return "ARMISD::ADDE";
1300   case ARMISD::SUBC:          return "ARMISD::SUBC";
1301   case ARMISD::SUBE:          return "ARMISD::SUBE";
1302 
1303   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1304   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1305   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1306   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1307   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1308 
1309   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1310   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1311   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1312 
1313   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1314 
1315   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1316 
1317   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1318 
1319   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1320 
1321   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1322 
1323   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1324   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1325 
1326   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1327   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1328   case ARMISD::VCGE:          return "ARMISD::VCGE";
1329   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1330   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1331   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1332   case ARMISD::VCGT:          return "ARMISD::VCGT";
1333   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1334   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1335   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1336   case ARMISD::VTST:          return "ARMISD::VTST";
1337 
1338   case ARMISD::VSHL:          return "ARMISD::VSHL";
1339   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1340   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1341   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1342   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1343   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1344   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1345   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1346   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1347   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1348   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1349   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1350   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1351   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1352   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1353   case ARMISD::VSLI:          return "ARMISD::VSLI";
1354   case ARMISD::VSRI:          return "ARMISD::VSRI";
1355   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1356   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1357   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1358   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1359   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1360   case ARMISD::VDUP:          return "ARMISD::VDUP";
1361   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1362   case ARMISD::VEXT:          return "ARMISD::VEXT";
1363   case ARMISD::VREV64:        return "ARMISD::VREV64";
1364   case ARMISD::VREV32:        return "ARMISD::VREV32";
1365   case ARMISD::VREV16:        return "ARMISD::VREV16";
1366   case ARMISD::VZIP:          return "ARMISD::VZIP";
1367   case ARMISD::VUZP:          return "ARMISD::VUZP";
1368   case ARMISD::VTRN:          return "ARMISD::VTRN";
1369   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1370   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1371   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1372   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1373   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1374   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1375   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1376   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1377   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1378   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1379   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1380   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1381   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1382   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1383   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1384   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1385   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1386   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1387   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1388   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1389   case ARMISD::BFI:           return "ARMISD::BFI";
1390   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1391   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1392   case ARMISD::VBSL:          return "ARMISD::VBSL";
1393   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1394   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1395   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1396   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1397   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1398   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1399   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1400   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1401   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1402   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1403   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1404   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1405   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1406   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1407   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1408   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1409   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1410   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1411   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1412   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1413   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1414   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1415   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1416   }
1417   return nullptr;
1418 }
1419 
1420 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1421                                           EVT VT) const {
1422   if (!VT.isVector())
1423     return getPointerTy(DL);
1424   return VT.changeVectorElementTypeToInteger();
1425 }
1426 
1427 /// getRegClassFor - Return the register class that should be used for the
1428 /// specified value type.
1429 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1430   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1431   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1432   // load / store 4 to 8 consecutive D registers.
1433   if (Subtarget->hasNEON()) {
1434     if (VT == MVT::v4i64)
1435       return &ARM::QQPRRegClass;
1436     if (VT == MVT::v8i64)
1437       return &ARM::QQQQPRRegClass;
1438   }
1439   return TargetLowering::getRegClassFor(VT);
1440 }
1441 
1442 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1443 // source/dest is aligned and the copy size is large enough. We therefore want
1444 // to align such objects passed to memory intrinsics.
1445 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1446                                                unsigned &PrefAlign) const {
1447   if (!isa<MemIntrinsic>(CI))
1448     return false;
1449   MinSize = 8;
1450   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1451   // cycle faster than 4-byte aligned LDM.
1452   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1453   return true;
1454 }
1455 
1456 // Create a fast isel object.
1457 FastISel *
1458 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1459                                   const TargetLibraryInfo *libInfo) const {
1460   return ARM::createFastISel(funcInfo, libInfo);
1461 }
1462 
1463 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1464   unsigned NumVals = N->getNumValues();
1465   if (!NumVals)
1466     return Sched::RegPressure;
1467 
1468   for (unsigned i = 0; i != NumVals; ++i) {
1469     EVT VT = N->getValueType(i);
1470     if (VT == MVT::Glue || VT == MVT::Other)
1471       continue;
1472     if (VT.isFloatingPoint() || VT.isVector())
1473       return Sched::ILP;
1474   }
1475 
1476   if (!N->isMachineOpcode())
1477     return Sched::RegPressure;
1478 
1479   // Load are scheduled for latency even if there instruction itinerary
1480   // is not available.
1481   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1482   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1483 
1484   if (MCID.getNumDefs() == 0)
1485     return Sched::RegPressure;
1486   if (!Itins->isEmpty() &&
1487       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1488     return Sched::ILP;
1489 
1490   return Sched::RegPressure;
1491 }
1492 
1493 //===----------------------------------------------------------------------===//
1494 // Lowering Code
1495 //===----------------------------------------------------------------------===//
1496 
1497 static bool isSRL16(const SDValue &Op) {
1498   if (Op.getOpcode() != ISD::SRL)
1499     return false;
1500   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1501     return Const->getZExtValue() == 16;
1502   return false;
1503 }
1504 
1505 static bool isSRA16(const SDValue &Op) {
1506   if (Op.getOpcode() != ISD::SRA)
1507     return false;
1508   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1509     return Const->getZExtValue() == 16;
1510   return false;
1511 }
1512 
1513 static bool isSHL16(const SDValue &Op) {
1514   if (Op.getOpcode() != ISD::SHL)
1515     return false;
1516   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1517     return Const->getZExtValue() == 16;
1518   return false;
1519 }
1520 
1521 // Check for a signed 16-bit value. We special case SRA because it makes it
1522 // more simple when also looking for SRAs that aren't sign extending a
1523 // smaller value. Without the check, we'd need to take extra care with
1524 // checking order for some operations.
1525 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1526   if (isSRA16(Op))
1527     return isSHL16(Op.getOperand(0));
1528   return DAG.ComputeNumSignBits(Op) == 17;
1529 }
1530 
1531 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1532 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1533   switch (CC) {
1534   default: llvm_unreachable("Unknown condition code!");
1535   case ISD::SETNE:  return ARMCC::NE;
1536   case ISD::SETEQ:  return ARMCC::EQ;
1537   case ISD::SETGT:  return ARMCC::GT;
1538   case ISD::SETGE:  return ARMCC::GE;
1539   case ISD::SETLT:  return ARMCC::LT;
1540   case ISD::SETLE:  return ARMCC::LE;
1541   case ISD::SETUGT: return ARMCC::HI;
1542   case ISD::SETUGE: return ARMCC::HS;
1543   case ISD::SETULT: return ARMCC::LO;
1544   case ISD::SETULE: return ARMCC::LS;
1545   }
1546 }
1547 
1548 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1549 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1550                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1551   CondCode2 = ARMCC::AL;
1552   InvalidOnQNaN = true;
1553   switch (CC) {
1554   default: llvm_unreachable("Unknown FP condition!");
1555   case ISD::SETEQ:
1556   case ISD::SETOEQ:
1557     CondCode = ARMCC::EQ;
1558     InvalidOnQNaN = false;
1559     break;
1560   case ISD::SETGT:
1561   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1562   case ISD::SETGE:
1563   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1564   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1565   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1566   case ISD::SETONE:
1567     CondCode = ARMCC::MI;
1568     CondCode2 = ARMCC::GT;
1569     InvalidOnQNaN = false;
1570     break;
1571   case ISD::SETO:   CondCode = ARMCC::VC; break;
1572   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1573   case ISD::SETUEQ:
1574     CondCode = ARMCC::EQ;
1575     CondCode2 = ARMCC::VS;
1576     InvalidOnQNaN = false;
1577     break;
1578   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1579   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1580   case ISD::SETLT:
1581   case ISD::SETULT: CondCode = ARMCC::LT; break;
1582   case ISD::SETLE:
1583   case ISD::SETULE: CondCode = ARMCC::LE; break;
1584   case ISD::SETNE:
1585   case ISD::SETUNE:
1586     CondCode = ARMCC::NE;
1587     InvalidOnQNaN = false;
1588     break;
1589   }
1590 }
1591 
1592 //===----------------------------------------------------------------------===//
1593 //                      Calling Convention Implementation
1594 //===----------------------------------------------------------------------===//
1595 
1596 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1597 /// account presence of floating point hardware and calling convention
1598 /// limitations, such as support for variadic functions.
1599 CallingConv::ID
1600 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1601                                            bool isVarArg) const {
1602   switch (CC) {
1603   default:
1604     report_fatal_error("Unsupported calling convention");
1605   case CallingConv::ARM_AAPCS:
1606   case CallingConv::ARM_APCS:
1607   case CallingConv::GHC:
1608     return CC;
1609   case CallingConv::PreserveMost:
1610     return CallingConv::PreserveMost;
1611   case CallingConv::ARM_AAPCS_VFP:
1612   case CallingConv::Swift:
1613     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1614   case CallingConv::C:
1615     if (!Subtarget->isAAPCS_ABI())
1616       return CallingConv::ARM_APCS;
1617     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1618              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1619              !isVarArg)
1620       return CallingConv::ARM_AAPCS_VFP;
1621     else
1622       return CallingConv::ARM_AAPCS;
1623   case CallingConv::Fast:
1624   case CallingConv::CXX_FAST_TLS:
1625     if (!Subtarget->isAAPCS_ABI()) {
1626       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1627         return CallingConv::Fast;
1628       return CallingConv::ARM_APCS;
1629     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1630       return CallingConv::ARM_AAPCS_VFP;
1631     else
1632       return CallingConv::ARM_AAPCS;
1633   }
1634 }
1635 
1636 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1637                                                  bool isVarArg) const {
1638   return CCAssignFnForNode(CC, false, isVarArg);
1639 }
1640 
1641 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1642                                                    bool isVarArg) const {
1643   return CCAssignFnForNode(CC, true, isVarArg);
1644 }
1645 
1646 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1647 /// CallingConvention.
1648 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1649                                                  bool Return,
1650                                                  bool isVarArg) const {
1651   switch (getEffectiveCallingConv(CC, isVarArg)) {
1652   default:
1653     report_fatal_error("Unsupported calling convention");
1654   case CallingConv::ARM_APCS:
1655     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1656   case CallingConv::ARM_AAPCS:
1657     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1658   case CallingConv::ARM_AAPCS_VFP:
1659     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1660   case CallingConv::Fast:
1661     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1662   case CallingConv::GHC:
1663     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1664   case CallingConv::PreserveMost:
1665     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1666   }
1667 }
1668 
1669 /// LowerCallResult - Lower the result values of a call into the
1670 /// appropriate copies out of appropriate physical registers.
1671 SDValue ARMTargetLowering::LowerCallResult(
1672     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1673     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1674     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1675     SDValue ThisVal) const {
1676   // Assign locations to each value returned by this call.
1677   SmallVector<CCValAssign, 16> RVLocs;
1678   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1679                  *DAG.getContext());
1680   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1681 
1682   // Copy all of the result registers out of their specified physreg.
1683   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1684     CCValAssign VA = RVLocs[i];
1685 
1686     // Pass 'this' value directly from the argument to return value, to avoid
1687     // reg unit interference
1688     if (i == 0 && isThisReturn) {
1689       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1690              "unexpected return calling convention register assignment");
1691       InVals.push_back(ThisVal);
1692       continue;
1693     }
1694 
1695     SDValue Val;
1696     if (VA.needsCustom()) {
1697       // Handle f64 or half of a v2f64.
1698       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1699                                       InFlag);
1700       Chain = Lo.getValue(1);
1701       InFlag = Lo.getValue(2);
1702       VA = RVLocs[++i]; // skip ahead to next loc
1703       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1704                                       InFlag);
1705       Chain = Hi.getValue(1);
1706       InFlag = Hi.getValue(2);
1707       if (!Subtarget->isLittle())
1708         std::swap (Lo, Hi);
1709       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1710 
1711       if (VA.getLocVT() == MVT::v2f64) {
1712         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1713         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1714                           DAG.getConstant(0, dl, MVT::i32));
1715 
1716         VA = RVLocs[++i]; // skip ahead to next loc
1717         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1718         Chain = Lo.getValue(1);
1719         InFlag = Lo.getValue(2);
1720         VA = RVLocs[++i]; // skip ahead to next loc
1721         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1722         Chain = Hi.getValue(1);
1723         InFlag = Hi.getValue(2);
1724         if (!Subtarget->isLittle())
1725           std::swap (Lo, Hi);
1726         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1727         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1728                           DAG.getConstant(1, dl, MVT::i32));
1729       }
1730     } else {
1731       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1732                                InFlag);
1733       Chain = Val.getValue(1);
1734       InFlag = Val.getValue(2);
1735     }
1736 
1737     switch (VA.getLocInfo()) {
1738     default: llvm_unreachable("Unknown loc info!");
1739     case CCValAssign::Full: break;
1740     case CCValAssign::BCvt:
1741       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1742       break;
1743     }
1744 
1745     InVals.push_back(Val);
1746   }
1747 
1748   return Chain;
1749 }
1750 
1751 /// LowerMemOpCallTo - Store the argument to the stack.
1752 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1753                                             SDValue Arg, const SDLoc &dl,
1754                                             SelectionDAG &DAG,
1755                                             const CCValAssign &VA,
1756                                             ISD::ArgFlagsTy Flags) const {
1757   unsigned LocMemOffset = VA.getLocMemOffset();
1758   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1759   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1760                        StackPtr, PtrOff);
1761   return DAG.getStore(
1762       Chain, dl, Arg, PtrOff,
1763       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1764 }
1765 
1766 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1767                                          SDValue Chain, SDValue &Arg,
1768                                          RegsToPassVector &RegsToPass,
1769                                          CCValAssign &VA, CCValAssign &NextVA,
1770                                          SDValue &StackPtr,
1771                                          SmallVectorImpl<SDValue> &MemOpChains,
1772                                          ISD::ArgFlagsTy Flags) const {
1773   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1774                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1775   unsigned id = Subtarget->isLittle() ? 0 : 1;
1776   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1777 
1778   if (NextVA.isRegLoc())
1779     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1780   else {
1781     assert(NextVA.isMemLoc());
1782     if (!StackPtr.getNode())
1783       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1784                                     getPointerTy(DAG.getDataLayout()));
1785 
1786     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1787                                            dl, DAG, NextVA,
1788                                            Flags));
1789   }
1790 }
1791 
1792 /// LowerCall - Lowering a call into a callseq_start <-
1793 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1794 /// nodes.
1795 SDValue
1796 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1797                              SmallVectorImpl<SDValue> &InVals) const {
1798   SelectionDAG &DAG                     = CLI.DAG;
1799   SDLoc &dl                             = CLI.DL;
1800   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1801   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1802   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1803   SDValue Chain                         = CLI.Chain;
1804   SDValue Callee                        = CLI.Callee;
1805   bool &isTailCall                      = CLI.IsTailCall;
1806   CallingConv::ID CallConv              = CLI.CallConv;
1807   bool doesNotRet                       = CLI.DoesNotReturn;
1808   bool isVarArg                         = CLI.IsVarArg;
1809 
1810   MachineFunction &MF = DAG.getMachineFunction();
1811   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1812   bool isThisReturn   = false;
1813   bool isSibCall      = false;
1814   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1815 
1816   // Disable tail calls if they're not supported.
1817   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1818     isTailCall = false;
1819 
1820   if (isTailCall) {
1821     // Check if it's really possible to do a tail call.
1822     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1823                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1824                                                    Outs, OutVals, Ins, DAG);
1825     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1826       report_fatal_error("failed to perform tail call elimination on a call "
1827                          "site marked musttail");
1828     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1829     // detected sibcalls.
1830     if (isTailCall) {
1831       ++NumTailCalls;
1832       isSibCall = true;
1833     }
1834   }
1835 
1836   // Analyze operands of the call, assigning locations to each operand.
1837   SmallVector<CCValAssign, 16> ArgLocs;
1838   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1839                  *DAG.getContext());
1840   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1841 
1842   // Get a count of how many bytes are to be pushed on the stack.
1843   unsigned NumBytes = CCInfo.getNextStackOffset();
1844 
1845   // For tail calls, memory operands are available in our caller's stack.
1846   if (isSibCall)
1847     NumBytes = 0;
1848 
1849   // Adjust the stack pointer for the new arguments...
1850   // These operations are automatically eliminated by the prolog/epilog pass
1851   if (!isSibCall)
1852     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1853 
1854   SDValue StackPtr =
1855       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1856 
1857   RegsToPassVector RegsToPass;
1858   SmallVector<SDValue, 8> MemOpChains;
1859 
1860   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1861   // of tail call optimization, arguments are handled later.
1862   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1863        i != e;
1864        ++i, ++realArgIdx) {
1865     CCValAssign &VA = ArgLocs[i];
1866     SDValue Arg = OutVals[realArgIdx];
1867     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1868     bool isByVal = Flags.isByVal();
1869 
1870     // Promote the value if needed.
1871     switch (VA.getLocInfo()) {
1872     default: llvm_unreachable("Unknown loc info!");
1873     case CCValAssign::Full: break;
1874     case CCValAssign::SExt:
1875       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1876       break;
1877     case CCValAssign::ZExt:
1878       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1879       break;
1880     case CCValAssign::AExt:
1881       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1882       break;
1883     case CCValAssign::BCvt:
1884       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1885       break;
1886     }
1887 
1888     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1889     if (VA.needsCustom()) {
1890       if (VA.getLocVT() == MVT::v2f64) {
1891         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1892                                   DAG.getConstant(0, dl, MVT::i32));
1893         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1894                                   DAG.getConstant(1, dl, MVT::i32));
1895 
1896         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1897                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1898 
1899         VA = ArgLocs[++i]; // skip ahead to next loc
1900         if (VA.isRegLoc()) {
1901           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1902                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1903         } else {
1904           assert(VA.isMemLoc());
1905 
1906           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1907                                                  dl, DAG, VA, Flags));
1908         }
1909       } else {
1910         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1911                          StackPtr, MemOpChains, Flags);
1912       }
1913     } else if (VA.isRegLoc()) {
1914       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1915           Outs[0].VT == MVT::i32) {
1916         assert(VA.getLocVT() == MVT::i32 &&
1917                "unexpected calling convention register assignment");
1918         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1919                "unexpected use of 'returned'");
1920         isThisReturn = true;
1921       }
1922       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1923     } else if (isByVal) {
1924       assert(VA.isMemLoc());
1925       unsigned offset = 0;
1926 
1927       // True if this byval aggregate will be split between registers
1928       // and memory.
1929       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1930       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1931 
1932       if (CurByValIdx < ByValArgsCount) {
1933 
1934         unsigned RegBegin, RegEnd;
1935         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1936 
1937         EVT PtrVT =
1938             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1939         unsigned int i, j;
1940         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1941           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1942           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1943           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1944                                      MachinePointerInfo(),
1945                                      DAG.InferPtrAlignment(AddArg));
1946           MemOpChains.push_back(Load.getValue(1));
1947           RegsToPass.push_back(std::make_pair(j, Load));
1948         }
1949 
1950         // If parameter size outsides register area, "offset" value
1951         // helps us to calculate stack slot for remained part properly.
1952         offset = RegEnd - RegBegin;
1953 
1954         CCInfo.nextInRegsParam();
1955       }
1956 
1957       if (Flags.getByValSize() > 4*offset) {
1958         auto PtrVT = getPointerTy(DAG.getDataLayout());
1959         unsigned LocMemOffset = VA.getLocMemOffset();
1960         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1961         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1962         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1963         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1964         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1965                                            MVT::i32);
1966         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1967                                             MVT::i32);
1968 
1969         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1970         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1971         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1972                                           Ops));
1973       }
1974     } else if (!isSibCall) {
1975       assert(VA.isMemLoc());
1976 
1977       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1978                                              dl, DAG, VA, Flags));
1979     }
1980   }
1981 
1982   if (!MemOpChains.empty())
1983     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1984 
1985   // Build a sequence of copy-to-reg nodes chained together with token chain
1986   // and flag operands which copy the outgoing args into the appropriate regs.
1987   SDValue InFlag;
1988   // Tail call byval lowering might overwrite argument registers so in case of
1989   // tail call optimization the copies to registers are lowered later.
1990   if (!isTailCall)
1991     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1992       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1993                                RegsToPass[i].second, InFlag);
1994       InFlag = Chain.getValue(1);
1995     }
1996 
1997   // For tail calls lower the arguments to the 'real' stack slot.
1998   if (isTailCall) {
1999     // Force all the incoming stack arguments to be loaded from the stack
2000     // before any new outgoing arguments are stored to the stack, because the
2001     // outgoing stack slots may alias the incoming argument stack slots, and
2002     // the alias isn't otherwise explicit. This is slightly more conservative
2003     // than necessary, because it means that each store effectively depends
2004     // on every argument instead of just those arguments it would clobber.
2005 
2006     // Do not flag preceding copytoreg stuff together with the following stuff.
2007     InFlag = SDValue();
2008     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2009       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2010                                RegsToPass[i].second, InFlag);
2011       InFlag = Chain.getValue(1);
2012     }
2013     InFlag = SDValue();
2014   }
2015 
2016   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2017   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2018   // node so that legalize doesn't hack it.
2019   bool isDirect = false;
2020 
2021   const TargetMachine &TM = getTargetMachine();
2022   const Module *Mod = MF.getFunction().getParent();
2023   const GlobalValue *GV = nullptr;
2024   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2025     GV = G->getGlobal();
2026   bool isStub =
2027       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2028 
2029   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2030   bool isLocalARMFunc = false;
2031   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2032   auto PtrVt = getPointerTy(DAG.getDataLayout());
2033 
2034   if (Subtarget->genLongCalls()) {
2035     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2036            "long-calls codegen is not position independent!");
2037     // Handle a global address or an external symbol. If it's not one of
2038     // those, the target's already in a register, so we don't need to do
2039     // anything extra.
2040     if (isa<GlobalAddressSDNode>(Callee)) {
2041       // Create a constant pool entry for the callee address
2042       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2043       ARMConstantPoolValue *CPV =
2044         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2045 
2046       // Get the address of the callee into a register
2047       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2048       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2049       Callee = DAG.getLoad(
2050           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2051           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2052     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2053       const char *Sym = S->getSymbol();
2054 
2055       // Create a constant pool entry for the callee address
2056       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2057       ARMConstantPoolValue *CPV =
2058         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2059                                       ARMPCLabelIndex, 0);
2060       // Get the address of the callee into a register
2061       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2062       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2063       Callee = DAG.getLoad(
2064           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2065           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2066     }
2067   } else if (isa<GlobalAddressSDNode>(Callee)) {
2068     // If we're optimizing for minimum size and the function is called three or
2069     // more times in this block, we can improve codesize by calling indirectly
2070     // as BLXr has a 16-bit encoding.
2071     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2072     auto *BB = CLI.CS.getParent();
2073     bool PreferIndirect =
2074         Subtarget->isThumb() && Subtarget->optForMinSize() &&
2075         count_if(GV->users(), [&BB](const User *U) {
2076           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2077         }) > 2;
2078 
2079     if (!PreferIndirect) {
2080       isDirect = true;
2081       bool isDef = GV->isStrongDefinitionForLinker();
2082 
2083       // ARM call to a local ARM function is predicable.
2084       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2085       // tBX takes a register source operand.
2086       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2087         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2088         Callee = DAG.getNode(
2089             ARMISD::WrapperPIC, dl, PtrVt,
2090             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2091         Callee = DAG.getLoad(
2092             PtrVt, dl, DAG.getEntryNode(), Callee,
2093             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2094             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2095                                      MachineMemOperand::MOInvariant);
2096       } else if (Subtarget->isTargetCOFF()) {
2097         assert(Subtarget->isTargetWindows() &&
2098                "Windows is the only supported COFF target");
2099         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2100                                    ? ARMII::MO_DLLIMPORT
2101                                    : ARMII::MO_NO_FLAG;
2102         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2103                                             TargetFlags);
2104         if (GV->hasDLLImportStorageClass())
2105           Callee =
2106               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2107                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2108                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2109       } else {
2110         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2111       }
2112     }
2113   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2114     isDirect = true;
2115     // tBX takes a register source operand.
2116     const char *Sym = S->getSymbol();
2117     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2118       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2119       ARMConstantPoolValue *CPV =
2120         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2121                                       ARMPCLabelIndex, 4);
2122       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2123       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2124       Callee = DAG.getLoad(
2125           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2126           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2127       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2128       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2129     } else {
2130       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2131     }
2132   }
2133 
2134   // FIXME: handle tail calls differently.
2135   unsigned CallOpc;
2136   if (Subtarget->isThumb()) {
2137     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2138       CallOpc = ARMISD::CALL_NOLINK;
2139     else
2140       CallOpc = ARMISD::CALL;
2141   } else {
2142     if (!isDirect && !Subtarget->hasV5TOps())
2143       CallOpc = ARMISD::CALL_NOLINK;
2144     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2145              // Emit regular call when code size is the priority
2146              !Subtarget->optForMinSize())
2147       // "mov lr, pc; b _foo" to avoid confusing the RSP
2148       CallOpc = ARMISD::CALL_NOLINK;
2149     else
2150       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2151   }
2152 
2153   std::vector<SDValue> Ops;
2154   Ops.push_back(Chain);
2155   Ops.push_back(Callee);
2156 
2157   // Add argument registers to the end of the list so that they are known live
2158   // into the call.
2159   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2160     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2161                                   RegsToPass[i].second.getValueType()));
2162 
2163   // Add a register mask operand representing the call-preserved registers.
2164   if (!isTailCall) {
2165     const uint32_t *Mask;
2166     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2167     if (isThisReturn) {
2168       // For 'this' returns, use the R0-preserving mask if applicable
2169       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2170       if (!Mask) {
2171         // Set isThisReturn to false if the calling convention is not one that
2172         // allows 'returned' to be modeled in this way, so LowerCallResult does
2173         // not try to pass 'this' straight through
2174         isThisReturn = false;
2175         Mask = ARI->getCallPreservedMask(MF, CallConv);
2176       }
2177     } else
2178       Mask = ARI->getCallPreservedMask(MF, CallConv);
2179 
2180     assert(Mask && "Missing call preserved mask for calling convention");
2181     Ops.push_back(DAG.getRegisterMask(Mask));
2182   }
2183 
2184   if (InFlag.getNode())
2185     Ops.push_back(InFlag);
2186 
2187   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2188   if (isTailCall) {
2189     MF.getFrameInfo().setHasTailCall();
2190     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2191   }
2192 
2193   // Returns a chain and a flag for retval copy to use.
2194   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2195   InFlag = Chain.getValue(1);
2196 
2197   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2198                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2199   if (!Ins.empty())
2200     InFlag = Chain.getValue(1);
2201 
2202   // Handle result values, copying them out of physregs into vregs that we
2203   // return.
2204   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2205                          InVals, isThisReturn,
2206                          isThisReturn ? OutVals[0] : SDValue());
2207 }
2208 
2209 /// HandleByVal - Every parameter *after* a byval parameter is passed
2210 /// on the stack.  Remember the next parameter register to allocate,
2211 /// and then confiscate the rest of the parameter registers to insure
2212 /// this.
2213 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2214                                     unsigned Align) const {
2215   // Byval (as with any stack) slots are always at least 4 byte aligned.
2216   Align = std::max(Align, 4U);
2217 
2218   unsigned Reg = State->AllocateReg(GPRArgRegs);
2219   if (!Reg)
2220     return;
2221 
2222   unsigned AlignInRegs = Align / 4;
2223   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2224   for (unsigned i = 0; i < Waste; ++i)
2225     Reg = State->AllocateReg(GPRArgRegs);
2226 
2227   if (!Reg)
2228     return;
2229 
2230   unsigned Excess = 4 * (ARM::R4 - Reg);
2231 
2232   // Special case when NSAA != SP and parameter size greater than size of
2233   // all remained GPR regs. In that case we can't split parameter, we must
2234   // send it to stack. We also must set NCRN to R4, so waste all
2235   // remained registers.
2236   const unsigned NSAAOffset = State->getNextStackOffset();
2237   if (NSAAOffset != 0 && Size > Excess) {
2238     while (State->AllocateReg(GPRArgRegs))
2239       ;
2240     return;
2241   }
2242 
2243   // First register for byval parameter is the first register that wasn't
2244   // allocated before this method call, so it would be "reg".
2245   // If parameter is small enough to be saved in range [reg, r4), then
2246   // the end (first after last) register would be reg + param-size-in-regs,
2247   // else parameter would be splitted between registers and stack,
2248   // end register would be r4 in this case.
2249   unsigned ByValRegBegin = Reg;
2250   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2251   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2252   // Note, first register is allocated in the beginning of function already,
2253   // allocate remained amount of registers we need.
2254   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2255     State->AllocateReg(GPRArgRegs);
2256   // A byval parameter that is split between registers and memory needs its
2257   // size truncated here.
2258   // In the case where the entire structure fits in registers, we set the
2259   // size in memory to zero.
2260   Size = std::max<int>(Size - Excess, 0);
2261 }
2262 
2263 /// MatchingStackOffset - Return true if the given stack call argument is
2264 /// already available in the same position (relatively) of the caller's
2265 /// incoming argument stack.
2266 static
2267 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2268                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2269                          const TargetInstrInfo *TII) {
2270   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2271   int FI = std::numeric_limits<int>::max();
2272   if (Arg.getOpcode() == ISD::CopyFromReg) {
2273     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2274     if (!TargetRegisterInfo::isVirtualRegister(VR))
2275       return false;
2276     MachineInstr *Def = MRI->getVRegDef(VR);
2277     if (!Def)
2278       return false;
2279     if (!Flags.isByVal()) {
2280       if (!TII->isLoadFromStackSlot(*Def, FI))
2281         return false;
2282     } else {
2283       return false;
2284     }
2285   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2286     if (Flags.isByVal())
2287       // ByVal argument is passed in as a pointer but it's now being
2288       // dereferenced. e.g.
2289       // define @foo(%struct.X* %A) {
2290       //   tail call @bar(%struct.X* byval %A)
2291       // }
2292       return false;
2293     SDValue Ptr = Ld->getBasePtr();
2294     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2295     if (!FINode)
2296       return false;
2297     FI = FINode->getIndex();
2298   } else
2299     return false;
2300 
2301   assert(FI != std::numeric_limits<int>::max());
2302   if (!MFI.isFixedObjectIndex(FI))
2303     return false;
2304   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2305 }
2306 
2307 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2308 /// for tail call optimization. Targets which want to do tail call
2309 /// optimization should implement this function.
2310 bool
2311 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2312                                                      CallingConv::ID CalleeCC,
2313                                                      bool isVarArg,
2314                                                      bool isCalleeStructRet,
2315                                                      bool isCallerStructRet,
2316                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2317                                     const SmallVectorImpl<SDValue> &OutVals,
2318                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2319                                                      SelectionDAG& DAG) const {
2320   MachineFunction &MF = DAG.getMachineFunction();
2321   const Function &CallerF = MF.getFunction();
2322   CallingConv::ID CallerCC = CallerF.getCallingConv();
2323 
2324   assert(Subtarget->supportsTailCall());
2325 
2326   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2327   // to the call take up r0-r3. The reason is that there are no legal registers
2328   // left to hold the pointer to the function to be called.
2329   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2330       !isa<GlobalAddressSDNode>(Callee.getNode()))
2331       return false;
2332 
2333   // Look for obvious safe cases to perform tail call optimization that do not
2334   // require ABI changes. This is what gcc calls sibcall.
2335 
2336   // Exception-handling functions need a special set of instructions to indicate
2337   // a return to the hardware. Tail-calling another function would probably
2338   // break this.
2339   if (CallerF.hasFnAttribute("interrupt"))
2340     return false;
2341 
2342   // Also avoid sibcall optimization if either caller or callee uses struct
2343   // return semantics.
2344   if (isCalleeStructRet || isCallerStructRet)
2345     return false;
2346 
2347   // Externally-defined functions with weak linkage should not be
2348   // tail-called on ARM when the OS does not support dynamic
2349   // pre-emption of symbols, as the AAELF spec requires normal calls
2350   // to undefined weak functions to be replaced with a NOP or jump to the
2351   // next instruction. The behaviour of branch instructions in this
2352   // situation (as used for tail calls) is implementation-defined, so we
2353   // cannot rely on the linker replacing the tail call with a return.
2354   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2355     const GlobalValue *GV = G->getGlobal();
2356     const Triple &TT = getTargetMachine().getTargetTriple();
2357     if (GV->hasExternalWeakLinkage() &&
2358         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2359       return false;
2360   }
2361 
2362   // Check that the call results are passed in the same way.
2363   LLVMContext &C = *DAG.getContext();
2364   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2365                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2366                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2367     return false;
2368   // The callee has to preserve all registers the caller needs to preserve.
2369   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2370   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2371   if (CalleeCC != CallerCC) {
2372     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2373     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2374       return false;
2375   }
2376 
2377   // If Caller's vararg or byval argument has been split between registers and
2378   // stack, do not perform tail call, since part of the argument is in caller's
2379   // local frame.
2380   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2381   if (AFI_Caller->getArgRegsSaveSize())
2382     return false;
2383 
2384   // If the callee takes no arguments then go on to check the results of the
2385   // call.
2386   if (!Outs.empty()) {
2387     // Check if stack adjustment is needed. For now, do not do this if any
2388     // argument is passed on the stack.
2389     SmallVector<CCValAssign, 16> ArgLocs;
2390     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2391     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2392     if (CCInfo.getNextStackOffset()) {
2393       // Check if the arguments are already laid out in the right way as
2394       // the caller's fixed stack objects.
2395       MachineFrameInfo &MFI = MF.getFrameInfo();
2396       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2397       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2398       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2399            i != e;
2400            ++i, ++realArgIdx) {
2401         CCValAssign &VA = ArgLocs[i];
2402         EVT RegVT = VA.getLocVT();
2403         SDValue Arg = OutVals[realArgIdx];
2404         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2405         if (VA.getLocInfo() == CCValAssign::Indirect)
2406           return false;
2407         if (VA.needsCustom()) {
2408           // f64 and vector types are split into multiple registers or
2409           // register/stack-slot combinations.  The types will not match
2410           // the registers; give up on memory f64 refs until we figure
2411           // out what to do about this.
2412           if (!VA.isRegLoc())
2413             return false;
2414           if (!ArgLocs[++i].isRegLoc())
2415             return false;
2416           if (RegVT == MVT::v2f64) {
2417             if (!ArgLocs[++i].isRegLoc())
2418               return false;
2419             if (!ArgLocs[++i].isRegLoc())
2420               return false;
2421           }
2422         } else if (!VA.isRegLoc()) {
2423           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2424                                    MFI, MRI, TII))
2425             return false;
2426         }
2427       }
2428     }
2429 
2430     const MachineRegisterInfo &MRI = MF.getRegInfo();
2431     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2432       return false;
2433   }
2434 
2435   return true;
2436 }
2437 
2438 bool
2439 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2440                                   MachineFunction &MF, bool isVarArg,
2441                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2442                                   LLVMContext &Context) const {
2443   SmallVector<CCValAssign, 16> RVLocs;
2444   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2445   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2446 }
2447 
2448 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2449                                     const SDLoc &DL, SelectionDAG &DAG) {
2450   const MachineFunction &MF = DAG.getMachineFunction();
2451   const Function &F = MF.getFunction();
2452 
2453   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2454 
2455   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2456   // version of the "preferred return address". These offsets affect the return
2457   // instruction if this is a return from PL1 without hypervisor extensions.
2458   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2459   //    SWI:     0      "subs pc, lr, #0"
2460   //    ABORT:   +4     "subs pc, lr, #4"
2461   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2462   // UNDEF varies depending on where the exception came from ARM or Thumb
2463   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2464 
2465   int64_t LROffset;
2466   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2467       IntKind == "ABORT")
2468     LROffset = 4;
2469   else if (IntKind == "SWI" || IntKind == "UNDEF")
2470     LROffset = 0;
2471   else
2472     report_fatal_error("Unsupported interrupt attribute. If present, value "
2473                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2474 
2475   RetOps.insert(RetOps.begin() + 1,
2476                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2477 
2478   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2479 }
2480 
2481 SDValue
2482 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2483                                bool isVarArg,
2484                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2485                                const SmallVectorImpl<SDValue> &OutVals,
2486                                const SDLoc &dl, SelectionDAG &DAG) const {
2487   // CCValAssign - represent the assignment of the return value to a location.
2488   SmallVector<CCValAssign, 16> RVLocs;
2489 
2490   // CCState - Info about the registers and stack slots.
2491   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2492                  *DAG.getContext());
2493 
2494   // Analyze outgoing return values.
2495   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2496 
2497   SDValue Flag;
2498   SmallVector<SDValue, 4> RetOps;
2499   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2500   bool isLittleEndian = Subtarget->isLittle();
2501 
2502   MachineFunction &MF = DAG.getMachineFunction();
2503   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2504   AFI->setReturnRegsCount(RVLocs.size());
2505 
2506   // Copy the result values into the output registers.
2507   for (unsigned i = 0, realRVLocIdx = 0;
2508        i != RVLocs.size();
2509        ++i, ++realRVLocIdx) {
2510     CCValAssign &VA = RVLocs[i];
2511     assert(VA.isRegLoc() && "Can only return in registers!");
2512 
2513     SDValue Arg = OutVals[realRVLocIdx];
2514     bool ReturnF16 = false;
2515 
2516     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2517       // Half-precision return values can be returned like this:
2518       //
2519       // t11 f16 = fadd ...
2520       // t12: i16 = bitcast t11
2521       //   t13: i32 = zero_extend t12
2522       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2523       //
2524       // to avoid code generation for bitcasts, we simply set Arg to the node
2525       // that produces the f16 value, t11 in this case.
2526       //
2527       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2528         SDValue ZE = Arg.getOperand(0);
2529         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2530           SDValue BC = ZE.getOperand(0);
2531           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2532             Arg = BC.getOperand(0);
2533             ReturnF16 = true;
2534           }
2535         }
2536       }
2537     }
2538 
2539     switch (VA.getLocInfo()) {
2540     default: llvm_unreachable("Unknown loc info!");
2541     case CCValAssign::Full: break;
2542     case CCValAssign::BCvt:
2543       if (!ReturnF16)
2544         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2545       break;
2546     }
2547 
2548     if (VA.needsCustom()) {
2549       if (VA.getLocVT() == MVT::v2f64) {
2550         // Extract the first half and return it in two registers.
2551         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2552                                    DAG.getConstant(0, dl, MVT::i32));
2553         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2554                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2555 
2556         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2557                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2558                                  Flag);
2559         Flag = Chain.getValue(1);
2560         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2561         VA = RVLocs[++i]; // skip ahead to next loc
2562         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2563                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2564                                  Flag);
2565         Flag = Chain.getValue(1);
2566         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2567         VA = RVLocs[++i]; // skip ahead to next loc
2568 
2569         // Extract the 2nd half and fall through to handle it as an f64 value.
2570         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2571                           DAG.getConstant(1, dl, MVT::i32));
2572       }
2573       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2574       // available.
2575       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2576                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2577       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2578                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2579                                Flag);
2580       Flag = Chain.getValue(1);
2581       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2582       VA = RVLocs[++i]; // skip ahead to next loc
2583       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2584                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2585                                Flag);
2586     } else
2587       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2588 
2589     // Guarantee that all emitted copies are
2590     // stuck together, avoiding something bad.
2591     Flag = Chain.getValue(1);
2592     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2593                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2594   }
2595   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2596   const MCPhysReg *I =
2597       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2598   if (I) {
2599     for (; *I; ++I) {
2600       if (ARM::GPRRegClass.contains(*I))
2601         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2602       else if (ARM::DPRRegClass.contains(*I))
2603         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2604       else
2605         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2606     }
2607   }
2608 
2609   // Update chain and glue.
2610   RetOps[0] = Chain;
2611   if (Flag.getNode())
2612     RetOps.push_back(Flag);
2613 
2614   // CPUs which aren't M-class use a special sequence to return from
2615   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2616   // though we use "subs pc, lr, #N").
2617   //
2618   // M-class CPUs actually use a normal return sequence with a special
2619   // (hardware-provided) value in LR, so the normal code path works.
2620   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2621       !Subtarget->isMClass()) {
2622     if (Subtarget->isThumb1Only())
2623       report_fatal_error("interrupt attribute is not supported in Thumb1");
2624     return LowerInterruptReturn(RetOps, dl, DAG);
2625   }
2626 
2627   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2628 }
2629 
2630 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2631   if (N->getNumValues() != 1)
2632     return false;
2633   if (!N->hasNUsesOfValue(1, 0))
2634     return false;
2635 
2636   SDValue TCChain = Chain;
2637   SDNode *Copy = *N->use_begin();
2638   if (Copy->getOpcode() == ISD::CopyToReg) {
2639     // If the copy has a glue operand, we conservatively assume it isn't safe to
2640     // perform a tail call.
2641     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2642       return false;
2643     TCChain = Copy->getOperand(0);
2644   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2645     SDNode *VMov = Copy;
2646     // f64 returned in a pair of GPRs.
2647     SmallPtrSet<SDNode*, 2> Copies;
2648     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2649          UI != UE; ++UI) {
2650       if (UI->getOpcode() != ISD::CopyToReg)
2651         return false;
2652       Copies.insert(*UI);
2653     }
2654     if (Copies.size() > 2)
2655       return false;
2656 
2657     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2658          UI != UE; ++UI) {
2659       SDValue UseChain = UI->getOperand(0);
2660       if (Copies.count(UseChain.getNode()))
2661         // Second CopyToReg
2662         Copy = *UI;
2663       else {
2664         // We are at the top of this chain.
2665         // If the copy has a glue operand, we conservatively assume it
2666         // isn't safe to perform a tail call.
2667         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2668           return false;
2669         // First CopyToReg
2670         TCChain = UseChain;
2671       }
2672     }
2673   } else if (Copy->getOpcode() == ISD::BITCAST) {
2674     // f32 returned in a single GPR.
2675     if (!Copy->hasOneUse())
2676       return false;
2677     Copy = *Copy->use_begin();
2678     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2679       return false;
2680     // If the copy has a glue operand, we conservatively assume it isn't safe to
2681     // perform a tail call.
2682     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2683       return false;
2684     TCChain = Copy->getOperand(0);
2685   } else {
2686     return false;
2687   }
2688 
2689   bool HasRet = false;
2690   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2691        UI != UE; ++UI) {
2692     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2693         UI->getOpcode() != ARMISD::INTRET_FLAG)
2694       return false;
2695     HasRet = true;
2696   }
2697 
2698   if (!HasRet)
2699     return false;
2700 
2701   Chain = TCChain;
2702   return true;
2703 }
2704 
2705 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2706   if (!Subtarget->supportsTailCall())
2707     return false;
2708 
2709   auto Attr =
2710       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2711   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2712     return false;
2713 
2714   return true;
2715 }
2716 
2717 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2718 // and pass the lower and high parts through.
2719 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2720   SDLoc DL(Op);
2721   SDValue WriteValue = Op->getOperand(2);
2722 
2723   // This function is only supposed to be called for i64 type argument.
2724   assert(WriteValue.getValueType() == MVT::i64
2725           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2726 
2727   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2728                            DAG.getConstant(0, DL, MVT::i32));
2729   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2730                            DAG.getConstant(1, DL, MVT::i32));
2731   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2732   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2733 }
2734 
2735 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2736 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2737 // one of the above mentioned nodes. It has to be wrapped because otherwise
2738 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2739 // be used to form addressing mode. These wrapped nodes will be selected
2740 // into MOVi.
2741 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2742                                              SelectionDAG &DAG) const {
2743   EVT PtrVT = Op.getValueType();
2744   // FIXME there is no actual debug info here
2745   SDLoc dl(Op);
2746   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2747   SDValue Res;
2748 
2749   // When generating execute-only code Constant Pools must be promoted to the
2750   // global data section. It's a bit ugly that we can't share them across basic
2751   // blocks, but this way we guarantee that execute-only behaves correct with
2752   // position-independent addressing modes.
2753   if (Subtarget->genExecuteOnly()) {
2754     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2755     auto T = const_cast<Type*>(CP->getType());
2756     auto C = const_cast<Constant*>(CP->getConstVal());
2757     auto M = const_cast<Module*>(DAG.getMachineFunction().
2758                                  getFunction().getParent());
2759     auto GV = new GlobalVariable(
2760                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2761                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2762                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2763                     Twine(AFI->createPICLabelUId())
2764                   );
2765     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2766                                             dl, PtrVT);
2767     return LowerGlobalAddress(GA, DAG);
2768   }
2769 
2770   if (CP->isMachineConstantPoolEntry())
2771     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2772                                     CP->getAlignment());
2773   else
2774     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2775                                     CP->getAlignment());
2776   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2777 }
2778 
2779 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2780   return MachineJumpTableInfo::EK_Inline;
2781 }
2782 
2783 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2784                                              SelectionDAG &DAG) const {
2785   MachineFunction &MF = DAG.getMachineFunction();
2786   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2787   unsigned ARMPCLabelIndex = 0;
2788   SDLoc DL(Op);
2789   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2790   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2791   SDValue CPAddr;
2792   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2793   if (!IsPositionIndependent) {
2794     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2795   } else {
2796     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2797     ARMPCLabelIndex = AFI->createPICLabelUId();
2798     ARMConstantPoolValue *CPV =
2799       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2800                                       ARMCP::CPBlockAddress, PCAdj);
2801     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2802   }
2803   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2804   SDValue Result = DAG.getLoad(
2805       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2806       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2807   if (!IsPositionIndependent)
2808     return Result;
2809   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2810   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2811 }
2812 
2813 /// Convert a TLS address reference into the correct sequence of loads
2814 /// and calls to compute the variable's address for Darwin, and return an
2815 /// SDValue containing the final node.
2816 
2817 /// Darwin only has one TLS scheme which must be capable of dealing with the
2818 /// fully general situation, in the worst case. This means:
2819 ///     + "extern __thread" declaration.
2820 ///     + Defined in a possibly unknown dynamic library.
2821 ///
2822 /// The general system is that each __thread variable has a [3 x i32] descriptor
2823 /// which contains information used by the runtime to calculate the address. The
2824 /// only part of this the compiler needs to know about is the first word, which
2825 /// contains a function pointer that must be called with the address of the
2826 /// entire descriptor in "r0".
2827 ///
2828 /// Since this descriptor may be in a different unit, in general access must
2829 /// proceed along the usual ARM rules. A common sequence to produce is:
2830 ///
2831 ///     movw rT1, :lower16:_var$non_lazy_ptr
2832 ///     movt rT1, :upper16:_var$non_lazy_ptr
2833 ///     ldr r0, [rT1]
2834 ///     ldr rT2, [r0]
2835 ///     blx rT2
2836 ///     [...address now in r0...]
2837 SDValue
2838 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2839                                                SelectionDAG &DAG) const {
2840   assert(Subtarget->isTargetDarwin() &&
2841          "This function expects a Darwin target");
2842   SDLoc DL(Op);
2843 
2844   // First step is to get the address of the actua global symbol. This is where
2845   // the TLS descriptor lives.
2846   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2847 
2848   // The first entry in the descriptor is a function pointer that we must call
2849   // to obtain the address of the variable.
2850   SDValue Chain = DAG.getEntryNode();
2851   SDValue FuncTLVGet = DAG.getLoad(
2852       MVT::i32, DL, Chain, DescAddr,
2853       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2854       /* Alignment = */ 4,
2855       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2856           MachineMemOperand::MOInvariant);
2857   Chain = FuncTLVGet.getValue(1);
2858 
2859   MachineFunction &F = DAG.getMachineFunction();
2860   MachineFrameInfo &MFI = F.getFrameInfo();
2861   MFI.setAdjustsStack(true);
2862 
2863   // TLS calls preserve all registers except those that absolutely must be
2864   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2865   // silly).
2866   auto TRI =
2867       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2868   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2869   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2870 
2871   // Finally, we can make the call. This is just a degenerate version of a
2872   // normal AArch64 call node: r0 takes the address of the descriptor, and
2873   // returns the address of the variable in this thread.
2874   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2875   Chain =
2876       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2877                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2878                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2879   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2880 }
2881 
2882 SDValue
2883 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2884                                                 SelectionDAG &DAG) const {
2885   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2886 
2887   SDValue Chain = DAG.getEntryNode();
2888   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2889   SDLoc DL(Op);
2890 
2891   // Load the current TEB (thread environment block)
2892   SDValue Ops[] = {Chain,
2893                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2894                    DAG.getConstant(15, DL, MVT::i32),
2895                    DAG.getConstant(0, DL, MVT::i32),
2896                    DAG.getConstant(13, DL, MVT::i32),
2897                    DAG.getConstant(0, DL, MVT::i32),
2898                    DAG.getConstant(2, DL, MVT::i32)};
2899   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2900                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2901 
2902   SDValue TEB = CurrentTEB.getValue(0);
2903   Chain = CurrentTEB.getValue(1);
2904 
2905   // Load the ThreadLocalStoragePointer from the TEB
2906   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2907   SDValue TLSArray =
2908       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2909   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2910 
2911   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2912   // offset into the TLSArray.
2913 
2914   // Load the TLS index from the C runtime
2915   SDValue TLSIndex =
2916       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2917   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2918   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2919 
2920   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2921                               DAG.getConstant(2, DL, MVT::i32));
2922   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2923                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2924                             MachinePointerInfo());
2925 
2926   // Get the offset of the start of the .tls section (section base)
2927   const auto *GA = cast<GlobalAddressSDNode>(Op);
2928   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2929   SDValue Offset = DAG.getLoad(
2930       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2931                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2932       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2933 
2934   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2935 }
2936 
2937 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2938 SDValue
2939 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2940                                                  SelectionDAG &DAG) const {
2941   SDLoc dl(GA);
2942   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2943   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2944   MachineFunction &MF = DAG.getMachineFunction();
2945   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2946   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2947   ARMConstantPoolValue *CPV =
2948     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2949                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2950   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2951   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2952   Argument = DAG.getLoad(
2953       PtrVT, dl, DAG.getEntryNode(), Argument,
2954       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2955   SDValue Chain = Argument.getValue(1);
2956 
2957   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2958   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2959 
2960   // call __tls_get_addr.
2961   ArgListTy Args;
2962   ArgListEntry Entry;
2963   Entry.Node = Argument;
2964   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2965   Args.push_back(Entry);
2966 
2967   // FIXME: is there useful debug info available here?
2968   TargetLowering::CallLoweringInfo CLI(DAG);
2969   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2970       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2971       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2972 
2973   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2974   return CallResult.first;
2975 }
2976 
2977 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2978 // "local exec" model.
2979 SDValue
2980 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2981                                         SelectionDAG &DAG,
2982                                         TLSModel::Model model) const {
2983   const GlobalValue *GV = GA->getGlobal();
2984   SDLoc dl(GA);
2985   SDValue Offset;
2986   SDValue Chain = DAG.getEntryNode();
2987   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2988   // Get the Thread Pointer
2989   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2990 
2991   if (model == TLSModel::InitialExec) {
2992     MachineFunction &MF = DAG.getMachineFunction();
2993     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2995     // Initial exec model.
2996     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2997     ARMConstantPoolValue *CPV =
2998       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2999                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3000                                       true);
3001     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3002     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3003     Offset = DAG.getLoad(
3004         PtrVT, dl, Chain, Offset,
3005         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3006     Chain = Offset.getValue(1);
3007 
3008     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3009     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3010 
3011     Offset = DAG.getLoad(
3012         PtrVT, dl, Chain, Offset,
3013         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3014   } else {
3015     // local exec model
3016     assert(model == TLSModel::LocalExec);
3017     ARMConstantPoolValue *CPV =
3018       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3019     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3020     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3021     Offset = DAG.getLoad(
3022         PtrVT, dl, Chain, Offset,
3023         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3024   }
3025 
3026   // The address of the thread local variable is the add of the thread
3027   // pointer with the offset of the variable.
3028   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3029 }
3030 
3031 SDValue
3032 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3033   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3034   if (DAG.getTarget().useEmulatedTLS())
3035     return LowerToTLSEmulatedModel(GA, DAG);
3036 
3037   if (Subtarget->isTargetDarwin())
3038     return LowerGlobalTLSAddressDarwin(Op, DAG);
3039 
3040   if (Subtarget->isTargetWindows())
3041     return LowerGlobalTLSAddressWindows(Op, DAG);
3042 
3043   // TODO: implement the "local dynamic" model
3044   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3045   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3046 
3047   switch (model) {
3048     case TLSModel::GeneralDynamic:
3049     case TLSModel::LocalDynamic:
3050       return LowerToTLSGeneralDynamicModel(GA, DAG);
3051     case TLSModel::InitialExec:
3052     case TLSModel::LocalExec:
3053       return LowerToTLSExecModels(GA, DAG, model);
3054   }
3055   llvm_unreachable("bogus TLS model");
3056 }
3057 
3058 /// Return true if all users of V are within function F, looking through
3059 /// ConstantExprs.
3060 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3061   SmallVector<const User*,4> Worklist;
3062   for (auto *U : V->users())
3063     Worklist.push_back(U);
3064   while (!Worklist.empty()) {
3065     auto *U = Worklist.pop_back_val();
3066     if (isa<ConstantExpr>(U)) {
3067       for (auto *UU : U->users())
3068         Worklist.push_back(UU);
3069       continue;
3070     }
3071 
3072     auto *I = dyn_cast<Instruction>(U);
3073     if (!I || I->getParent()->getParent() != F)
3074       return false;
3075   }
3076   return true;
3077 }
3078 
3079 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3080                                      const GlobalValue *GV, SelectionDAG &DAG,
3081                                      EVT PtrVT, const SDLoc &dl) {
3082   // If we're creating a pool entry for a constant global with unnamed address,
3083   // and the global is small enough, we can emit it inline into the constant pool
3084   // to save ourselves an indirection.
3085   //
3086   // This is a win if the constant is only used in one function (so it doesn't
3087   // need to be duplicated) or duplicating the constant wouldn't increase code
3088   // size (implying the constant is no larger than 4 bytes).
3089   const Function &F = DAG.getMachineFunction().getFunction();
3090 
3091   // We rely on this decision to inline being idemopotent and unrelated to the
3092   // use-site. We know that if we inline a variable at one use site, we'll
3093   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3094   // doesn't know about this optimization, so bail out if it's enabled else
3095   // we could decide to inline here (and thus never emit the GV) but require
3096   // the GV from fast-isel generated code.
3097   if (!EnableConstpoolPromotion ||
3098       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3099       return SDValue();
3100 
3101   auto *GVar = dyn_cast<GlobalVariable>(GV);
3102   if (!GVar || !GVar->hasInitializer() ||
3103       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3104       !GVar->hasLocalLinkage())
3105     return SDValue();
3106 
3107   // If we inline a value that contains relocations, we move the relocations
3108   // from .data to .text. This is not allowed in position-independent code.
3109   auto *Init = GVar->getInitializer();
3110   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3111       Init->needsRelocation())
3112     return SDValue();
3113 
3114   // The constant islands pass can only really deal with alignment requests
3115   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3116   // any type wanting greater alignment requirements than 4 bytes. We also
3117   // can only promote constants that are multiples of 4 bytes in size or
3118   // are paddable to a multiple of 4. Currently we only try and pad constants
3119   // that are strings for simplicity.
3120   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3121   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3122   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3123   unsigned RequiredPadding = 4 - (Size % 4);
3124   bool PaddingPossible =
3125     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3126   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3127       Size == 0)
3128     return SDValue();
3129 
3130   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3131   MachineFunction &MF = DAG.getMachineFunction();
3132   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3133 
3134   // We can't bloat the constant pool too much, else the ConstantIslands pass
3135   // may fail to converge. If we haven't promoted this global yet (it may have
3136   // multiple uses), and promoting it would increase the constant pool size (Sz
3137   // > 4), ensure we have space to do so up to MaxTotal.
3138   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3139     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3140         ConstpoolPromotionMaxTotal)
3141       return SDValue();
3142 
3143   // This is only valid if all users are in a single function; we can't clone
3144   // the constant in general. The LLVM IR unnamed_addr allows merging
3145   // constants, but not cloning them.
3146   //
3147   // We could potentially allow cloning if we could prove all uses of the
3148   // constant in the current function don't care about the address, like
3149   // printf format strings. But that isn't implemented for now.
3150   if (!allUsersAreInFunction(GVar, &F))
3151     return SDValue();
3152 
3153   // We're going to inline this global. Pad it out if needed.
3154   if (RequiredPadding != 4) {
3155     StringRef S = CDAInit->getAsString();
3156 
3157     SmallVector<uint8_t,16> V(S.size());
3158     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3159     while (RequiredPadding--)
3160       V.push_back(0);
3161     Init = ConstantDataArray::get(*DAG.getContext(), V);
3162   }
3163 
3164   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3165   SDValue CPAddr =
3166     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3167   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3168     AFI->markGlobalAsPromotedToConstantPool(GVar);
3169     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3170                                       PaddedSize - 4);
3171   }
3172   ++NumConstpoolPromoted;
3173   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3174 }
3175 
3176 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3177   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3178     if (!(GV = GA->getBaseObject()))
3179       return false;
3180   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3181     return V->isConstant();
3182   return isa<Function>(GV);
3183 }
3184 
3185 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3186                                               SelectionDAG &DAG) const {
3187   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3188   default: llvm_unreachable("unknown object format");
3189   case Triple::COFF:
3190     return LowerGlobalAddressWindows(Op, DAG);
3191   case Triple::ELF:
3192     return LowerGlobalAddressELF(Op, DAG);
3193   case Triple::MachO:
3194     return LowerGlobalAddressDarwin(Op, DAG);
3195   }
3196 }
3197 
3198 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3199                                                  SelectionDAG &DAG) const {
3200   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3201   SDLoc dl(Op);
3202   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3203   const TargetMachine &TM = getTargetMachine();
3204   bool IsRO = isReadOnly(GV);
3205 
3206   // promoteToConstantPool only if not generating XO text section
3207   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3208     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3209       return V;
3210 
3211   if (isPositionIndependent()) {
3212     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3213     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3214                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3215     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3216     if (UseGOT_PREL)
3217       Result =
3218           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3219                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3220     return Result;
3221   } else if (Subtarget->isROPI() && IsRO) {
3222     // PC-relative.
3223     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3224     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3225     return Result;
3226   } else if (Subtarget->isRWPI() && !IsRO) {
3227     // SB-relative.
3228     SDValue RelAddr;
3229     if (Subtarget->useMovt()) {
3230       ++NumMovwMovt;
3231       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3232       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3233     } else { // use literal pool for address constant
3234       ARMConstantPoolValue *CPV =
3235         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3236       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3237       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3238       RelAddr = DAG.getLoad(
3239           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3240           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3241     }
3242     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3243     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3244     return Result;
3245   }
3246 
3247   // If we have T2 ops, we can materialize the address directly via movt/movw
3248   // pair. This is always cheaper.
3249   if (Subtarget->useMovt()) {
3250     ++NumMovwMovt;
3251     // FIXME: Once remat is capable of dealing with instructions with register
3252     // operands, expand this into two nodes.
3253     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3254                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3255   } else {
3256     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3257     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3258     return DAG.getLoad(
3259         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3260         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3261   }
3262 }
3263 
3264 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3265                                                     SelectionDAG &DAG) const {
3266   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3267          "ROPI/RWPI not currently supported for Darwin");
3268   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3269   SDLoc dl(Op);
3270   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3271 
3272   if (Subtarget->useMovt())
3273     ++NumMovwMovt;
3274 
3275   // FIXME: Once remat is capable of dealing with instructions with register
3276   // operands, expand this into multiple nodes
3277   unsigned Wrapper =
3278       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3279 
3280   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3281   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3282 
3283   if (Subtarget->isGVIndirectSymbol(GV))
3284     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3285                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3286   return Result;
3287 }
3288 
3289 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3290                                                      SelectionDAG &DAG) const {
3291   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3292   assert(Subtarget->useMovt() &&
3293          "Windows on ARM expects to use movw/movt");
3294   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3295          "ROPI/RWPI not currently supported for Windows");
3296 
3297   const TargetMachine &TM = getTargetMachine();
3298   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3299   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3300   if (GV->hasDLLImportStorageClass())
3301     TargetFlags = ARMII::MO_DLLIMPORT;
3302   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3303     TargetFlags = ARMII::MO_COFFSTUB;
3304   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3305   SDValue Result;
3306   SDLoc DL(Op);
3307 
3308   ++NumMovwMovt;
3309 
3310   // FIXME: Once remat is capable of dealing with instructions with register
3311   // operands, expand this into two nodes.
3312   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3313                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3314                                                   TargetFlags));
3315   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3316     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3317                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3318   return Result;
3319 }
3320 
3321 SDValue
3322 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3323   SDLoc dl(Op);
3324   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3325   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3326                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3327                      Op.getOperand(1), Val);
3328 }
3329 
3330 SDValue
3331 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3332   SDLoc dl(Op);
3333   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3334                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3335 }
3336 
3337 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3338                                                       SelectionDAG &DAG) const {
3339   SDLoc dl(Op);
3340   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3341                      Op.getOperand(0));
3342 }
3343 
3344 SDValue
3345 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3346                                           const ARMSubtarget *Subtarget) const {
3347   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3348   SDLoc dl(Op);
3349   switch (IntNo) {
3350   default: return SDValue();    // Don't custom lower most intrinsics.
3351   case Intrinsic::thread_pointer: {
3352     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3353     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3354   }
3355   case Intrinsic::eh_sjlj_lsda: {
3356     MachineFunction &MF = DAG.getMachineFunction();
3357     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3358     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3359     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3360     SDValue CPAddr;
3361     bool IsPositionIndependent = isPositionIndependent();
3362     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3363     ARMConstantPoolValue *CPV =
3364       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3365                                       ARMCP::CPLSDA, PCAdj);
3366     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3367     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3368     SDValue Result = DAG.getLoad(
3369         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3370         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3371 
3372     if (IsPositionIndependent) {
3373       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3374       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3375     }
3376     return Result;
3377   }
3378   case Intrinsic::arm_neon_vabs:
3379     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3380                         Op.getOperand(1));
3381   case Intrinsic::arm_neon_vmulls:
3382   case Intrinsic::arm_neon_vmullu: {
3383     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3384       ? ARMISD::VMULLs : ARMISD::VMULLu;
3385     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3386                        Op.getOperand(1), Op.getOperand(2));
3387   }
3388   case Intrinsic::arm_neon_vminnm:
3389   case Intrinsic::arm_neon_vmaxnm: {
3390     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3391       ? ISD::FMINNUM : ISD::FMAXNUM;
3392     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3393                        Op.getOperand(1), Op.getOperand(2));
3394   }
3395   case Intrinsic::arm_neon_vminu:
3396   case Intrinsic::arm_neon_vmaxu: {
3397     if (Op.getValueType().isFloatingPoint())
3398       return SDValue();
3399     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3400       ? ISD::UMIN : ISD::UMAX;
3401     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3402                          Op.getOperand(1), Op.getOperand(2));
3403   }
3404   case Intrinsic::arm_neon_vmins:
3405   case Intrinsic::arm_neon_vmaxs: {
3406     // v{min,max}s is overloaded between signed integers and floats.
3407     if (!Op.getValueType().isFloatingPoint()) {
3408       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3409         ? ISD::SMIN : ISD::SMAX;
3410       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3411                          Op.getOperand(1), Op.getOperand(2));
3412     }
3413     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3414       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3415     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3416                        Op.getOperand(1), Op.getOperand(2));
3417   }
3418   case Intrinsic::arm_neon_vtbl1:
3419     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3420                        Op.getOperand(1), Op.getOperand(2));
3421   case Intrinsic::arm_neon_vtbl2:
3422     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3423                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3424   }
3425 }
3426 
3427 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3428                                  const ARMSubtarget *Subtarget) {
3429   SDLoc dl(Op);
3430   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3431   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3432   if (SSID == SyncScope::SingleThread)
3433     return Op;
3434 
3435   if (!Subtarget->hasDataBarrier()) {
3436     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3437     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3438     // here.
3439     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3440            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3441     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3442                        DAG.getConstant(0, dl, MVT::i32));
3443   }
3444 
3445   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3446   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3447   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3448   if (Subtarget->isMClass()) {
3449     // Only a full system barrier exists in the M-class architectures.
3450     Domain = ARM_MB::SY;
3451   } else if (Subtarget->preferISHSTBarriers() &&
3452              Ord == AtomicOrdering::Release) {
3453     // Swift happens to implement ISHST barriers in a way that's compatible with
3454     // Release semantics but weaker than ISH so we'd be fools not to use
3455     // it. Beware: other processors probably don't!
3456     Domain = ARM_MB::ISHST;
3457   }
3458 
3459   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3460                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3461                      DAG.getConstant(Domain, dl, MVT::i32));
3462 }
3463 
3464 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3465                              const ARMSubtarget *Subtarget) {
3466   // ARM pre v5TE and Thumb1 does not have preload instructions.
3467   if (!(Subtarget->isThumb2() ||
3468         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3469     // Just preserve the chain.
3470     return Op.getOperand(0);
3471 
3472   SDLoc dl(Op);
3473   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3474   if (!isRead &&
3475       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3476     // ARMv7 with MP extension has PLDW.
3477     return Op.getOperand(0);
3478 
3479   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3480   if (Subtarget->isThumb()) {
3481     // Invert the bits.
3482     isRead = ~isRead & 1;
3483     isData = ~isData & 1;
3484   }
3485 
3486   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3487                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3488                      DAG.getConstant(isData, dl, MVT::i32));
3489 }
3490 
3491 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3492   MachineFunction &MF = DAG.getMachineFunction();
3493   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3494 
3495   // vastart just stores the address of the VarArgsFrameIndex slot into the
3496   // memory location argument.
3497   SDLoc dl(Op);
3498   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3499   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3500   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3501   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3502                       MachinePointerInfo(SV));
3503 }
3504 
3505 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3506                                                 CCValAssign &NextVA,
3507                                                 SDValue &Root,
3508                                                 SelectionDAG &DAG,
3509                                                 const SDLoc &dl) const {
3510   MachineFunction &MF = DAG.getMachineFunction();
3511   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3512 
3513   const TargetRegisterClass *RC;
3514   if (AFI->isThumb1OnlyFunction())
3515     RC = &ARM::tGPRRegClass;
3516   else
3517     RC = &ARM::GPRRegClass;
3518 
3519   // Transform the arguments stored in physical registers into virtual ones.
3520   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3521   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3522 
3523   SDValue ArgValue2;
3524   if (NextVA.isMemLoc()) {
3525     MachineFrameInfo &MFI = MF.getFrameInfo();
3526     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3527 
3528     // Create load node to retrieve arguments from the stack.
3529     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3530     ArgValue2 = DAG.getLoad(
3531         MVT::i32, dl, Root, FIN,
3532         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3533   } else {
3534     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3535     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3536   }
3537   if (!Subtarget->isLittle())
3538     std::swap (ArgValue, ArgValue2);
3539   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3540 }
3541 
3542 // The remaining GPRs hold either the beginning of variable-argument
3543 // data, or the beginning of an aggregate passed by value (usually
3544 // byval).  Either way, we allocate stack slots adjacent to the data
3545 // provided by our caller, and store the unallocated registers there.
3546 // If this is a variadic function, the va_list pointer will begin with
3547 // these values; otherwise, this reassembles a (byval) structure that
3548 // was split between registers and memory.
3549 // Return: The frame index registers were stored into.
3550 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3551                                       const SDLoc &dl, SDValue &Chain,
3552                                       const Value *OrigArg,
3553                                       unsigned InRegsParamRecordIdx,
3554                                       int ArgOffset, unsigned ArgSize) const {
3555   // Currently, two use-cases possible:
3556   // Case #1. Non-var-args function, and we meet first byval parameter.
3557   //          Setup first unallocated register as first byval register;
3558   //          eat all remained registers
3559   //          (these two actions are performed by HandleByVal method).
3560   //          Then, here, we initialize stack frame with
3561   //          "store-reg" instructions.
3562   // Case #2. Var-args function, that doesn't contain byval parameters.
3563   //          The same: eat all remained unallocated registers,
3564   //          initialize stack frame.
3565 
3566   MachineFunction &MF = DAG.getMachineFunction();
3567   MachineFrameInfo &MFI = MF.getFrameInfo();
3568   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3569   unsigned RBegin, REnd;
3570   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3571     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3572   } else {
3573     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3574     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3575     REnd = ARM::R4;
3576   }
3577 
3578   if (REnd != RBegin)
3579     ArgOffset = -4 * (ARM::R4 - RBegin);
3580 
3581   auto PtrVT = getPointerTy(DAG.getDataLayout());
3582   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3583   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3584 
3585   SmallVector<SDValue, 4> MemOps;
3586   const TargetRegisterClass *RC =
3587       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3588 
3589   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3590     unsigned VReg = MF.addLiveIn(Reg, RC);
3591     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3592     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3593                                  MachinePointerInfo(OrigArg, 4 * i));
3594     MemOps.push_back(Store);
3595     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3596   }
3597 
3598   if (!MemOps.empty())
3599     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3600   return FrameIndex;
3601 }
3602 
3603 // Setup stack frame, the va_list pointer will start from.
3604 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3605                                              const SDLoc &dl, SDValue &Chain,
3606                                              unsigned ArgOffset,
3607                                              unsigned TotalArgRegsSaveSize,
3608                                              bool ForceMutable) const {
3609   MachineFunction &MF = DAG.getMachineFunction();
3610   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3611 
3612   // Try to store any remaining integer argument regs
3613   // to their spots on the stack so that they may be loaded by dereferencing
3614   // the result of va_next.
3615   // If there is no regs to be stored, just point address after last
3616   // argument passed via stack.
3617   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3618                                   CCInfo.getInRegsParamsCount(),
3619                                   CCInfo.getNextStackOffset(), 4);
3620   AFI->setVarArgsFrameIndex(FrameIndex);
3621 }
3622 
3623 SDValue ARMTargetLowering::LowerFormalArguments(
3624     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3625     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3626     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3627   MachineFunction &MF = DAG.getMachineFunction();
3628   MachineFrameInfo &MFI = MF.getFrameInfo();
3629 
3630   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3631 
3632   // Assign locations to all of the incoming arguments.
3633   SmallVector<CCValAssign, 16> ArgLocs;
3634   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3635                  *DAG.getContext());
3636   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3637 
3638   SmallVector<SDValue, 16> ArgValues;
3639   SDValue ArgValue;
3640   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3641   unsigned CurArgIdx = 0;
3642 
3643   // Initially ArgRegsSaveSize is zero.
3644   // Then we increase this value each time we meet byval parameter.
3645   // We also increase this value in case of varargs function.
3646   AFI->setArgRegsSaveSize(0);
3647 
3648   // Calculate the amount of stack space that we need to allocate to store
3649   // byval and variadic arguments that are passed in registers.
3650   // We need to know this before we allocate the first byval or variadic
3651   // argument, as they will be allocated a stack slot below the CFA (Canonical
3652   // Frame Address, the stack pointer at entry to the function).
3653   unsigned ArgRegBegin = ARM::R4;
3654   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3655     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3656       break;
3657 
3658     CCValAssign &VA = ArgLocs[i];
3659     unsigned Index = VA.getValNo();
3660     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3661     if (!Flags.isByVal())
3662       continue;
3663 
3664     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3665     unsigned RBegin, REnd;
3666     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3667     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3668 
3669     CCInfo.nextInRegsParam();
3670   }
3671   CCInfo.rewindByValRegsInfo();
3672 
3673   int lastInsIndex = -1;
3674   if (isVarArg && MFI.hasVAStart()) {
3675     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3676     if (RegIdx != array_lengthof(GPRArgRegs))
3677       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3678   }
3679 
3680   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3681   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3682   auto PtrVT = getPointerTy(DAG.getDataLayout());
3683 
3684   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3685     CCValAssign &VA = ArgLocs[i];
3686     if (Ins[VA.getValNo()].isOrigArg()) {
3687       std::advance(CurOrigArg,
3688                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3689       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3690     }
3691     // Arguments stored in registers.
3692     if (VA.isRegLoc()) {
3693       EVT RegVT = VA.getLocVT();
3694 
3695       if (VA.needsCustom()) {
3696         // f64 and vector types are split up into multiple registers or
3697         // combinations of registers and stack slots.
3698         if (VA.getLocVT() == MVT::v2f64) {
3699           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3700                                                    Chain, DAG, dl);
3701           VA = ArgLocs[++i]; // skip ahead to next loc
3702           SDValue ArgValue2;
3703           if (VA.isMemLoc()) {
3704             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3705             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3706             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3707                                     MachinePointerInfo::getFixedStack(
3708                                         DAG.getMachineFunction(), FI));
3709           } else {
3710             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3711                                              Chain, DAG, dl);
3712           }
3713           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3714           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3715                                  ArgValue, ArgValue1,
3716                                  DAG.getIntPtrConstant(0, dl));
3717           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3718                                  ArgValue, ArgValue2,
3719                                  DAG.getIntPtrConstant(1, dl));
3720         } else
3721           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3722       } else {
3723         const TargetRegisterClass *RC;
3724 
3725 
3726         if (RegVT == MVT::f16)
3727           RC = &ARM::HPRRegClass;
3728         else if (RegVT == MVT::f32)
3729           RC = &ARM::SPRRegClass;
3730         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3731           RC = &ARM::DPRRegClass;
3732         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3733           RC = &ARM::QPRRegClass;
3734         else if (RegVT == MVT::i32)
3735           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3736                                            : &ARM::GPRRegClass;
3737         else
3738           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3739 
3740         // Transform the arguments in physical registers into virtual ones.
3741         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3742         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3743       }
3744 
3745       // If this is an 8 or 16-bit value, it is really passed promoted
3746       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3747       // truncate to the right size.
3748       switch (VA.getLocInfo()) {
3749       default: llvm_unreachable("Unknown loc info!");
3750       case CCValAssign::Full: break;
3751       case CCValAssign::BCvt:
3752         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3753         break;
3754       case CCValAssign::SExt:
3755         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3756                                DAG.getValueType(VA.getValVT()));
3757         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3758         break;
3759       case CCValAssign::ZExt:
3760         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3761                                DAG.getValueType(VA.getValVT()));
3762         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3763         break;
3764       }
3765 
3766       InVals.push_back(ArgValue);
3767     } else { // VA.isRegLoc()
3768       // sanity check
3769       assert(VA.isMemLoc());
3770       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3771 
3772       int index = VA.getValNo();
3773 
3774       // Some Ins[] entries become multiple ArgLoc[] entries.
3775       // Process them only once.
3776       if (index != lastInsIndex)
3777         {
3778           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3779           // FIXME: For now, all byval parameter objects are marked mutable.
3780           // This can be changed with more analysis.
3781           // In case of tail call optimization mark all arguments mutable.
3782           // Since they could be overwritten by lowering of arguments in case of
3783           // a tail call.
3784           if (Flags.isByVal()) {
3785             assert(Ins[index].isOrigArg() &&
3786                    "Byval arguments cannot be implicit");
3787             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3788 
3789             int FrameIndex = StoreByValRegs(
3790                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3791                 VA.getLocMemOffset(), Flags.getByValSize());
3792             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3793             CCInfo.nextInRegsParam();
3794           } else {
3795             unsigned FIOffset = VA.getLocMemOffset();
3796             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3797                                            FIOffset, true);
3798 
3799             // Create load nodes to retrieve arguments from the stack.
3800             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3801             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3802                                          MachinePointerInfo::getFixedStack(
3803                                              DAG.getMachineFunction(), FI)));
3804           }
3805           lastInsIndex = index;
3806         }
3807     }
3808   }
3809 
3810   // varargs
3811   if (isVarArg && MFI.hasVAStart())
3812     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3813                          CCInfo.getNextStackOffset(),
3814                          TotalArgRegsSaveSize);
3815 
3816   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3817 
3818   return Chain;
3819 }
3820 
3821 /// isFloatingPointZero - Return true if this is +0.0.
3822 static bool isFloatingPointZero(SDValue Op) {
3823   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3824     return CFP->getValueAPF().isPosZero();
3825   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3826     // Maybe this has already been legalized into the constant pool?
3827     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3828       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3829       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3830         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3831           return CFP->getValueAPF().isPosZero();
3832     }
3833   } else if (Op->getOpcode() == ISD::BITCAST &&
3834              Op->getValueType(0) == MVT::f64) {
3835     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3836     // created by LowerConstantFP().
3837     SDValue BitcastOp = Op->getOperand(0);
3838     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3839         isNullConstant(BitcastOp->getOperand(0)))
3840       return true;
3841   }
3842   return false;
3843 }
3844 
3845 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3846 /// the given operands.
3847 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3848                                      SDValue &ARMcc, SelectionDAG &DAG,
3849                                      const SDLoc &dl) const {
3850   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3851     unsigned C = RHSC->getZExtValue();
3852     if (!isLegalICmpImmediate((int32_t)C)) {
3853       // Constant does not fit, try adjusting it by one.
3854       switch (CC) {
3855       default: break;
3856       case ISD::SETLT:
3857       case ISD::SETGE:
3858         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3859           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3860           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3861         }
3862         break;
3863       case ISD::SETULT:
3864       case ISD::SETUGE:
3865         if (C != 0 && isLegalICmpImmediate(C-1)) {
3866           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3867           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3868         }
3869         break;
3870       case ISD::SETLE:
3871       case ISD::SETGT:
3872         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3873           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3874           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3875         }
3876         break;
3877       case ISD::SETULE:
3878       case ISD::SETUGT:
3879         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3880           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3881           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3882         }
3883         break;
3884       }
3885     }
3886   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3887              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3888     // In ARM and Thumb-2, the compare instructions can shift their second
3889     // operand.
3890     CC = ISD::getSetCCSwappedOperands(CC);
3891     std::swap(LHS, RHS);
3892   }
3893 
3894   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3895   ARMISD::NodeType CompareType;
3896   switch (CondCode) {
3897   default:
3898     CompareType = ARMISD::CMP;
3899     break;
3900   case ARMCC::EQ:
3901   case ARMCC::NE:
3902     // Uses only Z Flag
3903     CompareType = ARMISD::CMPZ;
3904     break;
3905   }
3906   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3907   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3908 }
3909 
3910 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3911 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3912                                      SelectionDAG &DAG, const SDLoc &dl,
3913                                      bool InvalidOnQNaN) const {
3914   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3915   SDValue Cmp;
3916   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3917   if (!isFloatingPointZero(RHS))
3918     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3919   else
3920     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3921   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3922 }
3923 
3924 /// duplicateCmp - Glue values can have only one use, so this function
3925 /// duplicates a comparison node.
3926 SDValue
3927 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3928   unsigned Opc = Cmp.getOpcode();
3929   SDLoc DL(Cmp);
3930   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3931     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3932 
3933   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3934   Cmp = Cmp.getOperand(0);
3935   Opc = Cmp.getOpcode();
3936   if (Opc == ARMISD::CMPFP)
3937     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3938                       Cmp.getOperand(1), Cmp.getOperand(2));
3939   else {
3940     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3941     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3942                       Cmp.getOperand(1));
3943   }
3944   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3945 }
3946 
3947 // This function returns three things: the arithmetic computation itself
3948 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3949 // comparison and the condition code define the case in which the arithmetic
3950 // computation *does not* overflow.
3951 std::pair<SDValue, SDValue>
3952 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3953                                  SDValue &ARMcc) const {
3954   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3955 
3956   SDValue Value, OverflowCmp;
3957   SDValue LHS = Op.getOperand(0);
3958   SDValue RHS = Op.getOperand(1);
3959   SDLoc dl(Op);
3960 
3961   // FIXME: We are currently always generating CMPs because we don't support
3962   // generating CMN through the backend. This is not as good as the natural
3963   // CMP case because it causes a register dependency and cannot be folded
3964   // later.
3965 
3966   switch (Op.getOpcode()) {
3967   default:
3968     llvm_unreachable("Unknown overflow instruction!");
3969   case ISD::SADDO:
3970     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3971     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3972     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3973     break;
3974   case ISD::UADDO:
3975     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3976     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3977     // We do not use it in the USUBO case as Value may not be used.
3978     Value = DAG.getNode(ARMISD::ADDC, dl,
3979                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3980                 .getValue(0);
3981     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3982     break;
3983   case ISD::SSUBO:
3984     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3985     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3986     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3987     break;
3988   case ISD::USUBO:
3989     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3990     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3991     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3992     break;
3993   case ISD::UMULO:
3994     // We generate a UMUL_LOHI and then check if the high word is 0.
3995     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3996     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3997                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3998                         LHS, RHS);
3999     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4000                               DAG.getConstant(0, dl, MVT::i32));
4001     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4002     break;
4003   case ISD::SMULO:
4004     // We generate a SMUL_LOHI and then check if all the bits of the high word
4005     // are the same as the sign bit of the low word.
4006     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4007     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4008                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4009                         LHS, RHS);
4010     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4011                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4012                                           Value.getValue(0),
4013                                           DAG.getConstant(31, dl, MVT::i32)));
4014     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4015     break;
4016   } // switch (...)
4017 
4018   return std::make_pair(Value, OverflowCmp);
4019 }
4020 
4021 SDValue
4022 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4023   // Let legalize expand this if it isn't a legal type yet.
4024   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4025     return SDValue();
4026 
4027   SDValue Value, OverflowCmp;
4028   SDValue ARMcc;
4029   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4030   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4031   SDLoc dl(Op);
4032   // We use 0 and 1 as false and true values.
4033   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4034   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4035   EVT VT = Op.getValueType();
4036 
4037   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4038                                  ARMcc, CCR, OverflowCmp);
4039 
4040   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4041   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4042 }
4043 
4044 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4045                                               SelectionDAG &DAG) {
4046   SDLoc DL(BoolCarry);
4047   EVT CarryVT = BoolCarry.getValueType();
4048 
4049   // This converts the boolean value carry into the carry flag by doing
4050   // ARMISD::SUBC Carry, 1
4051   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4052                               DAG.getVTList(CarryVT, MVT::i32),
4053                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4054   return Carry.getValue(1);
4055 }
4056 
4057 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4058                                               SelectionDAG &DAG) {
4059   SDLoc DL(Flags);
4060 
4061   // Now convert the carry flag into a boolean carry. We do this
4062   // using ARMISD:ADDE 0, 0, Carry
4063   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4064                      DAG.getConstant(0, DL, MVT::i32),
4065                      DAG.getConstant(0, DL, MVT::i32), Flags);
4066 }
4067 
4068 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4069                                              SelectionDAG &DAG) const {
4070   // Let legalize expand this if it isn't a legal type yet.
4071   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4072     return SDValue();
4073 
4074   SDValue LHS = Op.getOperand(0);
4075   SDValue RHS = Op.getOperand(1);
4076   SDLoc dl(Op);
4077 
4078   EVT VT = Op.getValueType();
4079   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4080   SDValue Value;
4081   SDValue Overflow;
4082   switch (Op.getOpcode()) {
4083   default:
4084     llvm_unreachable("Unknown overflow instruction!");
4085   case ISD::UADDO:
4086     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4087     // Convert the carry flag into a boolean value.
4088     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4089     break;
4090   case ISD::USUBO: {
4091     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4092     // Convert the carry flag into a boolean value.
4093     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4094     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4095     // value. So compute 1 - C.
4096     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4097                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4098     break;
4099   }
4100   }
4101 
4102   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4103 }
4104 
4105 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4106   SDValue Cond = Op.getOperand(0);
4107   SDValue SelectTrue = Op.getOperand(1);
4108   SDValue SelectFalse = Op.getOperand(2);
4109   SDLoc dl(Op);
4110   unsigned Opc = Cond.getOpcode();
4111 
4112   if (Cond.getResNo() == 1 &&
4113       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4114        Opc == ISD::USUBO)) {
4115     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4116       return SDValue();
4117 
4118     SDValue Value, OverflowCmp;
4119     SDValue ARMcc;
4120     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4121     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4122     EVT VT = Op.getValueType();
4123 
4124     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4125                    OverflowCmp, DAG);
4126   }
4127 
4128   // Convert:
4129   //
4130   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4131   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4132   //
4133   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4134     const ConstantSDNode *CMOVTrue =
4135       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4136     const ConstantSDNode *CMOVFalse =
4137       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4138 
4139     if (CMOVTrue && CMOVFalse) {
4140       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4141       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4142 
4143       SDValue True;
4144       SDValue False;
4145       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4146         True = SelectTrue;
4147         False = SelectFalse;
4148       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4149         True = SelectFalse;
4150         False = SelectTrue;
4151       }
4152 
4153       if (True.getNode() && False.getNode()) {
4154         EVT VT = Op.getValueType();
4155         SDValue ARMcc = Cond.getOperand(2);
4156         SDValue CCR = Cond.getOperand(3);
4157         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4158         assert(True.getValueType() == VT);
4159         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4160       }
4161     }
4162   }
4163 
4164   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4165   // undefined bits before doing a full-word comparison with zero.
4166   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4167                      DAG.getConstant(1, dl, Cond.getValueType()));
4168 
4169   return DAG.getSelectCC(dl, Cond,
4170                          DAG.getConstant(0, dl, Cond.getValueType()),
4171                          SelectTrue, SelectFalse, ISD::SETNE);
4172 }
4173 
4174 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4175                                  bool &swpCmpOps, bool &swpVselOps) {
4176   // Start by selecting the GE condition code for opcodes that return true for
4177   // 'equality'
4178   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4179       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4180     CondCode = ARMCC::GE;
4181 
4182   // and GT for opcodes that return false for 'equality'.
4183   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4184            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4185     CondCode = ARMCC::GT;
4186 
4187   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4188   // to swap the compare operands.
4189   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4190       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4191     swpCmpOps = true;
4192 
4193   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4194   // If we have an unordered opcode, we need to swap the operands to the VSEL
4195   // instruction (effectively negating the condition).
4196   //
4197   // This also has the effect of swapping which one of 'less' or 'greater'
4198   // returns true, so we also swap the compare operands. It also switches
4199   // whether we return true for 'equality', so we compensate by picking the
4200   // opposite condition code to our original choice.
4201   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4202       CC == ISD::SETUGT) {
4203     swpCmpOps = !swpCmpOps;
4204     swpVselOps = !swpVselOps;
4205     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4206   }
4207 
4208   // 'ordered' is 'anything but unordered', so use the VS condition code and
4209   // swap the VSEL operands.
4210   if (CC == ISD::SETO) {
4211     CondCode = ARMCC::VS;
4212     swpVselOps = true;
4213   }
4214 
4215   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4216   // code and swap the VSEL operands. Also do this if we don't care about the
4217   // unordered case.
4218   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4219     CondCode = ARMCC::EQ;
4220     swpVselOps = true;
4221   }
4222 }
4223 
4224 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4225                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4226                                    SDValue Cmp, SelectionDAG &DAG) const {
4227   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4228     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4229                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4230     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4231                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4232 
4233     SDValue TrueLow = TrueVal.getValue(0);
4234     SDValue TrueHigh = TrueVal.getValue(1);
4235     SDValue FalseLow = FalseVal.getValue(0);
4236     SDValue FalseHigh = FalseVal.getValue(1);
4237 
4238     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4239                               ARMcc, CCR, Cmp);
4240     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4241                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4242 
4243     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4244   } else {
4245     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4246                        Cmp);
4247   }
4248 }
4249 
4250 static bool isGTorGE(ISD::CondCode CC) {
4251   return CC == ISD::SETGT || CC == ISD::SETGE;
4252 }
4253 
4254 static bool isLTorLE(ISD::CondCode CC) {
4255   return CC == ISD::SETLT || CC == ISD::SETLE;
4256 }
4257 
4258 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4259 // All of these conditions (and their <= and >= counterparts) will do:
4260 //          x < k ? k : x
4261 //          x > k ? x : k
4262 //          k < x ? x : k
4263 //          k > x ? k : x
4264 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4265                             const SDValue TrueVal, const SDValue FalseVal,
4266                             const ISD::CondCode CC, const SDValue K) {
4267   return (isGTorGE(CC) &&
4268           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4269          (isLTorLE(CC) &&
4270           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4271 }
4272 
4273 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4274 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4275                             const SDValue TrueVal, const SDValue FalseVal,
4276                             const ISD::CondCode CC, const SDValue K) {
4277   return (isGTorGE(CC) &&
4278           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4279          (isLTorLE(CC) &&
4280           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4281 }
4282 
4283 // Check if two chained conditionals could be converted into SSAT or USAT.
4284 //
4285 // SSAT can replace a set of two conditional selectors that bound a number to an
4286 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4287 //
4288 //     x < -k ? -k : (x > k ? k : x)
4289 //     x < -k ? -k : (x < k ? x : k)
4290 //     x > -k ? (x > k ? k : x) : -k
4291 //     x < k ? (x < -k ? -k : x) : k
4292 //     etc.
4293 //
4294 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4295 // a power of 2.
4296 //
4297 // It returns true if the conversion can be done, false otherwise.
4298 // Additionally, the variable is returned in parameter V, the constant in K and
4299 // usat is set to true if the conditional represents an unsigned saturation
4300 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4301                                     uint64_t &K, bool &usat) {
4302   SDValue LHS1 = Op.getOperand(0);
4303   SDValue RHS1 = Op.getOperand(1);
4304   SDValue TrueVal1 = Op.getOperand(2);
4305   SDValue FalseVal1 = Op.getOperand(3);
4306   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4307 
4308   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4309   if (Op2.getOpcode() != ISD::SELECT_CC)
4310     return false;
4311 
4312   SDValue LHS2 = Op2.getOperand(0);
4313   SDValue RHS2 = Op2.getOperand(1);
4314   SDValue TrueVal2 = Op2.getOperand(2);
4315   SDValue FalseVal2 = Op2.getOperand(3);
4316   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4317 
4318   // Find out which are the constants and which are the variables
4319   // in each conditional
4320   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4321                                                         ? &RHS1
4322                                                         : nullptr;
4323   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4324                                                         ? &RHS2
4325                                                         : nullptr;
4326   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4327   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4328   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4329   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4330 
4331   // We must detect cases where the original operations worked with 16- or
4332   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4333   // must work with sign-extended values but the select operations return
4334   // the original non-extended value.
4335   SDValue V2TmpReg = V2Tmp;
4336   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4337     V2TmpReg = V2Tmp->getOperand(0);
4338 
4339   // Check that the registers and the constants have the correct values
4340   // in both conditionals
4341   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4342       V2TmpReg != V2)
4343     return false;
4344 
4345   // Figure out which conditional is saturating the lower/upper bound.
4346   const SDValue *LowerCheckOp =
4347       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4348           ? &Op
4349           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4350                 ? &Op2
4351                 : nullptr;
4352   const SDValue *UpperCheckOp =
4353       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4354           ? &Op
4355           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4356                 ? &Op2
4357                 : nullptr;
4358 
4359   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4360     return false;
4361 
4362   // Check that the constant in the lower-bound check is
4363   // the opposite of the constant in the upper-bound check
4364   // in 1's complement.
4365   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4366   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4367   int64_t PosVal = std::max(Val1, Val2);
4368   int64_t NegVal = std::min(Val1, Val2);
4369 
4370   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4371        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4372       isPowerOf2_64(PosVal + 1)) {
4373 
4374     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4375     if (Val1 == ~Val2)
4376       usat = false;
4377     else if (NegVal == 0)
4378       usat = true;
4379     else
4380       return false;
4381 
4382     V = V2;
4383     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4384 
4385     return true;
4386   }
4387 
4388   return false;
4389 }
4390 
4391 // Check if a condition of the type x < k ? k : x can be converted into a
4392 // bit operation instead of conditional moves.
4393 // Currently this is allowed given:
4394 // - The conditions and values match up
4395 // - k is 0 or -1 (all ones)
4396 // This function will not check the last condition, thats up to the caller
4397 // It returns true if the transformation can be made, and in such case
4398 // returns x in V, and k in SatK.
4399 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4400                                          SDValue &SatK)
4401 {
4402   SDValue LHS = Op.getOperand(0);
4403   SDValue RHS = Op.getOperand(1);
4404   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4405   SDValue TrueVal = Op.getOperand(2);
4406   SDValue FalseVal = Op.getOperand(3);
4407 
4408   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4409                                                ? &RHS
4410                                                : nullptr;
4411 
4412   // No constant operation in comparison, early out
4413   if (!K)
4414     return false;
4415 
4416   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4417   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4418   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4419 
4420   // If the constant on left and right side, or variable on left and right,
4421   // does not match, early out
4422   if (*K != KTmp || V != VTmp)
4423     return false;
4424 
4425   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4426     SatK = *K;
4427     return true;
4428   }
4429 
4430   return false;
4431 }
4432 
4433 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4434   EVT VT = Op.getValueType();
4435   SDLoc dl(Op);
4436 
4437   // Try to convert two saturating conditional selects into a single SSAT
4438   SDValue SatValue;
4439   uint64_t SatConstant;
4440   bool SatUSat;
4441   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4442       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4443     if (SatUSat)
4444       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4445                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4446     else
4447       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4448                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4449   }
4450 
4451   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4452   // into more efficient bit operations, which is possible when k is 0 or -1
4453   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4454   // single instructions. On Thumb the shift and the bit operation will be two
4455   // instructions.
4456   // Only allow this transformation on full-width (32-bit) operations
4457   SDValue LowerSatConstant;
4458   if (VT == MVT::i32 &&
4459       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4460     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4461                                  DAG.getConstant(31, dl, VT));
4462     if (isNullConstant(LowerSatConstant)) {
4463       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4464                                       DAG.getAllOnesConstant(dl, VT));
4465       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4466     } else if (isAllOnesConstant(LowerSatConstant))
4467       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4468   }
4469 
4470   SDValue LHS = Op.getOperand(0);
4471   SDValue RHS = Op.getOperand(1);
4472   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4473   SDValue TrueVal = Op.getOperand(2);
4474   SDValue FalseVal = Op.getOperand(3);
4475 
4476   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4477     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4478                                                     dl);
4479 
4480     // If softenSetCCOperands only returned one value, we should compare it to
4481     // zero.
4482     if (!RHS.getNode()) {
4483       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4484       CC = ISD::SETNE;
4485     }
4486   }
4487 
4488   if (LHS.getValueType() == MVT::i32) {
4489     // Try to generate VSEL on ARMv8.
4490     // The VSEL instruction can't use all the usual ARM condition
4491     // codes: it only has two bits to select the condition code, so it's
4492     // constrained to use only GE, GT, VS and EQ.
4493     //
4494     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4495     // swap the operands of the previous compare instruction (effectively
4496     // inverting the compare condition, swapping 'less' and 'greater') and
4497     // sometimes need to swap the operands to the VSEL (which inverts the
4498     // condition in the sense of firing whenever the previous condition didn't)
4499     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f16 ||
4500                                     TrueVal.getValueType() == MVT::f32 ||
4501                                     TrueVal.getValueType() == MVT::f64)) {
4502       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4503       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4504           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4505         CC = ISD::getSetCCInverse(CC, true);
4506         std::swap(TrueVal, FalseVal);
4507       }
4508     }
4509 
4510     SDValue ARMcc;
4511     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4512     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4513     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4514   }
4515 
4516   ARMCC::CondCodes CondCode, CondCode2;
4517   bool InvalidOnQNaN;
4518   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4519 
4520   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4521   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4522   // must use VSEL (limited condition codes), due to not having conditional f16
4523   // moves.
4524   if (Subtarget->hasFPARMv8() &&
4525       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4526       (TrueVal.getValueType() == MVT::f16 ||
4527        TrueVal.getValueType() == MVT::f32 ||
4528        TrueVal.getValueType() == MVT::f64)) {
4529     bool swpCmpOps = false;
4530     bool swpVselOps = false;
4531     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4532 
4533     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4534         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4535       if (swpCmpOps)
4536         std::swap(LHS, RHS);
4537       if (swpVselOps)
4538         std::swap(TrueVal, FalseVal);
4539     }
4540   }
4541 
4542   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4543   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4544   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4545   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4546   if (CondCode2 != ARMCC::AL) {
4547     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4548     // FIXME: Needs another CMP because flag can have but one use.
4549     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4550     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4551   }
4552   return Result;
4553 }
4554 
4555 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4556 /// to morph to an integer compare sequence.
4557 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4558                            const ARMSubtarget *Subtarget) {
4559   SDNode *N = Op.getNode();
4560   if (!N->hasOneUse())
4561     // Otherwise it requires moving the value from fp to integer registers.
4562     return false;
4563   if (!N->getNumValues())
4564     return false;
4565   EVT VT = Op.getValueType();
4566   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4567     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4568     // vmrs are very slow, e.g. cortex-a8.
4569     return false;
4570 
4571   if (isFloatingPointZero(Op)) {
4572     SeenZero = true;
4573     return true;
4574   }
4575   return ISD::isNormalLoad(N);
4576 }
4577 
4578 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4579   if (isFloatingPointZero(Op))
4580     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4581 
4582   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4583     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4584                        Ld->getPointerInfo(), Ld->getAlignment(),
4585                        Ld->getMemOperand()->getFlags());
4586 
4587   llvm_unreachable("Unknown VFP cmp argument!");
4588 }
4589 
4590 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4591                            SDValue &RetVal1, SDValue &RetVal2) {
4592   SDLoc dl(Op);
4593 
4594   if (isFloatingPointZero(Op)) {
4595     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4596     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4597     return;
4598   }
4599 
4600   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4601     SDValue Ptr = Ld->getBasePtr();
4602     RetVal1 =
4603         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4604                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4605 
4606     EVT PtrType = Ptr.getValueType();
4607     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4608     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4609                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4610     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4611                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4612                           Ld->getMemOperand()->getFlags());
4613     return;
4614   }
4615 
4616   llvm_unreachable("Unknown VFP cmp argument!");
4617 }
4618 
4619 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4620 /// f32 and even f64 comparisons to integer ones.
4621 SDValue
4622 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4623   SDValue Chain = Op.getOperand(0);
4624   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4625   SDValue LHS = Op.getOperand(2);
4626   SDValue RHS = Op.getOperand(3);
4627   SDValue Dest = Op.getOperand(4);
4628   SDLoc dl(Op);
4629 
4630   bool LHSSeenZero = false;
4631   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4632   bool RHSSeenZero = false;
4633   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4634   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4635     // If unsafe fp math optimization is enabled and there are no other uses of
4636     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4637     // to an integer comparison.
4638     if (CC == ISD::SETOEQ)
4639       CC = ISD::SETEQ;
4640     else if (CC == ISD::SETUNE)
4641       CC = ISD::SETNE;
4642 
4643     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4644     SDValue ARMcc;
4645     if (LHS.getValueType() == MVT::f32) {
4646       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4647                         bitcastf32Toi32(LHS, DAG), Mask);
4648       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4649                         bitcastf32Toi32(RHS, DAG), Mask);
4650       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4651       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4652       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4653                          Chain, Dest, ARMcc, CCR, Cmp);
4654     }
4655 
4656     SDValue LHS1, LHS2;
4657     SDValue RHS1, RHS2;
4658     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4659     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4660     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4661     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4662     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4663     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4664     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4665     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4666     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4667   }
4668 
4669   return SDValue();
4670 }
4671 
4672 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4673   SDValue Chain = Op.getOperand(0);
4674   SDValue Cond = Op.getOperand(1);
4675   SDValue Dest = Op.getOperand(2);
4676   SDLoc dl(Op);
4677 
4678   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4679   // instruction.
4680   unsigned Opc = Cond.getOpcode();
4681   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4682                       !Subtarget->isThumb1Only();
4683   if (Cond.getResNo() == 1 &&
4684       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4685        Opc == ISD::USUBO || OptimizeMul)) {
4686     // Only lower legal XALUO ops.
4687     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4688       return SDValue();
4689 
4690     // The actual operation with overflow check.
4691     SDValue Value, OverflowCmp;
4692     SDValue ARMcc;
4693     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4694 
4695     // Reverse the condition code.
4696     ARMCC::CondCodes CondCode =
4697         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4698     CondCode = ARMCC::getOppositeCondition(CondCode);
4699     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4700     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4701 
4702     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4703                        OverflowCmp);
4704   }
4705 
4706   return SDValue();
4707 }
4708 
4709 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4710   SDValue Chain = Op.getOperand(0);
4711   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4712   SDValue LHS = Op.getOperand(2);
4713   SDValue RHS = Op.getOperand(3);
4714   SDValue Dest = Op.getOperand(4);
4715   SDLoc dl(Op);
4716 
4717   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4718     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4719                                                     dl);
4720 
4721     // If softenSetCCOperands only returned one value, we should compare it to
4722     // zero.
4723     if (!RHS.getNode()) {
4724       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4725       CC = ISD::SETNE;
4726     }
4727   }
4728 
4729   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4730   // instruction.
4731   unsigned Opc = LHS.getOpcode();
4732   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4733                       !Subtarget->isThumb1Only();
4734   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4735       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4736        Opc == ISD::USUBO || OptimizeMul) &&
4737       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4738     // Only lower legal XALUO ops.
4739     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4740       return SDValue();
4741 
4742     // The actual operation with overflow check.
4743     SDValue Value, OverflowCmp;
4744     SDValue ARMcc;
4745     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4746 
4747     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4748       // Reverse the condition code.
4749       ARMCC::CondCodes CondCode =
4750           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4751       CondCode = ARMCC::getOppositeCondition(CondCode);
4752       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4753     }
4754     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4755 
4756     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4757                        OverflowCmp);
4758   }
4759 
4760   if (LHS.getValueType() == MVT::i32) {
4761     SDValue ARMcc;
4762     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4763     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4764     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4765                        Chain, Dest, ARMcc, CCR, Cmp);
4766   }
4767 
4768   if (getTargetMachine().Options.UnsafeFPMath &&
4769       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4770        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4771     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4772       return Result;
4773   }
4774 
4775   ARMCC::CondCodes CondCode, CondCode2;
4776   bool InvalidOnQNaN;
4777   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4778 
4779   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4780   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4781   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4782   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4783   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4784   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4785   if (CondCode2 != ARMCC::AL) {
4786     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4787     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4788     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4789   }
4790   return Res;
4791 }
4792 
4793 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4794   SDValue Chain = Op.getOperand(0);
4795   SDValue Table = Op.getOperand(1);
4796   SDValue Index = Op.getOperand(2);
4797   SDLoc dl(Op);
4798 
4799   EVT PTy = getPointerTy(DAG.getDataLayout());
4800   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4801   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4802   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4803   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4804   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4805   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4806     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4807     // which does another jump to the destination. This also makes it easier
4808     // to translate it to TBB / TBH later (Thumb2 only).
4809     // FIXME: This might not work if the function is extremely large.
4810     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4811                        Addr, Op.getOperand(2), JTI);
4812   }
4813   if (isPositionIndependent() || Subtarget->isROPI()) {
4814     Addr =
4815         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4816                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4817     Chain = Addr.getValue(1);
4818     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4819     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4820   } else {
4821     Addr =
4822         DAG.getLoad(PTy, dl, Chain, Addr,
4823                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4824     Chain = Addr.getValue(1);
4825     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4826   }
4827 }
4828 
4829 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4830   EVT VT = Op.getValueType();
4831   SDLoc dl(Op);
4832 
4833   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4834     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4835       return Op;
4836     return DAG.UnrollVectorOp(Op.getNode());
4837   }
4838 
4839   const bool HasFullFP16 =
4840     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4841 
4842   EVT NewTy;
4843   const EVT OpTy = Op.getOperand(0).getValueType();
4844   if (OpTy == MVT::v4f32)
4845     NewTy = MVT::v4i32;
4846   else if (OpTy == MVT::v4f16 && HasFullFP16)
4847     NewTy = MVT::v4i16;
4848   else if (OpTy == MVT::v8f16 && HasFullFP16)
4849     NewTy = MVT::v8i16;
4850   else
4851     llvm_unreachable("Invalid type for custom lowering!");
4852 
4853   if (VT != MVT::v4i16 && VT != MVT::v8i16)
4854     return DAG.UnrollVectorOp(Op.getNode());
4855 
4856   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
4857   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4858 }
4859 
4860 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4861   EVT VT = Op.getValueType();
4862   if (VT.isVector())
4863     return LowerVectorFP_TO_INT(Op, DAG);
4864   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4865     RTLIB::Libcall LC;
4866     if (Op.getOpcode() == ISD::FP_TO_SINT)
4867       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4868                               Op.getValueType());
4869     else
4870       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4871                               Op.getValueType());
4872     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4873                        /*isSigned*/ false, SDLoc(Op)).first;
4874   }
4875 
4876   return Op;
4877 }
4878 
4879 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4880   EVT VT = Op.getValueType();
4881   SDLoc dl(Op);
4882 
4883   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4884     if (VT.getVectorElementType() == MVT::f32)
4885       return Op;
4886     return DAG.UnrollVectorOp(Op.getNode());
4887   }
4888 
4889   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
4890           Op.getOperand(0).getValueType() == MVT::v8i16) &&
4891          "Invalid type for custom lowering!");
4892 
4893   const bool HasFullFP16 =
4894     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4895 
4896   EVT DestVecType;
4897   if (VT == MVT::v4f32)
4898     DestVecType = MVT::v4i32;
4899   else if (VT == MVT::v4f16 && HasFullFP16)
4900     DestVecType = MVT::v4i16;
4901   else if (VT == MVT::v8f16 && HasFullFP16)
4902     DestVecType = MVT::v8i16;
4903   else
4904     return DAG.UnrollVectorOp(Op.getNode());
4905 
4906   unsigned CastOpc;
4907   unsigned Opc;
4908   switch (Op.getOpcode()) {
4909   default: llvm_unreachable("Invalid opcode!");
4910   case ISD::SINT_TO_FP:
4911     CastOpc = ISD::SIGN_EXTEND;
4912     Opc = ISD::SINT_TO_FP;
4913     break;
4914   case ISD::UINT_TO_FP:
4915     CastOpc = ISD::ZERO_EXTEND;
4916     Opc = ISD::UINT_TO_FP;
4917     break;
4918   }
4919 
4920   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
4921   return DAG.getNode(Opc, dl, VT, Op);
4922 }
4923 
4924 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4925   EVT VT = Op.getValueType();
4926   if (VT.isVector())
4927     return LowerVectorINT_TO_FP(Op, DAG);
4928   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4929     RTLIB::Libcall LC;
4930     if (Op.getOpcode() == ISD::SINT_TO_FP)
4931       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4932                               Op.getValueType());
4933     else
4934       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4935                               Op.getValueType());
4936     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4937                        /*isSigned*/ false, SDLoc(Op)).first;
4938   }
4939 
4940   return Op;
4941 }
4942 
4943 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4944   // Implement fcopysign with a fabs and a conditional fneg.
4945   SDValue Tmp0 = Op.getOperand(0);
4946   SDValue Tmp1 = Op.getOperand(1);
4947   SDLoc dl(Op);
4948   EVT VT = Op.getValueType();
4949   EVT SrcVT = Tmp1.getValueType();
4950   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4951     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4952   bool UseNEON = !InGPR && Subtarget->hasNEON();
4953 
4954   if (UseNEON) {
4955     // Use VBSL to copy the sign bit.
4956     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4957     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4958                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4959     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4960     if (VT == MVT::f64)
4961       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4962                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4963                          DAG.getConstant(32, dl, MVT::i32));
4964     else /*if (VT == MVT::f32)*/
4965       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4966     if (SrcVT == MVT::f32) {
4967       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4968       if (VT == MVT::f64)
4969         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4970                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4971                            DAG.getConstant(32, dl, MVT::i32));
4972     } else if (VT == MVT::f32)
4973       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4974                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4975                          DAG.getConstant(32, dl, MVT::i32));
4976     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4977     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4978 
4979     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4980                                             dl, MVT::i32);
4981     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4982     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4983                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4984 
4985     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4986                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4987                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4988     if (VT == MVT::f32) {
4989       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4990       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4991                         DAG.getConstant(0, dl, MVT::i32));
4992     } else {
4993       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4994     }
4995 
4996     return Res;
4997   }
4998 
4999   // Bitcast operand 1 to i32.
5000   if (SrcVT == MVT::f64)
5001     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5002                        Tmp1).getValue(1);
5003   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5004 
5005   // Or in the signbit with integer operations.
5006   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5007   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5008   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5009   if (VT == MVT::f32) {
5010     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5011                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5012     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5013                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5014   }
5015 
5016   // f64: Or the high part with signbit and then combine two parts.
5017   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5018                      Tmp0);
5019   SDValue Lo = Tmp0.getValue(0);
5020   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5021   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5022   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5023 }
5024 
5025 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5026   MachineFunction &MF = DAG.getMachineFunction();
5027   MachineFrameInfo &MFI = MF.getFrameInfo();
5028   MFI.setReturnAddressIsTaken(true);
5029 
5030   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5031     return SDValue();
5032 
5033   EVT VT = Op.getValueType();
5034   SDLoc dl(Op);
5035   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5036   if (Depth) {
5037     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5038     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5039     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5040                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5041                        MachinePointerInfo());
5042   }
5043 
5044   // Return LR, which contains the return address. Mark it an implicit live-in.
5045   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5046   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5047 }
5048 
5049 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5050   const ARMBaseRegisterInfo &ARI =
5051     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5052   MachineFunction &MF = DAG.getMachineFunction();
5053   MachineFrameInfo &MFI = MF.getFrameInfo();
5054   MFI.setFrameAddressIsTaken(true);
5055 
5056   EVT VT = Op.getValueType();
5057   SDLoc dl(Op);  // FIXME probably not meaningful
5058   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5059   unsigned FrameReg = ARI.getFrameRegister(MF);
5060   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5061   while (Depth--)
5062     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5063                             MachinePointerInfo());
5064   return FrameAddr;
5065 }
5066 
5067 // FIXME? Maybe this could be a TableGen attribute on some registers and
5068 // this table could be generated automatically from RegInfo.
5069 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5070                                               SelectionDAG &DAG) const {
5071   unsigned Reg = StringSwitch<unsigned>(RegName)
5072                        .Case("sp", ARM::SP)
5073                        .Default(0);
5074   if (Reg)
5075     return Reg;
5076   report_fatal_error(Twine("Invalid register name \""
5077                               + StringRef(RegName)  + "\"."));
5078 }
5079 
5080 // Result is 64 bit value so split into two 32 bit values and return as a
5081 // pair of values.
5082 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5083                                 SelectionDAG &DAG) {
5084   SDLoc DL(N);
5085 
5086   // This function is only supposed to be called for i64 type destination.
5087   assert(N->getValueType(0) == MVT::i64
5088           && "ExpandREAD_REGISTER called for non-i64 type result.");
5089 
5090   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5091                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5092                              N->getOperand(0),
5093                              N->getOperand(1));
5094 
5095   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5096                     Read.getValue(1)));
5097   Results.push_back(Read.getOperand(0));
5098 }
5099 
5100 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5101 /// When \p DstVT, the destination type of \p BC, is on the vector
5102 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5103 /// it might be possible to combine them, such that everything stays on the
5104 /// vector register bank.
5105 /// \p return The node that would replace \p BT, if the combine
5106 /// is possible.
5107 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5108                                                 SelectionDAG &DAG) {
5109   SDValue Op = BC->getOperand(0);
5110   EVT DstVT = BC->getValueType(0);
5111 
5112   // The only vector instruction that can produce a scalar (remember,
5113   // since the bitcast was about to be turned into VMOVDRR, the source
5114   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5115   // Moreover, we can do this combine only if there is one use.
5116   // Finally, if the destination type is not a vector, there is not
5117   // much point on forcing everything on the vector bank.
5118   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5119       !Op.hasOneUse())
5120     return SDValue();
5121 
5122   // If the index is not constant, we will introduce an additional
5123   // multiply that will stick.
5124   // Give up in that case.
5125   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5126   if (!Index)
5127     return SDValue();
5128   unsigned DstNumElt = DstVT.getVectorNumElements();
5129 
5130   // Compute the new index.
5131   const APInt &APIntIndex = Index->getAPIntValue();
5132   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5133   NewIndex *= APIntIndex;
5134   // Check if the new constant index fits into i32.
5135   if (NewIndex.getBitWidth() > 32)
5136     return SDValue();
5137 
5138   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5139   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5140   SDLoc dl(Op);
5141   SDValue ExtractSrc = Op.getOperand(0);
5142   EVT VecVT = EVT::getVectorVT(
5143       *DAG.getContext(), DstVT.getScalarType(),
5144       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5145   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5146   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5147                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5148 }
5149 
5150 /// ExpandBITCAST - If the target supports VFP, this function is called to
5151 /// expand a bit convert where either the source or destination type is i64 to
5152 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5153 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5154 /// vectors), since the legalizer won't know what to do with that.
5155 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5156                              const ARMSubtarget *Subtarget) {
5157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5158   SDLoc dl(N);
5159   SDValue Op = N->getOperand(0);
5160 
5161   // This function is only supposed to be called for i64 types, either as the
5162   // source or destination of the bit convert.
5163   EVT SrcVT = Op.getValueType();
5164   EVT DstVT = N->getValueType(0);
5165   const bool HasFullFP16 = Subtarget->hasFullFP16();
5166 
5167   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5168      // FullFP16: half values are passed in S-registers, and we don't
5169      // need any of the bitcast and moves:
5170      //
5171      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5172      //   t5: i32 = bitcast t2
5173      // t18: f16 = ARMISD::VMOVhr t5
5174      if (Op.getOpcode() != ISD::CopyFromReg ||
5175          Op.getValueType() != MVT::f32)
5176        return SDValue();
5177 
5178      auto Move = N->use_begin();
5179      if (Move->getOpcode() != ARMISD::VMOVhr)
5180        return SDValue();
5181 
5182      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5183      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5184      DAG.ReplaceAllUsesWith(*Move, &Copy);
5185      return Copy;
5186   }
5187 
5188   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5189     if (!HasFullFP16)
5190       return SDValue();
5191     // SoftFP: read half-precision arguments:
5192     //
5193     // t2: i32,ch = ...
5194     //        t7: i16 = truncate t2 <~~~~ Op
5195     //      t8: f16 = bitcast t7    <~~~~ N
5196     //
5197     if (Op.getOperand(0).getValueType() == MVT::i32)
5198       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5199                          MVT::f16, Op.getOperand(0));
5200 
5201     return SDValue();
5202   }
5203 
5204   // Half-precision return values
5205   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5206     if (!HasFullFP16)
5207       return SDValue();
5208     //
5209     //          t11: f16 = fadd t8, t10
5210     //        t12: i16 = bitcast t11       <~~~ SDNode N
5211     //      t13: i32 = zero_extend t12
5212     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5213     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5214     //
5215     // transform this into:
5216     //
5217     //    t20: i32 = ARMISD::VMOVrh t11
5218     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5219     //
5220     auto ZeroExtend = N->use_begin();
5221     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5222         ZeroExtend->getValueType(0) != MVT::i32)
5223       return SDValue();
5224 
5225     auto Copy = ZeroExtend->use_begin();
5226     if (Copy->getOpcode() == ISD::CopyToReg &&
5227         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5228       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5229       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5230       return Cvt;
5231     }
5232     return SDValue();
5233   }
5234 
5235   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5236     return SDValue();
5237 
5238   // Turn i64->f64 into VMOVDRR.
5239   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5240     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5241     // if we can combine the bitcast with its source.
5242     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5243       return Val;
5244 
5245     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5246                              DAG.getConstant(0, dl, MVT::i32));
5247     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5248                              DAG.getConstant(1, dl, MVT::i32));
5249     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5250                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5251   }
5252 
5253   // Turn f64->i64 into VMOVRRD.
5254   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5255     SDValue Cvt;
5256     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5257         SrcVT.getVectorNumElements() > 1)
5258       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5259                         DAG.getVTList(MVT::i32, MVT::i32),
5260                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5261     else
5262       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5263                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5264     // Merge the pieces into a single i64 value.
5265     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5266   }
5267 
5268   return SDValue();
5269 }
5270 
5271 /// getZeroVector - Returns a vector of specified type with all zero elements.
5272 /// Zero vectors are used to represent vector negation and in those cases
5273 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5274 /// not support i64 elements, so sometimes the zero vectors will need to be
5275 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5276 /// zero vector.
5277 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5278   assert(VT.isVector() && "Expected a vector type");
5279   // The canonical modified immediate encoding of a zero vector is....0!
5280   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5281   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5282   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5283   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5284 }
5285 
5286 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5287 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5288 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5289                                                 SelectionDAG &DAG) const {
5290   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5291   EVT VT = Op.getValueType();
5292   unsigned VTBits = VT.getSizeInBits();
5293   SDLoc dl(Op);
5294   SDValue ShOpLo = Op.getOperand(0);
5295   SDValue ShOpHi = Op.getOperand(1);
5296   SDValue ShAmt  = Op.getOperand(2);
5297   SDValue ARMcc;
5298   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5299   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5300 
5301   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5302 
5303   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5304                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5305   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5306   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5307                                    DAG.getConstant(VTBits, dl, MVT::i32));
5308   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5309   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5310   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5311   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5312                             ISD::SETGE, ARMcc, DAG, dl);
5313   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5314                            ARMcc, CCR, CmpLo);
5315 
5316   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5317   SDValue HiBigShift = Opc == ISD::SRA
5318                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5319                                          DAG.getConstant(VTBits - 1, dl, VT))
5320                            : DAG.getConstant(0, dl, VT);
5321   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5322                             ISD::SETGE, ARMcc, DAG, dl);
5323   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5324                            ARMcc, CCR, CmpHi);
5325 
5326   SDValue Ops[2] = { Lo, Hi };
5327   return DAG.getMergeValues(Ops, dl);
5328 }
5329 
5330 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5331 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5332 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5333                                                SelectionDAG &DAG) const {
5334   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5335   EVT VT = Op.getValueType();
5336   unsigned VTBits = VT.getSizeInBits();
5337   SDLoc dl(Op);
5338   SDValue ShOpLo = Op.getOperand(0);
5339   SDValue ShOpHi = Op.getOperand(1);
5340   SDValue ShAmt  = Op.getOperand(2);
5341   SDValue ARMcc;
5342   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5343 
5344   assert(Op.getOpcode() == ISD::SHL_PARTS);
5345   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5346                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5347   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5348   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5349   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5350 
5351   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5352                                    DAG.getConstant(VTBits, dl, MVT::i32));
5353   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5354   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5355                             ISD::SETGE, ARMcc, DAG, dl);
5356   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5357                            ARMcc, CCR, CmpHi);
5358 
5359   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5360                           ISD::SETGE, ARMcc, DAG, dl);
5361   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5362   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5363                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5364 
5365   SDValue Ops[2] = { Lo, Hi };
5366   return DAG.getMergeValues(Ops, dl);
5367 }
5368 
5369 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5370                                             SelectionDAG &DAG) const {
5371   // The rounding mode is in bits 23:22 of the FPSCR.
5372   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5373   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5374   // so that the shift + and get folded into a bitfield extract.
5375   SDLoc dl(Op);
5376   SDValue Ops[] = { DAG.getEntryNode(),
5377                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5378 
5379   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5380   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5381                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5382   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5383                               DAG.getConstant(22, dl, MVT::i32));
5384   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5385                      DAG.getConstant(3, dl, MVT::i32));
5386 }
5387 
5388 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5389                          const ARMSubtarget *ST) {
5390   SDLoc dl(N);
5391   EVT VT = N->getValueType(0);
5392   if (VT.isVector()) {
5393     assert(ST->hasNEON());
5394 
5395     // Compute the least significant set bit: LSB = X & -X
5396     SDValue X = N->getOperand(0);
5397     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5398     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5399 
5400     EVT ElemTy = VT.getVectorElementType();
5401 
5402     if (ElemTy == MVT::i8) {
5403       // Compute with: cttz(x) = ctpop(lsb - 1)
5404       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5405                                 DAG.getTargetConstant(1, dl, ElemTy));
5406       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5407       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5408     }
5409 
5410     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5411         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5412       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5413       unsigned NumBits = ElemTy.getSizeInBits();
5414       SDValue WidthMinus1 =
5415           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5416                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5417       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5418       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5419     }
5420 
5421     // Compute with: cttz(x) = ctpop(lsb - 1)
5422 
5423     // Compute LSB - 1.
5424     SDValue Bits;
5425     if (ElemTy == MVT::i64) {
5426       // Load constant 0xffff'ffff'ffff'ffff to register.
5427       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5428                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5429       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5430     } else {
5431       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5432                                 DAG.getTargetConstant(1, dl, ElemTy));
5433       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5434     }
5435     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5436   }
5437 
5438   if (!ST->hasV6T2Ops())
5439     return SDValue();
5440 
5441   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5442   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5443 }
5444 
5445 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5446                           const ARMSubtarget *ST) {
5447   EVT VT = N->getValueType(0);
5448   SDLoc DL(N);
5449 
5450   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5451   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5452           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5453          "Unexpected type for custom ctpop lowering");
5454 
5455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5456   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5457   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5458   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5459 
5460   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5461   unsigned EltSize = 8;
5462   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5463   while (EltSize != VT.getScalarSizeInBits()) {
5464     SmallVector<SDValue, 8> Ops;
5465     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5466                                   TLI.getPointerTy(DAG.getDataLayout())));
5467     Ops.push_back(Res);
5468 
5469     EltSize *= 2;
5470     NumElts /= 2;
5471     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5472     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5473   }
5474 
5475   return Res;
5476 }
5477 
5478 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5479                           const ARMSubtarget *ST) {
5480   EVT VT = N->getValueType(0);
5481   SDLoc dl(N);
5482 
5483   if (!VT.isVector())
5484     return SDValue();
5485 
5486   // Lower vector shifts on NEON to use VSHL.
5487   assert(ST->hasNEON() && "unexpected vector shift");
5488 
5489   // Left shifts translate directly to the vshiftu intrinsic.
5490   if (N->getOpcode() == ISD::SHL)
5491     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5492                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5493                                        MVT::i32),
5494                        N->getOperand(0), N->getOperand(1));
5495 
5496   assert((N->getOpcode() == ISD::SRA ||
5497           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5498 
5499   // NEON uses the same intrinsics for both left and right shifts.  For
5500   // right shifts, the shift amounts are negative, so negate the vector of
5501   // shift amounts.
5502   EVT ShiftVT = N->getOperand(1).getValueType();
5503   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5504                                      getZeroVector(ShiftVT, DAG, dl),
5505                                      N->getOperand(1));
5506   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5507                              Intrinsic::arm_neon_vshifts :
5508                              Intrinsic::arm_neon_vshiftu);
5509   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5510                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5511                      N->getOperand(0), NegatedCount);
5512 }
5513 
5514 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5515                                 const ARMSubtarget *ST) {
5516   EVT VT = N->getValueType(0);
5517   SDLoc dl(N);
5518 
5519   // We can get here for a node like i32 = ISD::SHL i32, i64
5520   if (VT != MVT::i64)
5521     return SDValue();
5522 
5523   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5524          "Unknown shift to lower!");
5525 
5526   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5527   if (!isOneConstant(N->getOperand(1)))
5528     return SDValue();
5529 
5530   // If we are in thumb mode, we don't have RRX.
5531   if (ST->isThumb1Only()) return SDValue();
5532 
5533   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5534   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5535                            DAG.getConstant(0, dl, MVT::i32));
5536   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5537                            DAG.getConstant(1, dl, MVT::i32));
5538 
5539   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5540   // captures the result into a carry flag.
5541   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5542   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5543 
5544   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5545   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5546 
5547   // Merge the pieces into a single i64 value.
5548  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5549 }
5550 
5551 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5552   SDValue TmpOp0, TmpOp1;
5553   bool Invert = false;
5554   bool Swap = false;
5555   unsigned Opc = 0;
5556 
5557   SDValue Op0 = Op.getOperand(0);
5558   SDValue Op1 = Op.getOperand(1);
5559   SDValue CC = Op.getOperand(2);
5560   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5561   EVT VT = Op.getValueType();
5562   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5563   SDLoc dl(Op);
5564 
5565   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5566       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5567     // Special-case integer 64-bit equality comparisons. They aren't legal,
5568     // but they can be lowered with a few vector instructions.
5569     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5570     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5571     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5572     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5573     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5574                               DAG.getCondCode(ISD::SETEQ));
5575     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5576     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5577     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5578     if (SetCCOpcode == ISD::SETNE)
5579       Merged = DAG.getNOT(dl, Merged, CmpVT);
5580     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5581     return Merged;
5582   }
5583 
5584   if (CmpVT.getVectorElementType() == MVT::i64)
5585     // 64-bit comparisons are not legal in general.
5586     return SDValue();
5587 
5588   if (Op1.getValueType().isFloatingPoint()) {
5589     switch (SetCCOpcode) {
5590     default: llvm_unreachable("Illegal FP comparison");
5591     case ISD::SETUNE:
5592     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5593     case ISD::SETOEQ:
5594     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5595     case ISD::SETOLT:
5596     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5597     case ISD::SETOGT:
5598     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5599     case ISD::SETOLE:
5600     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5601     case ISD::SETOGE:
5602     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5603     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5604     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5605     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5606     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5607     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5608     case ISD::SETONE:
5609       // Expand this to (OLT | OGT).
5610       TmpOp0 = Op0;
5611       TmpOp1 = Op1;
5612       Opc = ISD::OR;
5613       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5614       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5615       break;
5616     case ISD::SETUO:
5617       Invert = true;
5618       LLVM_FALLTHROUGH;
5619     case ISD::SETO:
5620       // Expand this to (OLT | OGE).
5621       TmpOp0 = Op0;
5622       TmpOp1 = Op1;
5623       Opc = ISD::OR;
5624       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5625       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5626       break;
5627     }
5628   } else {
5629     // Integer comparisons.
5630     switch (SetCCOpcode) {
5631     default: llvm_unreachable("Illegal integer comparison");
5632     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5633     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5634     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5635     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5636     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5637     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5638     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5639     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5640     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5641     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5642     }
5643 
5644     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5645     if (Opc == ARMISD::VCEQ) {
5646       SDValue AndOp;
5647       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5648         AndOp = Op0;
5649       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5650         AndOp = Op1;
5651 
5652       // Ignore bitconvert.
5653       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5654         AndOp = AndOp.getOperand(0);
5655 
5656       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5657         Opc = ARMISD::VTST;
5658         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5659         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5660         Invert = !Invert;
5661       }
5662     }
5663   }
5664 
5665   if (Swap)
5666     std::swap(Op0, Op1);
5667 
5668   // If one of the operands is a constant vector zero, attempt to fold the
5669   // comparison to a specialized compare-against-zero form.
5670   SDValue SingleOp;
5671   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5672     SingleOp = Op0;
5673   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5674     if (Opc == ARMISD::VCGE)
5675       Opc = ARMISD::VCLEZ;
5676     else if (Opc == ARMISD::VCGT)
5677       Opc = ARMISD::VCLTZ;
5678     SingleOp = Op1;
5679   }
5680 
5681   SDValue Result;
5682   if (SingleOp.getNode()) {
5683     switch (Opc) {
5684     case ARMISD::VCEQ:
5685       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5686     case ARMISD::VCGE:
5687       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5688     case ARMISD::VCLEZ:
5689       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5690     case ARMISD::VCGT:
5691       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5692     case ARMISD::VCLTZ:
5693       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5694     default:
5695       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5696     }
5697   } else {
5698      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5699   }
5700 
5701   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5702 
5703   if (Invert)
5704     Result = DAG.getNOT(dl, Result, VT);
5705 
5706   return Result;
5707 }
5708 
5709 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
5710   SDValue LHS = Op.getOperand(0);
5711   SDValue RHS = Op.getOperand(1);
5712   SDValue Carry = Op.getOperand(2);
5713   SDValue Cond = Op.getOperand(3);
5714   SDLoc DL(Op);
5715 
5716   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
5717 
5718   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
5719   // have to invert the carry first.
5720   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
5721                       DAG.getConstant(1, DL, MVT::i32), Carry);
5722   // This converts the boolean value carry into the carry flag.
5723   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
5724 
5725   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5726   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5727 
5728   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5729   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5730   SDValue ARMcc = DAG.getConstant(
5731       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5732   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5733   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5734                                    Cmp.getValue(1), SDValue());
5735   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5736                      CCR, Chain.getValue(1));
5737 }
5738 
5739 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5740 /// valid vector constant for a NEON instruction with a "modified immediate"
5741 /// operand (e.g., VMOV).  If so, return the encoded value.
5742 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5743                                  unsigned SplatBitSize, SelectionDAG &DAG,
5744                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5745                                  NEONModImmType type) {
5746   unsigned OpCmode, Imm;
5747 
5748   // SplatBitSize is set to the smallest size that splats the vector, so a
5749   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5750   // immediate instructions others than VMOV do not support the 8-bit encoding
5751   // of a zero vector, and the default encoding of zero is supposed to be the
5752   // 32-bit version.
5753   if (SplatBits == 0)
5754     SplatBitSize = 32;
5755 
5756   switch (SplatBitSize) {
5757   case 8:
5758     if (type != VMOVModImm)
5759       return SDValue();
5760     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5761     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5762     OpCmode = 0xe;
5763     Imm = SplatBits;
5764     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5765     break;
5766 
5767   case 16:
5768     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5769     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5770     if ((SplatBits & ~0xff) == 0) {
5771       // Value = 0x00nn: Op=x, Cmode=100x.
5772       OpCmode = 0x8;
5773       Imm = SplatBits;
5774       break;
5775     }
5776     if ((SplatBits & ~0xff00) == 0) {
5777       // Value = 0xnn00: Op=x, Cmode=101x.
5778       OpCmode = 0xa;
5779       Imm = SplatBits >> 8;
5780       break;
5781     }
5782     return SDValue();
5783 
5784   case 32:
5785     // NEON's 32-bit VMOV supports splat values where:
5786     // * only one byte is nonzero, or
5787     // * the least significant byte is 0xff and the second byte is nonzero, or
5788     // * the least significant 2 bytes are 0xff and the third is nonzero.
5789     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5790     if ((SplatBits & ~0xff) == 0) {
5791       // Value = 0x000000nn: Op=x, Cmode=000x.
5792       OpCmode = 0;
5793       Imm = SplatBits;
5794       break;
5795     }
5796     if ((SplatBits & ~0xff00) == 0) {
5797       // Value = 0x0000nn00: Op=x, Cmode=001x.
5798       OpCmode = 0x2;
5799       Imm = SplatBits >> 8;
5800       break;
5801     }
5802     if ((SplatBits & ~0xff0000) == 0) {
5803       // Value = 0x00nn0000: Op=x, Cmode=010x.
5804       OpCmode = 0x4;
5805       Imm = SplatBits >> 16;
5806       break;
5807     }
5808     if ((SplatBits & ~0xff000000) == 0) {
5809       // Value = 0xnn000000: Op=x, Cmode=011x.
5810       OpCmode = 0x6;
5811       Imm = SplatBits >> 24;
5812       break;
5813     }
5814 
5815     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5816     if (type == OtherModImm) return SDValue();
5817 
5818     if ((SplatBits & ~0xffff) == 0 &&
5819         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5820       // Value = 0x0000nnff: Op=x, Cmode=1100.
5821       OpCmode = 0xc;
5822       Imm = SplatBits >> 8;
5823       break;
5824     }
5825 
5826     if ((SplatBits & ~0xffffff) == 0 &&
5827         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5828       // Value = 0x00nnffff: Op=x, Cmode=1101.
5829       OpCmode = 0xd;
5830       Imm = SplatBits >> 16;
5831       break;
5832     }
5833 
5834     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5835     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5836     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5837     // and fall through here to test for a valid 64-bit splat.  But, then the
5838     // caller would also need to check and handle the change in size.
5839     return SDValue();
5840 
5841   case 64: {
5842     if (type != VMOVModImm)
5843       return SDValue();
5844     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5845     uint64_t BitMask = 0xff;
5846     uint64_t Val = 0;
5847     unsigned ImmMask = 1;
5848     Imm = 0;
5849     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5850       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5851         Val |= BitMask;
5852         Imm |= ImmMask;
5853       } else if ((SplatBits & BitMask) != 0) {
5854         return SDValue();
5855       }
5856       BitMask <<= 8;
5857       ImmMask <<= 1;
5858     }
5859 
5860     if (DAG.getDataLayout().isBigEndian())
5861       // swap higher and lower 32 bit word
5862       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5863 
5864     // Op=1, Cmode=1110.
5865     OpCmode = 0x1e;
5866     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5867     break;
5868   }
5869 
5870   default:
5871     llvm_unreachable("unexpected size for isNEONModifiedImm");
5872   }
5873 
5874   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5875   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5876 }
5877 
5878 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5879                                            const ARMSubtarget *ST) const {
5880   EVT VT = Op.getValueType();
5881   bool IsDouble = (VT == MVT::f64);
5882   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5883   const APFloat &FPVal = CFP->getValueAPF();
5884 
5885   // Prevent floating-point constants from using literal loads
5886   // when execute-only is enabled.
5887   if (ST->genExecuteOnly()) {
5888     // If we can represent the constant as an immediate, don't lower it
5889     if (isFPImmLegal(FPVal, VT))
5890       return Op;
5891     // Otherwise, construct as integer, and move to float register
5892     APInt INTVal = FPVal.bitcastToAPInt();
5893     SDLoc DL(CFP);
5894     switch (VT.getSimpleVT().SimpleTy) {
5895       default:
5896         llvm_unreachable("Unknown floating point type!");
5897         break;
5898       case MVT::f64: {
5899         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5900         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5901         if (!ST->isLittle())
5902           std::swap(Lo, Hi);
5903         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5904       }
5905       case MVT::f32:
5906           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
5907               DAG.getConstant(INTVal, DL, MVT::i32));
5908     }
5909   }
5910 
5911   if (!ST->hasVFP3())
5912     return SDValue();
5913 
5914   // Use the default (constant pool) lowering for double constants when we have
5915   // an SP-only FPU
5916   if (IsDouble && Subtarget->isFPOnlySP())
5917     return SDValue();
5918 
5919   // Try splatting with a VMOV.f32...
5920   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5921 
5922   if (ImmVal != -1) {
5923     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5924       // We have code in place to select a valid ConstantFP already, no need to
5925       // do any mangling.
5926       return Op;
5927     }
5928 
5929     // It's a float and we are trying to use NEON operations where
5930     // possible. Lower it to a splat followed by an extract.
5931     SDLoc DL(Op);
5932     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5933     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5934                                       NewVal);
5935     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5936                        DAG.getConstant(0, DL, MVT::i32));
5937   }
5938 
5939   // The rest of our options are NEON only, make sure that's allowed before
5940   // proceeding..
5941   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5942     return SDValue();
5943 
5944   EVT VMovVT;
5945   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5946 
5947   // It wouldn't really be worth bothering for doubles except for one very
5948   // important value, which does happen to match: 0.0. So make sure we don't do
5949   // anything stupid.
5950   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5951     return SDValue();
5952 
5953   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5954   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5955                                      VMovVT, false, VMOVModImm);
5956   if (NewVal != SDValue()) {
5957     SDLoc DL(Op);
5958     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5959                                       NewVal);
5960     if (IsDouble)
5961       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5962 
5963     // It's a float: cast and extract a vector element.
5964     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5965                                        VecConstant);
5966     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5967                        DAG.getConstant(0, DL, MVT::i32));
5968   }
5969 
5970   // Finally, try a VMVN.i32
5971   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5972                              false, VMVNModImm);
5973   if (NewVal != SDValue()) {
5974     SDLoc DL(Op);
5975     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5976 
5977     if (IsDouble)
5978       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5979 
5980     // It's a float: cast and extract a vector element.
5981     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5982                                        VecConstant);
5983     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5984                        DAG.getConstant(0, DL, MVT::i32));
5985   }
5986 
5987   return SDValue();
5988 }
5989 
5990 // check if an VEXT instruction can handle the shuffle mask when the
5991 // vector sources of the shuffle are the same.
5992 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5993   unsigned NumElts = VT.getVectorNumElements();
5994 
5995   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5996   if (M[0] < 0)
5997     return false;
5998 
5999   Imm = M[0];
6000 
6001   // If this is a VEXT shuffle, the immediate value is the index of the first
6002   // element.  The other shuffle indices must be the successive elements after
6003   // the first one.
6004   unsigned ExpectedElt = Imm;
6005   for (unsigned i = 1; i < NumElts; ++i) {
6006     // Increment the expected index.  If it wraps around, just follow it
6007     // back to index zero and keep going.
6008     ++ExpectedElt;
6009     if (ExpectedElt == NumElts)
6010       ExpectedElt = 0;
6011 
6012     if (M[i] < 0) continue; // ignore UNDEF indices
6013     if (ExpectedElt != static_cast<unsigned>(M[i]))
6014       return false;
6015   }
6016 
6017   return true;
6018 }
6019 
6020 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6021                        bool &ReverseVEXT, unsigned &Imm) {
6022   unsigned NumElts = VT.getVectorNumElements();
6023   ReverseVEXT = false;
6024 
6025   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6026   if (M[0] < 0)
6027     return false;
6028 
6029   Imm = M[0];
6030 
6031   // If this is a VEXT shuffle, the immediate value is the index of the first
6032   // element.  The other shuffle indices must be the successive elements after
6033   // the first one.
6034   unsigned ExpectedElt = Imm;
6035   for (unsigned i = 1; i < NumElts; ++i) {
6036     // Increment the expected index.  If it wraps around, it may still be
6037     // a VEXT but the source vectors must be swapped.
6038     ExpectedElt += 1;
6039     if (ExpectedElt == NumElts * 2) {
6040       ExpectedElt = 0;
6041       ReverseVEXT = true;
6042     }
6043 
6044     if (M[i] < 0) continue; // ignore UNDEF indices
6045     if (ExpectedElt != static_cast<unsigned>(M[i]))
6046       return false;
6047   }
6048 
6049   // Adjust the index value if the source operands will be swapped.
6050   if (ReverseVEXT)
6051     Imm -= NumElts;
6052 
6053   return true;
6054 }
6055 
6056 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6057 /// instruction with the specified blocksize.  (The order of the elements
6058 /// within each block of the vector is reversed.)
6059 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6060   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6061          "Only possible block sizes for VREV are: 16, 32, 64");
6062 
6063   unsigned EltSz = VT.getScalarSizeInBits();
6064   if (EltSz == 64)
6065     return false;
6066 
6067   unsigned NumElts = VT.getVectorNumElements();
6068   unsigned BlockElts = M[0] + 1;
6069   // If the first shuffle index is UNDEF, be optimistic.
6070   if (M[0] < 0)
6071     BlockElts = BlockSize / EltSz;
6072 
6073   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6074     return false;
6075 
6076   for (unsigned i = 0; i < NumElts; ++i) {
6077     if (M[i] < 0) continue; // ignore UNDEF indices
6078     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6079       return false;
6080   }
6081 
6082   return true;
6083 }
6084 
6085 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6086   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6087   // range, then 0 is placed into the resulting vector. So pretty much any mask
6088   // of 8 elements can work here.
6089   return VT == MVT::v8i8 && M.size() == 8;
6090 }
6091 
6092 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6093                                unsigned Index) {
6094   if (Mask.size() == Elements * 2)
6095     return Index / Elements;
6096   return Mask[Index] == 0 ? 0 : 1;
6097 }
6098 
6099 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6100 // checking that pairs of elements in the shuffle mask represent the same index
6101 // in each vector, incrementing the expected index by 2 at each step.
6102 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6103 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6104 //  v2={e,f,g,h}
6105 // WhichResult gives the offset for each element in the mask based on which
6106 // of the two results it belongs to.
6107 //
6108 // The transpose can be represented either as:
6109 // result1 = shufflevector v1, v2, result1_shuffle_mask
6110 // result2 = shufflevector v1, v2, result2_shuffle_mask
6111 // where v1/v2 and the shuffle masks have the same number of elements
6112 // (here WhichResult (see below) indicates which result is being checked)
6113 //
6114 // or as:
6115 // results = shufflevector v1, v2, shuffle_mask
6116 // where both results are returned in one vector and the shuffle mask has twice
6117 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6118 // want to check the low half and high half of the shuffle mask as if it were
6119 // the other case
6120 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6121   unsigned EltSz = VT.getScalarSizeInBits();
6122   if (EltSz == 64)
6123     return false;
6124 
6125   unsigned NumElts = VT.getVectorNumElements();
6126   if (M.size() != NumElts && M.size() != NumElts*2)
6127     return false;
6128 
6129   // If the mask is twice as long as the input vector then we need to check the
6130   // upper and lower parts of the mask with a matching value for WhichResult
6131   // FIXME: A mask with only even values will be rejected in case the first
6132   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6133   // M[0] is used to determine WhichResult
6134   for (unsigned i = 0; i < M.size(); i += NumElts) {
6135     WhichResult = SelectPairHalf(NumElts, M, i);
6136     for (unsigned j = 0; j < NumElts; j += 2) {
6137       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6138           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6139         return false;
6140     }
6141   }
6142 
6143   if (M.size() == NumElts*2)
6144     WhichResult = 0;
6145 
6146   return true;
6147 }
6148 
6149 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6150 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6151 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6152 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6153   unsigned EltSz = VT.getScalarSizeInBits();
6154   if (EltSz == 64)
6155     return false;
6156 
6157   unsigned NumElts = VT.getVectorNumElements();
6158   if (M.size() != NumElts && M.size() != NumElts*2)
6159     return false;
6160 
6161   for (unsigned i = 0; i < M.size(); i += NumElts) {
6162     WhichResult = SelectPairHalf(NumElts, M, i);
6163     for (unsigned j = 0; j < NumElts; j += 2) {
6164       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6165           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6166         return false;
6167     }
6168   }
6169 
6170   if (M.size() == NumElts*2)
6171     WhichResult = 0;
6172 
6173   return true;
6174 }
6175 
6176 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6177 // that the mask elements are either all even and in steps of size 2 or all odd
6178 // and in steps of size 2.
6179 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6180 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6181 //  v2={e,f,g,h}
6182 // Requires similar checks to that of isVTRNMask with
6183 // respect the how results are returned.
6184 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6185   unsigned EltSz = VT.getScalarSizeInBits();
6186   if (EltSz == 64)
6187     return false;
6188 
6189   unsigned NumElts = VT.getVectorNumElements();
6190   if (M.size() != NumElts && M.size() != NumElts*2)
6191     return false;
6192 
6193   for (unsigned i = 0; i < M.size(); i += NumElts) {
6194     WhichResult = SelectPairHalf(NumElts, M, i);
6195     for (unsigned j = 0; j < NumElts; ++j) {
6196       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6197         return false;
6198     }
6199   }
6200 
6201   if (M.size() == NumElts*2)
6202     WhichResult = 0;
6203 
6204   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6205   if (VT.is64BitVector() && EltSz == 32)
6206     return false;
6207 
6208   return true;
6209 }
6210 
6211 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6212 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6213 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6214 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6215   unsigned EltSz = VT.getScalarSizeInBits();
6216   if (EltSz == 64)
6217     return false;
6218 
6219   unsigned NumElts = VT.getVectorNumElements();
6220   if (M.size() != NumElts && M.size() != NumElts*2)
6221     return false;
6222 
6223   unsigned Half = NumElts / 2;
6224   for (unsigned i = 0; i < M.size(); i += NumElts) {
6225     WhichResult = SelectPairHalf(NumElts, M, i);
6226     for (unsigned j = 0; j < NumElts; j += Half) {
6227       unsigned Idx = WhichResult;
6228       for (unsigned k = 0; k < Half; ++k) {
6229         int MIdx = M[i + j + k];
6230         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6231           return false;
6232         Idx += 2;
6233       }
6234     }
6235   }
6236 
6237   if (M.size() == NumElts*2)
6238     WhichResult = 0;
6239 
6240   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6241   if (VT.is64BitVector() && EltSz == 32)
6242     return false;
6243 
6244   return true;
6245 }
6246 
6247 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6248 // that pairs of elements of the shufflemask represent the same index in each
6249 // vector incrementing sequentially through the vectors.
6250 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6251 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6252 //  v2={e,f,g,h}
6253 // Requires similar checks to that of isVTRNMask with respect the how results
6254 // are returned.
6255 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6256   unsigned EltSz = VT.getScalarSizeInBits();
6257   if (EltSz == 64)
6258     return false;
6259 
6260   unsigned NumElts = VT.getVectorNumElements();
6261   if (M.size() != NumElts && M.size() != NumElts*2)
6262     return false;
6263 
6264   for (unsigned i = 0; i < M.size(); i += NumElts) {
6265     WhichResult = SelectPairHalf(NumElts, M, i);
6266     unsigned Idx = WhichResult * NumElts / 2;
6267     for (unsigned j = 0; j < NumElts; j += 2) {
6268       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6269           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6270         return false;
6271       Idx += 1;
6272     }
6273   }
6274 
6275   if (M.size() == NumElts*2)
6276     WhichResult = 0;
6277 
6278   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6279   if (VT.is64BitVector() && EltSz == 32)
6280     return false;
6281 
6282   return true;
6283 }
6284 
6285 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6286 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6287 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6288 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6289   unsigned EltSz = VT.getScalarSizeInBits();
6290   if (EltSz == 64)
6291     return false;
6292 
6293   unsigned NumElts = VT.getVectorNumElements();
6294   if (M.size() != NumElts && M.size() != NumElts*2)
6295     return false;
6296 
6297   for (unsigned i = 0; i < M.size(); i += NumElts) {
6298     WhichResult = SelectPairHalf(NumElts, M, i);
6299     unsigned Idx = WhichResult * NumElts / 2;
6300     for (unsigned j = 0; j < NumElts; j += 2) {
6301       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6302           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6303         return false;
6304       Idx += 1;
6305     }
6306   }
6307 
6308   if (M.size() == NumElts*2)
6309     WhichResult = 0;
6310 
6311   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6312   if (VT.is64BitVector() && EltSz == 32)
6313     return false;
6314 
6315   return true;
6316 }
6317 
6318 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6319 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6320 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6321                                            unsigned &WhichResult,
6322                                            bool &isV_UNDEF) {
6323   isV_UNDEF = false;
6324   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6325     return ARMISD::VTRN;
6326   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6327     return ARMISD::VUZP;
6328   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6329     return ARMISD::VZIP;
6330 
6331   isV_UNDEF = true;
6332   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6333     return ARMISD::VTRN;
6334   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6335     return ARMISD::VUZP;
6336   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6337     return ARMISD::VZIP;
6338 
6339   return 0;
6340 }
6341 
6342 /// \return true if this is a reverse operation on an vector.
6343 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6344   unsigned NumElts = VT.getVectorNumElements();
6345   // Make sure the mask has the right size.
6346   if (NumElts != M.size())
6347       return false;
6348 
6349   // Look for <15, ..., 3, -1, 1, 0>.
6350   for (unsigned i = 0; i != NumElts; ++i)
6351     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6352       return false;
6353 
6354   return true;
6355 }
6356 
6357 // If N is an integer constant that can be moved into a register in one
6358 // instruction, return an SDValue of such a constant (will become a MOV
6359 // instruction).  Otherwise return null.
6360 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6361                                      const ARMSubtarget *ST, const SDLoc &dl) {
6362   uint64_t Val;
6363   if (!isa<ConstantSDNode>(N))
6364     return SDValue();
6365   Val = cast<ConstantSDNode>(N)->getZExtValue();
6366 
6367   if (ST->isThumb1Only()) {
6368     if (Val <= 255 || ~Val <= 255)
6369       return DAG.getConstant(Val, dl, MVT::i32);
6370   } else {
6371     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6372       return DAG.getConstant(Val, dl, MVT::i32);
6373   }
6374   return SDValue();
6375 }
6376 
6377 // If this is a case we can't handle, return null and let the default
6378 // expansion code take care of it.
6379 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6380                                              const ARMSubtarget *ST) const {
6381   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6382   SDLoc dl(Op);
6383   EVT VT = Op.getValueType();
6384 
6385   APInt SplatBits, SplatUndef;
6386   unsigned SplatBitSize;
6387   bool HasAnyUndefs;
6388   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6389     if (SplatUndef.isAllOnesValue())
6390       return DAG.getUNDEF(VT);
6391 
6392     if (SplatBitSize <= 64) {
6393       // Check if an immediate VMOV works.
6394       EVT VmovVT;
6395       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6396                                       SplatUndef.getZExtValue(), SplatBitSize,
6397                                       DAG, dl, VmovVT, VT.is128BitVector(),
6398                                       VMOVModImm);
6399       if (Val.getNode()) {
6400         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6401         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6402       }
6403 
6404       // Try an immediate VMVN.
6405       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6406       Val = isNEONModifiedImm(NegatedImm,
6407                                       SplatUndef.getZExtValue(), SplatBitSize,
6408                                       DAG, dl, VmovVT, VT.is128BitVector(),
6409                                       VMVNModImm);
6410       if (Val.getNode()) {
6411         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6412         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6413       }
6414 
6415       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6416       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6417         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6418         if (ImmVal != -1) {
6419           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6420           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6421         }
6422       }
6423     }
6424   }
6425 
6426   // Scan through the operands to see if only one value is used.
6427   //
6428   // As an optimisation, even if more than one value is used it may be more
6429   // profitable to splat with one value then change some lanes.
6430   //
6431   // Heuristically we decide to do this if the vector has a "dominant" value,
6432   // defined as splatted to more than half of the lanes.
6433   unsigned NumElts = VT.getVectorNumElements();
6434   bool isOnlyLowElement = true;
6435   bool usesOnlyOneValue = true;
6436   bool hasDominantValue = false;
6437   bool isConstant = true;
6438 
6439   // Map of the number of times a particular SDValue appears in the
6440   // element list.
6441   DenseMap<SDValue, unsigned> ValueCounts;
6442   SDValue Value;
6443   for (unsigned i = 0; i < NumElts; ++i) {
6444     SDValue V = Op.getOperand(i);
6445     if (V.isUndef())
6446       continue;
6447     if (i > 0)
6448       isOnlyLowElement = false;
6449     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6450       isConstant = false;
6451 
6452     ValueCounts.insert(std::make_pair(V, 0));
6453     unsigned &Count = ValueCounts[V];
6454 
6455     // Is this value dominant? (takes up more than half of the lanes)
6456     if (++Count > (NumElts / 2)) {
6457       hasDominantValue = true;
6458       Value = V;
6459     }
6460   }
6461   if (ValueCounts.size() != 1)
6462     usesOnlyOneValue = false;
6463   if (!Value.getNode() && !ValueCounts.empty())
6464     Value = ValueCounts.begin()->first;
6465 
6466   if (ValueCounts.empty())
6467     return DAG.getUNDEF(VT);
6468 
6469   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6470   // Keep going if we are hitting this case.
6471   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6472     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6473 
6474   unsigned EltSize = VT.getScalarSizeInBits();
6475 
6476   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6477   // i32 and try again.
6478   if (hasDominantValue && EltSize <= 32) {
6479     if (!isConstant) {
6480       SDValue N;
6481 
6482       // If we are VDUPing a value that comes directly from a vector, that will
6483       // cause an unnecessary move to and from a GPR, where instead we could
6484       // just use VDUPLANE. We can only do this if the lane being extracted
6485       // is at a constant index, as the VDUP from lane instructions only have
6486       // constant-index forms.
6487       ConstantSDNode *constIndex;
6488       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6489           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6490         // We need to create a new undef vector to use for the VDUPLANE if the
6491         // size of the vector from which we get the value is different than the
6492         // size of the vector that we need to create. We will insert the element
6493         // such that the register coalescer will remove unnecessary copies.
6494         if (VT != Value->getOperand(0).getValueType()) {
6495           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6496                              VT.getVectorNumElements();
6497           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6498                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6499                         Value, DAG.getConstant(index, dl, MVT::i32)),
6500                            DAG.getConstant(index, dl, MVT::i32));
6501         } else
6502           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6503                         Value->getOperand(0), Value->getOperand(1));
6504       } else
6505         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6506 
6507       if (!usesOnlyOneValue) {
6508         // The dominant value was splatted as 'N', but we now have to insert
6509         // all differing elements.
6510         for (unsigned I = 0; I < NumElts; ++I) {
6511           if (Op.getOperand(I) == Value)
6512             continue;
6513           SmallVector<SDValue, 3> Ops;
6514           Ops.push_back(N);
6515           Ops.push_back(Op.getOperand(I));
6516           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6517           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6518         }
6519       }
6520       return N;
6521     }
6522     if (VT.getVectorElementType().isFloatingPoint()) {
6523       SmallVector<SDValue, 8> Ops;
6524       for (unsigned i = 0; i < NumElts; ++i)
6525         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6526                                   Op.getOperand(i)));
6527       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6528       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6529       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6530       if (Val.getNode())
6531         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6532     }
6533     if (usesOnlyOneValue) {
6534       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6535       if (isConstant && Val.getNode())
6536         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6537     }
6538   }
6539 
6540   // If all elements are constants and the case above didn't get hit, fall back
6541   // to the default expansion, which will generate a load from the constant
6542   // pool.
6543   if (isConstant)
6544     return SDValue();
6545 
6546   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6547   if (NumElts >= 4) {
6548     SDValue shuffle = ReconstructShuffle(Op, DAG);
6549     if (shuffle != SDValue())
6550       return shuffle;
6551   }
6552 
6553   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6554     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6555     // into two 64-bit vectors; we might discover a better way to lower it.
6556     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6557     EVT ExtVT = VT.getVectorElementType();
6558     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6559     SDValue Lower =
6560         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6561     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6562       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6563     SDValue Upper = DAG.getBuildVector(
6564         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6565     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6566       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6567     if (Lower && Upper)
6568       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6569   }
6570 
6571   // Vectors with 32- or 64-bit elements can be built by directly assigning
6572   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6573   // will be legalized.
6574   if (EltSize >= 32) {
6575     // Do the expansion with floating-point types, since that is what the VFP
6576     // registers are defined to use, and since i64 is not legal.
6577     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6578     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6579     SmallVector<SDValue, 8> Ops;
6580     for (unsigned i = 0; i < NumElts; ++i)
6581       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6582     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6583     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6584   }
6585 
6586   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6587   // know the default expansion would otherwise fall back on something even
6588   // worse. For a vector with one or two non-undef values, that's
6589   // scalar_to_vector for the elements followed by a shuffle (provided the
6590   // shuffle is valid for the target) and materialization element by element
6591   // on the stack followed by a load for everything else.
6592   if (!isConstant && !usesOnlyOneValue) {
6593     SDValue Vec = DAG.getUNDEF(VT);
6594     for (unsigned i = 0 ; i < NumElts; ++i) {
6595       SDValue V = Op.getOperand(i);
6596       if (V.isUndef())
6597         continue;
6598       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6599       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6600     }
6601     return Vec;
6602   }
6603 
6604   return SDValue();
6605 }
6606 
6607 // Gather data to see if the operation can be modelled as a
6608 // shuffle in combination with VEXTs.
6609 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6610                                               SelectionDAG &DAG) const {
6611   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6612   SDLoc dl(Op);
6613   EVT VT = Op.getValueType();
6614   unsigned NumElts = VT.getVectorNumElements();
6615 
6616   struct ShuffleSourceInfo {
6617     SDValue Vec;
6618     unsigned MinElt = std::numeric_limits<unsigned>::max();
6619     unsigned MaxElt = 0;
6620 
6621     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6622     // be compatible with the shuffle we intend to construct. As a result
6623     // ShuffleVec will be some sliding window into the original Vec.
6624     SDValue ShuffleVec;
6625 
6626     // Code should guarantee that element i in Vec starts at element "WindowBase
6627     // + i * WindowScale in ShuffleVec".
6628     int WindowBase = 0;
6629     int WindowScale = 1;
6630 
6631     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6632 
6633     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6634   };
6635 
6636   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6637   // node.
6638   SmallVector<ShuffleSourceInfo, 2> Sources;
6639   for (unsigned i = 0; i < NumElts; ++i) {
6640     SDValue V = Op.getOperand(i);
6641     if (V.isUndef())
6642       continue;
6643     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6644       // A shuffle can only come from building a vector from various
6645       // elements of other vectors.
6646       return SDValue();
6647     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6648       // Furthermore, shuffles require a constant mask, whereas extractelts
6649       // accept variable indices.
6650       return SDValue();
6651     }
6652 
6653     // Add this element source to the list if it's not already there.
6654     SDValue SourceVec = V.getOperand(0);
6655     auto Source = llvm::find(Sources, SourceVec);
6656     if (Source == Sources.end())
6657       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6658 
6659     // Update the minimum and maximum lane number seen.
6660     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6661     Source->MinElt = std::min(Source->MinElt, EltNo);
6662     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6663   }
6664 
6665   // Currently only do something sane when at most two source vectors
6666   // are involved.
6667   if (Sources.size() > 2)
6668     return SDValue();
6669 
6670   // Find out the smallest element size among result and two sources, and use
6671   // it as element size to build the shuffle_vector.
6672   EVT SmallestEltTy = VT.getVectorElementType();
6673   for (auto &Source : Sources) {
6674     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6675     if (SrcEltTy.bitsLT(SmallestEltTy))
6676       SmallestEltTy = SrcEltTy;
6677   }
6678   unsigned ResMultiplier =
6679       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6680   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6681   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6682 
6683   // If the source vector is too wide or too narrow, we may nevertheless be able
6684   // to construct a compatible shuffle either by concatenating it with UNDEF or
6685   // extracting a suitable range of elements.
6686   for (auto &Src : Sources) {
6687     EVT SrcVT = Src.ShuffleVec.getValueType();
6688 
6689     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6690       continue;
6691 
6692     // This stage of the search produces a source with the same element type as
6693     // the original, but with a total width matching the BUILD_VECTOR output.
6694     EVT EltVT = SrcVT.getVectorElementType();
6695     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6696     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6697 
6698     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6699       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6700         return SDValue();
6701       // We can pad out the smaller vector for free, so if it's part of a
6702       // shuffle...
6703       Src.ShuffleVec =
6704           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6705                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6706       continue;
6707     }
6708 
6709     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6710       return SDValue();
6711 
6712     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6713       // Span too large for a VEXT to cope
6714       return SDValue();
6715     }
6716 
6717     if (Src.MinElt >= NumSrcElts) {
6718       // The extraction can just take the second half
6719       Src.ShuffleVec =
6720           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6721                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6722       Src.WindowBase = -NumSrcElts;
6723     } else if (Src.MaxElt < NumSrcElts) {
6724       // The extraction can just take the first half
6725       Src.ShuffleVec =
6726           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6727                       DAG.getConstant(0, dl, MVT::i32));
6728     } else {
6729       // An actual VEXT is needed
6730       SDValue VEXTSrc1 =
6731           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6732                       DAG.getConstant(0, dl, MVT::i32));
6733       SDValue VEXTSrc2 =
6734           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6735                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6736 
6737       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6738                                    VEXTSrc2,
6739                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6740       Src.WindowBase = -Src.MinElt;
6741     }
6742   }
6743 
6744   // Another possible incompatibility occurs from the vector element types. We
6745   // can fix this by bitcasting the source vectors to the same type we intend
6746   // for the shuffle.
6747   for (auto &Src : Sources) {
6748     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6749     if (SrcEltTy == SmallestEltTy)
6750       continue;
6751     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6752     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6753     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6754     Src.WindowBase *= Src.WindowScale;
6755   }
6756 
6757   // Final sanity check before we try to actually produce a shuffle.
6758   LLVM_DEBUG(for (auto Src
6759                   : Sources)
6760                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6761 
6762   // The stars all align, our next step is to produce the mask for the shuffle.
6763   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6764   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6765   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6766     SDValue Entry = Op.getOperand(i);
6767     if (Entry.isUndef())
6768       continue;
6769 
6770     auto Src = llvm::find(Sources, Entry.getOperand(0));
6771     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6772 
6773     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6774     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6775     // segment.
6776     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6777     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6778                                VT.getScalarSizeInBits());
6779     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6780 
6781     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6782     // starting at the appropriate offset.
6783     int *LaneMask = &Mask[i * ResMultiplier];
6784 
6785     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6786     ExtractBase += NumElts * (Src - Sources.begin());
6787     for (int j = 0; j < LanesDefined; ++j)
6788       LaneMask[j] = ExtractBase + j;
6789   }
6790 
6791   // Final check before we try to produce nonsense...
6792   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6793     return SDValue();
6794 
6795   // We can't handle more than two sources. This should have already
6796   // been checked before this point.
6797   assert(Sources.size() <= 2 && "Too many sources!");
6798 
6799   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6800   for (unsigned i = 0; i < Sources.size(); ++i)
6801     ShuffleOps[i] = Sources[i].ShuffleVec;
6802 
6803   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6804                                          ShuffleOps[1], Mask);
6805   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6806 }
6807 
6808 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6809 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6810 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6811 /// are assumed to be legal.
6812 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6813   if (VT.getVectorNumElements() == 4 &&
6814       (VT.is128BitVector() || VT.is64BitVector())) {
6815     unsigned PFIndexes[4];
6816     for (unsigned i = 0; i != 4; ++i) {
6817       if (M[i] < 0)
6818         PFIndexes[i] = 8;
6819       else
6820         PFIndexes[i] = M[i];
6821     }
6822 
6823     // Compute the index in the perfect shuffle table.
6824     unsigned PFTableIndex =
6825       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6826     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6827     unsigned Cost = (PFEntry >> 30);
6828 
6829     if (Cost <= 4)
6830       return true;
6831   }
6832 
6833   bool ReverseVEXT, isV_UNDEF;
6834   unsigned Imm, WhichResult;
6835 
6836   unsigned EltSize = VT.getScalarSizeInBits();
6837   return (EltSize >= 32 ||
6838           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6839           isVREVMask(M, VT, 64) ||
6840           isVREVMask(M, VT, 32) ||
6841           isVREVMask(M, VT, 16) ||
6842           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6843           isVTBLMask(M, VT) ||
6844           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6845           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6846 }
6847 
6848 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6849 /// the specified operations to build the shuffle.
6850 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6851                                       SDValue RHS, SelectionDAG &DAG,
6852                                       const SDLoc &dl) {
6853   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6854   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6855   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6856 
6857   enum {
6858     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6859     OP_VREV,
6860     OP_VDUP0,
6861     OP_VDUP1,
6862     OP_VDUP2,
6863     OP_VDUP3,
6864     OP_VEXT1,
6865     OP_VEXT2,
6866     OP_VEXT3,
6867     OP_VUZPL, // VUZP, left result
6868     OP_VUZPR, // VUZP, right result
6869     OP_VZIPL, // VZIP, left result
6870     OP_VZIPR, // VZIP, right result
6871     OP_VTRNL, // VTRN, left result
6872     OP_VTRNR  // VTRN, right result
6873   };
6874 
6875   if (OpNum == OP_COPY) {
6876     if (LHSID == (1*9+2)*9+3) return LHS;
6877     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6878     return RHS;
6879   }
6880 
6881   SDValue OpLHS, OpRHS;
6882   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6883   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6884   EVT VT = OpLHS.getValueType();
6885 
6886   switch (OpNum) {
6887   default: llvm_unreachable("Unknown shuffle opcode!");
6888   case OP_VREV:
6889     // VREV divides the vector in half and swaps within the half.
6890     if (VT.getVectorElementType() == MVT::i32 ||
6891         VT.getVectorElementType() == MVT::f32)
6892       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6893     // vrev <4 x i16> -> VREV32
6894     if (VT.getVectorElementType() == MVT::i16)
6895       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6896     // vrev <4 x i8> -> VREV16
6897     assert(VT.getVectorElementType() == MVT::i8);
6898     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6899   case OP_VDUP0:
6900   case OP_VDUP1:
6901   case OP_VDUP2:
6902   case OP_VDUP3:
6903     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6904                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6905   case OP_VEXT1:
6906   case OP_VEXT2:
6907   case OP_VEXT3:
6908     return DAG.getNode(ARMISD::VEXT, dl, VT,
6909                        OpLHS, OpRHS,
6910                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6911   case OP_VUZPL:
6912   case OP_VUZPR:
6913     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6914                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6915   case OP_VZIPL:
6916   case OP_VZIPR:
6917     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6918                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6919   case OP_VTRNL:
6920   case OP_VTRNR:
6921     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6922                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6923   }
6924 }
6925 
6926 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6927                                        ArrayRef<int> ShuffleMask,
6928                                        SelectionDAG &DAG) {
6929   // Check to see if we can use the VTBL instruction.
6930   SDValue V1 = Op.getOperand(0);
6931   SDValue V2 = Op.getOperand(1);
6932   SDLoc DL(Op);
6933 
6934   SmallVector<SDValue, 8> VTBLMask;
6935   for (ArrayRef<int>::iterator
6936          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6937     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6938 
6939   if (V2.getNode()->isUndef())
6940     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6941                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6942 
6943   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6944                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6945 }
6946 
6947 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6948                                                       SelectionDAG &DAG) {
6949   SDLoc DL(Op);
6950   SDValue OpLHS = Op.getOperand(0);
6951   EVT VT = OpLHS.getValueType();
6952 
6953   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6954          "Expect an v8i16/v16i8 type");
6955   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6956   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6957   // extract the first 8 bytes into the top double word and the last 8 bytes
6958   // into the bottom double word. The v8i16 case is similar.
6959   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6960   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6961                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6962 }
6963 
6964 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6965   SDValue V1 = Op.getOperand(0);
6966   SDValue V2 = Op.getOperand(1);
6967   SDLoc dl(Op);
6968   EVT VT = Op.getValueType();
6969   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6970 
6971   // Convert shuffles that are directly supported on NEON to target-specific
6972   // DAG nodes, instead of keeping them as shuffles and matching them again
6973   // during code selection.  This is more efficient and avoids the possibility
6974   // of inconsistencies between legalization and selection.
6975   // FIXME: floating-point vectors should be canonicalized to integer vectors
6976   // of the same time so that they get CSEd properly.
6977   ArrayRef<int> ShuffleMask = SVN->getMask();
6978 
6979   unsigned EltSize = VT.getScalarSizeInBits();
6980   if (EltSize <= 32) {
6981     if (SVN->isSplat()) {
6982       int Lane = SVN->getSplatIndex();
6983       // If this is undef splat, generate it via "just" vdup, if possible.
6984       if (Lane == -1) Lane = 0;
6985 
6986       // Test if V1 is a SCALAR_TO_VECTOR.
6987       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6988         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6989       }
6990       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6991       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6992       // reaches it).
6993       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6994           !isa<ConstantSDNode>(V1.getOperand(0))) {
6995         bool IsScalarToVector = true;
6996         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6997           if (!V1.getOperand(i).isUndef()) {
6998             IsScalarToVector = false;
6999             break;
7000           }
7001         if (IsScalarToVector)
7002           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7003       }
7004       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7005                          DAG.getConstant(Lane, dl, MVT::i32));
7006     }
7007 
7008     bool ReverseVEXT;
7009     unsigned Imm;
7010     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7011       if (ReverseVEXT)
7012         std::swap(V1, V2);
7013       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7014                          DAG.getConstant(Imm, dl, MVT::i32));
7015     }
7016 
7017     if (isVREVMask(ShuffleMask, VT, 64))
7018       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7019     if (isVREVMask(ShuffleMask, VT, 32))
7020       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7021     if (isVREVMask(ShuffleMask, VT, 16))
7022       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7023 
7024     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7025       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7026                          DAG.getConstant(Imm, dl, MVT::i32));
7027     }
7028 
7029     // Check for Neon shuffles that modify both input vectors in place.
7030     // If both results are used, i.e., if there are two shuffles with the same
7031     // source operands and with masks corresponding to both results of one of
7032     // these operations, DAG memoization will ensure that a single node is
7033     // used for both shuffles.
7034     unsigned WhichResult;
7035     bool isV_UNDEF;
7036     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7037             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7038       if (isV_UNDEF)
7039         V2 = V1;
7040       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7041           .getValue(WhichResult);
7042     }
7043 
7044     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7045     // shuffles that produce a result larger than their operands with:
7046     //   shuffle(concat(v1, undef), concat(v2, undef))
7047     // ->
7048     //   shuffle(concat(v1, v2), undef)
7049     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7050     //
7051     // This is useful in the general case, but there are special cases where
7052     // native shuffles produce larger results: the two-result ops.
7053     //
7054     // Look through the concat when lowering them:
7055     //   shuffle(concat(v1, v2), undef)
7056     // ->
7057     //   concat(VZIP(v1, v2):0, :1)
7058     //
7059     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7060       SDValue SubV1 = V1->getOperand(0);
7061       SDValue SubV2 = V1->getOperand(1);
7062       EVT SubVT = SubV1.getValueType();
7063 
7064       // We expect these to have been canonicalized to -1.
7065       assert(llvm::all_of(ShuffleMask, [&](int i) {
7066         return i < (int)VT.getVectorNumElements();
7067       }) && "Unexpected shuffle index into UNDEF operand!");
7068 
7069       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7070               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7071         if (isV_UNDEF)
7072           SubV2 = SubV1;
7073         assert((WhichResult == 0) &&
7074                "In-place shuffle of concat can only have one result!");
7075         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7076                                   SubV1, SubV2);
7077         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7078                            Res.getValue(1));
7079       }
7080     }
7081   }
7082 
7083   // If the shuffle is not directly supported and it has 4 elements, use
7084   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7085   unsigned NumElts = VT.getVectorNumElements();
7086   if (NumElts == 4) {
7087     unsigned PFIndexes[4];
7088     for (unsigned i = 0; i != 4; ++i) {
7089       if (ShuffleMask[i] < 0)
7090         PFIndexes[i] = 8;
7091       else
7092         PFIndexes[i] = ShuffleMask[i];
7093     }
7094 
7095     // Compute the index in the perfect shuffle table.
7096     unsigned PFTableIndex =
7097       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7098     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7099     unsigned Cost = (PFEntry >> 30);
7100 
7101     if (Cost <= 4)
7102       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7103   }
7104 
7105   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7106   if (EltSize >= 32) {
7107     // Do the expansion with floating-point types, since that is what the VFP
7108     // registers are defined to use, and since i64 is not legal.
7109     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7110     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7111     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7112     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7113     SmallVector<SDValue, 8> Ops;
7114     for (unsigned i = 0; i < NumElts; ++i) {
7115       if (ShuffleMask[i] < 0)
7116         Ops.push_back(DAG.getUNDEF(EltVT));
7117       else
7118         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7119                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7120                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7121                                                   dl, MVT::i32)));
7122     }
7123     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7124     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7125   }
7126 
7127   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7128     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7129 
7130   if (VT == MVT::v8i8)
7131     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7132       return NewOp;
7133 
7134   return SDValue();
7135 }
7136 
7137 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7138   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7139   SDValue Lane = Op.getOperand(2);
7140   if (!isa<ConstantSDNode>(Lane))
7141     return SDValue();
7142 
7143   return Op;
7144 }
7145 
7146 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7147   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7148   SDValue Lane = Op.getOperand(1);
7149   if (!isa<ConstantSDNode>(Lane))
7150     return SDValue();
7151 
7152   SDValue Vec = Op.getOperand(0);
7153   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7154     SDLoc dl(Op);
7155     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7156   }
7157 
7158   return Op;
7159 }
7160 
7161 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7162   // The only time a CONCAT_VECTORS operation can have legal types is when
7163   // two 64-bit vectors are concatenated to a 128-bit vector.
7164   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7165          "unexpected CONCAT_VECTORS");
7166   SDLoc dl(Op);
7167   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7168   SDValue Op0 = Op.getOperand(0);
7169   SDValue Op1 = Op.getOperand(1);
7170   if (!Op0.isUndef())
7171     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7172                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7173                       DAG.getIntPtrConstant(0, dl));
7174   if (!Op1.isUndef())
7175     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7176                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7177                       DAG.getIntPtrConstant(1, dl));
7178   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7179 }
7180 
7181 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7182 /// element has been zero/sign-extended, depending on the isSigned parameter,
7183 /// from an integer type half its size.
7184 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7185                                    bool isSigned) {
7186   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7187   EVT VT = N->getValueType(0);
7188   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7189     SDNode *BVN = N->getOperand(0).getNode();
7190     if (BVN->getValueType(0) != MVT::v4i32 ||
7191         BVN->getOpcode() != ISD::BUILD_VECTOR)
7192       return false;
7193     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7194     unsigned HiElt = 1 - LoElt;
7195     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7196     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7197     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7198     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7199     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7200       return false;
7201     if (isSigned) {
7202       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7203           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7204         return true;
7205     } else {
7206       if (Hi0->isNullValue() && Hi1->isNullValue())
7207         return true;
7208     }
7209     return false;
7210   }
7211 
7212   if (N->getOpcode() != ISD::BUILD_VECTOR)
7213     return false;
7214 
7215   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7216     SDNode *Elt = N->getOperand(i).getNode();
7217     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7218       unsigned EltSize = VT.getScalarSizeInBits();
7219       unsigned HalfSize = EltSize / 2;
7220       if (isSigned) {
7221         if (!isIntN(HalfSize, C->getSExtValue()))
7222           return false;
7223       } else {
7224         if (!isUIntN(HalfSize, C->getZExtValue()))
7225           return false;
7226       }
7227       continue;
7228     }
7229     return false;
7230   }
7231 
7232   return true;
7233 }
7234 
7235 /// isSignExtended - Check if a node is a vector value that is sign-extended
7236 /// or a constant BUILD_VECTOR with sign-extended elements.
7237 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7238   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7239     return true;
7240   if (isExtendedBUILD_VECTOR(N, DAG, true))
7241     return true;
7242   return false;
7243 }
7244 
7245 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7246 /// or a constant BUILD_VECTOR with zero-extended elements.
7247 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7248   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7249     return true;
7250   if (isExtendedBUILD_VECTOR(N, DAG, false))
7251     return true;
7252   return false;
7253 }
7254 
7255 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7256   if (OrigVT.getSizeInBits() >= 64)
7257     return OrigVT;
7258 
7259   assert(OrigVT.isSimple() && "Expecting a simple value type");
7260 
7261   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7262   switch (OrigSimpleTy) {
7263   default: llvm_unreachable("Unexpected Vector Type");
7264   case MVT::v2i8:
7265   case MVT::v2i16:
7266      return MVT::v2i32;
7267   case MVT::v4i8:
7268     return  MVT::v4i16;
7269   }
7270 }
7271 
7272 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7273 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7274 /// We insert the required extension here to get the vector to fill a D register.
7275 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7276                                             const EVT &OrigTy,
7277                                             const EVT &ExtTy,
7278                                             unsigned ExtOpcode) {
7279   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7280   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7281   // 64-bits we need to insert a new extension so that it will be 64-bits.
7282   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7283   if (OrigTy.getSizeInBits() >= 64)
7284     return N;
7285 
7286   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7287   EVT NewVT = getExtensionTo64Bits(OrigTy);
7288 
7289   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7290 }
7291 
7292 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7293 /// does not do any sign/zero extension. If the original vector is less
7294 /// than 64 bits, an appropriate extension will be added after the load to
7295 /// reach a total size of 64 bits. We have to add the extension separately
7296 /// because ARM does not have a sign/zero extending load for vectors.
7297 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7298   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7299 
7300   // The load already has the right type.
7301   if (ExtendedTy == LD->getMemoryVT())
7302     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7303                        LD->getBasePtr(), LD->getPointerInfo(),
7304                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7305 
7306   // We need to create a zextload/sextload. We cannot just create a load
7307   // followed by a zext/zext node because LowerMUL is also run during normal
7308   // operation legalization where we can't create illegal types.
7309   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7310                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7311                         LD->getMemoryVT(), LD->getAlignment(),
7312                         LD->getMemOperand()->getFlags());
7313 }
7314 
7315 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7316 /// extending load, or BUILD_VECTOR with extended elements, return the
7317 /// unextended value. The unextended vector should be 64 bits so that it can
7318 /// be used as an operand to a VMULL instruction. If the original vector size
7319 /// before extension is less than 64 bits we add a an extension to resize
7320 /// the vector to 64 bits.
7321 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7322   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7323     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7324                                         N->getOperand(0)->getValueType(0),
7325                                         N->getValueType(0),
7326                                         N->getOpcode());
7327 
7328   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7329     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7330            "Expected extending load");
7331 
7332     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7333     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7334     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7335     SDValue extLoad =
7336         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7337     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7338 
7339     return newLoad;
7340   }
7341 
7342   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7343   // have been legalized as a BITCAST from v4i32.
7344   if (N->getOpcode() == ISD::BITCAST) {
7345     SDNode *BVN = N->getOperand(0).getNode();
7346     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7347            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7348     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7349     return DAG.getBuildVector(
7350         MVT::v2i32, SDLoc(N),
7351         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7352   }
7353   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7354   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7355   EVT VT = N->getValueType(0);
7356   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7357   unsigned NumElts = VT.getVectorNumElements();
7358   MVT TruncVT = MVT::getIntegerVT(EltSize);
7359   SmallVector<SDValue, 8> Ops;
7360   SDLoc dl(N);
7361   for (unsigned i = 0; i != NumElts; ++i) {
7362     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7363     const APInt &CInt = C->getAPIntValue();
7364     // Element types smaller than 32 bits are not legal, so use i32 elements.
7365     // The values are implicitly truncated so sext vs. zext doesn't matter.
7366     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7367   }
7368   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7369 }
7370 
7371 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7372   unsigned Opcode = N->getOpcode();
7373   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7374     SDNode *N0 = N->getOperand(0).getNode();
7375     SDNode *N1 = N->getOperand(1).getNode();
7376     return N0->hasOneUse() && N1->hasOneUse() &&
7377       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7378   }
7379   return false;
7380 }
7381 
7382 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7383   unsigned Opcode = N->getOpcode();
7384   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7385     SDNode *N0 = N->getOperand(0).getNode();
7386     SDNode *N1 = N->getOperand(1).getNode();
7387     return N0->hasOneUse() && N1->hasOneUse() &&
7388       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7389   }
7390   return false;
7391 }
7392 
7393 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7394   // Multiplications are only custom-lowered for 128-bit vectors so that
7395   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7396   EVT VT = Op.getValueType();
7397   assert(VT.is128BitVector() && VT.isInteger() &&
7398          "unexpected type for custom-lowering ISD::MUL");
7399   SDNode *N0 = Op.getOperand(0).getNode();
7400   SDNode *N1 = Op.getOperand(1).getNode();
7401   unsigned NewOpc = 0;
7402   bool isMLA = false;
7403   bool isN0SExt = isSignExtended(N0, DAG);
7404   bool isN1SExt = isSignExtended(N1, DAG);
7405   if (isN0SExt && isN1SExt)
7406     NewOpc = ARMISD::VMULLs;
7407   else {
7408     bool isN0ZExt = isZeroExtended(N0, DAG);
7409     bool isN1ZExt = isZeroExtended(N1, DAG);
7410     if (isN0ZExt && isN1ZExt)
7411       NewOpc = ARMISD::VMULLu;
7412     else if (isN1SExt || isN1ZExt) {
7413       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7414       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7415       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7416         NewOpc = ARMISD::VMULLs;
7417         isMLA = true;
7418       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7419         NewOpc = ARMISD::VMULLu;
7420         isMLA = true;
7421       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7422         std::swap(N0, N1);
7423         NewOpc = ARMISD::VMULLu;
7424         isMLA = true;
7425       }
7426     }
7427 
7428     if (!NewOpc) {
7429       if (VT == MVT::v2i64)
7430         // Fall through to expand this.  It is not legal.
7431         return SDValue();
7432       else
7433         // Other vector multiplications are legal.
7434         return Op;
7435     }
7436   }
7437 
7438   // Legalize to a VMULL instruction.
7439   SDLoc DL(Op);
7440   SDValue Op0;
7441   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7442   if (!isMLA) {
7443     Op0 = SkipExtensionForVMULL(N0, DAG);
7444     assert(Op0.getValueType().is64BitVector() &&
7445            Op1.getValueType().is64BitVector() &&
7446            "unexpected types for extended operands to VMULL");
7447     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7448   }
7449 
7450   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7451   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7452   //   vmull q0, d4, d6
7453   //   vmlal q0, d5, d6
7454   // is faster than
7455   //   vaddl q0, d4, d5
7456   //   vmovl q1, d6
7457   //   vmul  q0, q0, q1
7458   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7459   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7460   EVT Op1VT = Op1.getValueType();
7461   return DAG.getNode(N0->getOpcode(), DL, VT,
7462                      DAG.getNode(NewOpc, DL, VT,
7463                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7464                      DAG.getNode(NewOpc, DL, VT,
7465                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7466 }
7467 
7468 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7469                               SelectionDAG &DAG) {
7470   // TODO: Should this propagate fast-math-flags?
7471 
7472   // Convert to float
7473   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7474   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7475   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7476   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7477   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7478   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7479   // Get reciprocal estimate.
7480   // float4 recip = vrecpeq_f32(yf);
7481   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7482                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7483                    Y);
7484   // Because char has a smaller range than uchar, we can actually get away
7485   // without any newton steps.  This requires that we use a weird bias
7486   // of 0xb000, however (again, this has been exhaustively tested).
7487   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7488   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7489   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7490   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7491   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7492   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7493   // Convert back to short.
7494   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7495   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7496   return X;
7497 }
7498 
7499 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7500                                SelectionDAG &DAG) {
7501   // TODO: Should this propagate fast-math-flags?
7502 
7503   SDValue N2;
7504   // Convert to float.
7505   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7506   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7507   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7508   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7509   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7510   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7511 
7512   // Use reciprocal estimate and one refinement step.
7513   // float4 recip = vrecpeq_f32(yf);
7514   // recip *= vrecpsq_f32(yf, recip);
7515   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7516                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7517                    N1);
7518   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7519                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7520                    N1, N2);
7521   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7522   // Because short has a smaller range than ushort, we can actually get away
7523   // with only a single newton step.  This requires that we use a weird bias
7524   // of 89, however (again, this has been exhaustively tested).
7525   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7526   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7527   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7528   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7529   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7530   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7531   // Convert back to integer and return.
7532   // return vmovn_s32(vcvt_s32_f32(result));
7533   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7534   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7535   return N0;
7536 }
7537 
7538 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7539   EVT VT = Op.getValueType();
7540   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7541          "unexpected type for custom-lowering ISD::SDIV");
7542 
7543   SDLoc dl(Op);
7544   SDValue N0 = Op.getOperand(0);
7545   SDValue N1 = Op.getOperand(1);
7546   SDValue N2, N3;
7547 
7548   if (VT == MVT::v8i8) {
7549     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7550     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7551 
7552     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7553                      DAG.getIntPtrConstant(4, dl));
7554     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7555                      DAG.getIntPtrConstant(4, dl));
7556     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7557                      DAG.getIntPtrConstant(0, dl));
7558     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7559                      DAG.getIntPtrConstant(0, dl));
7560 
7561     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7562     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7563 
7564     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7565     N0 = LowerCONCAT_VECTORS(N0, DAG);
7566 
7567     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7568     return N0;
7569   }
7570   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7571 }
7572 
7573 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7574   // TODO: Should this propagate fast-math-flags?
7575   EVT VT = Op.getValueType();
7576   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7577          "unexpected type for custom-lowering ISD::UDIV");
7578 
7579   SDLoc dl(Op);
7580   SDValue N0 = Op.getOperand(0);
7581   SDValue N1 = Op.getOperand(1);
7582   SDValue N2, N3;
7583 
7584   if (VT == MVT::v8i8) {
7585     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7586     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7587 
7588     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7589                      DAG.getIntPtrConstant(4, dl));
7590     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7591                      DAG.getIntPtrConstant(4, dl));
7592     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7593                      DAG.getIntPtrConstant(0, dl));
7594     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7595                      DAG.getIntPtrConstant(0, dl));
7596 
7597     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7598     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7599 
7600     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7601     N0 = LowerCONCAT_VECTORS(N0, DAG);
7602 
7603     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7604                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7605                                      MVT::i32),
7606                      N0);
7607     return N0;
7608   }
7609 
7610   // v4i16 sdiv ... Convert to float.
7611   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7612   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7613   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7614   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7615   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7616   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7617 
7618   // Use reciprocal estimate and two refinement steps.
7619   // float4 recip = vrecpeq_f32(yf);
7620   // recip *= vrecpsq_f32(yf, recip);
7621   // recip *= vrecpsq_f32(yf, recip);
7622   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7623                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7624                    BN1);
7625   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7626                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7627                    BN1, N2);
7628   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7629   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7630                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7631                    BN1, N2);
7632   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7633   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7634   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7635   // and that it will never cause us to return an answer too large).
7636   // float4 result = as_float4(as_int4(xf*recip) + 2);
7637   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7638   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7639   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7640   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7641   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7642   // Convert back to integer and return.
7643   // return vmovn_u32(vcvt_s32_f32(result));
7644   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7645   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7646   return N0;
7647 }
7648 
7649 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7650   SDNode *N = Op.getNode();
7651   EVT VT = N->getValueType(0);
7652   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7653 
7654   SDValue Carry = Op.getOperand(2);
7655 
7656   SDLoc DL(Op);
7657 
7658   SDValue Result;
7659   if (Op.getOpcode() == ISD::ADDCARRY) {
7660     // This converts the boolean value carry into the carry flag.
7661     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7662 
7663     // Do the addition proper using the carry flag we wanted.
7664     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7665                          Op.getOperand(1), Carry);
7666 
7667     // Now convert the carry flag into a boolean value.
7668     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7669   } else {
7670     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7671     // have to invert the carry first.
7672     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7673                         DAG.getConstant(1, DL, MVT::i32), Carry);
7674     // This converts the boolean value carry into the carry flag.
7675     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7676 
7677     // Do the subtraction proper using the carry flag we wanted.
7678     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7679                          Op.getOperand(1), Carry);
7680 
7681     // Now convert the carry flag into a boolean value.
7682     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7683     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7684     // by ISD::SUBCARRY, so compute 1 - C.
7685     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7686                         DAG.getConstant(1, DL, MVT::i32), Carry);
7687   }
7688 
7689   // Return both values.
7690   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7691 }
7692 
7693 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7694   assert(Subtarget->isTargetDarwin());
7695 
7696   // For iOS, we want to call an alternative entry point: __sincos_stret,
7697   // return values are passed via sret.
7698   SDLoc dl(Op);
7699   SDValue Arg = Op.getOperand(0);
7700   EVT ArgVT = Arg.getValueType();
7701   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7702   auto PtrVT = getPointerTy(DAG.getDataLayout());
7703 
7704   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7705   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7706 
7707   // Pair of floats / doubles used to pass the result.
7708   Type *RetTy = StructType::get(ArgTy, ArgTy);
7709   auto &DL = DAG.getDataLayout();
7710 
7711   ArgListTy Args;
7712   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7713   SDValue SRet;
7714   if (ShouldUseSRet) {
7715     // Create stack object for sret.
7716     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7717     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7718     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7719     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7720 
7721     ArgListEntry Entry;
7722     Entry.Node = SRet;
7723     Entry.Ty = RetTy->getPointerTo();
7724     Entry.IsSExt = false;
7725     Entry.IsZExt = false;
7726     Entry.IsSRet = true;
7727     Args.push_back(Entry);
7728     RetTy = Type::getVoidTy(*DAG.getContext());
7729   }
7730 
7731   ArgListEntry Entry;
7732   Entry.Node = Arg;
7733   Entry.Ty = ArgTy;
7734   Entry.IsSExt = false;
7735   Entry.IsZExt = false;
7736   Args.push_back(Entry);
7737 
7738   RTLIB::Libcall LC =
7739       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7740   const char *LibcallName = getLibcallName(LC);
7741   CallingConv::ID CC = getLibcallCallingConv(LC);
7742   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7743 
7744   TargetLowering::CallLoweringInfo CLI(DAG);
7745   CLI.setDebugLoc(dl)
7746       .setChain(DAG.getEntryNode())
7747       .setCallee(CC, RetTy, Callee, std::move(Args))
7748       .setDiscardResult(ShouldUseSRet);
7749   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7750 
7751   if (!ShouldUseSRet)
7752     return CallResult.first;
7753 
7754   SDValue LoadSin =
7755       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7756 
7757   // Address of cos field.
7758   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7759                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7760   SDValue LoadCos =
7761       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7762 
7763   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7764   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7765                      LoadSin.getValue(0), LoadCos.getValue(0));
7766 }
7767 
7768 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7769                                                   bool Signed,
7770                                                   SDValue &Chain) const {
7771   EVT VT = Op.getValueType();
7772   assert((VT == MVT::i32 || VT == MVT::i64) &&
7773          "unexpected type for custom lowering DIV");
7774   SDLoc dl(Op);
7775 
7776   const auto &DL = DAG.getDataLayout();
7777   const auto &TLI = DAG.getTargetLoweringInfo();
7778 
7779   const char *Name = nullptr;
7780   if (Signed)
7781     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7782   else
7783     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7784 
7785   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7786 
7787   ARMTargetLowering::ArgListTy Args;
7788 
7789   for (auto AI : {1, 0}) {
7790     ArgListEntry Arg;
7791     Arg.Node = Op.getOperand(AI);
7792     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7793     Args.push_back(Arg);
7794   }
7795 
7796   CallLoweringInfo CLI(DAG);
7797   CLI.setDebugLoc(dl)
7798     .setChain(Chain)
7799     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7800                ES, std::move(Args));
7801 
7802   return LowerCallTo(CLI).first;
7803 }
7804 
7805 // This is a code size optimisation: return the original SDIV node to
7806 // DAGCombiner when we don't want to expand SDIV into a sequence of
7807 // instructions, and an empty node otherwise which will cause the
7808 // SDIV to be expanded in DAGCombine.
7809 SDValue
7810 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7811                                  SelectionDAG &DAG,
7812                                  SmallVectorImpl<SDNode *> &Created) const {
7813   // TODO: Support SREM
7814   if (N->getOpcode() != ISD::SDIV)
7815     return SDValue();
7816 
7817   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
7818   const bool MinSize = ST.optForMinSize();
7819   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
7820                                       : ST.hasDivideInARMMode();
7821 
7822   // Don't touch vector types; rewriting this may lead to scalarizing
7823   // the int divs.
7824   if (N->getOperand(0).getValueType().isVector())
7825     return SDValue();
7826 
7827   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
7828   // hwdiv support for this to be really profitable.
7829   if (!(MinSize && HasDivide))
7830     return SDValue();
7831 
7832   // ARM mode is a bit simpler than Thumb: we can handle large power
7833   // of 2 immediates with 1 mov instruction; no further checks required,
7834   // just return the sdiv node.
7835   if (!ST.isThumb())
7836     return SDValue(N, 0);
7837 
7838   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
7839   // and thus lose the code size benefits of a MOVS that requires only 2.
7840   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
7841   // but as it's doing exactly this, it's not worth the trouble to get TTI.
7842   if (Divisor.sgt(128))
7843     return SDValue();
7844 
7845   return SDValue(N, 0);
7846 }
7847 
7848 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7849                                             bool Signed) const {
7850   assert(Op.getValueType() == MVT::i32 &&
7851          "unexpected type for custom lowering DIV");
7852   SDLoc dl(Op);
7853 
7854   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7855                                DAG.getEntryNode(), Op.getOperand(1));
7856 
7857   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7858 }
7859 
7860 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7861   SDLoc DL(N);
7862   SDValue Op = N->getOperand(1);
7863   if (N->getValueType(0) == MVT::i32)
7864     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7865   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7866                            DAG.getConstant(0, DL, MVT::i32));
7867   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7868                            DAG.getConstant(1, DL, MVT::i32));
7869   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7870                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7871 }
7872 
7873 void ARMTargetLowering::ExpandDIV_Windows(
7874     SDValue Op, SelectionDAG &DAG, bool Signed,
7875     SmallVectorImpl<SDValue> &Results) const {
7876   const auto &DL = DAG.getDataLayout();
7877   const auto &TLI = DAG.getTargetLoweringInfo();
7878 
7879   assert(Op.getValueType() == MVT::i64 &&
7880          "unexpected type for custom lowering DIV");
7881   SDLoc dl(Op);
7882 
7883   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7884 
7885   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7886 
7887   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7888   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7889                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7890   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7891 
7892   Results.push_back(Lower);
7893   Results.push_back(Upper);
7894 }
7895 
7896 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7897   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7898     // Acquire/Release load/store is not legal for targets without a dmb or
7899     // equivalent available.
7900     return SDValue();
7901 
7902   // Monotonic load/store is legal for all targets.
7903   return Op;
7904 }
7905 
7906 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7907                                     SmallVectorImpl<SDValue> &Results,
7908                                     SelectionDAG &DAG,
7909                                     const ARMSubtarget *Subtarget) {
7910   SDLoc DL(N);
7911   // Under Power Management extensions, the cycle-count is:
7912   //    mrc p15, #0, <Rt>, c9, c13, #0
7913   SDValue Ops[] = { N->getOperand(0), // Chain
7914                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7915                     DAG.getConstant(15, DL, MVT::i32),
7916                     DAG.getConstant(0, DL, MVT::i32),
7917                     DAG.getConstant(9, DL, MVT::i32),
7918                     DAG.getConstant(13, DL, MVT::i32),
7919                     DAG.getConstant(0, DL, MVT::i32)
7920   };
7921 
7922   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7923                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7924   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7925                                 DAG.getConstant(0, DL, MVT::i32)));
7926   Results.push_back(Cycles32.getValue(1));
7927 }
7928 
7929 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7930   SDLoc dl(V.getNode());
7931   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7932   SDValue VHi = DAG.getAnyExtOrTrunc(
7933       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7934       dl, MVT::i32);
7935   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7936   if (isBigEndian)
7937     std::swap (VLo, VHi);
7938   SDValue RegClass =
7939       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7940   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7941   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7942   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7943   return SDValue(
7944       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7945 }
7946 
7947 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7948                                        SmallVectorImpl<SDValue> & Results,
7949                                        SelectionDAG &DAG) {
7950   assert(N->getValueType(0) == MVT::i64 &&
7951          "AtomicCmpSwap on types less than 64 should be legal");
7952   SDValue Ops[] = {N->getOperand(1),
7953                    createGPRPairNode(DAG, N->getOperand(2)),
7954                    createGPRPairNode(DAG, N->getOperand(3)),
7955                    N->getOperand(0)};
7956   SDNode *CmpSwap = DAG.getMachineNode(
7957       ARM::CMP_SWAP_64, SDLoc(N),
7958       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7959 
7960   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
7961   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
7962 
7963   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7964 
7965   Results.push_back(
7966       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7967                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7968   Results.push_back(
7969       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7970                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7971   Results.push_back(SDValue(CmpSwap, 2));
7972 }
7973 
7974 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7975                           SelectionDAG &DAG) {
7976   const auto &TLI = DAG.getTargetLoweringInfo();
7977 
7978   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7979          "Custom lowering is MSVCRT specific!");
7980 
7981   SDLoc dl(Op);
7982   SDValue Val = Op.getOperand(0);
7983   MVT Ty = Val->getSimpleValueType(0);
7984   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7985   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7986                                          TLI.getPointerTy(DAG.getDataLayout()));
7987 
7988   TargetLowering::ArgListTy Args;
7989   TargetLowering::ArgListEntry Entry;
7990 
7991   Entry.Node = Val;
7992   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7993   Entry.IsZExt = true;
7994   Args.push_back(Entry);
7995 
7996   Entry.Node = Exponent;
7997   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7998   Entry.IsZExt = true;
7999   Args.push_back(Entry);
8000 
8001   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8002 
8003   // In the in-chain to the call is the entry node  If we are emitting a
8004   // tailcall, the chain will be mutated if the node has a non-entry input
8005   // chain.
8006   SDValue InChain = DAG.getEntryNode();
8007   SDValue TCChain = InChain;
8008 
8009   const Function &F = DAG.getMachineFunction().getFunction();
8010   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8011               F.getReturnType() == LCRTy;
8012   if (IsTC)
8013     InChain = TCChain;
8014 
8015   TargetLowering::CallLoweringInfo CLI(DAG);
8016   CLI.setDebugLoc(dl)
8017       .setChain(InChain)
8018       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8019       .setTailCall(IsTC);
8020   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8021 
8022   // Return the chain (the DAG root) if it is a tail call
8023   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8024 }
8025 
8026 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8027   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8028   switch (Op.getOpcode()) {
8029   default: llvm_unreachable("Don't know how to custom lower this!");
8030   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8031   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8032   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
8033   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8034   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8035   case ISD::SELECT:        return LowerSELECT(Op, DAG);
8036   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
8037   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
8038   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
8039   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
8040   case ISD::VASTART:       return LowerVASTART(Op, DAG);
8041   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8042   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
8043   case ISD::SINT_TO_FP:
8044   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
8045   case ISD::FP_TO_SINT:
8046   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
8047   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
8048   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
8049   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
8050   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8051   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8052   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8053   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8054                                                                Subtarget);
8055   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8056   case ISD::SHL:
8057   case ISD::SRL:
8058   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8059   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8060   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8061   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8062   case ISD::SRL_PARTS:
8063   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8064   case ISD::CTTZ:
8065   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8066   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8067   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8068   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
8069   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8070   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8071   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8072   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8073   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8074   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8075   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8076   case ISD::MUL:           return LowerMUL(Op, DAG);
8077   case ISD::SDIV:
8078     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8079       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8080     return LowerSDIV(Op, DAG);
8081   case ISD::UDIV:
8082     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8083       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8084     return LowerUDIV(Op, DAG);
8085   case ISD::ADDCARRY:
8086   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8087   case ISD::SADDO:
8088   case ISD::SSUBO:
8089     return LowerSignedALUO(Op, DAG);
8090   case ISD::UADDO:
8091   case ISD::USUBO:
8092     return LowerUnsignedALUO(Op, DAG);
8093   case ISD::ATOMIC_LOAD:
8094   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8095   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8096   case ISD::SDIVREM:
8097   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8098   case ISD::DYNAMIC_STACKALLOC:
8099     if (Subtarget->isTargetWindows())
8100       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8101     llvm_unreachable("Don't know how to custom lower this!");
8102   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8103   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8104   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8105   case ARMISD::WIN__DBZCHK: return SDValue();
8106   }
8107 }
8108 
8109 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8110                                  SelectionDAG &DAG) {
8111   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8112   unsigned Opc = 0;
8113   if (IntNo == Intrinsic::arm_smlald)
8114     Opc = ARMISD::SMLALD;
8115   else if (IntNo == Intrinsic::arm_smlaldx)
8116     Opc = ARMISD::SMLALDX;
8117   else if (IntNo == Intrinsic::arm_smlsld)
8118     Opc = ARMISD::SMLSLD;
8119   else if (IntNo == Intrinsic::arm_smlsldx)
8120     Opc = ARMISD::SMLSLDX;
8121   else
8122     return;
8123 
8124   SDLoc dl(N);
8125   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8126                            N->getOperand(3),
8127                            DAG.getConstant(0, dl, MVT::i32));
8128   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8129                            N->getOperand(3),
8130                            DAG.getConstant(1, dl, MVT::i32));
8131 
8132   SDValue LongMul = DAG.getNode(Opc, dl,
8133                                 DAG.getVTList(MVT::i32, MVT::i32),
8134                                 N->getOperand(1), N->getOperand(2),
8135                                 Lo, Hi);
8136   Results.push_back(LongMul.getValue(0));
8137   Results.push_back(LongMul.getValue(1));
8138 }
8139 
8140 /// ReplaceNodeResults - Replace the results of node with an illegal result
8141 /// type with new values built out of custom code.
8142 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8143                                            SmallVectorImpl<SDValue> &Results,
8144                                            SelectionDAG &DAG) const {
8145   SDValue Res;
8146   switch (N->getOpcode()) {
8147   default:
8148     llvm_unreachable("Don't know how to custom expand this!");
8149   case ISD::READ_REGISTER:
8150     ExpandREAD_REGISTER(N, Results, DAG);
8151     break;
8152   case ISD::BITCAST:
8153     Res = ExpandBITCAST(N, DAG, Subtarget);
8154     break;
8155   case ISD::SRL:
8156   case ISD::SRA:
8157     Res = Expand64BitShift(N, DAG, Subtarget);
8158     break;
8159   case ISD::SREM:
8160   case ISD::UREM:
8161     Res = LowerREM(N, DAG);
8162     break;
8163   case ISD::SDIVREM:
8164   case ISD::UDIVREM:
8165     Res = LowerDivRem(SDValue(N, 0), DAG);
8166     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8167     Results.push_back(Res.getValue(0));
8168     Results.push_back(Res.getValue(1));
8169     return;
8170   case ISD::READCYCLECOUNTER:
8171     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8172     return;
8173   case ISD::UDIV:
8174   case ISD::SDIV:
8175     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8176     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8177                              Results);
8178   case ISD::ATOMIC_CMP_SWAP:
8179     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8180     return;
8181   case ISD::INTRINSIC_WO_CHAIN:
8182     return ReplaceLongIntrinsic(N, Results, DAG);
8183   }
8184   if (Res.getNode())
8185     Results.push_back(Res);
8186 }
8187 
8188 //===----------------------------------------------------------------------===//
8189 //                           ARM Scheduler Hooks
8190 //===----------------------------------------------------------------------===//
8191 
8192 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8193 /// registers the function context.
8194 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8195                                                MachineBasicBlock *MBB,
8196                                                MachineBasicBlock *DispatchBB,
8197                                                int FI) const {
8198   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8199          "ROPI/RWPI not currently supported with SjLj");
8200   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8201   DebugLoc dl = MI.getDebugLoc();
8202   MachineFunction *MF = MBB->getParent();
8203   MachineRegisterInfo *MRI = &MF->getRegInfo();
8204   MachineConstantPool *MCP = MF->getConstantPool();
8205   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8206   const Function &F = MF->getFunction();
8207 
8208   bool isThumb = Subtarget->isThumb();
8209   bool isThumb2 = Subtarget->isThumb2();
8210 
8211   unsigned PCLabelId = AFI->createPICLabelUId();
8212   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8213   ARMConstantPoolValue *CPV =
8214     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8215   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8216 
8217   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8218                                            : &ARM::GPRRegClass;
8219 
8220   // Grab constant pool and fixed stack memory operands.
8221   MachineMemOperand *CPMMO =
8222       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8223                                MachineMemOperand::MOLoad, 4, 4);
8224 
8225   MachineMemOperand *FIMMOSt =
8226       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8227                                MachineMemOperand::MOStore, 4, 4);
8228 
8229   // Load the address of the dispatch MBB into the jump buffer.
8230   if (isThumb2) {
8231     // Incoming value: jbuf
8232     //   ldr.n  r5, LCPI1_1
8233     //   orr    r5, r5, #1
8234     //   add    r5, pc
8235     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8236     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8237     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8238         .addConstantPoolIndex(CPI)
8239         .addMemOperand(CPMMO)
8240         .add(predOps(ARMCC::AL));
8241     // Set the low bit because of thumb mode.
8242     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8243     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8244         .addReg(NewVReg1, RegState::Kill)
8245         .addImm(0x01)
8246         .add(predOps(ARMCC::AL))
8247         .add(condCodeOp());
8248     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8249     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8250       .addReg(NewVReg2, RegState::Kill)
8251       .addImm(PCLabelId);
8252     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8253         .addReg(NewVReg3, RegState::Kill)
8254         .addFrameIndex(FI)
8255         .addImm(36) // &jbuf[1] :: pc
8256         .addMemOperand(FIMMOSt)
8257         .add(predOps(ARMCC::AL));
8258   } else if (isThumb) {
8259     // Incoming value: jbuf
8260     //   ldr.n  r1, LCPI1_4
8261     //   add    r1, pc
8262     //   mov    r2, #1
8263     //   orrs   r1, r2
8264     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8265     //   str    r1, [r2]
8266     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8267     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8268         .addConstantPoolIndex(CPI)
8269         .addMemOperand(CPMMO)
8270         .add(predOps(ARMCC::AL));
8271     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8272     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8273       .addReg(NewVReg1, RegState::Kill)
8274       .addImm(PCLabelId);
8275     // Set the low bit because of thumb mode.
8276     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8277     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8278         .addReg(ARM::CPSR, RegState::Define)
8279         .addImm(1)
8280         .add(predOps(ARMCC::AL));
8281     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8282     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8283         .addReg(ARM::CPSR, RegState::Define)
8284         .addReg(NewVReg2, RegState::Kill)
8285         .addReg(NewVReg3, RegState::Kill)
8286         .add(predOps(ARMCC::AL));
8287     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8288     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8289             .addFrameIndex(FI)
8290             .addImm(36); // &jbuf[1] :: pc
8291     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8292         .addReg(NewVReg4, RegState::Kill)
8293         .addReg(NewVReg5, RegState::Kill)
8294         .addImm(0)
8295         .addMemOperand(FIMMOSt)
8296         .add(predOps(ARMCC::AL));
8297   } else {
8298     // Incoming value: jbuf
8299     //   ldr  r1, LCPI1_1
8300     //   add  r1, pc, r1
8301     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8302     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8303     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8304         .addConstantPoolIndex(CPI)
8305         .addImm(0)
8306         .addMemOperand(CPMMO)
8307         .add(predOps(ARMCC::AL));
8308     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8309     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8310         .addReg(NewVReg1, RegState::Kill)
8311         .addImm(PCLabelId)
8312         .add(predOps(ARMCC::AL));
8313     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8314         .addReg(NewVReg2, RegState::Kill)
8315         .addFrameIndex(FI)
8316         .addImm(36) // &jbuf[1] :: pc
8317         .addMemOperand(FIMMOSt)
8318         .add(predOps(ARMCC::AL));
8319   }
8320 }
8321 
8322 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8323                                               MachineBasicBlock *MBB) const {
8324   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8325   DebugLoc dl = MI.getDebugLoc();
8326   MachineFunction *MF = MBB->getParent();
8327   MachineRegisterInfo *MRI = &MF->getRegInfo();
8328   MachineFrameInfo &MFI = MF->getFrameInfo();
8329   int FI = MFI.getFunctionContextIndex();
8330 
8331   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8332                                                         : &ARM::GPRnopcRegClass;
8333 
8334   // Get a mapping of the call site numbers to all of the landing pads they're
8335   // associated with.
8336   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8337   unsigned MaxCSNum = 0;
8338   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8339        ++BB) {
8340     if (!BB->isEHPad()) continue;
8341 
8342     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8343     // pad.
8344     for (MachineBasicBlock::iterator
8345            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8346       if (!II->isEHLabel()) continue;
8347 
8348       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8349       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8350 
8351       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8352       for (SmallVectorImpl<unsigned>::iterator
8353              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8354            CSI != CSE; ++CSI) {
8355         CallSiteNumToLPad[*CSI].push_back(&*BB);
8356         MaxCSNum = std::max(MaxCSNum, *CSI);
8357       }
8358       break;
8359     }
8360   }
8361 
8362   // Get an ordered list of the machine basic blocks for the jump table.
8363   std::vector<MachineBasicBlock*> LPadList;
8364   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8365   LPadList.reserve(CallSiteNumToLPad.size());
8366   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8367     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8368     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8369            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8370       LPadList.push_back(*II);
8371       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8372     }
8373   }
8374 
8375   assert(!LPadList.empty() &&
8376          "No landing pad destinations for the dispatch jump table!");
8377 
8378   // Create the jump table and associated information.
8379   MachineJumpTableInfo *JTI =
8380     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8381   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8382 
8383   // Create the MBBs for the dispatch code.
8384 
8385   // Shove the dispatch's address into the return slot in the function context.
8386   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8387   DispatchBB->setIsEHPad();
8388 
8389   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8390   unsigned trap_opcode;
8391   if (Subtarget->isThumb())
8392     trap_opcode = ARM::tTRAP;
8393   else
8394     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8395 
8396   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8397   DispatchBB->addSuccessor(TrapBB);
8398 
8399   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8400   DispatchBB->addSuccessor(DispContBB);
8401 
8402   // Insert and MBBs.
8403   MF->insert(MF->end(), DispatchBB);
8404   MF->insert(MF->end(), DispContBB);
8405   MF->insert(MF->end(), TrapBB);
8406 
8407   // Insert code into the entry block that creates and registers the function
8408   // context.
8409   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8410 
8411   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8412       MachinePointerInfo::getFixedStack(*MF, FI),
8413       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8414 
8415   MachineInstrBuilder MIB;
8416   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8417 
8418   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8419   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8420 
8421   // Add a register mask with no preserved registers.  This results in all
8422   // registers being marked as clobbered. This can't work if the dispatch block
8423   // is in a Thumb1 function and is linked with ARM code which uses the FP
8424   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8425   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8426 
8427   bool IsPositionIndependent = isPositionIndependent();
8428   unsigned NumLPads = LPadList.size();
8429   if (Subtarget->isThumb2()) {
8430     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8431     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8432         .addFrameIndex(FI)
8433         .addImm(4)
8434         .addMemOperand(FIMMOLd)
8435         .add(predOps(ARMCC::AL));
8436 
8437     if (NumLPads < 256) {
8438       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8439           .addReg(NewVReg1)
8440           .addImm(LPadList.size())
8441           .add(predOps(ARMCC::AL));
8442     } else {
8443       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8444       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8445           .addImm(NumLPads & 0xFFFF)
8446           .add(predOps(ARMCC::AL));
8447 
8448       unsigned VReg2 = VReg1;
8449       if ((NumLPads & 0xFFFF0000) != 0) {
8450         VReg2 = MRI->createVirtualRegister(TRC);
8451         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8452             .addReg(VReg1)
8453             .addImm(NumLPads >> 16)
8454             .add(predOps(ARMCC::AL));
8455       }
8456 
8457       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8458           .addReg(NewVReg1)
8459           .addReg(VReg2)
8460           .add(predOps(ARMCC::AL));
8461     }
8462 
8463     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8464       .addMBB(TrapBB)
8465       .addImm(ARMCC::HI)
8466       .addReg(ARM::CPSR);
8467 
8468     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8469     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8470         .addJumpTableIndex(MJTI)
8471         .add(predOps(ARMCC::AL));
8472 
8473     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8474     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8475         .addReg(NewVReg3, RegState::Kill)
8476         .addReg(NewVReg1)
8477         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8478         .add(predOps(ARMCC::AL))
8479         .add(condCodeOp());
8480 
8481     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8482       .addReg(NewVReg4, RegState::Kill)
8483       .addReg(NewVReg1)
8484       .addJumpTableIndex(MJTI);
8485   } else if (Subtarget->isThumb()) {
8486     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8487     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8488         .addFrameIndex(FI)
8489         .addImm(1)
8490         .addMemOperand(FIMMOLd)
8491         .add(predOps(ARMCC::AL));
8492 
8493     if (NumLPads < 256) {
8494       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8495           .addReg(NewVReg1)
8496           .addImm(NumLPads)
8497           .add(predOps(ARMCC::AL));
8498     } else {
8499       MachineConstantPool *ConstantPool = MF->getConstantPool();
8500       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8501       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8502 
8503       // MachineConstantPool wants an explicit alignment.
8504       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8505       if (Align == 0)
8506         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8507       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8508 
8509       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8510       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8511           .addReg(VReg1, RegState::Define)
8512           .addConstantPoolIndex(Idx)
8513           .add(predOps(ARMCC::AL));
8514       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8515           .addReg(NewVReg1)
8516           .addReg(VReg1)
8517           .add(predOps(ARMCC::AL));
8518     }
8519 
8520     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8521       .addMBB(TrapBB)
8522       .addImm(ARMCC::HI)
8523       .addReg(ARM::CPSR);
8524 
8525     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8526     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8527         .addReg(ARM::CPSR, RegState::Define)
8528         .addReg(NewVReg1)
8529         .addImm(2)
8530         .add(predOps(ARMCC::AL));
8531 
8532     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8533     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8534         .addJumpTableIndex(MJTI)
8535         .add(predOps(ARMCC::AL));
8536 
8537     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8538     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8539         .addReg(ARM::CPSR, RegState::Define)
8540         .addReg(NewVReg2, RegState::Kill)
8541         .addReg(NewVReg3)
8542         .add(predOps(ARMCC::AL));
8543 
8544     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8545         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8546 
8547     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8548     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8549         .addReg(NewVReg4, RegState::Kill)
8550         .addImm(0)
8551         .addMemOperand(JTMMOLd)
8552         .add(predOps(ARMCC::AL));
8553 
8554     unsigned NewVReg6 = NewVReg5;
8555     if (IsPositionIndependent) {
8556       NewVReg6 = MRI->createVirtualRegister(TRC);
8557       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8558           .addReg(ARM::CPSR, RegState::Define)
8559           .addReg(NewVReg5, RegState::Kill)
8560           .addReg(NewVReg3)
8561           .add(predOps(ARMCC::AL));
8562     }
8563 
8564     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8565       .addReg(NewVReg6, RegState::Kill)
8566       .addJumpTableIndex(MJTI);
8567   } else {
8568     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8569     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8570         .addFrameIndex(FI)
8571         .addImm(4)
8572         .addMemOperand(FIMMOLd)
8573         .add(predOps(ARMCC::AL));
8574 
8575     if (NumLPads < 256) {
8576       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8577           .addReg(NewVReg1)
8578           .addImm(NumLPads)
8579           .add(predOps(ARMCC::AL));
8580     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8581       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8582       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8583           .addImm(NumLPads & 0xFFFF)
8584           .add(predOps(ARMCC::AL));
8585 
8586       unsigned VReg2 = VReg1;
8587       if ((NumLPads & 0xFFFF0000) != 0) {
8588         VReg2 = MRI->createVirtualRegister(TRC);
8589         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8590             .addReg(VReg1)
8591             .addImm(NumLPads >> 16)
8592             .add(predOps(ARMCC::AL));
8593       }
8594 
8595       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8596           .addReg(NewVReg1)
8597           .addReg(VReg2)
8598           .add(predOps(ARMCC::AL));
8599     } else {
8600       MachineConstantPool *ConstantPool = MF->getConstantPool();
8601       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8602       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8603 
8604       // MachineConstantPool wants an explicit alignment.
8605       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8606       if (Align == 0)
8607         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8608       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8609 
8610       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8611       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8612           .addReg(VReg1, RegState::Define)
8613           .addConstantPoolIndex(Idx)
8614           .addImm(0)
8615           .add(predOps(ARMCC::AL));
8616       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8617           .addReg(NewVReg1)
8618           .addReg(VReg1, RegState::Kill)
8619           .add(predOps(ARMCC::AL));
8620     }
8621 
8622     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8623       .addMBB(TrapBB)
8624       .addImm(ARMCC::HI)
8625       .addReg(ARM::CPSR);
8626 
8627     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8628     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8629         .addReg(NewVReg1)
8630         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8631         .add(predOps(ARMCC::AL))
8632         .add(condCodeOp());
8633     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8634     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8635         .addJumpTableIndex(MJTI)
8636         .add(predOps(ARMCC::AL));
8637 
8638     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8639         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8640     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8641     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8642         .addReg(NewVReg3, RegState::Kill)
8643         .addReg(NewVReg4)
8644         .addImm(0)
8645         .addMemOperand(JTMMOLd)
8646         .add(predOps(ARMCC::AL));
8647 
8648     if (IsPositionIndependent) {
8649       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8650         .addReg(NewVReg5, RegState::Kill)
8651         .addReg(NewVReg4)
8652         .addJumpTableIndex(MJTI);
8653     } else {
8654       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8655         .addReg(NewVReg5, RegState::Kill)
8656         .addJumpTableIndex(MJTI);
8657     }
8658   }
8659 
8660   // Add the jump table entries as successors to the MBB.
8661   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8662   for (std::vector<MachineBasicBlock*>::iterator
8663          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8664     MachineBasicBlock *CurMBB = *I;
8665     if (SeenMBBs.insert(CurMBB).second)
8666       DispContBB->addSuccessor(CurMBB);
8667   }
8668 
8669   // N.B. the order the invoke BBs are processed in doesn't matter here.
8670   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8671   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8672   for (MachineBasicBlock *BB : InvokeBBs) {
8673 
8674     // Remove the landing pad successor from the invoke block and replace it
8675     // with the new dispatch block.
8676     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8677                                                   BB->succ_end());
8678     while (!Successors.empty()) {
8679       MachineBasicBlock *SMBB = Successors.pop_back_val();
8680       if (SMBB->isEHPad()) {
8681         BB->removeSuccessor(SMBB);
8682         MBBLPads.push_back(SMBB);
8683       }
8684     }
8685 
8686     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8687     BB->normalizeSuccProbs();
8688 
8689     // Find the invoke call and mark all of the callee-saved registers as
8690     // 'implicit defined' so that they're spilled. This prevents code from
8691     // moving instructions to before the EH block, where they will never be
8692     // executed.
8693     for (MachineBasicBlock::reverse_iterator
8694            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8695       if (!II->isCall()) continue;
8696 
8697       DenseMap<unsigned, bool> DefRegs;
8698       for (MachineInstr::mop_iterator
8699              OI = II->operands_begin(), OE = II->operands_end();
8700            OI != OE; ++OI) {
8701         if (!OI->isReg()) continue;
8702         DefRegs[OI->getReg()] = true;
8703       }
8704 
8705       MachineInstrBuilder MIB(*MF, &*II);
8706 
8707       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8708         unsigned Reg = SavedRegs[i];
8709         if (Subtarget->isThumb2() &&
8710             !ARM::tGPRRegClass.contains(Reg) &&
8711             !ARM::hGPRRegClass.contains(Reg))
8712           continue;
8713         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8714           continue;
8715         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8716           continue;
8717         if (!DefRegs[Reg])
8718           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8719       }
8720 
8721       break;
8722     }
8723   }
8724 
8725   // Mark all former landing pads as non-landing pads. The dispatch is the only
8726   // landing pad now.
8727   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8728          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8729     (*I)->setIsEHPad(false);
8730 
8731   // The instruction is gone now.
8732   MI.eraseFromParent();
8733 }
8734 
8735 static
8736 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8737   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8738        E = MBB->succ_end(); I != E; ++I)
8739     if (*I != Succ)
8740       return *I;
8741   llvm_unreachable("Expecting a BB with two successors!");
8742 }
8743 
8744 /// Return the load opcode for a given load size. If load size >= 8,
8745 /// neon opcode will be returned.
8746 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8747   if (LdSize >= 8)
8748     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8749                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8750   if (IsThumb1)
8751     return LdSize == 4 ? ARM::tLDRi
8752                        : LdSize == 2 ? ARM::tLDRHi
8753                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8754   if (IsThumb2)
8755     return LdSize == 4 ? ARM::t2LDR_POST
8756                        : LdSize == 2 ? ARM::t2LDRH_POST
8757                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8758   return LdSize == 4 ? ARM::LDR_POST_IMM
8759                      : LdSize == 2 ? ARM::LDRH_POST
8760                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8761 }
8762 
8763 /// Return the store opcode for a given store size. If store size >= 8,
8764 /// neon opcode will be returned.
8765 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8766   if (StSize >= 8)
8767     return StSize == 16 ? ARM::VST1q32wb_fixed
8768                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8769   if (IsThumb1)
8770     return StSize == 4 ? ARM::tSTRi
8771                        : StSize == 2 ? ARM::tSTRHi
8772                                      : StSize == 1 ? ARM::tSTRBi : 0;
8773   if (IsThumb2)
8774     return StSize == 4 ? ARM::t2STR_POST
8775                        : StSize == 2 ? ARM::t2STRH_POST
8776                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8777   return StSize == 4 ? ARM::STR_POST_IMM
8778                      : StSize == 2 ? ARM::STRH_POST
8779                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8780 }
8781 
8782 /// Emit a post-increment load operation with given size. The instructions
8783 /// will be added to BB at Pos.
8784 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8785                        const TargetInstrInfo *TII, const DebugLoc &dl,
8786                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8787                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8788   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8789   assert(LdOpc != 0 && "Should have a load opcode");
8790   if (LdSize >= 8) {
8791     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8792         .addReg(AddrOut, RegState::Define)
8793         .addReg(AddrIn)
8794         .addImm(0)
8795         .add(predOps(ARMCC::AL));
8796   } else if (IsThumb1) {
8797     // load + update AddrIn
8798     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8799         .addReg(AddrIn)
8800         .addImm(0)
8801         .add(predOps(ARMCC::AL));
8802     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8803         .add(t1CondCodeOp())
8804         .addReg(AddrIn)
8805         .addImm(LdSize)
8806         .add(predOps(ARMCC::AL));
8807   } else if (IsThumb2) {
8808     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8809         .addReg(AddrOut, RegState::Define)
8810         .addReg(AddrIn)
8811         .addImm(LdSize)
8812         .add(predOps(ARMCC::AL));
8813   } else { // arm
8814     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8815         .addReg(AddrOut, RegState::Define)
8816         .addReg(AddrIn)
8817         .addReg(0)
8818         .addImm(LdSize)
8819         .add(predOps(ARMCC::AL));
8820   }
8821 }
8822 
8823 /// Emit a post-increment store operation with given size. The instructions
8824 /// will be added to BB at Pos.
8825 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8826                        const TargetInstrInfo *TII, const DebugLoc &dl,
8827                        unsigned StSize, unsigned Data, unsigned AddrIn,
8828                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8829   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8830   assert(StOpc != 0 && "Should have a store opcode");
8831   if (StSize >= 8) {
8832     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8833         .addReg(AddrIn)
8834         .addImm(0)
8835         .addReg(Data)
8836         .add(predOps(ARMCC::AL));
8837   } else if (IsThumb1) {
8838     // store + update AddrIn
8839     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8840         .addReg(Data)
8841         .addReg(AddrIn)
8842         .addImm(0)
8843         .add(predOps(ARMCC::AL));
8844     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8845         .add(t1CondCodeOp())
8846         .addReg(AddrIn)
8847         .addImm(StSize)
8848         .add(predOps(ARMCC::AL));
8849   } else if (IsThumb2) {
8850     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8851         .addReg(Data)
8852         .addReg(AddrIn)
8853         .addImm(StSize)
8854         .add(predOps(ARMCC::AL));
8855   } else { // arm
8856     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8857         .addReg(Data)
8858         .addReg(AddrIn)
8859         .addReg(0)
8860         .addImm(StSize)
8861         .add(predOps(ARMCC::AL));
8862   }
8863 }
8864 
8865 MachineBasicBlock *
8866 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8867                                    MachineBasicBlock *BB) const {
8868   // This pseudo instruction has 3 operands: dst, src, size
8869   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8870   // Otherwise, we will generate unrolled scalar copies.
8871   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8872   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8873   MachineFunction::iterator It = ++BB->getIterator();
8874 
8875   unsigned dest = MI.getOperand(0).getReg();
8876   unsigned src = MI.getOperand(1).getReg();
8877   unsigned SizeVal = MI.getOperand(2).getImm();
8878   unsigned Align = MI.getOperand(3).getImm();
8879   DebugLoc dl = MI.getDebugLoc();
8880 
8881   MachineFunction *MF = BB->getParent();
8882   MachineRegisterInfo &MRI = MF->getRegInfo();
8883   unsigned UnitSize = 0;
8884   const TargetRegisterClass *TRC = nullptr;
8885   const TargetRegisterClass *VecTRC = nullptr;
8886 
8887   bool IsThumb1 = Subtarget->isThumb1Only();
8888   bool IsThumb2 = Subtarget->isThumb2();
8889   bool IsThumb = Subtarget->isThumb();
8890 
8891   if (Align & 1) {
8892     UnitSize = 1;
8893   } else if (Align & 2) {
8894     UnitSize = 2;
8895   } else {
8896     // Check whether we can use NEON instructions.
8897     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8898         Subtarget->hasNEON()) {
8899       if ((Align % 16 == 0) && SizeVal >= 16)
8900         UnitSize = 16;
8901       else if ((Align % 8 == 0) && SizeVal >= 8)
8902         UnitSize = 8;
8903     }
8904     // Can't use NEON instructions.
8905     if (UnitSize == 0)
8906       UnitSize = 4;
8907   }
8908 
8909   // Select the correct opcode and register class for unit size load/store
8910   bool IsNeon = UnitSize >= 8;
8911   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8912   if (IsNeon)
8913     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8914                             : UnitSize == 8 ? &ARM::DPRRegClass
8915                                             : nullptr;
8916 
8917   unsigned BytesLeft = SizeVal % UnitSize;
8918   unsigned LoopSize = SizeVal - BytesLeft;
8919 
8920   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8921     // Use LDR and STR to copy.
8922     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8923     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8924     unsigned srcIn = src;
8925     unsigned destIn = dest;
8926     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8927       unsigned srcOut = MRI.createVirtualRegister(TRC);
8928       unsigned destOut = MRI.createVirtualRegister(TRC);
8929       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8930       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8931                  IsThumb1, IsThumb2);
8932       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8933                  IsThumb1, IsThumb2);
8934       srcIn = srcOut;
8935       destIn = destOut;
8936     }
8937 
8938     // Handle the leftover bytes with LDRB and STRB.
8939     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8940     // [destOut] = STRB_POST(scratch, destIn, 1)
8941     for (unsigned i = 0; i < BytesLeft; i++) {
8942       unsigned srcOut = MRI.createVirtualRegister(TRC);
8943       unsigned destOut = MRI.createVirtualRegister(TRC);
8944       unsigned scratch = MRI.createVirtualRegister(TRC);
8945       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8946                  IsThumb1, IsThumb2);
8947       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8948                  IsThumb1, IsThumb2);
8949       srcIn = srcOut;
8950       destIn = destOut;
8951     }
8952     MI.eraseFromParent(); // The instruction is gone now.
8953     return BB;
8954   }
8955 
8956   // Expand the pseudo op to a loop.
8957   // thisMBB:
8958   //   ...
8959   //   movw varEnd, # --> with thumb2
8960   //   movt varEnd, #
8961   //   ldrcp varEnd, idx --> without thumb2
8962   //   fallthrough --> loopMBB
8963   // loopMBB:
8964   //   PHI varPhi, varEnd, varLoop
8965   //   PHI srcPhi, src, srcLoop
8966   //   PHI destPhi, dst, destLoop
8967   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8968   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8969   //   subs varLoop, varPhi, #UnitSize
8970   //   bne loopMBB
8971   //   fallthrough --> exitMBB
8972   // exitMBB:
8973   //   epilogue to handle left-over bytes
8974   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8975   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8976   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8977   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8978   MF->insert(It, loopMBB);
8979   MF->insert(It, exitMBB);
8980 
8981   // Transfer the remainder of BB and its successor edges to exitMBB.
8982   exitMBB->splice(exitMBB->begin(), BB,
8983                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8984   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8985 
8986   // Load an immediate to varEnd.
8987   unsigned varEnd = MRI.createVirtualRegister(TRC);
8988   if (Subtarget->useMovt()) {
8989     unsigned Vtmp = varEnd;
8990     if ((LoopSize & 0xFFFF0000) != 0)
8991       Vtmp = MRI.createVirtualRegister(TRC);
8992     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8993         .addImm(LoopSize & 0xFFFF)
8994         .add(predOps(ARMCC::AL));
8995 
8996     if ((LoopSize & 0xFFFF0000) != 0)
8997       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8998           .addReg(Vtmp)
8999           .addImm(LoopSize >> 16)
9000           .add(predOps(ARMCC::AL));
9001   } else {
9002     MachineConstantPool *ConstantPool = MF->getConstantPool();
9003     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9004     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9005 
9006     // MachineConstantPool wants an explicit alignment.
9007     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9008     if (Align == 0)
9009       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9010     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9011 
9012     if (IsThumb)
9013       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9014           .addReg(varEnd, RegState::Define)
9015           .addConstantPoolIndex(Idx)
9016           .add(predOps(ARMCC::AL));
9017     else
9018       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9019           .addReg(varEnd, RegState::Define)
9020           .addConstantPoolIndex(Idx)
9021           .addImm(0)
9022           .add(predOps(ARMCC::AL));
9023   }
9024   BB->addSuccessor(loopMBB);
9025 
9026   // Generate the loop body:
9027   //   varPhi = PHI(varLoop, varEnd)
9028   //   srcPhi = PHI(srcLoop, src)
9029   //   destPhi = PHI(destLoop, dst)
9030   MachineBasicBlock *entryBB = BB;
9031   BB = loopMBB;
9032   unsigned varLoop = MRI.createVirtualRegister(TRC);
9033   unsigned varPhi = MRI.createVirtualRegister(TRC);
9034   unsigned srcLoop = MRI.createVirtualRegister(TRC);
9035   unsigned srcPhi = MRI.createVirtualRegister(TRC);
9036   unsigned destLoop = MRI.createVirtualRegister(TRC);
9037   unsigned destPhi = MRI.createVirtualRegister(TRC);
9038 
9039   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9040     .addReg(varLoop).addMBB(loopMBB)
9041     .addReg(varEnd).addMBB(entryBB);
9042   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9043     .addReg(srcLoop).addMBB(loopMBB)
9044     .addReg(src).addMBB(entryBB);
9045   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9046     .addReg(destLoop).addMBB(loopMBB)
9047     .addReg(dest).addMBB(entryBB);
9048 
9049   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9050   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9051   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9052   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9053              IsThumb1, IsThumb2);
9054   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9055              IsThumb1, IsThumb2);
9056 
9057   // Decrement loop variable by UnitSize.
9058   if (IsThumb1) {
9059     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9060         .add(t1CondCodeOp())
9061         .addReg(varPhi)
9062         .addImm(UnitSize)
9063         .add(predOps(ARMCC::AL));
9064   } else {
9065     MachineInstrBuilder MIB =
9066         BuildMI(*BB, BB->end(), dl,
9067                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9068     MIB.addReg(varPhi)
9069         .addImm(UnitSize)
9070         .add(predOps(ARMCC::AL))
9071         .add(condCodeOp());
9072     MIB->getOperand(5).setReg(ARM::CPSR);
9073     MIB->getOperand(5).setIsDef(true);
9074   }
9075   BuildMI(*BB, BB->end(), dl,
9076           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9077       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9078 
9079   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9080   BB->addSuccessor(loopMBB);
9081   BB->addSuccessor(exitMBB);
9082 
9083   // Add epilogue to handle BytesLeft.
9084   BB = exitMBB;
9085   auto StartOfExit = exitMBB->begin();
9086 
9087   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9088   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9089   unsigned srcIn = srcLoop;
9090   unsigned destIn = destLoop;
9091   for (unsigned i = 0; i < BytesLeft; i++) {
9092     unsigned srcOut = MRI.createVirtualRegister(TRC);
9093     unsigned destOut = MRI.createVirtualRegister(TRC);
9094     unsigned scratch = MRI.createVirtualRegister(TRC);
9095     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9096                IsThumb1, IsThumb2);
9097     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9098                IsThumb1, IsThumb2);
9099     srcIn = srcOut;
9100     destIn = destOut;
9101   }
9102 
9103   MI.eraseFromParent(); // The instruction is gone now.
9104   return BB;
9105 }
9106 
9107 MachineBasicBlock *
9108 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9109                                        MachineBasicBlock *MBB) const {
9110   const TargetMachine &TM = getTargetMachine();
9111   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9112   DebugLoc DL = MI.getDebugLoc();
9113 
9114   assert(Subtarget->isTargetWindows() &&
9115          "__chkstk is only supported on Windows");
9116   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9117 
9118   // __chkstk takes the number of words to allocate on the stack in R4, and
9119   // returns the stack adjustment in number of bytes in R4.  This will not
9120   // clober any other registers (other than the obvious lr).
9121   //
9122   // Although, technically, IP should be considered a register which may be
9123   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9124   // thumb-2 environment, so there is no interworking required.  As a result, we
9125   // do not expect a veneer to be emitted by the linker, clobbering IP.
9126   //
9127   // Each module receives its own copy of __chkstk, so no import thunk is
9128   // required, again, ensuring that IP is not clobbered.
9129   //
9130   // Finally, although some linkers may theoretically provide a trampoline for
9131   // out of range calls (which is quite common due to a 32M range limitation of
9132   // branches for Thumb), we can generate the long-call version via
9133   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9134   // IP.
9135 
9136   switch (TM.getCodeModel()) {
9137   case CodeModel::Tiny:
9138     llvm_unreachable("Tiny code model not available on ARM.");
9139   case CodeModel::Small:
9140   case CodeModel::Medium:
9141   case CodeModel::Kernel:
9142     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9143         .add(predOps(ARMCC::AL))
9144         .addExternalSymbol("__chkstk")
9145         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9146         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9147         .addReg(ARM::R12,
9148                 RegState::Implicit | RegState::Define | RegState::Dead)
9149         .addReg(ARM::CPSR,
9150                 RegState::Implicit | RegState::Define | RegState::Dead);
9151     break;
9152   case CodeModel::Large: {
9153     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9154     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9155 
9156     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9157       .addExternalSymbol("__chkstk");
9158     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9159         .add(predOps(ARMCC::AL))
9160         .addReg(Reg, RegState::Kill)
9161         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9162         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9163         .addReg(ARM::R12,
9164                 RegState::Implicit | RegState::Define | RegState::Dead)
9165         .addReg(ARM::CPSR,
9166                 RegState::Implicit | RegState::Define | RegState::Dead);
9167     break;
9168   }
9169   }
9170 
9171   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9172       .addReg(ARM::SP, RegState::Kill)
9173       .addReg(ARM::R4, RegState::Kill)
9174       .setMIFlags(MachineInstr::FrameSetup)
9175       .add(predOps(ARMCC::AL))
9176       .add(condCodeOp());
9177 
9178   MI.eraseFromParent();
9179   return MBB;
9180 }
9181 
9182 MachineBasicBlock *
9183 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9184                                        MachineBasicBlock *MBB) const {
9185   DebugLoc DL = MI.getDebugLoc();
9186   MachineFunction *MF = MBB->getParent();
9187   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9188 
9189   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9190   MF->insert(++MBB->getIterator(), ContBB);
9191   ContBB->splice(ContBB->begin(), MBB,
9192                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9193   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9194   MBB->addSuccessor(ContBB);
9195 
9196   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9197   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9198   MF->push_back(TrapBB);
9199   MBB->addSuccessor(TrapBB);
9200 
9201   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9202       .addReg(MI.getOperand(0).getReg())
9203       .addImm(0)
9204       .add(predOps(ARMCC::AL));
9205   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9206       .addMBB(TrapBB)
9207       .addImm(ARMCC::EQ)
9208       .addReg(ARM::CPSR);
9209 
9210   MI.eraseFromParent();
9211   return ContBB;
9212 }
9213 
9214 // The CPSR operand of SelectItr might be missing a kill marker
9215 // because there were multiple uses of CPSR, and ISel didn't know
9216 // which to mark. Figure out whether SelectItr should have had a
9217 // kill marker, and set it if it should. Returns the correct kill
9218 // marker value.
9219 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9220                                    MachineBasicBlock* BB,
9221                                    const TargetRegisterInfo* TRI) {
9222   // Scan forward through BB for a use/def of CPSR.
9223   MachineBasicBlock::iterator miI(std::next(SelectItr));
9224   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9225     const MachineInstr& mi = *miI;
9226     if (mi.readsRegister(ARM::CPSR))
9227       return false;
9228     if (mi.definesRegister(ARM::CPSR))
9229       break; // Should have kill-flag - update below.
9230   }
9231 
9232   // If we hit the end of the block, check whether CPSR is live into a
9233   // successor.
9234   if (miI == BB->end()) {
9235     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9236                                           sEnd = BB->succ_end();
9237          sItr != sEnd; ++sItr) {
9238       MachineBasicBlock* succ = *sItr;
9239       if (succ->isLiveIn(ARM::CPSR))
9240         return false;
9241     }
9242   }
9243 
9244   // We found a def, or hit the end of the basic block and CPSR wasn't live
9245   // out. SelectMI should have a kill flag on CPSR.
9246   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9247   return true;
9248 }
9249 
9250 MachineBasicBlock *
9251 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9252                                                MachineBasicBlock *BB) const {
9253   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9254   DebugLoc dl = MI.getDebugLoc();
9255   bool isThumb2 = Subtarget->isThumb2();
9256   switch (MI.getOpcode()) {
9257   default: {
9258     MI.print(errs());
9259     llvm_unreachable("Unexpected instr type to insert");
9260   }
9261 
9262   // Thumb1 post-indexed loads are really just single-register LDMs.
9263   case ARM::tLDR_postidx: {
9264     MachineOperand Def(MI.getOperand(1));
9265     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9266         .add(Def)  // Rn_wb
9267         .add(MI.getOperand(2))  // Rn
9268         .add(MI.getOperand(3))  // PredImm
9269         .add(MI.getOperand(4))  // PredReg
9270         .add(MI.getOperand(0)); // Rt
9271     MI.eraseFromParent();
9272     return BB;
9273   }
9274 
9275   // The Thumb2 pre-indexed stores have the same MI operands, they just
9276   // define them differently in the .td files from the isel patterns, so
9277   // they need pseudos.
9278   case ARM::t2STR_preidx:
9279     MI.setDesc(TII->get(ARM::t2STR_PRE));
9280     return BB;
9281   case ARM::t2STRB_preidx:
9282     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9283     return BB;
9284   case ARM::t2STRH_preidx:
9285     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9286     return BB;
9287 
9288   case ARM::STRi_preidx:
9289   case ARM::STRBi_preidx: {
9290     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9291                                                          : ARM::STRB_PRE_IMM;
9292     // Decode the offset.
9293     unsigned Offset = MI.getOperand(4).getImm();
9294     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9295     Offset = ARM_AM::getAM2Offset(Offset);
9296     if (isSub)
9297       Offset = -Offset;
9298 
9299     MachineMemOperand *MMO = *MI.memoperands_begin();
9300     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9301         .add(MI.getOperand(0)) // Rn_wb
9302         .add(MI.getOperand(1)) // Rt
9303         .add(MI.getOperand(2)) // Rn
9304         .addImm(Offset)        // offset (skip GPR==zero_reg)
9305         .add(MI.getOperand(5)) // pred
9306         .add(MI.getOperand(6))
9307         .addMemOperand(MMO);
9308     MI.eraseFromParent();
9309     return BB;
9310   }
9311   case ARM::STRr_preidx:
9312   case ARM::STRBr_preidx:
9313   case ARM::STRH_preidx: {
9314     unsigned NewOpc;
9315     switch (MI.getOpcode()) {
9316     default: llvm_unreachable("unexpected opcode!");
9317     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9318     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9319     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9320     }
9321     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9322     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9323       MIB.add(MI.getOperand(i));
9324     MI.eraseFromParent();
9325     return BB;
9326   }
9327 
9328   case ARM::tMOVCCr_pseudo: {
9329     // To "insert" a SELECT_CC instruction, we actually have to insert the
9330     // diamond control-flow pattern.  The incoming instruction knows the
9331     // destination vreg to set, the condition code register to branch on, the
9332     // true/false values to select between, and a branch opcode to use.
9333     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9334     MachineFunction::iterator It = ++BB->getIterator();
9335 
9336     //  thisMBB:
9337     //  ...
9338     //   TrueVal = ...
9339     //   cmpTY ccX, r1, r2
9340     //   bCC copy1MBB
9341     //   fallthrough --> copy0MBB
9342     MachineBasicBlock *thisMBB  = BB;
9343     MachineFunction *F = BB->getParent();
9344     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9345     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9346     F->insert(It, copy0MBB);
9347     F->insert(It, sinkMBB);
9348 
9349     // Check whether CPSR is live past the tMOVCCr_pseudo.
9350     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
9351     if (!MI.killsRegister(ARM::CPSR) &&
9352         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
9353       copy0MBB->addLiveIn(ARM::CPSR);
9354       sinkMBB->addLiveIn(ARM::CPSR);
9355     }
9356 
9357     // Transfer the remainder of BB and its successor edges to sinkMBB.
9358     sinkMBB->splice(sinkMBB->begin(), BB,
9359                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9360     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9361 
9362     BB->addSuccessor(copy0MBB);
9363     BB->addSuccessor(sinkMBB);
9364 
9365     BuildMI(BB, dl, TII->get(ARM::tBcc))
9366         .addMBB(sinkMBB)
9367         .addImm(MI.getOperand(3).getImm())
9368         .addReg(MI.getOperand(4).getReg());
9369 
9370     //  copy0MBB:
9371     //   %FalseValue = ...
9372     //   # fallthrough to sinkMBB
9373     BB = copy0MBB;
9374 
9375     // Update machine-CFG edges
9376     BB->addSuccessor(sinkMBB);
9377 
9378     //  sinkMBB:
9379     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9380     //  ...
9381     BB = sinkMBB;
9382     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9383         .addReg(MI.getOperand(1).getReg())
9384         .addMBB(copy0MBB)
9385         .addReg(MI.getOperand(2).getReg())
9386         .addMBB(thisMBB);
9387 
9388     MI.eraseFromParent(); // The pseudo instruction is gone now.
9389     return BB;
9390   }
9391 
9392   case ARM::BCCi64:
9393   case ARM::BCCZi64: {
9394     // If there is an unconditional branch to the other successor, remove it.
9395     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9396 
9397     // Compare both parts that make up the double comparison separately for
9398     // equality.
9399     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9400 
9401     unsigned LHS1 = MI.getOperand(1).getReg();
9402     unsigned LHS2 = MI.getOperand(2).getReg();
9403     if (RHSisZero) {
9404       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9405           .addReg(LHS1)
9406           .addImm(0)
9407           .add(predOps(ARMCC::AL));
9408       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9409         .addReg(LHS2).addImm(0)
9410         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9411     } else {
9412       unsigned RHS1 = MI.getOperand(3).getReg();
9413       unsigned RHS2 = MI.getOperand(4).getReg();
9414       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9415           .addReg(LHS1)
9416           .addReg(RHS1)
9417           .add(predOps(ARMCC::AL));
9418       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9419         .addReg(LHS2).addReg(RHS2)
9420         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9421     }
9422 
9423     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9424     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9425     if (MI.getOperand(0).getImm() == ARMCC::NE)
9426       std::swap(destMBB, exitMBB);
9427 
9428     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9429       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9430     if (isThumb2)
9431       BuildMI(BB, dl, TII->get(ARM::t2B))
9432           .addMBB(exitMBB)
9433           .add(predOps(ARMCC::AL));
9434     else
9435       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9436 
9437     MI.eraseFromParent(); // The pseudo instruction is gone now.
9438     return BB;
9439   }
9440 
9441   case ARM::Int_eh_sjlj_setjmp:
9442   case ARM::Int_eh_sjlj_setjmp_nofp:
9443   case ARM::tInt_eh_sjlj_setjmp:
9444   case ARM::t2Int_eh_sjlj_setjmp:
9445   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9446     return BB;
9447 
9448   case ARM::Int_eh_sjlj_setup_dispatch:
9449     EmitSjLjDispatchBlock(MI, BB);
9450     return BB;
9451 
9452   case ARM::ABS:
9453   case ARM::t2ABS: {
9454     // To insert an ABS instruction, we have to insert the
9455     // diamond control-flow pattern.  The incoming instruction knows the
9456     // source vreg to test against 0, the destination vreg to set,
9457     // the condition code register to branch on, the
9458     // true/false values to select between, and a branch opcode to use.
9459     // It transforms
9460     //     V1 = ABS V0
9461     // into
9462     //     V2 = MOVS V0
9463     //     BCC                      (branch to SinkBB if V0 >= 0)
9464     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9465     //     SinkBB: V1 = PHI(V2, V3)
9466     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9467     MachineFunction::iterator BBI = ++BB->getIterator();
9468     MachineFunction *Fn = BB->getParent();
9469     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9470     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9471     Fn->insert(BBI, RSBBB);
9472     Fn->insert(BBI, SinkBB);
9473 
9474     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9475     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9476     bool ABSSrcKIll = MI.getOperand(1).isKill();
9477     bool isThumb2 = Subtarget->isThumb2();
9478     MachineRegisterInfo &MRI = Fn->getRegInfo();
9479     // In Thumb mode S must not be specified if source register is the SP or
9480     // PC and if destination register is the SP, so restrict register class
9481     unsigned NewRsbDstReg =
9482       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9483 
9484     // Transfer the remainder of BB and its successor edges to sinkMBB.
9485     SinkBB->splice(SinkBB->begin(), BB,
9486                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9487     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9488 
9489     BB->addSuccessor(RSBBB);
9490     BB->addSuccessor(SinkBB);
9491 
9492     // fall through to SinkMBB
9493     RSBBB->addSuccessor(SinkBB);
9494 
9495     // insert a cmp at the end of BB
9496     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9497         .addReg(ABSSrcReg)
9498         .addImm(0)
9499         .add(predOps(ARMCC::AL));
9500 
9501     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9502     BuildMI(BB, dl,
9503       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9504       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9505 
9506     // insert rsbri in RSBBB
9507     // Note: BCC and rsbri will be converted into predicated rsbmi
9508     // by if-conversion pass
9509     BuildMI(*RSBBB, RSBBB->begin(), dl,
9510             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9511         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9512         .addImm(0)
9513         .add(predOps(ARMCC::AL))
9514         .add(condCodeOp());
9515 
9516     // insert PHI in SinkBB,
9517     // reuse ABSDstReg to not change uses of ABS instruction
9518     BuildMI(*SinkBB, SinkBB->begin(), dl,
9519       TII->get(ARM::PHI), ABSDstReg)
9520       .addReg(NewRsbDstReg).addMBB(RSBBB)
9521       .addReg(ABSSrcReg).addMBB(BB);
9522 
9523     // remove ABS instruction
9524     MI.eraseFromParent();
9525 
9526     // return last added BB
9527     return SinkBB;
9528   }
9529   case ARM::COPY_STRUCT_BYVAL_I32:
9530     ++NumLoopByVals;
9531     return EmitStructByval(MI, BB);
9532   case ARM::WIN__CHKSTK:
9533     return EmitLowered__chkstk(MI, BB);
9534   case ARM::WIN__DBZCHK:
9535     return EmitLowered__dbzchk(MI, BB);
9536   }
9537 }
9538 
9539 /// Attaches vregs to MEMCPY that it will use as scratch registers
9540 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9541 /// instead of as a custom inserter because we need the use list from the SDNode.
9542 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9543                                     MachineInstr &MI, const SDNode *Node) {
9544   bool isThumb1 = Subtarget->isThumb1Only();
9545 
9546   DebugLoc DL = MI.getDebugLoc();
9547   MachineFunction *MF = MI.getParent()->getParent();
9548   MachineRegisterInfo &MRI = MF->getRegInfo();
9549   MachineInstrBuilder MIB(*MF, MI);
9550 
9551   // If the new dst/src is unused mark it as dead.
9552   if (!Node->hasAnyUseOfValue(0)) {
9553     MI.getOperand(0).setIsDead(true);
9554   }
9555   if (!Node->hasAnyUseOfValue(1)) {
9556     MI.getOperand(1).setIsDead(true);
9557   }
9558 
9559   // The MEMCPY both defines and kills the scratch registers.
9560   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9561     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9562                                                          : &ARM::GPRRegClass);
9563     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9564   }
9565 }
9566 
9567 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9568                                                       SDNode *Node) const {
9569   if (MI.getOpcode() == ARM::MEMCPY) {
9570     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9571     return;
9572   }
9573 
9574   const MCInstrDesc *MCID = &MI.getDesc();
9575   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9576   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9577   // operand is still set to noreg. If needed, set the optional operand's
9578   // register to CPSR, and remove the redundant implicit def.
9579   //
9580   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9581 
9582   // Rename pseudo opcodes.
9583   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9584   unsigned ccOutIdx;
9585   if (NewOpc) {
9586     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9587     MCID = &TII->get(NewOpc);
9588 
9589     assert(MCID->getNumOperands() ==
9590            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9591         && "converted opcode should be the same except for cc_out"
9592            " (and, on Thumb1, pred)");
9593 
9594     MI.setDesc(*MCID);
9595 
9596     // Add the optional cc_out operand
9597     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9598 
9599     // On Thumb1, move all input operands to the end, then add the predicate
9600     if (Subtarget->isThumb1Only()) {
9601       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9602         MI.addOperand(MI.getOperand(1));
9603         MI.RemoveOperand(1);
9604       }
9605 
9606       // Restore the ties
9607       for (unsigned i = MI.getNumOperands(); i--;) {
9608         const MachineOperand& op = MI.getOperand(i);
9609         if (op.isReg() && op.isUse()) {
9610           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9611           if (DefIdx != -1)
9612             MI.tieOperands(DefIdx, i);
9613         }
9614       }
9615 
9616       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9617       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9618       ccOutIdx = 1;
9619     } else
9620       ccOutIdx = MCID->getNumOperands() - 1;
9621   } else
9622     ccOutIdx = MCID->getNumOperands() - 1;
9623 
9624   // Any ARM instruction that sets the 's' bit should specify an optional
9625   // "cc_out" operand in the last operand position.
9626   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9627     assert(!NewOpc && "Optional cc_out operand required");
9628     return;
9629   }
9630   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9631   // since we already have an optional CPSR def.
9632   bool definesCPSR = false;
9633   bool deadCPSR = false;
9634   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9635        ++i) {
9636     const MachineOperand &MO = MI.getOperand(i);
9637     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9638       definesCPSR = true;
9639       if (MO.isDead())
9640         deadCPSR = true;
9641       MI.RemoveOperand(i);
9642       break;
9643     }
9644   }
9645   if (!definesCPSR) {
9646     assert(!NewOpc && "Optional cc_out operand required");
9647     return;
9648   }
9649   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9650   if (deadCPSR) {
9651     assert(!MI.getOperand(ccOutIdx).getReg() &&
9652            "expect uninitialized optional cc_out operand");
9653     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9654     if (!Subtarget->isThumb1Only())
9655       return;
9656   }
9657 
9658   // If this instruction was defined with an optional CPSR def and its dag node
9659   // had a live implicit CPSR def, then activate the optional CPSR def.
9660   MachineOperand &MO = MI.getOperand(ccOutIdx);
9661   MO.setReg(ARM::CPSR);
9662   MO.setIsDef(true);
9663 }
9664 
9665 //===----------------------------------------------------------------------===//
9666 //                           ARM Optimization Hooks
9667 //===----------------------------------------------------------------------===//
9668 
9669 // Helper function that checks if N is a null or all ones constant.
9670 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9671   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9672 }
9673 
9674 // Return true if N is conditionally 0 or all ones.
9675 // Detects these expressions where cc is an i1 value:
9676 //
9677 //   (select cc 0, y)   [AllOnes=0]
9678 //   (select cc y, 0)   [AllOnes=0]
9679 //   (zext cc)          [AllOnes=0]
9680 //   (sext cc)          [AllOnes=0/1]
9681 //   (select cc -1, y)  [AllOnes=1]
9682 //   (select cc y, -1)  [AllOnes=1]
9683 //
9684 // Invert is set when N is the null/all ones constant when CC is false.
9685 // OtherOp is set to the alternative value of N.
9686 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9687                                        SDValue &CC, bool &Invert,
9688                                        SDValue &OtherOp,
9689                                        SelectionDAG &DAG) {
9690   switch (N->getOpcode()) {
9691   default: return false;
9692   case ISD::SELECT: {
9693     CC = N->getOperand(0);
9694     SDValue N1 = N->getOperand(1);
9695     SDValue N2 = N->getOperand(2);
9696     if (isZeroOrAllOnes(N1, AllOnes)) {
9697       Invert = false;
9698       OtherOp = N2;
9699       return true;
9700     }
9701     if (isZeroOrAllOnes(N2, AllOnes)) {
9702       Invert = true;
9703       OtherOp = N1;
9704       return true;
9705     }
9706     return false;
9707   }
9708   case ISD::ZERO_EXTEND:
9709     // (zext cc) can never be the all ones value.
9710     if (AllOnes)
9711       return false;
9712     LLVM_FALLTHROUGH;
9713   case ISD::SIGN_EXTEND: {
9714     SDLoc dl(N);
9715     EVT VT = N->getValueType(0);
9716     CC = N->getOperand(0);
9717     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9718       return false;
9719     Invert = !AllOnes;
9720     if (AllOnes)
9721       // When looking for an AllOnes constant, N is an sext, and the 'other'
9722       // value is 0.
9723       OtherOp = DAG.getConstant(0, dl, VT);
9724     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9725       // When looking for a 0 constant, N can be zext or sext.
9726       OtherOp = DAG.getConstant(1, dl, VT);
9727     else
9728       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9729                                 VT);
9730     return true;
9731   }
9732   }
9733 }
9734 
9735 // Combine a constant select operand into its use:
9736 //
9737 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9738 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9739 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9740 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9741 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9742 //
9743 // The transform is rejected if the select doesn't have a constant operand that
9744 // is null, or all ones when AllOnes is set.
9745 //
9746 // Also recognize sext/zext from i1:
9747 //
9748 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9749 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9750 //
9751 // These transformations eventually create predicated instructions.
9752 //
9753 // @param N       The node to transform.
9754 // @param Slct    The N operand that is a select.
9755 // @param OtherOp The other N operand (x above).
9756 // @param DCI     Context.
9757 // @param AllOnes Require the select constant to be all ones instead of null.
9758 // @returns The new node, or SDValue() on failure.
9759 static
9760 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9761                             TargetLowering::DAGCombinerInfo &DCI,
9762                             bool AllOnes = false) {
9763   SelectionDAG &DAG = DCI.DAG;
9764   EVT VT = N->getValueType(0);
9765   SDValue NonConstantVal;
9766   SDValue CCOp;
9767   bool SwapSelectOps;
9768   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9769                                   NonConstantVal, DAG))
9770     return SDValue();
9771 
9772   // Slct is now know to be the desired identity constant when CC is true.
9773   SDValue TrueVal = OtherOp;
9774   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9775                                  OtherOp, NonConstantVal);
9776   // Unless SwapSelectOps says CC should be false.
9777   if (SwapSelectOps)
9778     std::swap(TrueVal, FalseVal);
9779 
9780   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9781                      CCOp, TrueVal, FalseVal);
9782 }
9783 
9784 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9785 static
9786 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9787                                        TargetLowering::DAGCombinerInfo &DCI) {
9788   SDValue N0 = N->getOperand(0);
9789   SDValue N1 = N->getOperand(1);
9790   if (N0.getNode()->hasOneUse())
9791     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9792       return Result;
9793   if (N1.getNode()->hasOneUse())
9794     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9795       return Result;
9796   return SDValue();
9797 }
9798 
9799 static bool IsVUZPShuffleNode(SDNode *N) {
9800   // VUZP shuffle node.
9801   if (N->getOpcode() == ARMISD::VUZP)
9802     return true;
9803 
9804   // "VUZP" on i32 is an alias for VTRN.
9805   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9806     return true;
9807 
9808   return false;
9809 }
9810 
9811 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9812                                  TargetLowering::DAGCombinerInfo &DCI,
9813                                  const ARMSubtarget *Subtarget) {
9814   // Look for ADD(VUZP.0, VUZP.1).
9815   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9816       N0 == N1)
9817    return SDValue();
9818 
9819   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9820   if (!N->getValueType(0).is64BitVector())
9821     return SDValue();
9822 
9823   // Generate vpadd.
9824   SelectionDAG &DAG = DCI.DAG;
9825   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9826   SDLoc dl(N);
9827   SDNode *Unzip = N0.getNode();
9828   EVT VT = N->getValueType(0);
9829 
9830   SmallVector<SDValue, 8> Ops;
9831   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9832                                 TLI.getPointerTy(DAG.getDataLayout())));
9833   Ops.push_back(Unzip->getOperand(0));
9834   Ops.push_back(Unzip->getOperand(1));
9835 
9836   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9837 }
9838 
9839 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9840                                       TargetLowering::DAGCombinerInfo &DCI,
9841                                       const ARMSubtarget *Subtarget) {
9842   // Check for two extended operands.
9843   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9844         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9845       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9846         N1.getOpcode() == ISD::ZERO_EXTEND))
9847     return SDValue();
9848 
9849   SDValue N00 = N0.getOperand(0);
9850   SDValue N10 = N1.getOperand(0);
9851 
9852   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9853   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9854       N00 == N10)
9855     return SDValue();
9856 
9857   // We only recognize Q register paddl here; this can't be reached until
9858   // after type legalization.
9859   if (!N00.getValueType().is64BitVector() ||
9860       !N0.getValueType().is128BitVector())
9861     return SDValue();
9862 
9863   // Generate vpaddl.
9864   SelectionDAG &DAG = DCI.DAG;
9865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9866   SDLoc dl(N);
9867   EVT VT = N->getValueType(0);
9868 
9869   SmallVector<SDValue, 8> Ops;
9870   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9871   unsigned Opcode;
9872   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9873     Opcode = Intrinsic::arm_neon_vpaddls;
9874   else
9875     Opcode = Intrinsic::arm_neon_vpaddlu;
9876   Ops.push_back(DAG.getConstant(Opcode, dl,
9877                                 TLI.getPointerTy(DAG.getDataLayout())));
9878   EVT ElemTy = N00.getValueType().getVectorElementType();
9879   unsigned NumElts = VT.getVectorNumElements();
9880   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9881   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9882                                N00.getOperand(0), N00.getOperand(1));
9883   Ops.push_back(Concat);
9884 
9885   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9886 }
9887 
9888 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9889 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9890 // much easier to match.
9891 static SDValue
9892 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9893                                TargetLowering::DAGCombinerInfo &DCI,
9894                                const ARMSubtarget *Subtarget) {
9895   // Only perform optimization if after legalize, and if NEON is available. We
9896   // also expected both operands to be BUILD_VECTORs.
9897   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9898       || N0.getOpcode() != ISD::BUILD_VECTOR
9899       || N1.getOpcode() != ISD::BUILD_VECTOR)
9900     return SDValue();
9901 
9902   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9903   EVT VT = N->getValueType(0);
9904   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9905     return SDValue();
9906 
9907   // Check that the vector operands are of the right form.
9908   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9909   // operands, where N is the size of the formed vector.
9910   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9911   // index such that we have a pair wise add pattern.
9912 
9913   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9914   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9915     return SDValue();
9916   SDValue Vec = N0->getOperand(0)->getOperand(0);
9917   SDNode *V = Vec.getNode();
9918   unsigned nextIndex = 0;
9919 
9920   // For each operands to the ADD which are BUILD_VECTORs,
9921   // check to see if each of their operands are an EXTRACT_VECTOR with
9922   // the same vector and appropriate index.
9923   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9924     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9925         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9926 
9927       SDValue ExtVec0 = N0->getOperand(i);
9928       SDValue ExtVec1 = N1->getOperand(i);
9929 
9930       // First operand is the vector, verify its the same.
9931       if (V != ExtVec0->getOperand(0).getNode() ||
9932           V != ExtVec1->getOperand(0).getNode())
9933         return SDValue();
9934 
9935       // Second is the constant, verify its correct.
9936       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9937       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9938 
9939       // For the constant, we want to see all the even or all the odd.
9940       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9941           || C1->getZExtValue() != nextIndex+1)
9942         return SDValue();
9943 
9944       // Increment index.
9945       nextIndex+=2;
9946     } else
9947       return SDValue();
9948   }
9949 
9950   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9951   // we're using the entire input vector, otherwise there's a size/legality
9952   // mismatch somewhere.
9953   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9954       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9955     return SDValue();
9956 
9957   // Create VPADDL node.
9958   SelectionDAG &DAG = DCI.DAG;
9959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9960 
9961   SDLoc dl(N);
9962 
9963   // Build operand list.
9964   SmallVector<SDValue, 8> Ops;
9965   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9966                                 TLI.getPointerTy(DAG.getDataLayout())));
9967 
9968   // Input is the vector.
9969   Ops.push_back(Vec);
9970 
9971   // Get widened type and narrowed type.
9972   MVT widenType;
9973   unsigned numElem = VT.getVectorNumElements();
9974 
9975   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9976   switch (inputLaneType.getSimpleVT().SimpleTy) {
9977     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9978     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9979     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9980     default:
9981       llvm_unreachable("Invalid vector element type for padd optimization.");
9982   }
9983 
9984   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9985   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9986   return DAG.getNode(ExtOp, dl, VT, tmp);
9987 }
9988 
9989 static SDValue findMUL_LOHI(SDValue V) {
9990   if (V->getOpcode() == ISD::UMUL_LOHI ||
9991       V->getOpcode() == ISD::SMUL_LOHI)
9992     return V;
9993   return SDValue();
9994 }
9995 
9996 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9997                                         TargetLowering::DAGCombinerInfo &DCI,
9998                                         const ARMSubtarget *Subtarget) {
9999   if (Subtarget->isThumb()) {
10000     if (!Subtarget->hasDSP())
10001       return SDValue();
10002   } else if (!Subtarget->hasV5TEOps())
10003     return SDValue();
10004 
10005   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10006   // accumulates the product into a 64-bit value. The 16-bit values will
10007   // be sign extended somehow or SRA'd into 32-bit values
10008   // (addc (adde (mul 16bit, 16bit), lo), hi)
10009   SDValue Mul = AddcNode->getOperand(0);
10010   SDValue Lo = AddcNode->getOperand(1);
10011   if (Mul.getOpcode() != ISD::MUL) {
10012     Lo = AddcNode->getOperand(0);
10013     Mul = AddcNode->getOperand(1);
10014     if (Mul.getOpcode() != ISD::MUL)
10015       return SDValue();
10016   }
10017 
10018   SDValue SRA = AddeNode->getOperand(0);
10019   SDValue Hi = AddeNode->getOperand(1);
10020   if (SRA.getOpcode() != ISD::SRA) {
10021     SRA = AddeNode->getOperand(1);
10022     Hi = AddeNode->getOperand(0);
10023     if (SRA.getOpcode() != ISD::SRA)
10024       return SDValue();
10025   }
10026   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10027     if (Const->getZExtValue() != 31)
10028       return SDValue();
10029   } else
10030     return SDValue();
10031 
10032   if (SRA.getOperand(0) != Mul)
10033     return SDValue();
10034 
10035   SelectionDAG &DAG = DCI.DAG;
10036   SDLoc dl(AddcNode);
10037   unsigned Opcode = 0;
10038   SDValue Op0;
10039   SDValue Op1;
10040 
10041   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10042     Opcode = ARMISD::SMLALBB;
10043     Op0 = Mul.getOperand(0);
10044     Op1 = Mul.getOperand(1);
10045   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10046     Opcode = ARMISD::SMLALBT;
10047     Op0 = Mul.getOperand(0);
10048     Op1 = Mul.getOperand(1).getOperand(0);
10049   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10050     Opcode = ARMISD::SMLALTB;
10051     Op0 = Mul.getOperand(0).getOperand(0);
10052     Op1 = Mul.getOperand(1);
10053   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10054     Opcode = ARMISD::SMLALTT;
10055     Op0 = Mul->getOperand(0).getOperand(0);
10056     Op1 = Mul->getOperand(1).getOperand(0);
10057   }
10058 
10059   if (!Op0 || !Op1)
10060     return SDValue();
10061 
10062   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10063                               Op0, Op1, Lo, Hi);
10064   // Replace the ADDs' nodes uses by the MLA node's values.
10065   SDValue HiMLALResult(SMLAL.getNode(), 1);
10066   SDValue LoMLALResult(SMLAL.getNode(), 0);
10067 
10068   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10069   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10070 
10071   // Return original node to notify the driver to stop replacing.
10072   SDValue resNode(AddcNode, 0);
10073   return resNode;
10074 }
10075 
10076 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10077                                      TargetLowering::DAGCombinerInfo &DCI,
10078                                      const ARMSubtarget *Subtarget) {
10079   // Look for multiply add opportunities.
10080   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10081   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10082   // a glue link from the first add to the second add.
10083   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10084   // a S/UMLAL instruction.
10085   //                  UMUL_LOHI
10086   //                 / :lo    \ :hi
10087   //                V          \          [no multiline comment]
10088   //    loAdd ->  ADDC         |
10089   //                 \ :carry /
10090   //                  V      V
10091   //                    ADDE   <- hiAdd
10092   //
10093   // In the special case where only the higher part of a signed result is used
10094   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10095   // a constant with the exact value of 0x80000000, we recognize we are dealing
10096   // with a "rounded multiply and add" (or subtract) and transform it into
10097   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10098 
10099   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10100           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10101          "Expect an ADDE or SUBE");
10102 
10103   assert(AddeSubeNode->getNumOperands() == 3 &&
10104          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10105          "ADDE node has the wrong inputs");
10106 
10107   // Check that we are chained to the right ADDC or SUBC node.
10108   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10109   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10110        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10111       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10112        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10113     return SDValue();
10114 
10115   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10116   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10117 
10118   // Check if the two operands are from the same mul_lohi node.
10119   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10120     return SDValue();
10121 
10122   assert(AddcSubcNode->getNumValues() == 2 &&
10123          AddcSubcNode->getValueType(0) == MVT::i32 &&
10124          "Expect ADDC with two result values. First: i32");
10125 
10126   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10127   // maybe a SMLAL which multiplies two 16-bit values.
10128   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10129       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10130       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10131       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10132       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10133     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10134 
10135   // Check for the triangle shape.
10136   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10137   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10138 
10139   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10140   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10141     return SDValue();
10142 
10143   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10144   bool IsLeftOperandMUL = false;
10145   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10146   if (MULOp == SDValue())
10147     MULOp = findMUL_LOHI(AddeSubeOp1);
10148   else
10149     IsLeftOperandMUL = true;
10150   if (MULOp == SDValue())
10151     return SDValue();
10152 
10153   // Figure out the right opcode.
10154   unsigned Opc = MULOp->getOpcode();
10155   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10156 
10157   // Figure out the high and low input values to the MLAL node.
10158   SDValue *HiAddSub = nullptr;
10159   SDValue *LoMul = nullptr;
10160   SDValue *LowAddSub = nullptr;
10161 
10162   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10163   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10164     return SDValue();
10165 
10166   if (IsLeftOperandMUL)
10167     HiAddSub = &AddeSubeOp1;
10168   else
10169     HiAddSub = &AddeSubeOp0;
10170 
10171   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10172   // whose low result is fed to the ADDC/SUBC we are checking.
10173 
10174   if (AddcSubcOp0 == MULOp.getValue(0)) {
10175     LoMul = &AddcSubcOp0;
10176     LowAddSub = &AddcSubcOp1;
10177   }
10178   if (AddcSubcOp1 == MULOp.getValue(0)) {
10179     LoMul = &AddcSubcOp1;
10180     LowAddSub = &AddcSubcOp0;
10181   }
10182 
10183   if (!LoMul)
10184     return SDValue();
10185 
10186   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10187   // the replacement below will create a cycle.
10188   if (AddcSubcNode == HiAddSub->getNode() ||
10189       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10190     return SDValue();
10191 
10192   // Create the merged node.
10193   SelectionDAG &DAG = DCI.DAG;
10194 
10195   // Start building operand list.
10196   SmallVector<SDValue, 8> Ops;
10197   Ops.push_back(LoMul->getOperand(0));
10198   Ops.push_back(LoMul->getOperand(1));
10199 
10200   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10201   // the case, we must be doing signed multiplication and only use the higher
10202   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10203   // addition or subtraction with the value of 0x800000.
10204   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10205       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10206       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10207       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10208           0x80000000) {
10209     Ops.push_back(*HiAddSub);
10210     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10211       FinalOpc = ARMISD::SMMLSR;
10212     } else {
10213       FinalOpc = ARMISD::SMMLAR;
10214     }
10215     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10216     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10217 
10218     return SDValue(AddeSubeNode, 0);
10219   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10220     // SMMLS is generated during instruction selection and the rest of this
10221     // function can not handle the case where AddcSubcNode is a SUBC.
10222     return SDValue();
10223 
10224   // Finish building the operand list for {U/S}MLAL
10225   Ops.push_back(*LowAddSub);
10226   Ops.push_back(*HiAddSub);
10227 
10228   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10229                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10230 
10231   // Replace the ADDs' nodes uses by the MLA node's values.
10232   SDValue HiMLALResult(MLALNode.getNode(), 1);
10233   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10234 
10235   SDValue LoMLALResult(MLALNode.getNode(), 0);
10236   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10237 
10238   // Return original node to notify the driver to stop replacing.
10239   return SDValue(AddeSubeNode, 0);
10240 }
10241 
10242 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10243                                       TargetLowering::DAGCombinerInfo &DCI,
10244                                       const ARMSubtarget *Subtarget) {
10245   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10246   // While trying to combine for the other MLAL nodes, first search for the
10247   // chance to use UMAAL. Check if Addc uses a node which has already
10248   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10249   // as the addend, and it's handled in PerformUMLALCombine.
10250 
10251   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10252     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10253 
10254   // Check that we have a glued ADDC node.
10255   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10256   if (AddcNode->getOpcode() != ARMISD::ADDC)
10257     return SDValue();
10258 
10259   // Find the converted UMAAL or quit if it doesn't exist.
10260   SDNode *UmlalNode = nullptr;
10261   SDValue AddHi;
10262   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10263     UmlalNode = AddcNode->getOperand(0).getNode();
10264     AddHi = AddcNode->getOperand(1);
10265   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10266     UmlalNode = AddcNode->getOperand(1).getNode();
10267     AddHi = AddcNode->getOperand(0);
10268   } else {
10269     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10270   }
10271 
10272   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10273   // the ADDC as well as Zero.
10274   if (!isNullConstant(UmlalNode->getOperand(3)))
10275     return SDValue();
10276 
10277   if ((isNullConstant(AddeNode->getOperand(0)) &&
10278        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10279       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10280        isNullConstant(AddeNode->getOperand(1)))) {
10281     SelectionDAG &DAG = DCI.DAG;
10282     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10283                       UmlalNode->getOperand(2), AddHi };
10284     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10285                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10286 
10287     // Replace the ADDs' nodes uses by the UMAAL node's values.
10288     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10289     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10290 
10291     // Return original node to notify the driver to stop replacing.
10292     return SDValue(AddeNode, 0);
10293   }
10294   return SDValue();
10295 }
10296 
10297 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10298                                    const ARMSubtarget *Subtarget) {
10299   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10300     return SDValue();
10301 
10302   // Check that we have a pair of ADDC and ADDE as operands.
10303   // Both addends of the ADDE must be zero.
10304   SDNode* AddcNode = N->getOperand(2).getNode();
10305   SDNode* AddeNode = N->getOperand(3).getNode();
10306   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10307       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10308       isNullConstant(AddeNode->getOperand(0)) &&
10309       isNullConstant(AddeNode->getOperand(1)) &&
10310       (AddeNode->getOperand(2).getNode() == AddcNode))
10311     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10312                        DAG.getVTList(MVT::i32, MVT::i32),
10313                        {N->getOperand(0), N->getOperand(1),
10314                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10315   else
10316     return SDValue();
10317 }
10318 
10319 static SDValue PerformAddcSubcCombine(SDNode *N,
10320                                       TargetLowering::DAGCombinerInfo &DCI,
10321                                       const ARMSubtarget *Subtarget) {
10322   SelectionDAG &DAG(DCI.DAG);
10323 
10324   if (N->getOpcode() == ARMISD::SUBC) {
10325     // (SUBC (ADDE 0, 0, C), 1) -> C
10326     SDValue LHS = N->getOperand(0);
10327     SDValue RHS = N->getOperand(1);
10328     if (LHS->getOpcode() == ARMISD::ADDE &&
10329         isNullConstant(LHS->getOperand(0)) &&
10330         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10331       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10332     }
10333   }
10334 
10335   if (Subtarget->isThumb1Only()) {
10336     SDValue RHS = N->getOperand(1);
10337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10338       int32_t imm = C->getSExtValue();
10339       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10340         SDLoc DL(N);
10341         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10342         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10343                                                            : ARMISD::ADDC;
10344         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10345       }
10346     }
10347   }
10348 
10349   return SDValue();
10350 }
10351 
10352 static SDValue PerformAddeSubeCombine(SDNode *N,
10353                                       TargetLowering::DAGCombinerInfo &DCI,
10354                                       const ARMSubtarget *Subtarget) {
10355   if (Subtarget->isThumb1Only()) {
10356     SelectionDAG &DAG = DCI.DAG;
10357     SDValue RHS = N->getOperand(1);
10358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10359       int64_t imm = C->getSExtValue();
10360       if (imm < 0) {
10361         SDLoc DL(N);
10362 
10363         // The with-carry-in form matches bitwise not instead of the negation.
10364         // Effectively, the inverse interpretation of the carry flag already
10365         // accounts for part of the negation.
10366         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10367 
10368         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10369                                                            : ARMISD::ADDE;
10370         return DAG.getNode(Opcode, DL, N->getVTList(),
10371                            N->getOperand(0), RHS, N->getOperand(2));
10372       }
10373     }
10374   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10375     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10376   }
10377   return SDValue();
10378 }
10379 
10380 /// PerformADDECombine - Target-specific dag combine transform from
10381 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10382 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10383 static SDValue PerformADDECombine(SDNode *N,
10384                                   TargetLowering::DAGCombinerInfo &DCI,
10385                                   const ARMSubtarget *Subtarget) {
10386   // Only ARM and Thumb2 support UMLAL/SMLAL.
10387   if (Subtarget->isThumb1Only())
10388     return PerformAddeSubeCombine(N, DCI, Subtarget);
10389 
10390   // Only perform the checks after legalize when the pattern is available.
10391   if (DCI.isBeforeLegalize()) return SDValue();
10392 
10393   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10394 }
10395 
10396 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10397 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10398 /// called with the default operands, and if that fails, with commuted
10399 /// operands.
10400 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10401                                           TargetLowering::DAGCombinerInfo &DCI,
10402                                           const ARMSubtarget *Subtarget){
10403   // Attempt to create vpadd for this add.
10404   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10405     return Result;
10406 
10407   // Attempt to create vpaddl for this add.
10408   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10409     return Result;
10410   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10411                                                       Subtarget))
10412     return Result;
10413 
10414   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10415   if (N0.getNode()->hasOneUse())
10416     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10417       return Result;
10418   return SDValue();
10419 }
10420 
10421 bool
10422 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10423                                                  CombineLevel Level) const {
10424   if (Level == BeforeLegalizeTypes)
10425     return true;
10426 
10427   if (N->getOpcode() != ISD::SHL)
10428     return true;
10429 
10430   if (Subtarget->isThumb1Only()) {
10431     // Avoid making expensive immediates by commuting shifts. (This logic
10432     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
10433     // for free.)
10434     if (N->getOpcode() != ISD::SHL)
10435       return true;
10436     SDValue N1 = N->getOperand(0);
10437     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
10438         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
10439       return true;
10440     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
10441       if (Const->getAPIntValue().ult(256))
10442         return false;
10443       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
10444           Const->getAPIntValue().sgt(-256))
10445         return false;
10446     }
10447     return true;
10448   }
10449 
10450   // Turn off commute-with-shift transform after legalization, so it doesn't
10451   // conflict with PerformSHLSimplify.  (We could try to detect when
10452   // PerformSHLSimplify would trigger more precisely, but it isn't
10453   // really necessary.)
10454   return false;
10455 }
10456 
10457 bool
10458 ARMTargetLowering::shouldFoldShiftPairToMask(const SDNode *N,
10459                                              CombineLevel Level) const {
10460   if (!Subtarget->isThumb1Only())
10461     return true;
10462 
10463   if (Level == BeforeLegalizeTypes)
10464     return true;
10465 
10466   return false;
10467 }
10468 
10469 static SDValue PerformSHLSimplify(SDNode *N,
10470                                 TargetLowering::DAGCombinerInfo &DCI,
10471                                 const ARMSubtarget *ST) {
10472   // Allow the generic combiner to identify potential bswaps.
10473   if (DCI.isBeforeLegalize())
10474     return SDValue();
10475 
10476   // DAG combiner will fold:
10477   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10478   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10479   // Other code patterns that can be also be modified have the following form:
10480   // b + ((a << 1) | 510)
10481   // b + ((a << 1) & 510)
10482   // b + ((a << 1) ^ 510)
10483   // b + ((a << 1) + 510)
10484 
10485   // Many instructions can  perform the shift for free, but it requires both
10486   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10487   // instruction will needed. So, unfold back to the original pattern if:
10488   // - if c1 and c2 are small enough that they don't require mov imms.
10489   // - the user(s) of the node can perform an shl
10490 
10491   // No shifted operands for 16-bit instructions.
10492   if (ST->isThumb() && ST->isThumb1Only())
10493     return SDValue();
10494 
10495   // Check that all the users could perform the shl themselves.
10496   for (auto U : N->uses()) {
10497     switch(U->getOpcode()) {
10498     default:
10499       return SDValue();
10500     case ISD::SUB:
10501     case ISD::ADD:
10502     case ISD::AND:
10503     case ISD::OR:
10504     case ISD::XOR:
10505     case ISD::SETCC:
10506     case ARMISD::CMP:
10507       // Check that the user isn't already using a constant because there
10508       // aren't any instructions that support an immediate operand and a
10509       // shifted operand.
10510       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10511           isa<ConstantSDNode>(U->getOperand(1)))
10512         return SDValue();
10513 
10514       // Check that it's not already using a shift.
10515       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10516           U->getOperand(1).getOpcode() == ISD::SHL)
10517         return SDValue();
10518       break;
10519     }
10520   }
10521 
10522   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10523       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10524     return SDValue();
10525 
10526   if (N->getOperand(0).getOpcode() != ISD::SHL)
10527     return SDValue();
10528 
10529   SDValue SHL = N->getOperand(0);
10530 
10531   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10532   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10533   if (!C1ShlC2 || !C2)
10534     return SDValue();
10535 
10536   APInt C2Int = C2->getAPIntValue();
10537   APInt C1Int = C1ShlC2->getAPIntValue();
10538 
10539   // Check that performing a lshr will not lose any information.
10540   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10541                                      C2Int.getBitWidth() - C2->getZExtValue());
10542   if ((C1Int & Mask) != C1Int)
10543     return SDValue();
10544 
10545   // Shift the first constant.
10546   C1Int.lshrInPlace(C2Int);
10547 
10548   // The immediates are encoded as an 8-bit value that can be rotated.
10549   auto LargeImm = [](const APInt &Imm) {
10550     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10551     return Imm.getBitWidth() - Zeros > 8;
10552   };
10553 
10554   if (LargeImm(C1Int) || LargeImm(C2Int))
10555     return SDValue();
10556 
10557   SelectionDAG &DAG = DCI.DAG;
10558   SDLoc dl(N);
10559   SDValue X = SHL.getOperand(0);
10560   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10561                               DAG.getConstant(C1Int, dl, MVT::i32));
10562   // Shift left to compensate for the lshr of C1Int.
10563   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10564 
10565   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
10566              SHL.dump(); N->dump());
10567   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10568   return Res;
10569 }
10570 
10571 
10572 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10573 ///
10574 static SDValue PerformADDCombine(SDNode *N,
10575                                  TargetLowering::DAGCombinerInfo &DCI,
10576                                  const ARMSubtarget *Subtarget) {
10577   SDValue N0 = N->getOperand(0);
10578   SDValue N1 = N->getOperand(1);
10579 
10580   // Only works one way, because it needs an immediate operand.
10581   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10582     return Result;
10583 
10584   // First try with the default operand order.
10585   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10586     return Result;
10587 
10588   // If that didn't work, try again with the operands commuted.
10589   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10590 }
10591 
10592 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10593 ///
10594 static SDValue PerformSUBCombine(SDNode *N,
10595                                  TargetLowering::DAGCombinerInfo &DCI) {
10596   SDValue N0 = N->getOperand(0);
10597   SDValue N1 = N->getOperand(1);
10598 
10599   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10600   if (N1.getNode()->hasOneUse())
10601     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10602       return Result;
10603 
10604   return SDValue();
10605 }
10606 
10607 /// PerformVMULCombine
10608 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10609 /// special multiplier accumulator forwarding.
10610 ///   vmul d3, d0, d2
10611 ///   vmla d3, d1, d2
10612 /// is faster than
10613 ///   vadd d3, d0, d1
10614 ///   vmul d3, d3, d2
10615 //  However, for (A + B) * (A + B),
10616 //    vadd d2, d0, d1
10617 //    vmul d3, d0, d2
10618 //    vmla d3, d1, d2
10619 //  is slower than
10620 //    vadd d2, d0, d1
10621 //    vmul d3, d2, d2
10622 static SDValue PerformVMULCombine(SDNode *N,
10623                                   TargetLowering::DAGCombinerInfo &DCI,
10624                                   const ARMSubtarget *Subtarget) {
10625   if (!Subtarget->hasVMLxForwarding())
10626     return SDValue();
10627 
10628   SelectionDAG &DAG = DCI.DAG;
10629   SDValue N0 = N->getOperand(0);
10630   SDValue N1 = N->getOperand(1);
10631   unsigned Opcode = N0.getOpcode();
10632   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10633       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10634     Opcode = N1.getOpcode();
10635     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10636         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10637       return SDValue();
10638     std::swap(N0, N1);
10639   }
10640 
10641   if (N0 == N1)
10642     return SDValue();
10643 
10644   EVT VT = N->getValueType(0);
10645   SDLoc DL(N);
10646   SDValue N00 = N0->getOperand(0);
10647   SDValue N01 = N0->getOperand(1);
10648   return DAG.getNode(Opcode, DL, VT,
10649                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10650                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10651 }
10652 
10653 static SDValue PerformMULCombine(SDNode *N,
10654                                  TargetLowering::DAGCombinerInfo &DCI,
10655                                  const ARMSubtarget *Subtarget) {
10656   SelectionDAG &DAG = DCI.DAG;
10657 
10658   if (Subtarget->isThumb1Only())
10659     return SDValue();
10660 
10661   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10662     return SDValue();
10663 
10664   EVT VT = N->getValueType(0);
10665   if (VT.is64BitVector() || VT.is128BitVector())
10666     return PerformVMULCombine(N, DCI, Subtarget);
10667   if (VT != MVT::i32)
10668     return SDValue();
10669 
10670   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10671   if (!C)
10672     return SDValue();
10673 
10674   int64_t MulAmt = C->getSExtValue();
10675   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10676 
10677   ShiftAmt = ShiftAmt & (32 - 1);
10678   SDValue V = N->getOperand(0);
10679   SDLoc DL(N);
10680 
10681   SDValue Res;
10682   MulAmt >>= ShiftAmt;
10683 
10684   if (MulAmt >= 0) {
10685     if (isPowerOf2_32(MulAmt - 1)) {
10686       // (mul x, 2^N + 1) => (add (shl x, N), x)
10687       Res = DAG.getNode(ISD::ADD, DL, VT,
10688                         V,
10689                         DAG.getNode(ISD::SHL, DL, VT,
10690                                     V,
10691                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10692                                                     MVT::i32)));
10693     } else if (isPowerOf2_32(MulAmt + 1)) {
10694       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10695       Res = DAG.getNode(ISD::SUB, DL, VT,
10696                         DAG.getNode(ISD::SHL, DL, VT,
10697                                     V,
10698                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10699                                                     MVT::i32)),
10700                         V);
10701     } else
10702       return SDValue();
10703   } else {
10704     uint64_t MulAmtAbs = -MulAmt;
10705     if (isPowerOf2_32(MulAmtAbs + 1)) {
10706       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10707       Res = DAG.getNode(ISD::SUB, DL, VT,
10708                         V,
10709                         DAG.getNode(ISD::SHL, DL, VT,
10710                                     V,
10711                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10712                                                     MVT::i32)));
10713     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10714       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10715       Res = DAG.getNode(ISD::ADD, DL, VT,
10716                         V,
10717                         DAG.getNode(ISD::SHL, DL, VT,
10718                                     V,
10719                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10720                                                     MVT::i32)));
10721       Res = DAG.getNode(ISD::SUB, DL, VT,
10722                         DAG.getConstant(0, DL, MVT::i32), Res);
10723     } else
10724       return SDValue();
10725   }
10726 
10727   if (ShiftAmt != 0)
10728     Res = DAG.getNode(ISD::SHL, DL, VT,
10729                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10730 
10731   // Do not add new nodes to DAG combiner worklist.
10732   DCI.CombineTo(N, Res, false);
10733   return SDValue();
10734 }
10735 
10736 static SDValue CombineANDShift(SDNode *N,
10737                                TargetLowering::DAGCombinerInfo &DCI,
10738                                const ARMSubtarget *Subtarget) {
10739   // Allow DAGCombine to pattern-match before we touch the canonical form.
10740   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10741     return SDValue();
10742 
10743   if (N->getValueType(0) != MVT::i32)
10744     return SDValue();
10745 
10746   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10747   if (!N1C)
10748     return SDValue();
10749 
10750   uint32_t C1 = (uint32_t)N1C->getZExtValue();
10751   // Don't transform uxtb/uxth.
10752   if (C1 == 255 || C1 == 65535)
10753     return SDValue();
10754 
10755   SDNode *N0 = N->getOperand(0).getNode();
10756   if (!N0->hasOneUse())
10757     return SDValue();
10758 
10759   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
10760     return SDValue();
10761 
10762   bool LeftShift = N0->getOpcode() == ISD::SHL;
10763 
10764   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10765   if (!N01C)
10766     return SDValue();
10767 
10768   uint32_t C2 = (uint32_t)N01C->getZExtValue();
10769   if (!C2 || C2 >= 32)
10770     return SDValue();
10771 
10772   // Clear irrelevant bits in the mask.
10773   if (LeftShift)
10774     C1 &= (-1U << C2);
10775   else
10776     C1 &= (-1U >> C2);
10777 
10778   SelectionDAG &DAG = DCI.DAG;
10779   SDLoc DL(N);
10780 
10781   // We have a pattern of the form "(and (shl x, c2) c1)" or
10782   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
10783   // transform to a pair of shifts, to save materializing c1.
10784 
10785   // First pattern: right shift, then mask off leading bits.
10786   // FIXME: Use demanded bits?
10787   if (!LeftShift && isMask_32(C1)) {
10788     uint32_t C3 = countLeadingZeros(C1);
10789     if (C2 < C3) {
10790       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10791                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10792       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10793                          DAG.getConstant(C3, DL, MVT::i32));
10794     }
10795   }
10796 
10797   // First pattern, reversed: left shift, then mask off trailing bits.
10798   if (LeftShift && isMask_32(~C1)) {
10799     uint32_t C3 = countTrailingZeros(C1);
10800     if (C2 < C3) {
10801       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
10802                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10803       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
10804                          DAG.getConstant(C3, DL, MVT::i32));
10805     }
10806   }
10807 
10808   // Second pattern: left shift, then mask off leading bits.
10809   // FIXME: Use demanded bits?
10810   if (LeftShift && isShiftedMask_32(C1)) {
10811     uint32_t Trailing = countTrailingZeros(C1);
10812     uint32_t C3 = countLeadingZeros(C1);
10813     if (Trailing == C2 && C2 + C3 < 32) {
10814       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10815                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10816       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10817                         DAG.getConstant(C3, DL, MVT::i32));
10818     }
10819   }
10820 
10821   // Second pattern, reversed: right shift, then mask off trailing bits.
10822   // FIXME: Handle other patterns of known/demanded bits.
10823   if (!LeftShift && isShiftedMask_32(C1)) {
10824     uint32_t Leading = countLeadingZeros(C1);
10825     uint32_t C3 = countTrailingZeros(C1);
10826     if (Leading == C2 && C2 + C3 < 32) {
10827       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
10828                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10829       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
10830                          DAG.getConstant(C3, DL, MVT::i32));
10831     }
10832   }
10833 
10834   // FIXME: Transform "(and (shl x, c2) c1)" ->
10835   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
10836   // c1.
10837   return SDValue();
10838 }
10839 
10840 static SDValue PerformANDCombine(SDNode *N,
10841                                  TargetLowering::DAGCombinerInfo &DCI,
10842                                  const ARMSubtarget *Subtarget) {
10843   // Attempt to use immediate-form VBIC
10844   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10845   SDLoc dl(N);
10846   EVT VT = N->getValueType(0);
10847   SelectionDAG &DAG = DCI.DAG;
10848 
10849   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10850     return SDValue();
10851 
10852   APInt SplatBits, SplatUndef;
10853   unsigned SplatBitSize;
10854   bool HasAnyUndefs;
10855   if (BVN &&
10856       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10857     if (SplatBitSize <= 64) {
10858       EVT VbicVT;
10859       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10860                                       SplatUndef.getZExtValue(), SplatBitSize,
10861                                       DAG, dl, VbicVT, VT.is128BitVector(),
10862                                       OtherModImm);
10863       if (Val.getNode()) {
10864         SDValue Input =
10865           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10866         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10867         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10868       }
10869     }
10870   }
10871 
10872   if (!Subtarget->isThumb1Only()) {
10873     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10874     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10875       return Result;
10876 
10877     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10878       return Result;
10879   }
10880 
10881   if (Subtarget->isThumb1Only())
10882     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
10883       return Result;
10884 
10885   return SDValue();
10886 }
10887 
10888 // Try combining OR nodes to SMULWB, SMULWT.
10889 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10890                                          TargetLowering::DAGCombinerInfo &DCI,
10891                                          const ARMSubtarget *Subtarget) {
10892   if (!Subtarget->hasV6Ops() ||
10893       (Subtarget->isThumb() &&
10894        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10895     return SDValue();
10896 
10897   SDValue SRL = OR->getOperand(0);
10898   SDValue SHL = OR->getOperand(1);
10899 
10900   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10901     SRL = OR->getOperand(1);
10902     SHL = OR->getOperand(0);
10903   }
10904   if (!isSRL16(SRL) || !isSHL16(SHL))
10905     return SDValue();
10906 
10907   // The first operands to the shifts need to be the two results from the
10908   // same smul_lohi node.
10909   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10910        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10911     return SDValue();
10912 
10913   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10914   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10915       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10916     return SDValue();
10917 
10918   // Now we have:
10919   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10920   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10921   // For SMUWB the 16-bit value will signed extended somehow.
10922   // For SMULWT only the SRA is required.
10923   // Check both sides of SMUL_LOHI
10924   SDValue OpS16 = SMULLOHI->getOperand(0);
10925   SDValue OpS32 = SMULLOHI->getOperand(1);
10926 
10927   SelectionDAG &DAG = DCI.DAG;
10928   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10929     OpS16 = OpS32;
10930     OpS32 = SMULLOHI->getOperand(0);
10931   }
10932 
10933   SDLoc dl(OR);
10934   unsigned Opcode = 0;
10935   if (isS16(OpS16, DAG))
10936     Opcode = ARMISD::SMULWB;
10937   else if (isSRA16(OpS16)) {
10938     Opcode = ARMISD::SMULWT;
10939     OpS16 = OpS16->getOperand(0);
10940   }
10941   else
10942     return SDValue();
10943 
10944   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10945   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10946   return SDValue(OR, 0);
10947 }
10948 
10949 static SDValue PerformORCombineToBFI(SDNode *N,
10950                                      TargetLowering::DAGCombinerInfo &DCI,
10951                                      const ARMSubtarget *Subtarget) {
10952   // BFI is only available on V6T2+
10953   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10954     return SDValue();
10955 
10956   EVT VT = N->getValueType(0);
10957   SDValue N0 = N->getOperand(0);
10958   SDValue N1 = N->getOperand(1);
10959   SelectionDAG &DAG = DCI.DAG;
10960   SDLoc DL(N);
10961   // 1) or (and A, mask), val => ARMbfi A, val, mask
10962   //      iff (val & mask) == val
10963   //
10964   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10965   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10966   //          && mask == ~mask2
10967   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10968   //          && ~mask == mask2
10969   //  (i.e., copy a bitfield value into another bitfield of the same width)
10970 
10971   if (VT != MVT::i32)
10972     return SDValue();
10973 
10974   SDValue N00 = N0.getOperand(0);
10975 
10976   // The value and the mask need to be constants so we can verify this is
10977   // actually a bitfield set. If the mask is 0xffff, we can do better
10978   // via a movt instruction, so don't use BFI in that case.
10979   SDValue MaskOp = N0.getOperand(1);
10980   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10981   if (!MaskC)
10982     return SDValue();
10983   unsigned Mask = MaskC->getZExtValue();
10984   if (Mask == 0xffff)
10985     return SDValue();
10986   SDValue Res;
10987   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10988   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10989   if (N1C) {
10990     unsigned Val = N1C->getZExtValue();
10991     if ((Val & ~Mask) != Val)
10992       return SDValue();
10993 
10994     if (ARM::isBitFieldInvertedMask(Mask)) {
10995       Val >>= countTrailingZeros(~Mask);
10996 
10997       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10998                         DAG.getConstant(Val, DL, MVT::i32),
10999                         DAG.getConstant(Mask, DL, MVT::i32));
11000 
11001       DCI.CombineTo(N, Res, false);
11002       // Return value from the original node to inform the combiner than N is
11003       // now dead.
11004       return SDValue(N, 0);
11005     }
11006   } else if (N1.getOpcode() == ISD::AND) {
11007     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11008     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11009     if (!N11C)
11010       return SDValue();
11011     unsigned Mask2 = N11C->getZExtValue();
11012 
11013     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11014     // as is to match.
11015     if (ARM::isBitFieldInvertedMask(Mask) &&
11016         (Mask == ~Mask2)) {
11017       // The pack halfword instruction works better for masks that fit it,
11018       // so use that when it's available.
11019       if (Subtarget->hasDSP() &&
11020           (Mask == 0xffff || Mask == 0xffff0000))
11021         return SDValue();
11022       // 2a
11023       unsigned amt = countTrailingZeros(Mask2);
11024       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11025                         DAG.getConstant(amt, DL, MVT::i32));
11026       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11027                         DAG.getConstant(Mask, DL, MVT::i32));
11028       DCI.CombineTo(N, Res, false);
11029       // Return value from the original node to inform the combiner than N is
11030       // now dead.
11031       return SDValue(N, 0);
11032     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11033                (~Mask == Mask2)) {
11034       // The pack halfword instruction works better for masks that fit it,
11035       // so use that when it's available.
11036       if (Subtarget->hasDSP() &&
11037           (Mask2 == 0xffff || Mask2 == 0xffff0000))
11038         return SDValue();
11039       // 2b
11040       unsigned lsb = countTrailingZeros(Mask);
11041       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11042                         DAG.getConstant(lsb, DL, MVT::i32));
11043       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11044                         DAG.getConstant(Mask2, DL, MVT::i32));
11045       DCI.CombineTo(N, Res, false);
11046       // Return value from the original node to inform the combiner than N is
11047       // now dead.
11048       return SDValue(N, 0);
11049     }
11050   }
11051 
11052   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11053       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11054       ARM::isBitFieldInvertedMask(~Mask)) {
11055     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11056     // where lsb(mask) == #shamt and masked bits of B are known zero.
11057     SDValue ShAmt = N00.getOperand(1);
11058     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11059     unsigned LSB = countTrailingZeros(Mask);
11060     if (ShAmtC != LSB)
11061       return SDValue();
11062 
11063     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11064                       DAG.getConstant(~Mask, DL, MVT::i32));
11065 
11066     DCI.CombineTo(N, Res, false);
11067     // Return value from the original node to inform the combiner than N is
11068     // now dead.
11069     return SDValue(N, 0);
11070   }
11071 
11072   return SDValue();
11073 }
11074 
11075 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11076 static SDValue PerformORCombine(SDNode *N,
11077                                 TargetLowering::DAGCombinerInfo &DCI,
11078                                 const ARMSubtarget *Subtarget) {
11079   // Attempt to use immediate-form VORR
11080   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11081   SDLoc dl(N);
11082   EVT VT = N->getValueType(0);
11083   SelectionDAG &DAG = DCI.DAG;
11084 
11085   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11086     return SDValue();
11087 
11088   APInt SplatBits, SplatUndef;
11089   unsigned SplatBitSize;
11090   bool HasAnyUndefs;
11091   if (BVN && Subtarget->hasNEON() &&
11092       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11093     if (SplatBitSize <= 64) {
11094       EVT VorrVT;
11095       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
11096                                       SplatUndef.getZExtValue(), SplatBitSize,
11097                                       DAG, dl, VorrVT, VT.is128BitVector(),
11098                                       OtherModImm);
11099       if (Val.getNode()) {
11100         SDValue Input =
11101           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11102         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11103         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11104       }
11105     }
11106   }
11107 
11108   if (!Subtarget->isThumb1Only()) {
11109     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11110     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11111       return Result;
11112     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11113       return Result;
11114   }
11115 
11116   SDValue N0 = N->getOperand(0);
11117   SDValue N1 = N->getOperand(1);
11118 
11119   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11120   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11121       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11122 
11123     // The code below optimizes (or (and X, Y), Z).
11124     // The AND operand needs to have a single user to make these optimizations
11125     // profitable.
11126     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11127       return SDValue();
11128 
11129     APInt SplatUndef;
11130     unsigned SplatBitSize;
11131     bool HasAnyUndefs;
11132 
11133     APInt SplatBits0, SplatBits1;
11134     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11135     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11136     // Ensure that the second operand of both ands are constants
11137     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11138                                       HasAnyUndefs) && !HasAnyUndefs) {
11139         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11140                                           HasAnyUndefs) && !HasAnyUndefs) {
11141             // Ensure that the bit width of the constants are the same and that
11142             // the splat arguments are logical inverses as per the pattern we
11143             // are trying to simplify.
11144             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11145                 SplatBits0 == ~SplatBits1) {
11146                 // Canonicalize the vector type to make instruction selection
11147                 // simpler.
11148                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11149                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11150                                              N0->getOperand(1),
11151                                              N0->getOperand(0),
11152                                              N1->getOperand(0));
11153                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11154             }
11155         }
11156     }
11157   }
11158 
11159   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11160   // reasonable.
11161   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11162     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11163       return Res;
11164   }
11165 
11166   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11167     return Result;
11168 
11169   return SDValue();
11170 }
11171 
11172 static SDValue PerformXORCombine(SDNode *N,
11173                                  TargetLowering::DAGCombinerInfo &DCI,
11174                                  const ARMSubtarget *Subtarget) {
11175   EVT VT = N->getValueType(0);
11176   SelectionDAG &DAG = DCI.DAG;
11177 
11178   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11179     return SDValue();
11180 
11181   if (!Subtarget->isThumb1Only()) {
11182     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11183     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11184       return Result;
11185 
11186     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11187       return Result;
11188   }
11189 
11190   return SDValue();
11191 }
11192 
11193 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11194 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11195 // their position in "to" (Rd).
11196 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11197   assert(N->getOpcode() == ARMISD::BFI);
11198 
11199   SDValue From = N->getOperand(1);
11200   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11201   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11202 
11203   // If the Base came from a SHR #C, we can deduce that it is really testing bit
11204   // #C in the base of the SHR.
11205   if (From->getOpcode() == ISD::SRL &&
11206       isa<ConstantSDNode>(From->getOperand(1))) {
11207     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11208     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11209     FromMask <<= Shift.getLimitedValue(31);
11210     From = From->getOperand(0);
11211   }
11212 
11213   return From;
11214 }
11215 
11216 // If A and B contain one contiguous set of bits, does A | B == A . B?
11217 //
11218 // Neither A nor B must be zero.
11219 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11220   unsigned LastActiveBitInA =  A.countTrailingZeros();
11221   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11222   return LastActiveBitInA - 1 == FirstActiveBitInB;
11223 }
11224 
11225 static SDValue FindBFIToCombineWith(SDNode *N) {
11226   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11227   // if one exists.
11228   APInt ToMask, FromMask;
11229   SDValue From = ParseBFI(N, ToMask, FromMask);
11230   SDValue To = N->getOperand(0);
11231 
11232   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11233   // aren't compatible, but not if they set the same bit in their destination as
11234   // we do (or that of any BFI we're going to combine with).
11235   SDValue V = To;
11236   APInt CombinedToMask = ToMask;
11237   while (V.getOpcode() == ARMISD::BFI) {
11238     APInt NewToMask, NewFromMask;
11239     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11240     if (NewFrom != From) {
11241       // This BFI has a different base. Keep going.
11242       CombinedToMask |= NewToMask;
11243       V = V.getOperand(0);
11244       continue;
11245     }
11246 
11247     // Do the written bits conflict with any we've seen so far?
11248     if ((NewToMask & CombinedToMask).getBoolValue())
11249       // Conflicting bits - bail out because going further is unsafe.
11250       return SDValue();
11251 
11252     // Are the new bits contiguous when combined with the old bits?
11253     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11254         BitsProperlyConcatenate(FromMask, NewFromMask))
11255       return V;
11256     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11257         BitsProperlyConcatenate(NewFromMask, FromMask))
11258       return V;
11259 
11260     // We've seen a write to some bits, so track it.
11261     CombinedToMask |= NewToMask;
11262     // Keep going...
11263     V = V.getOperand(0);
11264   }
11265 
11266   return SDValue();
11267 }
11268 
11269 static SDValue PerformBFICombine(SDNode *N,
11270                                  TargetLowering::DAGCombinerInfo &DCI) {
11271   SDValue N1 = N->getOperand(1);
11272   if (N1.getOpcode() == ISD::AND) {
11273     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11274     // the bits being cleared by the AND are not demanded by the BFI.
11275     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11276     if (!N11C)
11277       return SDValue();
11278     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11279     unsigned LSB = countTrailingZeros(~InvMask);
11280     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11281     assert(Width <
11282                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11283            "undefined behavior");
11284     unsigned Mask = (1u << Width) - 1;
11285     unsigned Mask2 = N11C->getZExtValue();
11286     if ((Mask & (~Mask2)) == 0)
11287       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11288                              N->getOperand(0), N1.getOperand(0),
11289                              N->getOperand(2));
11290   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11291     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11292     // Keep track of any consecutive bits set that all come from the same base
11293     // value. We can combine these together into a single BFI.
11294     SDValue CombineBFI = FindBFIToCombineWith(N);
11295     if (CombineBFI == SDValue())
11296       return SDValue();
11297 
11298     // We've found a BFI.
11299     APInt ToMask1, FromMask1;
11300     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11301 
11302     APInt ToMask2, FromMask2;
11303     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11304     assert(From1 == From2);
11305     (void)From2;
11306 
11307     // First, unlink CombineBFI.
11308     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11309     // Then create a new BFI, combining the two together.
11310     APInt NewFromMask = FromMask1 | FromMask2;
11311     APInt NewToMask = ToMask1 | ToMask2;
11312 
11313     EVT VT = N->getValueType(0);
11314     SDLoc dl(N);
11315 
11316     if (NewFromMask[0] == 0)
11317       From1 = DCI.DAG.getNode(
11318         ISD::SRL, dl, VT, From1,
11319         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11320     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11321                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11322   }
11323   return SDValue();
11324 }
11325 
11326 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11327 /// ARMISD::VMOVRRD.
11328 static SDValue PerformVMOVRRDCombine(SDNode *N,
11329                                      TargetLowering::DAGCombinerInfo &DCI,
11330                                      const ARMSubtarget *Subtarget) {
11331   // vmovrrd(vmovdrr x, y) -> x,y
11332   SDValue InDouble = N->getOperand(0);
11333   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
11334     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11335 
11336   // vmovrrd(load f64) -> (load i32), (load i32)
11337   SDNode *InNode = InDouble.getNode();
11338   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11339       InNode->getValueType(0) == MVT::f64 &&
11340       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11341       !cast<LoadSDNode>(InNode)->isVolatile()) {
11342     // TODO: Should this be done for non-FrameIndex operands?
11343     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11344 
11345     SelectionDAG &DAG = DCI.DAG;
11346     SDLoc DL(LD);
11347     SDValue BasePtr = LD->getBasePtr();
11348     SDValue NewLD1 =
11349         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11350                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11351 
11352     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11353                                     DAG.getConstant(4, DL, MVT::i32));
11354     SDValue NewLD2 = DAG.getLoad(
11355         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11356         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11357 
11358     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11359     if (DCI.DAG.getDataLayout().isBigEndian())
11360       std::swap (NewLD1, NewLD2);
11361     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11362     return Result;
11363   }
11364 
11365   return SDValue();
11366 }
11367 
11368 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11369 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11370 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11371   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11372   SDValue Op0 = N->getOperand(0);
11373   SDValue Op1 = N->getOperand(1);
11374   if (Op0.getOpcode() == ISD::BITCAST)
11375     Op0 = Op0.getOperand(0);
11376   if (Op1.getOpcode() == ISD::BITCAST)
11377     Op1 = Op1.getOperand(0);
11378   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11379       Op0.getNode() == Op1.getNode() &&
11380       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11381     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11382                        N->getValueType(0), Op0.getOperand(0));
11383   return SDValue();
11384 }
11385 
11386 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11387 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11388 /// i64 vector to have f64 elements, since the value can then be loaded
11389 /// directly into a VFP register.
11390 static bool hasNormalLoadOperand(SDNode *N) {
11391   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11392   for (unsigned i = 0; i < NumElts; ++i) {
11393     SDNode *Elt = N->getOperand(i).getNode();
11394     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11395       return true;
11396   }
11397   return false;
11398 }
11399 
11400 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11401 /// ISD::BUILD_VECTOR.
11402 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11403                                           TargetLowering::DAGCombinerInfo &DCI,
11404                                           const ARMSubtarget *Subtarget) {
11405   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11406   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11407   // into a pair of GPRs, which is fine when the value is used as a scalar,
11408   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11409   SelectionDAG &DAG = DCI.DAG;
11410   if (N->getNumOperands() == 2)
11411     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11412       return RV;
11413 
11414   // Load i64 elements as f64 values so that type legalization does not split
11415   // them up into i32 values.
11416   EVT VT = N->getValueType(0);
11417   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11418     return SDValue();
11419   SDLoc dl(N);
11420   SmallVector<SDValue, 8> Ops;
11421   unsigned NumElts = VT.getVectorNumElements();
11422   for (unsigned i = 0; i < NumElts; ++i) {
11423     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11424     Ops.push_back(V);
11425     // Make the DAGCombiner fold the bitcast.
11426     DCI.AddToWorklist(V.getNode());
11427   }
11428   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11429   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11430   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11431 }
11432 
11433 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11434 static SDValue
11435 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11436   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11437   // At that time, we may have inserted bitcasts from integer to float.
11438   // If these bitcasts have survived DAGCombine, change the lowering of this
11439   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11440   // force to use floating point types.
11441 
11442   // Make sure we can change the type of the vector.
11443   // This is possible iff:
11444   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11445   //    1.1. Vector is used only once.
11446   //    1.2. Use is a bit convert to an integer type.
11447   // 2. The size of its operands are 32-bits (64-bits are not legal).
11448   EVT VT = N->getValueType(0);
11449   EVT EltVT = VT.getVectorElementType();
11450 
11451   // Check 1.1. and 2.
11452   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11453     return SDValue();
11454 
11455   // By construction, the input type must be float.
11456   assert(EltVT == MVT::f32 && "Unexpected type!");
11457 
11458   // Check 1.2.
11459   SDNode *Use = *N->use_begin();
11460   if (Use->getOpcode() != ISD::BITCAST ||
11461       Use->getValueType(0).isFloatingPoint())
11462     return SDValue();
11463 
11464   // Check profitability.
11465   // Model is, if more than half of the relevant operands are bitcast from
11466   // i32, turn the build_vector into a sequence of insert_vector_elt.
11467   // Relevant operands are everything that is not statically
11468   // (i.e., at compile time) bitcasted.
11469   unsigned NumOfBitCastedElts = 0;
11470   unsigned NumElts = VT.getVectorNumElements();
11471   unsigned NumOfRelevantElts = NumElts;
11472   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11473     SDValue Elt = N->getOperand(Idx);
11474     if (Elt->getOpcode() == ISD::BITCAST) {
11475       // Assume only bit cast to i32 will go away.
11476       if (Elt->getOperand(0).getValueType() == MVT::i32)
11477         ++NumOfBitCastedElts;
11478     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11479       // Constants are statically casted, thus do not count them as
11480       // relevant operands.
11481       --NumOfRelevantElts;
11482   }
11483 
11484   // Check if more than half of the elements require a non-free bitcast.
11485   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11486     return SDValue();
11487 
11488   SelectionDAG &DAG = DCI.DAG;
11489   // Create the new vector type.
11490   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11491   // Check if the type is legal.
11492   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11493   if (!TLI.isTypeLegal(VecVT))
11494     return SDValue();
11495 
11496   // Combine:
11497   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11498   // => BITCAST INSERT_VECTOR_ELT
11499   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11500   //                      (BITCAST EN), N.
11501   SDValue Vec = DAG.getUNDEF(VecVT);
11502   SDLoc dl(N);
11503   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11504     SDValue V = N->getOperand(Idx);
11505     if (V.isUndef())
11506       continue;
11507     if (V.getOpcode() == ISD::BITCAST &&
11508         V->getOperand(0).getValueType() == MVT::i32)
11509       // Fold obvious case.
11510       V = V.getOperand(0);
11511     else {
11512       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11513       // Make the DAGCombiner fold the bitcasts.
11514       DCI.AddToWorklist(V.getNode());
11515     }
11516     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11517     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11518   }
11519   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11520   // Make the DAGCombiner fold the bitcasts.
11521   DCI.AddToWorklist(Vec.getNode());
11522   return Vec;
11523 }
11524 
11525 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11526 /// ISD::INSERT_VECTOR_ELT.
11527 static SDValue PerformInsertEltCombine(SDNode *N,
11528                                        TargetLowering::DAGCombinerInfo &DCI) {
11529   // Bitcast an i64 load inserted into a vector to f64.
11530   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11531   EVT VT = N->getValueType(0);
11532   SDNode *Elt = N->getOperand(1).getNode();
11533   if (VT.getVectorElementType() != MVT::i64 ||
11534       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11535     return SDValue();
11536 
11537   SelectionDAG &DAG = DCI.DAG;
11538   SDLoc dl(N);
11539   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11540                                  VT.getVectorNumElements());
11541   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11542   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11543   // Make the DAGCombiner fold the bitcasts.
11544   DCI.AddToWorklist(Vec.getNode());
11545   DCI.AddToWorklist(V.getNode());
11546   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11547                                Vec, V, N->getOperand(2));
11548   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11549 }
11550 
11551 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11552 /// ISD::VECTOR_SHUFFLE.
11553 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11554   // The LLVM shufflevector instruction does not require the shuffle mask
11555   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11556   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11557   // operands do not match the mask length, they are extended by concatenating
11558   // them with undef vectors.  That is probably the right thing for other
11559   // targets, but for NEON it is better to concatenate two double-register
11560   // size vector operands into a single quad-register size vector.  Do that
11561   // transformation here:
11562   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11563   //   shuffle(concat(v1, v2), undef)
11564   SDValue Op0 = N->getOperand(0);
11565   SDValue Op1 = N->getOperand(1);
11566   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11567       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11568       Op0.getNumOperands() != 2 ||
11569       Op1.getNumOperands() != 2)
11570     return SDValue();
11571   SDValue Concat0Op1 = Op0.getOperand(1);
11572   SDValue Concat1Op1 = Op1.getOperand(1);
11573   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11574     return SDValue();
11575   // Skip the transformation if any of the types are illegal.
11576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11577   EVT VT = N->getValueType(0);
11578   if (!TLI.isTypeLegal(VT) ||
11579       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11580       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11581     return SDValue();
11582 
11583   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11584                                   Op0.getOperand(0), Op1.getOperand(0));
11585   // Translate the shuffle mask.
11586   SmallVector<int, 16> NewMask;
11587   unsigned NumElts = VT.getVectorNumElements();
11588   unsigned HalfElts = NumElts/2;
11589   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11590   for (unsigned n = 0; n < NumElts; ++n) {
11591     int MaskElt = SVN->getMaskElt(n);
11592     int NewElt = -1;
11593     if (MaskElt < (int)HalfElts)
11594       NewElt = MaskElt;
11595     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11596       NewElt = HalfElts + MaskElt - NumElts;
11597     NewMask.push_back(NewElt);
11598   }
11599   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11600                               DAG.getUNDEF(VT), NewMask);
11601 }
11602 
11603 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11604 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11605 /// base address updates.
11606 /// For generic load/stores, the memory type is assumed to be a vector.
11607 /// The caller is assumed to have checked legality.
11608 static SDValue CombineBaseUpdate(SDNode *N,
11609                                  TargetLowering::DAGCombinerInfo &DCI) {
11610   SelectionDAG &DAG = DCI.DAG;
11611   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11612                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11613   const bool isStore = N->getOpcode() == ISD::STORE;
11614   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11615   SDValue Addr = N->getOperand(AddrOpIdx);
11616   MemSDNode *MemN = cast<MemSDNode>(N);
11617   SDLoc dl(N);
11618 
11619   // Search for a use of the address operand that is an increment.
11620   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11621          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11622     SDNode *User = *UI;
11623     if (User->getOpcode() != ISD::ADD ||
11624         UI.getUse().getResNo() != Addr.getResNo())
11625       continue;
11626 
11627     // Check that the add is independent of the load/store.  Otherwise, folding
11628     // it would create a cycle. We can avoid searching through Addr as it's a
11629     // predecessor to both.
11630     SmallPtrSet<const SDNode *, 32> Visited;
11631     SmallVector<const SDNode *, 16> Worklist;
11632     Visited.insert(Addr.getNode());
11633     Worklist.push_back(N);
11634     Worklist.push_back(User);
11635     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11636         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11637       continue;
11638 
11639     // Find the new opcode for the updating load/store.
11640     bool isLoadOp = true;
11641     bool isLaneOp = false;
11642     unsigned NewOpc = 0;
11643     unsigned NumVecs = 0;
11644     if (isIntrinsic) {
11645       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11646       switch (IntNo) {
11647       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11648       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11649         NumVecs = 1; break;
11650       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11651         NumVecs = 2; break;
11652       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11653         NumVecs = 3; break;
11654       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11655         NumVecs = 4; break;
11656       case Intrinsic::arm_neon_vld2dup:
11657       case Intrinsic::arm_neon_vld3dup:
11658       case Intrinsic::arm_neon_vld4dup:
11659         // TODO: Support updating VLDxDUP nodes. For now, we just skip
11660         // combining base updates for such intrinsics.
11661         continue;
11662       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11663         NumVecs = 2; isLaneOp = true; break;
11664       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11665         NumVecs = 3; isLaneOp = true; break;
11666       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11667         NumVecs = 4; isLaneOp = true; break;
11668       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11669         NumVecs = 1; isLoadOp = false; break;
11670       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11671         NumVecs = 2; isLoadOp = false; break;
11672       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11673         NumVecs = 3; isLoadOp = false; break;
11674       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11675         NumVecs = 4; isLoadOp = false; break;
11676       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11677         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11678       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11679         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11680       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11681         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11682       }
11683     } else {
11684       isLaneOp = true;
11685       switch (N->getOpcode()) {
11686       default: llvm_unreachable("unexpected opcode for Neon base update");
11687       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11688       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11689       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11690       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11691       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11692         NumVecs = 1; isLaneOp = false; break;
11693       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11694         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11695       }
11696     }
11697 
11698     // Find the size of memory referenced by the load/store.
11699     EVT VecTy;
11700     if (isLoadOp) {
11701       VecTy = N->getValueType(0);
11702     } else if (isIntrinsic) {
11703       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11704     } else {
11705       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11706       VecTy = N->getOperand(1).getValueType();
11707     }
11708 
11709     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11710     if (isLaneOp)
11711       NumBytes /= VecTy.getVectorNumElements();
11712 
11713     // If the increment is a constant, it must match the memory ref size.
11714     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11715     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11716     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11717       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11718       // separate instructions that make it harder to use a non-constant update.
11719       continue;
11720     }
11721 
11722     // OK, we found an ADD we can fold into the base update.
11723     // Now, create a _UPD node, taking care of not breaking alignment.
11724 
11725     EVT AlignedVecTy = VecTy;
11726     unsigned Alignment = MemN->getAlignment();
11727 
11728     // If this is a less-than-standard-aligned load/store, change the type to
11729     // match the standard alignment.
11730     // The alignment is overlooked when selecting _UPD variants; and it's
11731     // easier to introduce bitcasts here than fix that.
11732     // There are 3 ways to get to this base-update combine:
11733     // - intrinsics: they are assumed to be properly aligned (to the standard
11734     //   alignment of the memory type), so we don't need to do anything.
11735     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11736     //   intrinsics, so, likewise, there's nothing to do.
11737     // - generic load/store instructions: the alignment is specified as an
11738     //   explicit operand, rather than implicitly as the standard alignment
11739     //   of the memory type (like the intrisics).  We need to change the
11740     //   memory type to match the explicit alignment.  That way, we don't
11741     //   generate non-standard-aligned ARMISD::VLDx nodes.
11742     if (isa<LSBaseSDNode>(N)) {
11743       if (Alignment == 0)
11744         Alignment = 1;
11745       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11746         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11747         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11748         assert(!isLaneOp && "Unexpected generic load/store lane.");
11749         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11750         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11751       }
11752       // Don't set an explicit alignment on regular load/stores that we want
11753       // to transform to VLD/VST 1_UPD nodes.
11754       // This matches the behavior of regular load/stores, which only get an
11755       // explicit alignment if the MMO alignment is larger than the standard
11756       // alignment of the memory type.
11757       // Intrinsics, however, always get an explicit alignment, set to the
11758       // alignment of the MMO.
11759       Alignment = 1;
11760     }
11761 
11762     // Create the new updating load/store node.
11763     // First, create an SDVTList for the new updating node's results.
11764     EVT Tys[6];
11765     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11766     unsigned n;
11767     for (n = 0; n < NumResultVecs; ++n)
11768       Tys[n] = AlignedVecTy;
11769     Tys[n++] = MVT::i32;
11770     Tys[n] = MVT::Other;
11771     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11772 
11773     // Then, gather the new node's operands.
11774     SmallVector<SDValue, 8> Ops;
11775     Ops.push_back(N->getOperand(0)); // incoming chain
11776     Ops.push_back(N->getOperand(AddrOpIdx));
11777     Ops.push_back(Inc);
11778 
11779     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11780       // Try to match the intrinsic's signature
11781       Ops.push_back(StN->getValue());
11782     } else {
11783       // Loads (and of course intrinsics) match the intrinsics' signature,
11784       // so just add all but the alignment operand.
11785       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11786         Ops.push_back(N->getOperand(i));
11787     }
11788 
11789     // For all node types, the alignment operand is always the last one.
11790     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11791 
11792     // If this is a non-standard-aligned STORE, the penultimate operand is the
11793     // stored value.  Bitcast it to the aligned type.
11794     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11795       SDValue &StVal = Ops[Ops.size()-2];
11796       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11797     }
11798 
11799     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11800     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11801                                            MemN->getMemOperand());
11802 
11803     // Update the uses.
11804     SmallVector<SDValue, 5> NewResults;
11805     for (unsigned i = 0; i < NumResultVecs; ++i)
11806       NewResults.push_back(SDValue(UpdN.getNode(), i));
11807 
11808     // If this is an non-standard-aligned LOAD, the first result is the loaded
11809     // value.  Bitcast it to the expected result type.
11810     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11811       SDValue &LdVal = NewResults[0];
11812       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11813     }
11814 
11815     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11816     DCI.CombineTo(N, NewResults);
11817     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11818 
11819     break;
11820   }
11821   return SDValue();
11822 }
11823 
11824 static SDValue PerformVLDCombine(SDNode *N,
11825                                  TargetLowering::DAGCombinerInfo &DCI) {
11826   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11827     return SDValue();
11828 
11829   return CombineBaseUpdate(N, DCI);
11830 }
11831 
11832 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11833 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11834 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11835 /// return true.
11836 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11837   SelectionDAG &DAG = DCI.DAG;
11838   EVT VT = N->getValueType(0);
11839   // vldN-dup instructions only support 64-bit vectors for N > 1.
11840   if (!VT.is64BitVector())
11841     return false;
11842 
11843   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11844   SDNode *VLD = N->getOperand(0).getNode();
11845   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11846     return false;
11847   unsigned NumVecs = 0;
11848   unsigned NewOpc = 0;
11849   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11850   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11851     NumVecs = 2;
11852     NewOpc = ARMISD::VLD2DUP;
11853   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11854     NumVecs = 3;
11855     NewOpc = ARMISD::VLD3DUP;
11856   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11857     NumVecs = 4;
11858     NewOpc = ARMISD::VLD4DUP;
11859   } else {
11860     return false;
11861   }
11862 
11863   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11864   // numbers match the load.
11865   unsigned VLDLaneNo =
11866     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11867   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11868        UI != UE; ++UI) {
11869     // Ignore uses of the chain result.
11870     if (UI.getUse().getResNo() == NumVecs)
11871       continue;
11872     SDNode *User = *UI;
11873     if (User->getOpcode() != ARMISD::VDUPLANE ||
11874         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11875       return false;
11876   }
11877 
11878   // Create the vldN-dup node.
11879   EVT Tys[5];
11880   unsigned n;
11881   for (n = 0; n < NumVecs; ++n)
11882     Tys[n] = VT;
11883   Tys[n] = MVT::Other;
11884   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11885   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11886   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11887   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11888                                            Ops, VLDMemInt->getMemoryVT(),
11889                                            VLDMemInt->getMemOperand());
11890 
11891   // Update the uses.
11892   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11893        UI != UE; ++UI) {
11894     unsigned ResNo = UI.getUse().getResNo();
11895     // Ignore uses of the chain result.
11896     if (ResNo == NumVecs)
11897       continue;
11898     SDNode *User = *UI;
11899     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11900   }
11901 
11902   // Now the vldN-lane intrinsic is dead except for its chain result.
11903   // Update uses of the chain.
11904   std::vector<SDValue> VLDDupResults;
11905   for (unsigned n = 0; n < NumVecs; ++n)
11906     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11907   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11908   DCI.CombineTo(VLD, VLDDupResults);
11909 
11910   return true;
11911 }
11912 
11913 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11914 /// ARMISD::VDUPLANE.
11915 static SDValue PerformVDUPLANECombine(SDNode *N,
11916                                       TargetLowering::DAGCombinerInfo &DCI) {
11917   SDValue Op = N->getOperand(0);
11918 
11919   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11920   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11921   if (CombineVLDDUP(N, DCI))
11922     return SDValue(N, 0);
11923 
11924   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11925   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11926   while (Op.getOpcode() == ISD::BITCAST)
11927     Op = Op.getOperand(0);
11928   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11929     return SDValue();
11930 
11931   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11932   unsigned EltSize = Op.getScalarValueSizeInBits();
11933   // The canonical VMOV for a zero vector uses a 32-bit element size.
11934   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11935   unsigned EltBits;
11936   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11937     EltSize = 8;
11938   EVT VT = N->getValueType(0);
11939   if (EltSize > VT.getScalarSizeInBits())
11940     return SDValue();
11941 
11942   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11943 }
11944 
11945 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11946 static SDValue PerformVDUPCombine(SDNode *N,
11947                                   TargetLowering::DAGCombinerInfo &DCI) {
11948   SelectionDAG &DAG = DCI.DAG;
11949   SDValue Op = N->getOperand(0);
11950 
11951   // Match VDUP(LOAD) -> VLD1DUP.
11952   // We match this pattern here rather than waiting for isel because the
11953   // transform is only legal for unindexed loads.
11954   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11955   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11956       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11957     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11958                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11959     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11960     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11961                                              Ops, LD->getMemoryVT(),
11962                                              LD->getMemOperand());
11963     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11964     return VLDDup;
11965   }
11966 
11967   return SDValue();
11968 }
11969 
11970 static SDValue PerformLOADCombine(SDNode *N,
11971                                   TargetLowering::DAGCombinerInfo &DCI) {
11972   EVT VT = N->getValueType(0);
11973 
11974   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11975   if (ISD::isNormalLoad(N) && VT.isVector() &&
11976       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11977     return CombineBaseUpdate(N, DCI);
11978 
11979   return SDValue();
11980 }
11981 
11982 /// PerformSTORECombine - Target-specific dag combine xforms for
11983 /// ISD::STORE.
11984 static SDValue PerformSTORECombine(SDNode *N,
11985                                    TargetLowering::DAGCombinerInfo &DCI) {
11986   StoreSDNode *St = cast<StoreSDNode>(N);
11987   if (St->isVolatile())
11988     return SDValue();
11989 
11990   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11991   // pack all of the elements in one place.  Next, store to memory in fewer
11992   // chunks.
11993   SDValue StVal = St->getValue();
11994   EVT VT = StVal.getValueType();
11995   if (St->isTruncatingStore() && VT.isVector()) {
11996     SelectionDAG &DAG = DCI.DAG;
11997     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11998     EVT StVT = St->getMemoryVT();
11999     unsigned NumElems = VT.getVectorNumElements();
12000     assert(StVT != VT && "Cannot truncate to the same type");
12001     unsigned FromEltSz = VT.getScalarSizeInBits();
12002     unsigned ToEltSz = StVT.getScalarSizeInBits();
12003 
12004     // From, To sizes and ElemCount must be pow of two
12005     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
12006 
12007     // We are going to use the original vector elt for storing.
12008     // Accumulated smaller vector elements must be a multiple of the store size.
12009     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
12010 
12011     unsigned SizeRatio  = FromEltSz / ToEltSz;
12012     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
12013 
12014     // Create a type on which we perform the shuffle.
12015     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
12016                                      NumElems*SizeRatio);
12017     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
12018 
12019     SDLoc DL(St);
12020     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
12021     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
12022     for (unsigned i = 0; i < NumElems; ++i)
12023       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
12024                           ? (i + 1) * SizeRatio - 1
12025                           : i * SizeRatio;
12026 
12027     // Can't shuffle using an illegal type.
12028     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
12029 
12030     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
12031                                 DAG.getUNDEF(WideVec.getValueType()),
12032                                 ShuffleVec);
12033     // At this point all of the data is stored at the bottom of the
12034     // register. We now need to save it to mem.
12035 
12036     // Find the largest store unit
12037     MVT StoreType = MVT::i8;
12038     for (MVT Tp : MVT::integer_valuetypes()) {
12039       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
12040         StoreType = Tp;
12041     }
12042     // Didn't find a legal store type.
12043     if (!TLI.isTypeLegal(StoreType))
12044       return SDValue();
12045 
12046     // Bitcast the original vector into a vector of store-size units
12047     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
12048             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
12049     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
12050     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
12051     SmallVector<SDValue, 8> Chains;
12052     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
12053                                         TLI.getPointerTy(DAG.getDataLayout()));
12054     SDValue BasePtr = St->getBasePtr();
12055 
12056     // Perform one or more big stores into memory.
12057     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
12058     for (unsigned I = 0; I < E; I++) {
12059       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
12060                                    StoreType, ShuffWide,
12061                                    DAG.getIntPtrConstant(I, DL));
12062       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12063                                 St->getPointerInfo(), St->getAlignment(),
12064                                 St->getMemOperand()->getFlags());
12065       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12066                             Increment);
12067       Chains.push_back(Ch);
12068     }
12069     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12070   }
12071 
12072   if (!ISD::isNormalStore(St))
12073     return SDValue();
12074 
12075   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12076   // ARM stores of arguments in the same cache line.
12077   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12078       StVal.getNode()->hasOneUse()) {
12079     SelectionDAG  &DAG = DCI.DAG;
12080     bool isBigEndian = DAG.getDataLayout().isBigEndian();
12081     SDLoc DL(St);
12082     SDValue BasePtr = St->getBasePtr();
12083     SDValue NewST1 = DAG.getStore(
12084         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12085         BasePtr, St->getPointerInfo(), St->getAlignment(),
12086         St->getMemOperand()->getFlags());
12087 
12088     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12089                                     DAG.getConstant(4, DL, MVT::i32));
12090     return DAG.getStore(NewST1.getValue(0), DL,
12091                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12092                         OffsetPtr, St->getPointerInfo(),
12093                         std::min(4U, St->getAlignment() / 2),
12094                         St->getMemOperand()->getFlags());
12095   }
12096 
12097   if (StVal.getValueType() == MVT::i64 &&
12098       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12099 
12100     // Bitcast an i64 store extracted from a vector to f64.
12101     // Otherwise, the i64 value will be legalized to a pair of i32 values.
12102     SelectionDAG &DAG = DCI.DAG;
12103     SDLoc dl(StVal);
12104     SDValue IntVec = StVal.getOperand(0);
12105     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12106                                    IntVec.getValueType().getVectorNumElements());
12107     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12108     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12109                                  Vec, StVal.getOperand(1));
12110     dl = SDLoc(N);
12111     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12112     // Make the DAGCombiner fold the bitcasts.
12113     DCI.AddToWorklist(Vec.getNode());
12114     DCI.AddToWorklist(ExtElt.getNode());
12115     DCI.AddToWorklist(V.getNode());
12116     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12117                         St->getPointerInfo(), St->getAlignment(),
12118                         St->getMemOperand()->getFlags(), St->getAAInfo());
12119   }
12120 
12121   // If this is a legal vector store, try to combine it into a VST1_UPD.
12122   if (ISD::isNormalStore(N) && VT.isVector() &&
12123       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12124     return CombineBaseUpdate(N, DCI);
12125 
12126   return SDValue();
12127 }
12128 
12129 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12130 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12131 /// when the VMUL has a constant operand that is a power of 2.
12132 ///
12133 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12134 ///  vmul.f32        d16, d17, d16
12135 ///  vcvt.s32.f32    d16, d16
12136 /// becomes:
12137 ///  vcvt.s32.f32    d16, d16, #3
12138 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12139                                   const ARMSubtarget *Subtarget) {
12140   if (!Subtarget->hasNEON())
12141     return SDValue();
12142 
12143   SDValue Op = N->getOperand(0);
12144   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12145       Op.getOpcode() != ISD::FMUL)
12146     return SDValue();
12147 
12148   SDValue ConstVec = Op->getOperand(1);
12149   if (!isa<BuildVectorSDNode>(ConstVec))
12150     return SDValue();
12151 
12152   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12153   uint32_t FloatBits = FloatTy.getSizeInBits();
12154   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12155   uint32_t IntBits = IntTy.getSizeInBits();
12156   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12157   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12158     // These instructions only exist converting from f32 to i32. We can handle
12159     // smaller integers by generating an extra truncate, but larger ones would
12160     // be lossy. We also can't handle more then 4 lanes, since these intructions
12161     // only support v2i32/v4i32 types.
12162     return SDValue();
12163   }
12164 
12165   BitVector UndefElements;
12166   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12167   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12168   if (C == -1 || C == 0 || C > 32)
12169     return SDValue();
12170 
12171   SDLoc dl(N);
12172   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12173   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12174     Intrinsic::arm_neon_vcvtfp2fxu;
12175   SDValue FixConv = DAG.getNode(
12176       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12177       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12178       DAG.getConstant(C, dl, MVT::i32));
12179 
12180   if (IntBits < FloatBits)
12181     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12182 
12183   return FixConv;
12184 }
12185 
12186 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12187 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12188 /// when the VDIV has a constant operand that is a power of 2.
12189 ///
12190 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12191 ///  vcvt.f32.s32    d16, d16
12192 ///  vdiv.f32        d16, d17, d16
12193 /// becomes:
12194 ///  vcvt.f32.s32    d16, d16, #3
12195 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12196                                   const ARMSubtarget *Subtarget) {
12197   if (!Subtarget->hasNEON())
12198     return SDValue();
12199 
12200   SDValue Op = N->getOperand(0);
12201   unsigned OpOpcode = Op.getNode()->getOpcode();
12202   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12203       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12204     return SDValue();
12205 
12206   SDValue ConstVec = N->getOperand(1);
12207   if (!isa<BuildVectorSDNode>(ConstVec))
12208     return SDValue();
12209 
12210   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12211   uint32_t FloatBits = FloatTy.getSizeInBits();
12212   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12213   uint32_t IntBits = IntTy.getSizeInBits();
12214   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12215   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12216     // These instructions only exist converting from i32 to f32. We can handle
12217     // smaller integers by generating an extra extend, but larger ones would
12218     // be lossy. We also can't handle more then 4 lanes, since these intructions
12219     // only support v2i32/v4i32 types.
12220     return SDValue();
12221   }
12222 
12223   BitVector UndefElements;
12224   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12225   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12226   if (C == -1 || C == 0 || C > 32)
12227     return SDValue();
12228 
12229   SDLoc dl(N);
12230   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12231   SDValue ConvInput = Op.getOperand(0);
12232   if (IntBits < FloatBits)
12233     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12234                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12235                             ConvInput);
12236 
12237   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12238     Intrinsic::arm_neon_vcvtfxu2fp;
12239   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12240                      Op.getValueType(),
12241                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12242                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
12243 }
12244 
12245 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12246 /// operand of a vector shift operation, where all the elements of the
12247 /// build_vector must have the same constant integer value.
12248 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12249   // Ignore bit_converts.
12250   while (Op.getOpcode() == ISD::BITCAST)
12251     Op = Op.getOperand(0);
12252   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12253   APInt SplatBits, SplatUndef;
12254   unsigned SplatBitSize;
12255   bool HasAnyUndefs;
12256   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12257                                       HasAnyUndefs, ElementBits) ||
12258       SplatBitSize > ElementBits)
12259     return false;
12260   Cnt = SplatBits.getSExtValue();
12261   return true;
12262 }
12263 
12264 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12265 /// operand of a vector shift left operation.  That value must be in the range:
12266 ///   0 <= Value < ElementBits for a left shift; or
12267 ///   0 <= Value <= ElementBits for a long left shift.
12268 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12269   assert(VT.isVector() && "vector shift count is not a vector type");
12270   int64_t ElementBits = VT.getScalarSizeInBits();
12271   if (! getVShiftImm(Op, ElementBits, Cnt))
12272     return false;
12273   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12274 }
12275 
12276 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12277 /// operand of a vector shift right operation.  For a shift opcode, the value
12278 /// is positive, but for an intrinsic the value count must be negative. The
12279 /// absolute value must be in the range:
12280 ///   1 <= |Value| <= ElementBits for a right shift; or
12281 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12282 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12283                          int64_t &Cnt) {
12284   assert(VT.isVector() && "vector shift count is not a vector type");
12285   int64_t ElementBits = VT.getScalarSizeInBits();
12286   if (! getVShiftImm(Op, ElementBits, Cnt))
12287     return false;
12288   if (!isIntrinsic)
12289     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12290   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12291     Cnt = -Cnt;
12292     return true;
12293   }
12294   return false;
12295 }
12296 
12297 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12298 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12299   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12300   switch (IntNo) {
12301   default:
12302     // Don't do anything for most intrinsics.
12303     break;
12304 
12305   // Vector shifts: check for immediate versions and lower them.
12306   // Note: This is done during DAG combining instead of DAG legalizing because
12307   // the build_vectors for 64-bit vector element shift counts are generally
12308   // not legal, and it is hard to see their values after they get legalized to
12309   // loads from a constant pool.
12310   case Intrinsic::arm_neon_vshifts:
12311   case Intrinsic::arm_neon_vshiftu:
12312   case Intrinsic::arm_neon_vrshifts:
12313   case Intrinsic::arm_neon_vrshiftu:
12314   case Intrinsic::arm_neon_vrshiftn:
12315   case Intrinsic::arm_neon_vqshifts:
12316   case Intrinsic::arm_neon_vqshiftu:
12317   case Intrinsic::arm_neon_vqshiftsu:
12318   case Intrinsic::arm_neon_vqshiftns:
12319   case Intrinsic::arm_neon_vqshiftnu:
12320   case Intrinsic::arm_neon_vqshiftnsu:
12321   case Intrinsic::arm_neon_vqrshiftns:
12322   case Intrinsic::arm_neon_vqrshiftnu:
12323   case Intrinsic::arm_neon_vqrshiftnsu: {
12324     EVT VT = N->getOperand(1).getValueType();
12325     int64_t Cnt;
12326     unsigned VShiftOpc = 0;
12327 
12328     switch (IntNo) {
12329     case Intrinsic::arm_neon_vshifts:
12330     case Intrinsic::arm_neon_vshiftu:
12331       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12332         VShiftOpc = ARMISD::VSHL;
12333         break;
12334       }
12335       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12336         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12337                      ARMISD::VSHRs : ARMISD::VSHRu);
12338         break;
12339       }
12340       return SDValue();
12341 
12342     case Intrinsic::arm_neon_vrshifts:
12343     case Intrinsic::arm_neon_vrshiftu:
12344       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12345         break;
12346       return SDValue();
12347 
12348     case Intrinsic::arm_neon_vqshifts:
12349     case Intrinsic::arm_neon_vqshiftu:
12350       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12351         break;
12352       return SDValue();
12353 
12354     case Intrinsic::arm_neon_vqshiftsu:
12355       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12356         break;
12357       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12358 
12359     case Intrinsic::arm_neon_vrshiftn:
12360     case Intrinsic::arm_neon_vqshiftns:
12361     case Intrinsic::arm_neon_vqshiftnu:
12362     case Intrinsic::arm_neon_vqshiftnsu:
12363     case Intrinsic::arm_neon_vqrshiftns:
12364     case Intrinsic::arm_neon_vqrshiftnu:
12365     case Intrinsic::arm_neon_vqrshiftnsu:
12366       // Narrowing shifts require an immediate right shift.
12367       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12368         break;
12369       llvm_unreachable("invalid shift count for narrowing vector shift "
12370                        "intrinsic");
12371 
12372     default:
12373       llvm_unreachable("unhandled vector shift");
12374     }
12375 
12376     switch (IntNo) {
12377     case Intrinsic::arm_neon_vshifts:
12378     case Intrinsic::arm_neon_vshiftu:
12379       // Opcode already set above.
12380       break;
12381     case Intrinsic::arm_neon_vrshifts:
12382       VShiftOpc = ARMISD::VRSHRs; break;
12383     case Intrinsic::arm_neon_vrshiftu:
12384       VShiftOpc = ARMISD::VRSHRu; break;
12385     case Intrinsic::arm_neon_vrshiftn:
12386       VShiftOpc = ARMISD::VRSHRN; break;
12387     case Intrinsic::arm_neon_vqshifts:
12388       VShiftOpc = ARMISD::VQSHLs; break;
12389     case Intrinsic::arm_neon_vqshiftu:
12390       VShiftOpc = ARMISD::VQSHLu; break;
12391     case Intrinsic::arm_neon_vqshiftsu:
12392       VShiftOpc = ARMISD::VQSHLsu; break;
12393     case Intrinsic::arm_neon_vqshiftns:
12394       VShiftOpc = ARMISD::VQSHRNs; break;
12395     case Intrinsic::arm_neon_vqshiftnu:
12396       VShiftOpc = ARMISD::VQSHRNu; break;
12397     case Intrinsic::arm_neon_vqshiftnsu:
12398       VShiftOpc = ARMISD::VQSHRNsu; break;
12399     case Intrinsic::arm_neon_vqrshiftns:
12400       VShiftOpc = ARMISD::VQRSHRNs; break;
12401     case Intrinsic::arm_neon_vqrshiftnu:
12402       VShiftOpc = ARMISD::VQRSHRNu; break;
12403     case Intrinsic::arm_neon_vqrshiftnsu:
12404       VShiftOpc = ARMISD::VQRSHRNsu; break;
12405     }
12406 
12407     SDLoc dl(N);
12408     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12409                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12410   }
12411 
12412   case Intrinsic::arm_neon_vshiftins: {
12413     EVT VT = N->getOperand(1).getValueType();
12414     int64_t Cnt;
12415     unsigned VShiftOpc = 0;
12416 
12417     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12418       VShiftOpc = ARMISD::VSLI;
12419     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12420       VShiftOpc = ARMISD::VSRI;
12421     else {
12422       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12423     }
12424 
12425     SDLoc dl(N);
12426     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12427                        N->getOperand(1), N->getOperand(2),
12428                        DAG.getConstant(Cnt, dl, MVT::i32));
12429   }
12430 
12431   case Intrinsic::arm_neon_vqrshifts:
12432   case Intrinsic::arm_neon_vqrshiftu:
12433     // No immediate versions of these to check for.
12434     break;
12435   }
12436 
12437   return SDValue();
12438 }
12439 
12440 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12441 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12442 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12443 /// vector element shift counts are generally not legal, and it is hard to see
12444 /// their values after they get legalized to loads from a constant pool.
12445 static SDValue PerformShiftCombine(SDNode *N,
12446                                    TargetLowering::DAGCombinerInfo &DCI,
12447                                    const ARMSubtarget *ST) {
12448   SelectionDAG &DAG = DCI.DAG;
12449   EVT VT = N->getValueType(0);
12450   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12451     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12452     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12453     SDValue N1 = N->getOperand(1);
12454     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12455       SDValue N0 = N->getOperand(0);
12456       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12457           DAG.MaskedValueIsZero(N0.getOperand(0),
12458                                 APInt::getHighBitsSet(32, 16)))
12459         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12460     }
12461   }
12462 
12463   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
12464       N->getOperand(0)->getOpcode() == ISD::AND &&
12465       N->getOperand(0)->hasOneUse()) {
12466     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12467       return SDValue();
12468     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
12469     // usually show up because instcombine prefers to canonicalize it to
12470     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
12471     // out of GEP lowering in some cases.
12472     SDValue N0 = N->getOperand(0);
12473     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
12474     if (!ShiftAmtNode)
12475       return SDValue();
12476     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
12477     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12478     if (!AndMaskNode)
12479       return SDValue();
12480     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
12481     // Don't transform uxtb/uxth.
12482     if (AndMask == 255 || AndMask == 65535)
12483       return SDValue();
12484     if (isMask_32(AndMask)) {
12485       uint32_t MaskedBits = countLeadingZeros(AndMask);
12486       if (MaskedBits > ShiftAmt) {
12487         SDLoc DL(N);
12488         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12489                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
12490         return DAG.getNode(
12491             ISD::SRL, DL, MVT::i32, SHL,
12492             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
12493       }
12494     }
12495   }
12496 
12497   // Nothing to be done for scalar shifts.
12498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12499   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12500     return SDValue();
12501 
12502   assert(ST->hasNEON() && "unexpected vector shift");
12503   int64_t Cnt;
12504 
12505   switch (N->getOpcode()) {
12506   default: llvm_unreachable("unexpected shift opcode");
12507 
12508   case ISD::SHL:
12509     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12510       SDLoc dl(N);
12511       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12512                          DAG.getConstant(Cnt, dl, MVT::i32));
12513     }
12514     break;
12515 
12516   case ISD::SRA:
12517   case ISD::SRL:
12518     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12519       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12520                             ARMISD::VSHRs : ARMISD::VSHRu);
12521       SDLoc dl(N);
12522       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12523                          DAG.getConstant(Cnt, dl, MVT::i32));
12524     }
12525   }
12526   return SDValue();
12527 }
12528 
12529 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12530 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12531 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12532                                     const ARMSubtarget *ST) {
12533   SDValue N0 = N->getOperand(0);
12534 
12535   // Check for sign- and zero-extensions of vector extract operations of 8-
12536   // and 16-bit vector elements.  NEON supports these directly.  They are
12537   // handled during DAG combining because type legalization will promote them
12538   // to 32-bit types and it is messy to recognize the operations after that.
12539   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12540     SDValue Vec = N0.getOperand(0);
12541     SDValue Lane = N0.getOperand(1);
12542     EVT VT = N->getValueType(0);
12543     EVT EltVT = N0.getValueType();
12544     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12545 
12546     if (VT == MVT::i32 &&
12547         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12548         TLI.isTypeLegal(Vec.getValueType()) &&
12549         isa<ConstantSDNode>(Lane)) {
12550 
12551       unsigned Opc = 0;
12552       switch (N->getOpcode()) {
12553       default: llvm_unreachable("unexpected opcode");
12554       case ISD::SIGN_EXTEND:
12555         Opc = ARMISD::VGETLANEs;
12556         break;
12557       case ISD::ZERO_EXTEND:
12558       case ISD::ANY_EXTEND:
12559         Opc = ARMISD::VGETLANEu;
12560         break;
12561       }
12562       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12563     }
12564   }
12565 
12566   return SDValue();
12567 }
12568 
12569 static const APInt *isPowerOf2Constant(SDValue V) {
12570   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12571   if (!C)
12572     return nullptr;
12573   const APInt *CV = &C->getAPIntValue();
12574   return CV->isPowerOf2() ? CV : nullptr;
12575 }
12576 
12577 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12578   // If we have a CMOV, OR and AND combination such as:
12579   //   if (x & CN)
12580   //     y |= CM;
12581   //
12582   // And:
12583   //   * CN is a single bit;
12584   //   * All bits covered by CM are known zero in y
12585   //
12586   // Then we can convert this into a sequence of BFI instructions. This will
12587   // always be a win if CM is a single bit, will always be no worse than the
12588   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12589   // three bits (due to the extra IT instruction).
12590 
12591   SDValue Op0 = CMOV->getOperand(0);
12592   SDValue Op1 = CMOV->getOperand(1);
12593   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12594   auto CC = CCNode->getAPIntValue().getLimitedValue();
12595   SDValue CmpZ = CMOV->getOperand(4);
12596 
12597   // The compare must be against zero.
12598   if (!isNullConstant(CmpZ->getOperand(1)))
12599     return SDValue();
12600 
12601   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12602   SDValue And = CmpZ->getOperand(0);
12603   if (And->getOpcode() != ISD::AND)
12604     return SDValue();
12605   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12606   if (!AndC)
12607     return SDValue();
12608   SDValue X = And->getOperand(0);
12609 
12610   if (CC == ARMCC::EQ) {
12611     // We're performing an "equal to zero" compare. Swap the operands so we
12612     // canonicalize on a "not equal to zero" compare.
12613     std::swap(Op0, Op1);
12614   } else {
12615     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12616   }
12617 
12618   if (Op1->getOpcode() != ISD::OR)
12619     return SDValue();
12620 
12621   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12622   if (!OrC)
12623     return SDValue();
12624   SDValue Y = Op1->getOperand(0);
12625 
12626   if (Op0 != Y)
12627     return SDValue();
12628 
12629   // Now, is it profitable to continue?
12630   APInt OrCI = OrC->getAPIntValue();
12631   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12632   if (OrCI.countPopulation() > Heuristic)
12633     return SDValue();
12634 
12635   // Lastly, can we determine that the bits defined by OrCI
12636   // are zero in Y?
12637   KnownBits Known = DAG.computeKnownBits(Y);
12638   if ((OrCI & Known.Zero) != OrCI)
12639     return SDValue();
12640 
12641   // OK, we can do the combine.
12642   SDValue V = Y;
12643   SDLoc dl(X);
12644   EVT VT = X.getValueType();
12645   unsigned BitInX = AndC->logBase2();
12646 
12647   if (BitInX != 0) {
12648     // We must shift X first.
12649     X = DAG.getNode(ISD::SRL, dl, VT, X,
12650                     DAG.getConstant(BitInX, dl, VT));
12651   }
12652 
12653   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12654        BitInY < NumActiveBits; ++BitInY) {
12655     if (OrCI[BitInY] == 0)
12656       continue;
12657     APInt Mask(VT.getSizeInBits(), 0);
12658     Mask.setBit(BitInY);
12659     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12660                     // Confusingly, the operand is an *inverted* mask.
12661                     DAG.getConstant(~Mask, dl, VT));
12662   }
12663 
12664   return V;
12665 }
12666 
12667 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12668 SDValue
12669 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12670   SDValue Cmp = N->getOperand(4);
12671   if (Cmp.getOpcode() != ARMISD::CMPZ)
12672     // Only looking at NE cases.
12673     return SDValue();
12674 
12675   EVT VT = N->getValueType(0);
12676   SDLoc dl(N);
12677   SDValue LHS = Cmp.getOperand(0);
12678   SDValue RHS = Cmp.getOperand(1);
12679   SDValue Chain = N->getOperand(0);
12680   SDValue BB = N->getOperand(1);
12681   SDValue ARMcc = N->getOperand(2);
12682   ARMCC::CondCodes CC =
12683     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12684 
12685   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12686   // -> (brcond Chain BB CC CPSR Cmp)
12687   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12688       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12689       LHS->getOperand(0)->hasOneUse()) {
12690     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12691     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12692     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12693     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12694     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12695         (LHS01C && LHS01C->getZExtValue() == 1) &&
12696         (LHS1C && LHS1C->getZExtValue() == 1) &&
12697         (RHSC && RHSC->getZExtValue() == 0)) {
12698       return DAG.getNode(
12699           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12700           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12701     }
12702   }
12703 
12704   return SDValue();
12705 }
12706 
12707 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12708 SDValue
12709 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12710   SDValue Cmp = N->getOperand(4);
12711   if (Cmp.getOpcode() != ARMISD::CMPZ)
12712     // Only looking at EQ and NE cases.
12713     return SDValue();
12714 
12715   EVT VT = N->getValueType(0);
12716   SDLoc dl(N);
12717   SDValue LHS = Cmp.getOperand(0);
12718   SDValue RHS = Cmp.getOperand(1);
12719   SDValue FalseVal = N->getOperand(0);
12720   SDValue TrueVal = N->getOperand(1);
12721   SDValue ARMcc = N->getOperand(2);
12722   ARMCC::CondCodes CC =
12723     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12724 
12725   // BFI is only available on V6T2+.
12726   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12727     SDValue R = PerformCMOVToBFICombine(N, DAG);
12728     if (R)
12729       return R;
12730   }
12731 
12732   // Simplify
12733   //   mov     r1, r0
12734   //   cmp     r1, x
12735   //   mov     r0, y
12736   //   moveq   r0, x
12737   // to
12738   //   cmp     r0, x
12739   //   movne   r0, y
12740   //
12741   //   mov     r1, r0
12742   //   cmp     r1, x
12743   //   mov     r0, x
12744   //   movne   r0, y
12745   // to
12746   //   cmp     r0, x
12747   //   movne   r0, y
12748   /// FIXME: Turn this into a target neutral optimization?
12749   SDValue Res;
12750   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12751     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12752                       N->getOperand(3), Cmp);
12753   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12754     SDValue ARMcc;
12755     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12756     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12757                       N->getOperand(3), NewCmp);
12758   }
12759 
12760   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12761   // -> (cmov F T CC CPSR Cmp)
12762   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12763     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12764     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12765     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12766     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12767         (LHS1C && LHS1C->getZExtValue() == 1) &&
12768         (RHSC && RHSC->getZExtValue() == 0)) {
12769       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12770                          LHS->getOperand(2), LHS->getOperand(3),
12771                          LHS->getOperand(4));
12772     }
12773   }
12774 
12775   if (!VT.isInteger())
12776       return SDValue();
12777 
12778   // Materialize a boolean comparison for integers so we can avoid branching.
12779   if (isNullConstant(FalseVal)) {
12780     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
12781       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
12782         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
12783         // right 5 bits will make that 32 be 1, otherwise it will be 0.
12784         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
12785         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12786         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
12787                           DAG.getConstant(5, dl, MVT::i32));
12788       } else {
12789         // CMOV 0, 1, ==, (CMPZ x, y) ->
12790         //     (ADDCARRY (SUB x, y), t:0, t:1)
12791         // where t = (SUBCARRY 0, (SUB x, y), 0)
12792         //
12793         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
12794         // x != y. In other words, a carry C == 1 when x == y, C == 0
12795         // otherwise.
12796         // The final ADDCARRY computes
12797         //     x - y + (0 - (x - y)) + C == C
12798         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12799         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12800         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
12801         // ISD::SUBCARRY returns a borrow but we want the carry here
12802         // actually.
12803         SDValue Carry =
12804             DAG.getNode(ISD::SUB, dl, MVT::i32,
12805                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
12806         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
12807       }
12808     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
12809                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
12810       // This seems pointless but will allow us to combine it further below.
12811       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12812       SDValue Sub =
12813           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12814       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12815                                           Sub.getValue(1), SDValue());
12816       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
12817                         N->getOperand(3), CPSRGlue.getValue(1));
12818       FalseVal = Sub;
12819     }
12820   } else if (isNullConstant(TrueVal)) {
12821     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
12822         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
12823       // This seems pointless but will allow us to combine it further below
12824       // Note that we change == for != as this is the dual for the case above.
12825       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12826       SDValue Sub =
12827           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12828       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12829                                           Sub.getValue(1), SDValue());
12830       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
12831                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
12832                         N->getOperand(3), CPSRGlue.getValue(1));
12833       FalseVal = Sub;
12834     }
12835   }
12836 
12837   // On Thumb1, the DAG above may be further combined if z is a power of 2
12838   // (z == 2 ^ K).
12839   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
12840   //       merge t3, t4
12841   // where t1 = (SUBCARRY (SUB x, y), z, 0)
12842   //       t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
12843   //       t3 = if K != 0 then (SHL t2:0, K) else t2:0
12844   //       t4 = (SUB 1, t2:1)   [ we want a carry, not a borrow ]
12845   const APInt *TrueConst;
12846   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
12847       (FalseVal.getOpcode() == ARMISD::SUBS) &&
12848       (FalseVal.getOperand(0) == LHS) && (FalseVal.getOperand(1) == RHS) &&
12849       (TrueConst = isPowerOf2Constant(TrueVal))) {
12850     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12851     unsigned ShiftAmount = TrueConst->logBase2();
12852     if (ShiftAmount)
12853       TrueVal = DAG.getConstant(1, dl, VT);
12854     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
12855     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
12856     // Make it a carry, not a borrow.
12857     SDValue Carry = DAG.getNode(
12858         ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1));
12859     Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry);
12860 
12861     if (ShiftAmount)
12862       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
12863                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
12864   }
12865 
12866   if (Res.getNode()) {
12867     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
12868     // Capture demanded bits information that would be otherwise lost.
12869     if (Known.Zero == 0xfffffffe)
12870       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12871                         DAG.getValueType(MVT::i1));
12872     else if (Known.Zero == 0xffffff00)
12873       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12874                         DAG.getValueType(MVT::i8));
12875     else if (Known.Zero == 0xffff0000)
12876       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12877                         DAG.getValueType(MVT::i16));
12878   }
12879 
12880   return Res;
12881 }
12882 
12883 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12884                                              DAGCombinerInfo &DCI) const {
12885   switch (N->getOpcode()) {
12886   default: break;
12887   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12888   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12889   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12890   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12891   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12892   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12893   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12894   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12895   case ARMISD::ADDC:
12896   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12897   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12898   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12899   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12900   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12901   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12902   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12903   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12904   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12905   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12906   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12907   case ISD::FP_TO_SINT:
12908   case ISD::FP_TO_UINT:
12909     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12910   case ISD::FDIV:
12911     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12912   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12913   case ISD::SHL:
12914   case ISD::SRA:
12915   case ISD::SRL:
12916     return PerformShiftCombine(N, DCI, Subtarget);
12917   case ISD::SIGN_EXTEND:
12918   case ISD::ZERO_EXTEND:
12919   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12920   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12921   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12922   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12923   case ARMISD::VLD1DUP:
12924   case ARMISD::VLD2DUP:
12925   case ARMISD::VLD3DUP:
12926   case ARMISD::VLD4DUP:
12927     return PerformVLDCombine(N, DCI);
12928   case ARMISD::BUILD_VECTOR:
12929     return PerformARMBUILD_VECTORCombine(N, DCI);
12930   case ARMISD::SMULWB: {
12931     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12932     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12933     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12934       return SDValue();
12935     break;
12936   }
12937   case ARMISD::SMULWT: {
12938     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12939     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12940     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12941       return SDValue();
12942     break;
12943   }
12944   case ARMISD::SMLALBB: {
12945     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12946     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12947     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12948         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12949       return SDValue();
12950     break;
12951   }
12952   case ARMISD::SMLALBT: {
12953     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12954     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12955     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12956     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12957     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12958         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12959       return SDValue();
12960     break;
12961   }
12962   case ARMISD::SMLALTB: {
12963     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12964     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12965     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12966     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12967     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12968         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12969       return SDValue();
12970     break;
12971   }
12972   case ARMISD::SMLALTT: {
12973     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12974     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12975     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12976         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12977       return SDValue();
12978     break;
12979   }
12980   case ISD::INTRINSIC_VOID:
12981   case ISD::INTRINSIC_W_CHAIN:
12982     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12983     case Intrinsic::arm_neon_vld1:
12984     case Intrinsic::arm_neon_vld1x2:
12985     case Intrinsic::arm_neon_vld1x3:
12986     case Intrinsic::arm_neon_vld1x4:
12987     case Intrinsic::arm_neon_vld2:
12988     case Intrinsic::arm_neon_vld3:
12989     case Intrinsic::arm_neon_vld4:
12990     case Intrinsic::arm_neon_vld2lane:
12991     case Intrinsic::arm_neon_vld3lane:
12992     case Intrinsic::arm_neon_vld4lane:
12993     case Intrinsic::arm_neon_vld2dup:
12994     case Intrinsic::arm_neon_vld3dup:
12995     case Intrinsic::arm_neon_vld4dup:
12996     case Intrinsic::arm_neon_vst1:
12997     case Intrinsic::arm_neon_vst1x2:
12998     case Intrinsic::arm_neon_vst1x3:
12999     case Intrinsic::arm_neon_vst1x4:
13000     case Intrinsic::arm_neon_vst2:
13001     case Intrinsic::arm_neon_vst3:
13002     case Intrinsic::arm_neon_vst4:
13003     case Intrinsic::arm_neon_vst2lane:
13004     case Intrinsic::arm_neon_vst3lane:
13005     case Intrinsic::arm_neon_vst4lane:
13006       return PerformVLDCombine(N, DCI);
13007     default: break;
13008     }
13009     break;
13010   }
13011   return SDValue();
13012 }
13013 
13014 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
13015                                                           EVT VT) const {
13016   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
13017 }
13018 
13019 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13020                                                        unsigned,
13021                                                        unsigned,
13022                                                        bool *Fast) const {
13023   // Depends what it gets converted into if the type is weird.
13024   if (!VT.isSimple())
13025     return false;
13026 
13027   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
13028   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
13029 
13030   switch (VT.getSimpleVT().SimpleTy) {
13031   default:
13032     return false;
13033   case MVT::i8:
13034   case MVT::i16:
13035   case MVT::i32: {
13036     // Unaligned access can use (for example) LRDB, LRDH, LDR
13037     if (AllowsUnaligned) {
13038       if (Fast)
13039         *Fast = Subtarget->hasV7Ops();
13040       return true;
13041     }
13042     return false;
13043   }
13044   case MVT::f64:
13045   case MVT::v2f64: {
13046     // For any little-endian targets with neon, we can support unaligned ld/st
13047     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
13048     // A big-endian target may also explicitly support unaligned accesses
13049     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
13050       if (Fast)
13051         *Fast = true;
13052       return true;
13053     }
13054     return false;
13055   }
13056   }
13057 }
13058 
13059 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
13060                        unsigned AlignCheck) {
13061   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
13062           (DstAlign == 0 || DstAlign % AlignCheck == 0));
13063 }
13064 
13065 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
13066                                            unsigned DstAlign, unsigned SrcAlign,
13067                                            bool IsMemset, bool ZeroMemset,
13068                                            bool MemcpyStrSrc,
13069                                            MachineFunction &MF) const {
13070   const Function &F = MF.getFunction();
13071 
13072   // See if we can use NEON instructions for this...
13073   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
13074       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
13075     bool Fast;
13076     if (Size >= 16 &&
13077         (memOpAlign(SrcAlign, DstAlign, 16) ||
13078          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
13079       return MVT::v2f64;
13080     } else if (Size >= 8 &&
13081                (memOpAlign(SrcAlign, DstAlign, 8) ||
13082                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
13083                  Fast))) {
13084       return MVT::f64;
13085     }
13086   }
13087 
13088   // Let the target-independent logic figure it out.
13089   return MVT::Other;
13090 }
13091 
13092 // 64-bit integers are split into their high and low parts and held in two
13093 // different registers, so the trunc is free since the low register can just
13094 // be used.
13095 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
13096   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
13097     return false;
13098   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
13099   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
13100   return (SrcBits == 64 && DestBits == 32);
13101 }
13102 
13103 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
13104   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
13105       !DstVT.isInteger())
13106     return false;
13107   unsigned SrcBits = SrcVT.getSizeInBits();
13108   unsigned DestBits = DstVT.getSizeInBits();
13109   return (SrcBits == 64 && DestBits == 32);
13110 }
13111 
13112 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13113   if (Val.getOpcode() != ISD::LOAD)
13114     return false;
13115 
13116   EVT VT1 = Val.getValueType();
13117   if (!VT1.isSimple() || !VT1.isInteger() ||
13118       !VT2.isSimple() || !VT2.isInteger())
13119     return false;
13120 
13121   switch (VT1.getSimpleVT().SimpleTy) {
13122   default: break;
13123   case MVT::i1:
13124   case MVT::i8:
13125   case MVT::i16:
13126     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
13127     return true;
13128   }
13129 
13130   return false;
13131 }
13132 
13133 bool ARMTargetLowering::isFNegFree(EVT VT) const {
13134   if (!VT.isSimple())
13135     return false;
13136 
13137   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
13138   // negate values directly (fneg is free). So, we don't want to let the DAG
13139   // combiner rewrite fneg into xors and some other instructions.  For f16 and
13140   // FullFP16 argument passing, some bitcast nodes may be introduced,
13141   // triggering this DAG combine rewrite, so we are avoiding that with this.
13142   switch (VT.getSimpleVT().SimpleTy) {
13143   default: break;
13144   case MVT::f16:
13145     return Subtarget->hasFullFP16();
13146   }
13147 
13148   return false;
13149 }
13150 
13151 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
13152 /// of the vector elements.
13153 static bool areExtractExts(Value *Ext1, Value *Ext2) {
13154   auto areExtDoubled = [](Instruction *Ext) {
13155     return Ext->getType()->getScalarSizeInBits() ==
13156            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
13157   };
13158 
13159   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
13160       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
13161       !areExtDoubled(cast<Instruction>(Ext1)) ||
13162       !areExtDoubled(cast<Instruction>(Ext2)))
13163     return false;
13164 
13165   return true;
13166 }
13167 
13168 /// Check if sinking \p I's operands to I's basic block is profitable, because
13169 /// the operands can be folded into a target instruction, e.g.
13170 /// sext/zext can be folded into vsubl.
13171 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
13172                                            SmallVectorImpl<Use *> &Ops) const {
13173   if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
13174     return false;
13175 
13176   switch (I->getOpcode()) {
13177   case Instruction::Sub:
13178   case Instruction::Add: {
13179     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
13180       return false;
13181     Ops.push_back(&I->getOperandUse(0));
13182     Ops.push_back(&I->getOperandUse(1));
13183     return true;
13184   }
13185   default:
13186     return false;
13187   }
13188   return false;
13189 }
13190 
13191 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
13192   EVT VT = ExtVal.getValueType();
13193 
13194   if (!isTypeLegal(VT))
13195     return false;
13196 
13197   // Don't create a loadext if we can fold the extension into a wide/long
13198   // instruction.
13199   // If there's more than one user instruction, the loadext is desirable no
13200   // matter what.  There can be two uses by the same instruction.
13201   if (ExtVal->use_empty() ||
13202       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
13203     return true;
13204 
13205   SDNode *U = *ExtVal->use_begin();
13206   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
13207        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
13208     return false;
13209 
13210   return true;
13211 }
13212 
13213 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13214   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13215     return false;
13216 
13217   if (!isTypeLegal(EVT::getEVT(Ty1)))
13218     return false;
13219 
13220   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13221 
13222   // Assuming the caller doesn't have a zeroext or signext return parameter,
13223   // truncation all the way down to i1 is valid.
13224   return true;
13225 }
13226 
13227 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
13228                                                 const AddrMode &AM, Type *Ty,
13229                                                 unsigned AS) const {
13230   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
13231     if (Subtarget->hasFPAO())
13232       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
13233     return 0;
13234   }
13235   return -1;
13236 }
13237 
13238 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
13239   if (V < 0)
13240     return false;
13241 
13242   unsigned Scale = 1;
13243   switch (VT.getSimpleVT().SimpleTy) {
13244   default: return false;
13245   case MVT::i1:
13246   case MVT::i8:
13247     // Scale == 1;
13248     break;
13249   case MVT::i16:
13250     // Scale == 2;
13251     Scale = 2;
13252     break;
13253   case MVT::i32:
13254     // Scale == 4;
13255     Scale = 4;
13256     break;
13257   }
13258 
13259   if ((V & (Scale - 1)) != 0)
13260     return false;
13261   V /= Scale;
13262   return V == (V & ((1LL << 5) - 1));
13263 }
13264 
13265 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
13266                                       const ARMSubtarget *Subtarget) {
13267   bool isNeg = false;
13268   if (V < 0) {
13269     isNeg = true;
13270     V = - V;
13271   }
13272 
13273   switch (VT.getSimpleVT().SimpleTy) {
13274   default: return false;
13275   case MVT::i1:
13276   case MVT::i8:
13277   case MVT::i16:
13278   case MVT::i32:
13279     // + imm12 or - imm8
13280     if (isNeg)
13281       return V == (V & ((1LL << 8) - 1));
13282     return V == (V & ((1LL << 12) - 1));
13283   case MVT::f32:
13284   case MVT::f64:
13285     // Same as ARM mode. FIXME: NEON?
13286     if (!Subtarget->hasVFP2())
13287       return false;
13288     if ((V & 3) != 0)
13289       return false;
13290     V >>= 2;
13291     return V == (V & ((1LL << 8) - 1));
13292   }
13293 }
13294 
13295 /// isLegalAddressImmediate - Return true if the integer value can be used
13296 /// as the offset of the target addressing mode for load / store of the
13297 /// given type.
13298 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13299                                     const ARMSubtarget *Subtarget) {
13300   if (V == 0)
13301     return true;
13302 
13303   if (!VT.isSimple())
13304     return false;
13305 
13306   if (Subtarget->isThumb1Only())
13307     return isLegalT1AddressImmediate(V, VT);
13308   else if (Subtarget->isThumb2())
13309     return isLegalT2AddressImmediate(V, VT, Subtarget);
13310 
13311   // ARM mode.
13312   if (V < 0)
13313     V = - V;
13314   switch (VT.getSimpleVT().SimpleTy) {
13315   default: return false;
13316   case MVT::i1:
13317   case MVT::i8:
13318   case MVT::i32:
13319     // +- imm12
13320     return V == (V & ((1LL << 12) - 1));
13321   case MVT::i16:
13322     // +- imm8
13323     return V == (V & ((1LL << 8) - 1));
13324   case MVT::f32:
13325   case MVT::f64:
13326     if (!Subtarget->hasVFP2()) // FIXME: NEON?
13327       return false;
13328     if ((V & 3) != 0)
13329       return false;
13330     V >>= 2;
13331     return V == (V & ((1LL << 8) - 1));
13332   }
13333 }
13334 
13335 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13336                                                       EVT VT) const {
13337   int Scale = AM.Scale;
13338   if (Scale < 0)
13339     return false;
13340 
13341   switch (VT.getSimpleVT().SimpleTy) {
13342   default: return false;
13343   case MVT::i1:
13344   case MVT::i8:
13345   case MVT::i16:
13346   case MVT::i32:
13347     if (Scale == 1)
13348       return true;
13349     // r + r << imm
13350     Scale = Scale & ~1;
13351     return Scale == 2 || Scale == 4 || Scale == 8;
13352   case MVT::i64:
13353     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13354     // version in Thumb mode.
13355     // r + r
13356     if (Scale == 1)
13357       return true;
13358     // r * 2 (this can be lowered to r + r).
13359     if (!AM.HasBaseReg && Scale == 2)
13360       return true;
13361     return false;
13362   case MVT::isVoid:
13363     // Note, we allow "void" uses (basically, uses that aren't loads or
13364     // stores), because arm allows folding a scale into many arithmetic
13365     // operations.  This should be made more precise and revisited later.
13366 
13367     // Allow r << imm, but the imm has to be a multiple of two.
13368     if (Scale & 1) return false;
13369     return isPowerOf2_32(Scale);
13370   }
13371 }
13372 
13373 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13374                                                       EVT VT) const {
13375   const int Scale = AM.Scale;
13376 
13377   // Negative scales are not supported in Thumb1.
13378   if (Scale < 0)
13379     return false;
13380 
13381   // Thumb1 addressing modes do not support register scaling excepting the
13382   // following cases:
13383   // 1. Scale == 1 means no scaling.
13384   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13385   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13386 }
13387 
13388 /// isLegalAddressingMode - Return true if the addressing mode represented
13389 /// by AM is legal for this target, for a load/store of the specified type.
13390 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13391                                               const AddrMode &AM, Type *Ty,
13392                                               unsigned AS, Instruction *I) const {
13393   EVT VT = getValueType(DL, Ty, true);
13394   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13395     return false;
13396 
13397   // Can never fold addr of global into load/store.
13398   if (AM.BaseGV)
13399     return false;
13400 
13401   switch (AM.Scale) {
13402   case 0:  // no scale reg, must be "r+i" or "r", or "i".
13403     break;
13404   default:
13405     // ARM doesn't support any R+R*scale+imm addr modes.
13406     if (AM.BaseOffs)
13407       return false;
13408 
13409     if (!VT.isSimple())
13410       return false;
13411 
13412     if (Subtarget->isThumb1Only())
13413       return isLegalT1ScaledAddressingMode(AM, VT);
13414 
13415     if (Subtarget->isThumb2())
13416       return isLegalT2ScaledAddressingMode(AM, VT);
13417 
13418     int Scale = AM.Scale;
13419     switch (VT.getSimpleVT().SimpleTy) {
13420     default: return false;
13421     case MVT::i1:
13422     case MVT::i8:
13423     case MVT::i32:
13424       if (Scale < 0) Scale = -Scale;
13425       if (Scale == 1)
13426         return true;
13427       // r + r << imm
13428       return isPowerOf2_32(Scale & ~1);
13429     case MVT::i16:
13430     case MVT::i64:
13431       // r +/- r
13432       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13433         return true;
13434       // r * 2 (this can be lowered to r + r).
13435       if (!AM.HasBaseReg && Scale == 2)
13436         return true;
13437       return false;
13438 
13439     case MVT::isVoid:
13440       // Note, we allow "void" uses (basically, uses that aren't loads or
13441       // stores), because arm allows folding a scale into many arithmetic
13442       // operations.  This should be made more precise and revisited later.
13443 
13444       // Allow r << imm, but the imm has to be a multiple of two.
13445       if (Scale & 1) return false;
13446       return isPowerOf2_32(Scale);
13447     }
13448   }
13449   return true;
13450 }
13451 
13452 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13453 /// icmp immediate, that is the target has icmp instructions which can compare
13454 /// a register against the immediate without having to materialize the
13455 /// immediate into a register.
13456 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13457   // Thumb2 and ARM modes can use cmn for negative immediates.
13458   if (!Subtarget->isThumb())
13459     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
13460            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
13461   if (Subtarget->isThumb2())
13462     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
13463            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
13464   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13465   return Imm >= 0 && Imm <= 255;
13466 }
13467 
13468 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13469 /// *or sub* immediate, that is the target has add or sub instructions which can
13470 /// add a register with the immediate without having to materialize the
13471 /// immediate into a register.
13472 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13473   // Same encoding for add/sub, just flip the sign.
13474   int64_t AbsImm = std::abs(Imm);
13475   if (!Subtarget->isThumb())
13476     return ARM_AM::getSOImmVal(AbsImm) != -1;
13477   if (Subtarget->isThumb2())
13478     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13479   // Thumb1 only has 8-bit unsigned immediate.
13480   return AbsImm >= 0 && AbsImm <= 255;
13481 }
13482 
13483 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13484                                       bool isSEXTLoad, SDValue &Base,
13485                                       SDValue &Offset, bool &isInc,
13486                                       SelectionDAG &DAG) {
13487   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13488     return false;
13489 
13490   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13491     // AddressingMode 3
13492     Base = Ptr->getOperand(0);
13493     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13494       int RHSC = (int)RHS->getZExtValue();
13495       if (RHSC < 0 && RHSC > -256) {
13496         assert(Ptr->getOpcode() == ISD::ADD);
13497         isInc = false;
13498         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13499         return true;
13500       }
13501     }
13502     isInc = (Ptr->getOpcode() == ISD::ADD);
13503     Offset = Ptr->getOperand(1);
13504     return true;
13505   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13506     // AddressingMode 2
13507     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13508       int RHSC = (int)RHS->getZExtValue();
13509       if (RHSC < 0 && RHSC > -0x1000) {
13510         assert(Ptr->getOpcode() == ISD::ADD);
13511         isInc = false;
13512         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13513         Base = Ptr->getOperand(0);
13514         return true;
13515       }
13516     }
13517 
13518     if (Ptr->getOpcode() == ISD::ADD) {
13519       isInc = true;
13520       ARM_AM::ShiftOpc ShOpcVal=
13521         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13522       if (ShOpcVal != ARM_AM::no_shift) {
13523         Base = Ptr->getOperand(1);
13524         Offset = Ptr->getOperand(0);
13525       } else {
13526         Base = Ptr->getOperand(0);
13527         Offset = Ptr->getOperand(1);
13528       }
13529       return true;
13530     }
13531 
13532     isInc = (Ptr->getOpcode() == ISD::ADD);
13533     Base = Ptr->getOperand(0);
13534     Offset = Ptr->getOperand(1);
13535     return true;
13536   }
13537 
13538   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13539   return false;
13540 }
13541 
13542 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13543                                      bool isSEXTLoad, SDValue &Base,
13544                                      SDValue &Offset, bool &isInc,
13545                                      SelectionDAG &DAG) {
13546   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13547     return false;
13548 
13549   Base = Ptr->getOperand(0);
13550   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13551     int RHSC = (int)RHS->getZExtValue();
13552     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13553       assert(Ptr->getOpcode() == ISD::ADD);
13554       isInc = false;
13555       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13556       return true;
13557     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13558       isInc = Ptr->getOpcode() == ISD::ADD;
13559       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13560       return true;
13561     }
13562   }
13563 
13564   return false;
13565 }
13566 
13567 /// getPreIndexedAddressParts - returns true by value, base pointer and
13568 /// offset pointer and addressing mode by reference if the node's address
13569 /// can be legally represented as pre-indexed load / store address.
13570 bool
13571 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13572                                              SDValue &Offset,
13573                                              ISD::MemIndexedMode &AM,
13574                                              SelectionDAG &DAG) const {
13575   if (Subtarget->isThumb1Only())
13576     return false;
13577 
13578   EVT VT;
13579   SDValue Ptr;
13580   bool isSEXTLoad = false;
13581   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13582     Ptr = LD->getBasePtr();
13583     VT  = LD->getMemoryVT();
13584     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13585   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13586     Ptr = ST->getBasePtr();
13587     VT  = ST->getMemoryVT();
13588   } else
13589     return false;
13590 
13591   bool isInc;
13592   bool isLegal = false;
13593   if (Subtarget->isThumb2())
13594     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13595                                        Offset, isInc, DAG);
13596   else
13597     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13598                                         Offset, isInc, DAG);
13599   if (!isLegal)
13600     return false;
13601 
13602   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13603   return true;
13604 }
13605 
13606 /// getPostIndexedAddressParts - returns true by value, base pointer and
13607 /// offset pointer and addressing mode by reference if this node can be
13608 /// combined with a load / store to form a post-indexed load / store.
13609 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13610                                                    SDValue &Base,
13611                                                    SDValue &Offset,
13612                                                    ISD::MemIndexedMode &AM,
13613                                                    SelectionDAG &DAG) const {
13614   EVT VT;
13615   SDValue Ptr;
13616   bool isSEXTLoad = false, isNonExt;
13617   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13618     VT  = LD->getMemoryVT();
13619     Ptr = LD->getBasePtr();
13620     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13621     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13622   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13623     VT  = ST->getMemoryVT();
13624     Ptr = ST->getBasePtr();
13625     isNonExt = !ST->isTruncatingStore();
13626   } else
13627     return false;
13628 
13629   if (Subtarget->isThumb1Only()) {
13630     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13631     // must be non-extending/truncating, i32, with an offset of 4.
13632     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13633     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13634       return false;
13635     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13636     if (!RHS || RHS->getZExtValue() != 4)
13637       return false;
13638 
13639     Offset = Op->getOperand(1);
13640     Base = Op->getOperand(0);
13641     AM = ISD::POST_INC;
13642     return true;
13643   }
13644 
13645   bool isInc;
13646   bool isLegal = false;
13647   if (Subtarget->isThumb2())
13648     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13649                                        isInc, DAG);
13650   else
13651     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13652                                         isInc, DAG);
13653   if (!isLegal)
13654     return false;
13655 
13656   if (Ptr != Base) {
13657     // Swap base ptr and offset to catch more post-index load / store when
13658     // it's legal. In Thumb2 mode, offset must be an immediate.
13659     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13660         !Subtarget->isThumb2())
13661       std::swap(Base, Offset);
13662 
13663     // Post-indexed load / store update the base pointer.
13664     if (Ptr != Base)
13665       return false;
13666   }
13667 
13668   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13669   return true;
13670 }
13671 
13672 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13673                                                       KnownBits &Known,
13674                                                       const APInt &DemandedElts,
13675                                                       const SelectionDAG &DAG,
13676                                                       unsigned Depth) const {
13677   unsigned BitWidth = Known.getBitWidth();
13678   Known.resetAll();
13679   switch (Op.getOpcode()) {
13680   default: break;
13681   case ARMISD::ADDC:
13682   case ARMISD::ADDE:
13683   case ARMISD::SUBC:
13684   case ARMISD::SUBE:
13685     // Special cases when we convert a carry to a boolean.
13686     if (Op.getResNo() == 0) {
13687       SDValue LHS = Op.getOperand(0);
13688       SDValue RHS = Op.getOperand(1);
13689       // (ADDE 0, 0, C) will give us a single bit.
13690       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13691           isNullConstant(RHS)) {
13692         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13693         return;
13694       }
13695     }
13696     break;
13697   case ARMISD::CMOV: {
13698     // Bits are known zero/one if known on the LHS and RHS.
13699     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
13700     if (Known.isUnknown())
13701       return;
13702 
13703     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
13704     Known.Zero &= KnownRHS.Zero;
13705     Known.One  &= KnownRHS.One;
13706     return;
13707   }
13708   case ISD::INTRINSIC_W_CHAIN: {
13709     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13710     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13711     switch (IntID) {
13712     default: return;
13713     case Intrinsic::arm_ldaex:
13714     case Intrinsic::arm_ldrex: {
13715       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13716       unsigned MemBits = VT.getScalarSizeInBits();
13717       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13718       return;
13719     }
13720     }
13721   }
13722   case ARMISD::BFI: {
13723     // Conservatively, we can recurse down the first operand
13724     // and just mask out all affected bits.
13725     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
13726 
13727     // The operand to BFI is already a mask suitable for removing the bits it
13728     // sets.
13729     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13730     const APInt &Mask = CI->getAPIntValue();
13731     Known.Zero &= Mask;
13732     Known.One &= Mask;
13733     return;
13734   }
13735   case ARMISD::VGETLANEs:
13736   case ARMISD::VGETLANEu: {
13737     const SDValue &SrcSV = Op.getOperand(0);
13738     EVT VecVT = SrcSV.getValueType();
13739     assert(VecVT.isVector() && "VGETLANE expected a vector type");
13740     const unsigned NumSrcElts = VecVT.getVectorNumElements();
13741     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
13742     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
13743            "VGETLANE index out of bounds");
13744     unsigned Idx = Pos->getZExtValue();
13745     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
13746     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
13747 
13748     EVT VT = Op.getValueType();
13749     const unsigned DstSz = VT.getScalarSizeInBits();
13750     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
13751     (void)SrcSz;
13752     assert(SrcSz == Known.getBitWidth());
13753     assert(DstSz > SrcSz);
13754     if (Op.getOpcode() == ARMISD::VGETLANEs)
13755       Known = Known.sext(DstSz);
13756     else {
13757       Known = Known.zext(DstSz, true /* extended bits are known zero */);
13758     }
13759     assert(DstSz == Known.getBitWidth());
13760     break;
13761   }
13762   }
13763 }
13764 
13765 bool
13766 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
13767                                                 const APInt &DemandedAPInt,
13768                                                 TargetLoweringOpt &TLO) const {
13769   // Delay optimization, so we don't have to deal with illegal types, or block
13770   // optimizations.
13771   if (!TLO.LegalOps)
13772     return false;
13773 
13774   // Only optimize AND for now.
13775   if (Op.getOpcode() != ISD::AND)
13776     return false;
13777 
13778   EVT VT = Op.getValueType();
13779 
13780   // Ignore vectors.
13781   if (VT.isVector())
13782     return false;
13783 
13784   assert(VT == MVT::i32 && "Unexpected integer type");
13785 
13786   // Make sure the RHS really is a constant.
13787   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13788   if (!C)
13789     return false;
13790 
13791   unsigned Mask = C->getZExtValue();
13792 
13793   unsigned Demanded = DemandedAPInt.getZExtValue();
13794   unsigned ShrunkMask = Mask & Demanded;
13795   unsigned ExpandedMask = Mask | ~Demanded;
13796 
13797   // If the mask is all zeros, let the target-independent code replace the
13798   // result with zero.
13799   if (ShrunkMask == 0)
13800     return false;
13801 
13802   // If the mask is all ones, erase the AND. (Currently, the target-independent
13803   // code won't do this, so we have to do it explicitly to avoid an infinite
13804   // loop in obscure cases.)
13805   if (ExpandedMask == ~0U)
13806     return TLO.CombineTo(Op, Op.getOperand(0));
13807 
13808   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
13809     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
13810   };
13811   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
13812     if (NewMask == Mask)
13813       return true;
13814     SDLoc DL(Op);
13815     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
13816     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
13817     return TLO.CombineTo(Op, NewOp);
13818   };
13819 
13820   // Prefer uxtb mask.
13821   if (IsLegalMask(0xFF))
13822     return UseMask(0xFF);
13823 
13824   // Prefer uxth mask.
13825   if (IsLegalMask(0xFFFF))
13826     return UseMask(0xFFFF);
13827 
13828   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
13829   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13830   if (ShrunkMask < 256)
13831     return UseMask(ShrunkMask);
13832 
13833   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
13834   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13835   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
13836     return UseMask(ExpandedMask);
13837 
13838   // Potential improvements:
13839   //
13840   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
13841   // We could try to prefer Thumb1 immediates which can be lowered to a
13842   // two-instruction sequence.
13843   // We could try to recognize more legal ARM/Thumb2 immediates here.
13844 
13845   return false;
13846 }
13847 
13848 
13849 //===----------------------------------------------------------------------===//
13850 //                           ARM Inline Assembly Support
13851 //===----------------------------------------------------------------------===//
13852 
13853 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13854   // Looking for "rev" which is V6+.
13855   if (!Subtarget->hasV6Ops())
13856     return false;
13857 
13858   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13859   std::string AsmStr = IA->getAsmString();
13860   SmallVector<StringRef, 4> AsmPieces;
13861   SplitString(AsmStr, AsmPieces, ";\n");
13862 
13863   switch (AsmPieces.size()) {
13864   default: return false;
13865   case 1:
13866     AsmStr = AsmPieces[0];
13867     AsmPieces.clear();
13868     SplitString(AsmStr, AsmPieces, " \t,");
13869 
13870     // rev $0, $1
13871     if (AsmPieces.size() == 3 &&
13872         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13873         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13874       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13875       if (Ty && Ty->getBitWidth() == 32)
13876         return IntrinsicLowering::LowerToByteSwap(CI);
13877     }
13878     break;
13879   }
13880 
13881   return false;
13882 }
13883 
13884 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13885   // At this point, we have to lower this constraint to something else, so we
13886   // lower it to an "r" or "w". However, by doing this we will force the result
13887   // to be in register, while the X constraint is much more permissive.
13888   //
13889   // Although we are correct (we are free to emit anything, without
13890   // constraints), we might break use cases that would expect us to be more
13891   // efficient and emit something else.
13892   if (!Subtarget->hasVFP2())
13893     return "r";
13894   if (ConstraintVT.isFloatingPoint())
13895     return "w";
13896   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13897      (ConstraintVT.getSizeInBits() == 64 ||
13898       ConstraintVT.getSizeInBits() == 128))
13899     return "w";
13900 
13901   return "r";
13902 }
13903 
13904 /// getConstraintType - Given a constraint letter, return the type of
13905 /// constraint it is for this target.
13906 ARMTargetLowering::ConstraintType
13907 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13908   if (Constraint.size() == 1) {
13909     switch (Constraint[0]) {
13910     default:  break;
13911     case 'l': return C_RegisterClass;
13912     case 'w': return C_RegisterClass;
13913     case 'h': return C_RegisterClass;
13914     case 'x': return C_RegisterClass;
13915     case 't': return C_RegisterClass;
13916     case 'j': return C_Other; // Constant for movw.
13917       // An address with a single base register. Due to the way we
13918       // currently handle addresses it is the same as an 'r' memory constraint.
13919     case 'Q': return C_Memory;
13920     }
13921   } else if (Constraint.size() == 2) {
13922     switch (Constraint[0]) {
13923     default: break;
13924     // All 'U+' constraints are addresses.
13925     case 'U': return C_Memory;
13926     }
13927   }
13928   return TargetLowering::getConstraintType(Constraint);
13929 }
13930 
13931 /// Examine constraint type and operand type and determine a weight value.
13932 /// This object must already have been set up with the operand type
13933 /// and the current alternative constraint selected.
13934 TargetLowering::ConstraintWeight
13935 ARMTargetLowering::getSingleConstraintMatchWeight(
13936     AsmOperandInfo &info, const char *constraint) const {
13937   ConstraintWeight weight = CW_Invalid;
13938   Value *CallOperandVal = info.CallOperandVal;
13939     // If we don't have a value, we can't do a match,
13940     // but allow it at the lowest weight.
13941   if (!CallOperandVal)
13942     return CW_Default;
13943   Type *type = CallOperandVal->getType();
13944   // Look at the constraint type.
13945   switch (*constraint) {
13946   default:
13947     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13948     break;
13949   case 'l':
13950     if (type->isIntegerTy()) {
13951       if (Subtarget->isThumb())
13952         weight = CW_SpecificReg;
13953       else
13954         weight = CW_Register;
13955     }
13956     break;
13957   case 'w':
13958     if (type->isFloatingPointTy())
13959       weight = CW_Register;
13960     break;
13961   }
13962   return weight;
13963 }
13964 
13965 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13966 
13967 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13968     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13969   if (Constraint.size() == 1) {
13970     // GCC ARM Constraint Letters
13971     switch (Constraint[0]) {
13972     case 'l': // Low regs or general regs.
13973       if (Subtarget->isThumb())
13974         return RCPair(0U, &ARM::tGPRRegClass);
13975       return RCPair(0U, &ARM::GPRRegClass);
13976     case 'h': // High regs or no regs.
13977       if (Subtarget->isThumb())
13978         return RCPair(0U, &ARM::hGPRRegClass);
13979       break;
13980     case 'r':
13981       if (Subtarget->isThumb1Only())
13982         return RCPair(0U, &ARM::tGPRRegClass);
13983       return RCPair(0U, &ARM::GPRRegClass);
13984     case 'w':
13985       if (VT == MVT::Other)
13986         break;
13987       if (VT == MVT::f32)
13988         return RCPair(0U, &ARM::SPRRegClass);
13989       if (VT.getSizeInBits() == 64)
13990         return RCPair(0U, &ARM::DPRRegClass);
13991       if (VT.getSizeInBits() == 128)
13992         return RCPair(0U, &ARM::QPRRegClass);
13993       break;
13994     case 'x':
13995       if (VT == MVT::Other)
13996         break;
13997       if (VT == MVT::f32)
13998         return RCPair(0U, &ARM::SPR_8RegClass);
13999       if (VT.getSizeInBits() == 64)
14000         return RCPair(0U, &ARM::DPR_8RegClass);
14001       if (VT.getSizeInBits() == 128)
14002         return RCPair(0U, &ARM::QPR_8RegClass);
14003       break;
14004     case 't':
14005       if (VT == MVT::Other)
14006         break;
14007       if (VT == MVT::f32 || VT == MVT::i32)
14008         return RCPair(0U, &ARM::SPRRegClass);
14009       if (VT.getSizeInBits() == 64)
14010         return RCPair(0U, &ARM::DPR_VFP2RegClass);
14011       if (VT.getSizeInBits() == 128)
14012         return RCPair(0U, &ARM::QPR_VFP2RegClass);
14013       break;
14014     }
14015   }
14016   if (StringRef("{cc}").equals_lower(Constraint))
14017     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
14018 
14019   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14020 }
14021 
14022 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14023 /// vector.  If it is invalid, don't add anything to Ops.
14024 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14025                                                      std::string &Constraint,
14026                                                      std::vector<SDValue>&Ops,
14027                                                      SelectionDAG &DAG) const {
14028   SDValue Result;
14029 
14030   // Currently only support length 1 constraints.
14031   if (Constraint.length() != 1) return;
14032 
14033   char ConstraintLetter = Constraint[0];
14034   switch (ConstraintLetter) {
14035   default: break;
14036   case 'j':
14037   case 'I': case 'J': case 'K': case 'L':
14038   case 'M': case 'N': case 'O':
14039     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
14040     if (!C)
14041       return;
14042 
14043     int64_t CVal64 = C->getSExtValue();
14044     int CVal = (int) CVal64;
14045     // None of these constraints allow values larger than 32 bits.  Check
14046     // that the value fits in an int.
14047     if (CVal != CVal64)
14048       return;
14049 
14050     switch (ConstraintLetter) {
14051       case 'j':
14052         // Constant suitable for movw, must be between 0 and
14053         // 65535.
14054         if (Subtarget->hasV6T2Ops())
14055           if (CVal >= 0 && CVal <= 65535)
14056             break;
14057         return;
14058       case 'I':
14059         if (Subtarget->isThumb1Only()) {
14060           // This must be a constant between 0 and 255, for ADD
14061           // immediates.
14062           if (CVal >= 0 && CVal <= 255)
14063             break;
14064         } else if (Subtarget->isThumb2()) {
14065           // A constant that can be used as an immediate value in a
14066           // data-processing instruction.
14067           if (ARM_AM::getT2SOImmVal(CVal) != -1)
14068             break;
14069         } else {
14070           // A constant that can be used as an immediate value in a
14071           // data-processing instruction.
14072           if (ARM_AM::getSOImmVal(CVal) != -1)
14073             break;
14074         }
14075         return;
14076 
14077       case 'J':
14078         if (Subtarget->isThumb1Only()) {
14079           // This must be a constant between -255 and -1, for negated ADD
14080           // immediates. This can be used in GCC with an "n" modifier that
14081           // prints the negated value, for use with SUB instructions. It is
14082           // not useful otherwise but is implemented for compatibility.
14083           if (CVal >= -255 && CVal <= -1)
14084             break;
14085         } else {
14086           // This must be a constant between -4095 and 4095. It is not clear
14087           // what this constraint is intended for. Implemented for
14088           // compatibility with GCC.
14089           if (CVal >= -4095 && CVal <= 4095)
14090             break;
14091         }
14092         return;
14093 
14094       case 'K':
14095         if (Subtarget->isThumb1Only()) {
14096           // A 32-bit value where only one byte has a nonzero value. Exclude
14097           // zero to match GCC. This constraint is used by GCC internally for
14098           // constants that can be loaded with a move/shift combination.
14099           // It is not useful otherwise but is implemented for compatibility.
14100           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
14101             break;
14102         } else if (Subtarget->isThumb2()) {
14103           // A constant whose bitwise inverse can be used as an immediate
14104           // value in a data-processing instruction. This can be used in GCC
14105           // with a "B" modifier that prints the inverted value, for use with
14106           // BIC and MVN instructions. It is not useful otherwise but is
14107           // implemented for compatibility.
14108           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
14109             break;
14110         } else {
14111           // A constant whose bitwise inverse can be used as an immediate
14112           // value in a data-processing instruction. This can be used in GCC
14113           // with a "B" modifier that prints the inverted value, for use with
14114           // BIC and MVN instructions. It is not useful otherwise but is
14115           // implemented for compatibility.
14116           if (ARM_AM::getSOImmVal(~CVal) != -1)
14117             break;
14118         }
14119         return;
14120 
14121       case 'L':
14122         if (Subtarget->isThumb1Only()) {
14123           // This must be a constant between -7 and 7,
14124           // for 3-operand ADD/SUB immediate instructions.
14125           if (CVal >= -7 && CVal < 7)
14126             break;
14127         } else if (Subtarget->isThumb2()) {
14128           // A constant whose negation can be used as an immediate value in a
14129           // data-processing instruction. This can be used in GCC with an "n"
14130           // modifier that prints the negated value, for use with SUB
14131           // instructions. It is not useful otherwise but is implemented for
14132           // compatibility.
14133           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
14134             break;
14135         } else {
14136           // A constant whose negation can be used as an immediate value in a
14137           // data-processing instruction. This can be used in GCC with an "n"
14138           // modifier that prints the negated value, for use with SUB
14139           // instructions. It is not useful otherwise but is implemented for
14140           // compatibility.
14141           if (ARM_AM::getSOImmVal(-CVal) != -1)
14142             break;
14143         }
14144         return;
14145 
14146       case 'M':
14147         if (Subtarget->isThumb1Only()) {
14148           // This must be a multiple of 4 between 0 and 1020, for
14149           // ADD sp + immediate.
14150           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
14151             break;
14152         } else {
14153           // A power of two or a constant between 0 and 32.  This is used in
14154           // GCC for the shift amount on shifted register operands, but it is
14155           // useful in general for any shift amounts.
14156           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
14157             break;
14158         }
14159         return;
14160 
14161       case 'N':
14162         if (Subtarget->isThumb()) {  // FIXME thumb2
14163           // This must be a constant between 0 and 31, for shift amounts.
14164           if (CVal >= 0 && CVal <= 31)
14165             break;
14166         }
14167         return;
14168 
14169       case 'O':
14170         if (Subtarget->isThumb()) {  // FIXME thumb2
14171           // This must be a multiple of 4 between -508 and 508, for
14172           // ADD/SUB sp = sp + immediate.
14173           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
14174             break;
14175         }
14176         return;
14177     }
14178     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
14179     break;
14180   }
14181 
14182   if (Result.getNode()) {
14183     Ops.push_back(Result);
14184     return;
14185   }
14186   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14187 }
14188 
14189 static RTLIB::Libcall getDivRemLibcall(
14190     const SDNode *N, MVT::SimpleValueType SVT) {
14191   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14192           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14193          "Unhandled Opcode in getDivRemLibcall");
14194   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14195                   N->getOpcode() == ISD::SREM;
14196   RTLIB::Libcall LC;
14197   switch (SVT) {
14198   default: llvm_unreachable("Unexpected request for libcall!");
14199   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
14200   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
14201   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
14202   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
14203   }
14204   return LC;
14205 }
14206 
14207 static TargetLowering::ArgListTy getDivRemArgList(
14208     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
14209   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14210           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14211          "Unhandled Opcode in getDivRemArgList");
14212   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14213                   N->getOpcode() == ISD::SREM;
14214   TargetLowering::ArgListTy Args;
14215   TargetLowering::ArgListEntry Entry;
14216   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14217     EVT ArgVT = N->getOperand(i).getValueType();
14218     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
14219     Entry.Node = N->getOperand(i);
14220     Entry.Ty = ArgTy;
14221     Entry.IsSExt = isSigned;
14222     Entry.IsZExt = !isSigned;
14223     Args.push_back(Entry);
14224   }
14225   if (Subtarget->isTargetWindows() && Args.size() >= 2)
14226     std::swap(Args[0], Args[1]);
14227   return Args;
14228 }
14229 
14230 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
14231   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
14232           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
14233           Subtarget->isTargetWindows()) &&
14234          "Register-based DivRem lowering only");
14235   unsigned Opcode = Op->getOpcode();
14236   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
14237          "Invalid opcode for Div/Rem lowering");
14238   bool isSigned = (Opcode == ISD::SDIVREM);
14239   EVT VT = Op->getValueType(0);
14240   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
14241   SDLoc dl(Op);
14242 
14243   // If the target has hardware divide, use divide + multiply + subtract:
14244   //     div = a / b
14245   //     rem = a - b * div
14246   //     return {div, rem}
14247   // This should be lowered into UDIV/SDIV + MLS later on.
14248   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
14249                                         : Subtarget->hasDivideInARMMode();
14250   if (hasDivide && Op->getValueType(0).isSimple() &&
14251       Op->getSimpleValueType(0) == MVT::i32) {
14252     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
14253     const SDValue Dividend = Op->getOperand(0);
14254     const SDValue Divisor = Op->getOperand(1);
14255     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
14256     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
14257     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
14258 
14259     SDValue Values[2] = {Div, Rem};
14260     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
14261   }
14262 
14263   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
14264                                        VT.getSimpleVT().SimpleTy);
14265   SDValue InChain = DAG.getEntryNode();
14266 
14267   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
14268                                                     DAG.getContext(),
14269                                                     Subtarget);
14270 
14271   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14272                                          getPointerTy(DAG.getDataLayout()));
14273 
14274   Type *RetTy = StructType::get(Ty, Ty);
14275 
14276   if (Subtarget->isTargetWindows())
14277     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
14278 
14279   TargetLowering::CallLoweringInfo CLI(DAG);
14280   CLI.setDebugLoc(dl).setChain(InChain)
14281     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
14282     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14283 
14284   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14285   return CallInfo.first;
14286 }
14287 
14288 // Lowers REM using divmod helpers
14289 // see RTABI section 4.2/4.3
14290 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
14291   // Build return types (div and rem)
14292   std::vector<Type*> RetTyParams;
14293   Type *RetTyElement;
14294 
14295   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
14296   default: llvm_unreachable("Unexpected request for libcall!");
14297   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
14298   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
14299   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
14300   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
14301   }
14302 
14303   RetTyParams.push_back(RetTyElement);
14304   RetTyParams.push_back(RetTyElement);
14305   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
14306   Type *RetTy = StructType::get(*DAG.getContext(), ret);
14307 
14308   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
14309                                                              SimpleTy);
14310   SDValue InChain = DAG.getEntryNode();
14311   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
14312                                                     Subtarget);
14313   bool isSigned = N->getOpcode() == ISD::SREM;
14314   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14315                                          getPointerTy(DAG.getDataLayout()));
14316 
14317   if (Subtarget->isTargetWindows())
14318     InChain = WinDBZCheckDenominator(DAG, N, InChain);
14319 
14320   // Lower call
14321   CallLoweringInfo CLI(DAG);
14322   CLI.setChain(InChain)
14323      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
14324      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
14325   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
14326 
14327   // Return second (rem) result operand (first contains div)
14328   SDNode *ResNode = CallResult.first.getNode();
14329   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
14330   return ResNode->getOperand(1);
14331 }
14332 
14333 SDValue
14334 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
14335   assert(Subtarget->isTargetWindows() && "unsupported target platform");
14336   SDLoc DL(Op);
14337 
14338   // Get the inputs.
14339   SDValue Chain = Op.getOperand(0);
14340   SDValue Size  = Op.getOperand(1);
14341 
14342   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
14343           "no-stack-arg-probe")) {
14344     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14345     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14346     Chain = SP.getValue(1);
14347     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
14348     if (Align)
14349       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
14350                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
14351     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
14352     SDValue Ops[2] = { SP, Chain };
14353     return DAG.getMergeValues(Ops, DL);
14354   }
14355 
14356   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
14357                               DAG.getConstant(2, DL, MVT::i32));
14358 
14359   SDValue Flag;
14360   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
14361   Flag = Chain.getValue(1);
14362 
14363   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14364   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
14365 
14366   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14367   Chain = NewSP.getValue(1);
14368 
14369   SDValue Ops[2] = { NewSP, Chain };
14370   return DAG.getMergeValues(Ops, DL);
14371 }
14372 
14373 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
14374   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
14375          "Unexpected type for custom-lowering FP_EXTEND");
14376 
14377   RTLIB::Libcall LC;
14378   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
14379 
14380   SDValue SrcVal = Op.getOperand(0);
14381   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14382                      SDLoc(Op)).first;
14383 }
14384 
14385 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14386   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
14387          Subtarget->isFPOnlySP() &&
14388          "Unexpected type for custom-lowering FP_ROUND");
14389 
14390   RTLIB::Libcall LC;
14391   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
14392 
14393   SDValue SrcVal = Op.getOperand(0);
14394   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14395                      SDLoc(Op)).first;
14396 }
14397 
14398 bool
14399 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14400   // The ARM target isn't yet aware of offsets.
14401   return false;
14402 }
14403 
14404 bool ARM::isBitFieldInvertedMask(unsigned v) {
14405   if (v == 0xffffffff)
14406     return false;
14407 
14408   // there can be 1's on either or both "outsides", all the "inside"
14409   // bits must be 0's
14410   return isShiftedMask_32(~v);
14411 }
14412 
14413 /// isFPImmLegal - Returns true if the target can instruction select the
14414 /// specified FP immediate natively. If false, the legalizer will
14415 /// materialize the FP immediate as a load from a constant pool.
14416 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14417   if (!Subtarget->hasVFP3())
14418     return false;
14419   if (VT == MVT::f16 && Subtarget->hasFullFP16())
14420     return ARM_AM::getFP16Imm(Imm) != -1;
14421   if (VT == MVT::f32)
14422     return ARM_AM::getFP32Imm(Imm) != -1;
14423   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
14424     return ARM_AM::getFP64Imm(Imm) != -1;
14425   return false;
14426 }
14427 
14428 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14429 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
14430 /// specified in the intrinsic calls.
14431 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14432                                            const CallInst &I,
14433                                            MachineFunction &MF,
14434                                            unsigned Intrinsic) const {
14435   switch (Intrinsic) {
14436   case Intrinsic::arm_neon_vld1:
14437   case Intrinsic::arm_neon_vld2:
14438   case Intrinsic::arm_neon_vld3:
14439   case Intrinsic::arm_neon_vld4:
14440   case Intrinsic::arm_neon_vld2lane:
14441   case Intrinsic::arm_neon_vld3lane:
14442   case Intrinsic::arm_neon_vld4lane:
14443   case Intrinsic::arm_neon_vld2dup:
14444   case Intrinsic::arm_neon_vld3dup:
14445   case Intrinsic::arm_neon_vld4dup: {
14446     Info.opc = ISD::INTRINSIC_W_CHAIN;
14447     // Conservatively set memVT to the entire set of vectors loaded.
14448     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14449     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14450     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14451     Info.ptrVal = I.getArgOperand(0);
14452     Info.offset = 0;
14453     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14454     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14455     // volatile loads with NEON intrinsics not supported
14456     Info.flags = MachineMemOperand::MOLoad;
14457     return true;
14458   }
14459   case Intrinsic::arm_neon_vld1x2:
14460   case Intrinsic::arm_neon_vld1x3:
14461   case Intrinsic::arm_neon_vld1x4: {
14462     Info.opc = ISD::INTRINSIC_W_CHAIN;
14463     // Conservatively set memVT to the entire set of vectors loaded.
14464     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14465     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14466     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14467     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
14468     Info.offset = 0;
14469     Info.align = 0;
14470     // volatile loads with NEON intrinsics not supported
14471     Info.flags = MachineMemOperand::MOLoad;
14472     return true;
14473   }
14474   case Intrinsic::arm_neon_vst1:
14475   case Intrinsic::arm_neon_vst2:
14476   case Intrinsic::arm_neon_vst3:
14477   case Intrinsic::arm_neon_vst4:
14478   case Intrinsic::arm_neon_vst2lane:
14479   case Intrinsic::arm_neon_vst3lane:
14480   case Intrinsic::arm_neon_vst4lane: {
14481     Info.opc = ISD::INTRINSIC_VOID;
14482     // Conservatively set memVT to the entire set of vectors stored.
14483     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14484     unsigned NumElts = 0;
14485     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14486       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14487       if (!ArgTy->isVectorTy())
14488         break;
14489       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14490     }
14491     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14492     Info.ptrVal = I.getArgOperand(0);
14493     Info.offset = 0;
14494     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14495     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14496     // volatile stores with NEON intrinsics not supported
14497     Info.flags = MachineMemOperand::MOStore;
14498     return true;
14499   }
14500   case Intrinsic::arm_neon_vst1x2:
14501   case Intrinsic::arm_neon_vst1x3:
14502   case Intrinsic::arm_neon_vst1x4: {
14503     Info.opc = ISD::INTRINSIC_VOID;
14504     // Conservatively set memVT to the entire set of vectors stored.
14505     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14506     unsigned NumElts = 0;
14507     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14508       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14509       if (!ArgTy->isVectorTy())
14510         break;
14511       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14512     }
14513     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14514     Info.ptrVal = I.getArgOperand(0);
14515     Info.offset = 0;
14516     Info.align = 0;
14517     // volatile stores with NEON intrinsics not supported
14518     Info.flags = MachineMemOperand::MOStore;
14519     return true;
14520   }
14521   case Intrinsic::arm_ldaex:
14522   case Intrinsic::arm_ldrex: {
14523     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14524     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
14525     Info.opc = ISD::INTRINSIC_W_CHAIN;
14526     Info.memVT = MVT::getVT(PtrTy->getElementType());
14527     Info.ptrVal = I.getArgOperand(0);
14528     Info.offset = 0;
14529     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14530     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14531     return true;
14532   }
14533   case Intrinsic::arm_stlex:
14534   case Intrinsic::arm_strex: {
14535     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14536     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
14537     Info.opc = ISD::INTRINSIC_W_CHAIN;
14538     Info.memVT = MVT::getVT(PtrTy->getElementType());
14539     Info.ptrVal = I.getArgOperand(1);
14540     Info.offset = 0;
14541     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14542     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14543     return true;
14544   }
14545   case Intrinsic::arm_stlexd:
14546   case Intrinsic::arm_strexd:
14547     Info.opc = ISD::INTRINSIC_W_CHAIN;
14548     Info.memVT = MVT::i64;
14549     Info.ptrVal = I.getArgOperand(2);
14550     Info.offset = 0;
14551     Info.align = 8;
14552     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14553     return true;
14554 
14555   case Intrinsic::arm_ldaexd:
14556   case Intrinsic::arm_ldrexd:
14557     Info.opc = ISD::INTRINSIC_W_CHAIN;
14558     Info.memVT = MVT::i64;
14559     Info.ptrVal = I.getArgOperand(0);
14560     Info.offset = 0;
14561     Info.align = 8;
14562     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14563     return true;
14564 
14565   default:
14566     break;
14567   }
14568 
14569   return false;
14570 }
14571 
14572 /// Returns true if it is beneficial to convert a load of a constant
14573 /// to just the constant itself.
14574 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14575                                                           Type *Ty) const {
14576   assert(Ty->isIntegerTy());
14577 
14578   unsigned Bits = Ty->getPrimitiveSizeInBits();
14579   if (Bits == 0 || Bits > 32)
14580     return false;
14581   return true;
14582 }
14583 
14584 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
14585                                                 unsigned Index) const {
14586   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
14587     return false;
14588 
14589   return (Index == 0 || Index == ResVT.getVectorNumElements());
14590 }
14591 
14592 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
14593                                         ARM_MB::MemBOpt Domain) const {
14594   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14595 
14596   // First, if the target has no DMB, see what fallback we can use.
14597   if (!Subtarget->hasDataBarrier()) {
14598     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14599     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14600     // here.
14601     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14602       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14603       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14604                         Builder.getInt32(0), Builder.getInt32(7),
14605                         Builder.getInt32(10), Builder.getInt32(5)};
14606       return Builder.CreateCall(MCR, args);
14607     } else {
14608       // Instead of using barriers, atomic accesses on these subtargets use
14609       // libcalls.
14610       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14611     }
14612   } else {
14613     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14614     // Only a full system barrier exists in the M-class architectures.
14615     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14616     Constant *CDomain = Builder.getInt32(Domain);
14617     return Builder.CreateCall(DMB, CDomain);
14618   }
14619 }
14620 
14621 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14622 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14623                                                  Instruction *Inst,
14624                                                  AtomicOrdering Ord) const {
14625   switch (Ord) {
14626   case AtomicOrdering::NotAtomic:
14627   case AtomicOrdering::Unordered:
14628     llvm_unreachable("Invalid fence: unordered/non-atomic");
14629   case AtomicOrdering::Monotonic:
14630   case AtomicOrdering::Acquire:
14631     return nullptr; // Nothing to do
14632   case AtomicOrdering::SequentiallyConsistent:
14633     if (!Inst->hasAtomicStore())
14634       return nullptr; // Nothing to do
14635     LLVM_FALLTHROUGH;
14636   case AtomicOrdering::Release:
14637   case AtomicOrdering::AcquireRelease:
14638     if (Subtarget->preferISHSTBarriers())
14639       return makeDMB(Builder, ARM_MB::ISHST);
14640     // FIXME: add a comment with a link to documentation justifying this.
14641     else
14642       return makeDMB(Builder, ARM_MB::ISH);
14643   }
14644   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14645 }
14646 
14647 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14648                                                   Instruction *Inst,
14649                                                   AtomicOrdering Ord) const {
14650   switch (Ord) {
14651   case AtomicOrdering::NotAtomic:
14652   case AtomicOrdering::Unordered:
14653     llvm_unreachable("Invalid fence: unordered/not-atomic");
14654   case AtomicOrdering::Monotonic:
14655   case AtomicOrdering::Release:
14656     return nullptr; // Nothing to do
14657   case AtomicOrdering::Acquire:
14658   case AtomicOrdering::AcquireRelease:
14659   case AtomicOrdering::SequentiallyConsistent:
14660     return makeDMB(Builder, ARM_MB::ISH);
14661   }
14662   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14663 }
14664 
14665 // Loads and stores less than 64-bits are already atomic; ones above that
14666 // are doomed anyway, so defer to the default libcall and blame the OS when
14667 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14668 // anything for those.
14669 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14670   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14671   return (Size == 64) && !Subtarget->isMClass();
14672 }
14673 
14674 // Loads and stores less than 64-bits are already atomic; ones above that
14675 // are doomed anyway, so defer to the default libcall and blame the OS when
14676 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14677 // anything for those.
14678 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14679 // guarantee, see DDI0406C ARM architecture reference manual,
14680 // sections A8.8.72-74 LDRD)
14681 TargetLowering::AtomicExpansionKind
14682 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14683   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14684   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14685                                                   : AtomicExpansionKind::None;
14686 }
14687 
14688 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14689 // and up to 64 bits on the non-M profiles
14690 TargetLowering::AtomicExpansionKind
14691 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14692   if (AI->isFloatingPointOperation())
14693     return AtomicExpansionKind::CmpXChg;
14694 
14695   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14696   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14697   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14698              ? AtomicExpansionKind::LLSC
14699              : AtomicExpansionKind::None;
14700 }
14701 
14702 TargetLowering::AtomicExpansionKind
14703 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
14704   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14705   // implement cmpxchg without spilling. If the address being exchanged is also
14706   // on the stack and close enough to the spill slot, this can lead to a
14707   // situation where the monitor always gets cleared and the atomic operation
14708   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14709   bool HasAtomicCmpXchg =
14710       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14711   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
14712     return AtomicExpansionKind::LLSC;
14713   return AtomicExpansionKind::None;
14714 }
14715 
14716 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14717     const Instruction *I) const {
14718   return InsertFencesForAtomic;
14719 }
14720 
14721 // This has so far only been implemented for MachO.
14722 bool ARMTargetLowering::useLoadStackGuardNode() const {
14723   return Subtarget->isTargetMachO();
14724 }
14725 
14726 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14727                                                   unsigned &Cost) const {
14728   // If we do not have NEON, vector types are not natively supported.
14729   if (!Subtarget->hasNEON())
14730     return false;
14731 
14732   // Floating point values and vector values map to the same register file.
14733   // Therefore, although we could do a store extract of a vector type, this is
14734   // better to leave at float as we have more freedom in the addressing mode for
14735   // those.
14736   if (VectorTy->isFPOrFPVectorTy())
14737     return false;
14738 
14739   // If the index is unknown at compile time, this is very expensive to lower
14740   // and it is not possible to combine the store with the extract.
14741   if (!isa<ConstantInt>(Idx))
14742     return false;
14743 
14744   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14745   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14746   // We can do a store + vector extract on any vector that fits perfectly in a D
14747   // or Q register.
14748   if (BitWidth == 64 || BitWidth == 128) {
14749     Cost = 0;
14750     return true;
14751   }
14752   return false;
14753 }
14754 
14755 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14756   return Subtarget->hasV6T2Ops();
14757 }
14758 
14759 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14760   return Subtarget->hasV6T2Ops();
14761 }
14762 
14763 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
14764   return !Subtarget->optForMinSize();
14765 }
14766 
14767 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14768                                          AtomicOrdering Ord) const {
14769   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14770   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14771   bool IsAcquire = isAcquireOrStronger(Ord);
14772 
14773   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14774   // intrinsic must return {i32, i32} and we have to recombine them into a
14775   // single i64 here.
14776   if (ValTy->getPrimitiveSizeInBits() == 64) {
14777     Intrinsic::ID Int =
14778         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14779     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14780 
14781     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14782     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14783 
14784     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14785     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14786     if (!Subtarget->isLittle())
14787       std::swap (Lo, Hi);
14788     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14789     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14790     return Builder.CreateOr(
14791         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14792   }
14793 
14794   Type *Tys[] = { Addr->getType() };
14795   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14796   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14797 
14798   return Builder.CreateTruncOrBitCast(
14799       Builder.CreateCall(Ldrex, Addr),
14800       cast<PointerType>(Addr->getType())->getElementType());
14801 }
14802 
14803 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14804     IRBuilder<> &Builder) const {
14805   if (!Subtarget->hasV7Ops())
14806     return;
14807   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14808   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14809 }
14810 
14811 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14812                                                Value *Addr,
14813                                                AtomicOrdering Ord) const {
14814   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14815   bool IsRelease = isReleaseOrStronger(Ord);
14816 
14817   // Since the intrinsics must have legal type, the i64 intrinsics take two
14818   // parameters: "i32, i32". We must marshal Val into the appropriate form
14819   // before the call.
14820   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14821     Intrinsic::ID Int =
14822         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14823     Function *Strex = Intrinsic::getDeclaration(M, Int);
14824     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14825 
14826     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14827     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14828     if (!Subtarget->isLittle())
14829       std::swap(Lo, Hi);
14830     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14831     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14832   }
14833 
14834   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14835   Type *Tys[] = { Addr->getType() };
14836   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14837 
14838   return Builder.CreateCall(
14839       Strex, {Builder.CreateZExtOrBitCast(
14840                   Val, Strex->getFunctionType()->getParamType(0)),
14841               Addr});
14842 }
14843 
14844 
14845 bool ARMTargetLowering::alignLoopsWithOptSize() const {
14846   return Subtarget->isMClass();
14847 }
14848 
14849 /// A helper function for determining the number of interleaved accesses we
14850 /// will generate when lowering accesses of the given type.
14851 unsigned
14852 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14853                                              const DataLayout &DL) const {
14854   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14855 }
14856 
14857 bool ARMTargetLowering::isLegalInterleavedAccessType(
14858     VectorType *VecTy, const DataLayout &DL) const {
14859 
14860   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14861   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14862 
14863   // Ensure the vector doesn't have f16 elements. Even though we could do an
14864   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14865   // f32.
14866   if (VecTy->getElementType()->isHalfTy())
14867     return false;
14868 
14869   // Ensure the number of vector elements is greater than 1.
14870   if (VecTy->getNumElements() < 2)
14871     return false;
14872 
14873   // Ensure the element type is legal.
14874   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14875     return false;
14876 
14877   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14878   // 128 will be split into multiple interleaved accesses.
14879   return VecSize == 64 || VecSize % 128 == 0;
14880 }
14881 
14882 /// Lower an interleaved load into a vldN intrinsic.
14883 ///
14884 /// E.g. Lower an interleaved load (Factor = 2):
14885 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14886 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14887 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14888 ///
14889 ///      Into:
14890 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14891 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14892 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14893 bool ARMTargetLowering::lowerInterleavedLoad(
14894     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14895     ArrayRef<unsigned> Indices, unsigned Factor) const {
14896   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14897          "Invalid interleave factor");
14898   assert(!Shuffles.empty() && "Empty shufflevector input");
14899   assert(Shuffles.size() == Indices.size() &&
14900          "Unmatched number of shufflevectors and indices");
14901 
14902   VectorType *VecTy = Shuffles[0]->getType();
14903   Type *EltTy = VecTy->getVectorElementType();
14904 
14905   const DataLayout &DL = LI->getModule()->getDataLayout();
14906 
14907   // Skip if we do not have NEON and skip illegal vector types. We can
14908   // "legalize" wide vector types into multiple interleaved accesses as long as
14909   // the vector types are divisible by 128.
14910   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14911     return false;
14912 
14913   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14914 
14915   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14916   // load integer vectors first and then convert to pointer vectors.
14917   if (EltTy->isPointerTy())
14918     VecTy =
14919         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14920 
14921   IRBuilder<> Builder(LI);
14922 
14923   // The base address of the load.
14924   Value *BaseAddr = LI->getPointerOperand();
14925 
14926   if (NumLoads > 1) {
14927     // If we're going to generate more than one load, reset the sub-vector type
14928     // to something legal.
14929     VecTy = VectorType::get(VecTy->getVectorElementType(),
14930                             VecTy->getVectorNumElements() / NumLoads);
14931 
14932     // We will compute the pointer operand of each load from the original base
14933     // address using GEPs. Cast the base address to a pointer to the scalar
14934     // element type.
14935     BaseAddr = Builder.CreateBitCast(
14936         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14937                       LI->getPointerAddressSpace()));
14938   }
14939 
14940   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14941 
14942   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14943   Type *Tys[] = {VecTy, Int8Ptr};
14944   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14945                                             Intrinsic::arm_neon_vld3,
14946                                             Intrinsic::arm_neon_vld4};
14947   Function *VldnFunc =
14948       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14949 
14950   // Holds sub-vectors extracted from the load intrinsic return values. The
14951   // sub-vectors are associated with the shufflevector instructions they will
14952   // replace.
14953   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14954 
14955   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14956     // If we're generating more than one load, compute the base address of
14957     // subsequent loads as an offset from the previous.
14958     if (LoadCount > 0)
14959       BaseAddr =
14960           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
14961                                      VecTy->getVectorNumElements() * Factor);
14962 
14963     SmallVector<Value *, 2> Ops;
14964     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14965     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14966 
14967     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14968 
14969     // Replace uses of each shufflevector with the corresponding vector loaded
14970     // by ldN.
14971     for (unsigned i = 0; i < Shuffles.size(); i++) {
14972       ShuffleVectorInst *SV = Shuffles[i];
14973       unsigned Index = Indices[i];
14974 
14975       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14976 
14977       // Convert the integer vector to pointer vector if the element is pointer.
14978       if (EltTy->isPointerTy())
14979         SubVec = Builder.CreateIntToPtr(
14980             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14981                                     VecTy->getVectorNumElements()));
14982 
14983       SubVecs[SV].push_back(SubVec);
14984     }
14985   }
14986 
14987   // Replace uses of the shufflevector instructions with the sub-vectors
14988   // returned by the load intrinsic. If a shufflevector instruction is
14989   // associated with more than one sub-vector, those sub-vectors will be
14990   // concatenated into a single wide vector.
14991   for (ShuffleVectorInst *SVI : Shuffles) {
14992     auto &SubVec = SubVecs[SVI];
14993     auto *WideVec =
14994         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14995     SVI->replaceAllUsesWith(WideVec);
14996   }
14997 
14998   return true;
14999 }
15000 
15001 /// Lower an interleaved store into a vstN intrinsic.
15002 ///
15003 /// E.g. Lower an interleaved store (Factor = 3):
15004 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
15005 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
15006 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
15007 ///
15008 ///      Into:
15009 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
15010 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
15011 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
15012 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
15013 ///
15014 /// Note that the new shufflevectors will be removed and we'll only generate one
15015 /// vst3 instruction in CodeGen.
15016 ///
15017 /// Example for a more general valid mask (Factor 3). Lower:
15018 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
15019 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
15020 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
15021 ///
15022 ///      Into:
15023 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
15024 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
15025 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
15026 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
15027 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
15028                                               ShuffleVectorInst *SVI,
15029                                               unsigned Factor) const {
15030   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
15031          "Invalid interleave factor");
15032 
15033   VectorType *VecTy = SVI->getType();
15034   assert(VecTy->getVectorNumElements() % Factor == 0 &&
15035          "Invalid interleaved store");
15036 
15037   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
15038   Type *EltTy = VecTy->getVectorElementType();
15039   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
15040 
15041   const DataLayout &DL = SI->getModule()->getDataLayout();
15042 
15043   // Skip if we do not have NEON and skip illegal vector types. We can
15044   // "legalize" wide vector types into multiple interleaved accesses as long as
15045   // the vector types are divisible by 128.
15046   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
15047     return false;
15048 
15049   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
15050 
15051   Value *Op0 = SVI->getOperand(0);
15052   Value *Op1 = SVI->getOperand(1);
15053   IRBuilder<> Builder(SI);
15054 
15055   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
15056   // vectors to integer vectors.
15057   if (EltTy->isPointerTy()) {
15058     Type *IntTy = DL.getIntPtrType(EltTy);
15059 
15060     // Convert to the corresponding integer vector.
15061     Type *IntVecTy =
15062         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
15063     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
15064     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
15065 
15066     SubVecTy = VectorType::get(IntTy, LaneLen);
15067   }
15068 
15069   // The base address of the store.
15070   Value *BaseAddr = SI->getPointerOperand();
15071 
15072   if (NumStores > 1) {
15073     // If we're going to generate more than one store, reset the lane length
15074     // and sub-vector type to something legal.
15075     LaneLen /= NumStores;
15076     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
15077 
15078     // We will compute the pointer operand of each store from the original base
15079     // address using GEPs. Cast the base address to a pointer to the scalar
15080     // element type.
15081     BaseAddr = Builder.CreateBitCast(
15082         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
15083                       SI->getPointerAddressSpace()));
15084   }
15085 
15086   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
15087 
15088   auto Mask = SVI->getShuffleMask();
15089 
15090   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
15091   Type *Tys[] = {Int8Ptr, SubVecTy};
15092   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
15093                                              Intrinsic::arm_neon_vst3,
15094                                              Intrinsic::arm_neon_vst4};
15095 
15096   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
15097     // If we generating more than one store, we compute the base address of
15098     // subsequent stores as an offset from the previous.
15099     if (StoreCount > 0)
15100       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
15101                                             BaseAddr, LaneLen * Factor);
15102 
15103     SmallVector<Value *, 6> Ops;
15104     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
15105 
15106     Function *VstNFunc =
15107         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
15108 
15109     // Split the shufflevector operands into sub vectors for the new vstN call.
15110     for (unsigned i = 0; i < Factor; i++) {
15111       unsigned IdxI = StoreCount * LaneLen * Factor + i;
15112       if (Mask[IdxI] >= 0) {
15113         Ops.push_back(Builder.CreateShuffleVector(
15114             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
15115       } else {
15116         unsigned StartMask = 0;
15117         for (unsigned j = 1; j < LaneLen; j++) {
15118           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
15119           if (Mask[IdxJ * Factor + IdxI] >= 0) {
15120             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
15121             break;
15122           }
15123         }
15124         // Note: If all elements in a chunk are undefs, StartMask=0!
15125         // Note: Filling undef gaps with random elements is ok, since
15126         // those elements were being written anyway (with undefs).
15127         // In the case of all undefs we're defaulting to using elems from 0
15128         // Note: StartMask cannot be negative, it's checked in
15129         // isReInterleaveMask
15130         Ops.push_back(Builder.CreateShuffleVector(
15131             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
15132       }
15133     }
15134 
15135     Ops.push_back(Builder.getInt32(SI->getAlignment()));
15136     Builder.CreateCall(VstNFunc, Ops);
15137   }
15138   return true;
15139 }
15140 
15141 enum HABaseType {
15142   HA_UNKNOWN = 0,
15143   HA_FLOAT,
15144   HA_DOUBLE,
15145   HA_VECT64,
15146   HA_VECT128
15147 };
15148 
15149 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
15150                                    uint64_t &Members) {
15151   if (auto *ST = dyn_cast<StructType>(Ty)) {
15152     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
15153       uint64_t SubMembers = 0;
15154       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
15155         return false;
15156       Members += SubMembers;
15157     }
15158   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
15159     uint64_t SubMembers = 0;
15160     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
15161       return false;
15162     Members += SubMembers * AT->getNumElements();
15163   } else if (Ty->isFloatTy()) {
15164     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
15165       return false;
15166     Members = 1;
15167     Base = HA_FLOAT;
15168   } else if (Ty->isDoubleTy()) {
15169     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
15170       return false;
15171     Members = 1;
15172     Base = HA_DOUBLE;
15173   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
15174     Members = 1;
15175     switch (Base) {
15176     case HA_FLOAT:
15177     case HA_DOUBLE:
15178       return false;
15179     case HA_VECT64:
15180       return VT->getBitWidth() == 64;
15181     case HA_VECT128:
15182       return VT->getBitWidth() == 128;
15183     case HA_UNKNOWN:
15184       switch (VT->getBitWidth()) {
15185       case 64:
15186         Base = HA_VECT64;
15187         return true;
15188       case 128:
15189         Base = HA_VECT128;
15190         return true;
15191       default:
15192         return false;
15193       }
15194     }
15195   }
15196 
15197   return (Members > 0 && Members <= 4);
15198 }
15199 
15200 /// Return the correct alignment for the current calling convention.
15201 unsigned
15202 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
15203                                                  DataLayout DL) const {
15204   if (!ArgTy->isVectorTy())
15205     return DL.getABITypeAlignment(ArgTy);
15206 
15207   // Avoid over-aligning vector parameters. It would require realigning the
15208   // stack and waste space for no real benefit.
15209   return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
15210 }
15211 
15212 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
15213 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
15214 /// passing according to AAPCS rules.
15215 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
15216     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15217   if (getEffectiveCallingConv(CallConv, isVarArg) !=
15218       CallingConv::ARM_AAPCS_VFP)
15219     return false;
15220 
15221   HABaseType Base = HA_UNKNOWN;
15222   uint64_t Members = 0;
15223   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
15224   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
15225 
15226   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
15227   return IsHA || IsIntArray;
15228 }
15229 
15230 unsigned ARMTargetLowering::getExceptionPointerRegister(
15231     const Constant *PersonalityFn) const {
15232   // Platforms which do not use SjLj EH may return values in these registers
15233   // via the personality function.
15234   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
15235 }
15236 
15237 unsigned ARMTargetLowering::getExceptionSelectorRegister(
15238     const Constant *PersonalityFn) const {
15239   // Platforms which do not use SjLj EH may return values in these registers
15240   // via the personality function.
15241   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
15242 }
15243 
15244 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15245   // Update IsSplitCSR in ARMFunctionInfo.
15246   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
15247   AFI->setIsSplitCSR(true);
15248 }
15249 
15250 void ARMTargetLowering::insertCopiesSplitCSR(
15251     MachineBasicBlock *Entry,
15252     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15253   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
15254   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15255   if (!IStart)
15256     return;
15257 
15258   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15259   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15260   MachineBasicBlock::iterator MBBI = Entry->begin();
15261   for (const MCPhysReg *I = IStart; *I; ++I) {
15262     const TargetRegisterClass *RC = nullptr;
15263     if (ARM::GPRRegClass.contains(*I))
15264       RC = &ARM::GPRRegClass;
15265     else if (ARM::DPRRegClass.contains(*I))
15266       RC = &ARM::DPRRegClass;
15267     else
15268       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15269 
15270     unsigned NewVR = MRI->createVirtualRegister(RC);
15271     // Create copy from CSR to a virtual register.
15272     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15273     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15274     // nounwind. If we want to generalize this later, we may need to emit
15275     // CFI pseudo-instructions.
15276     assert(Entry->getParent()->getFunction().hasFnAttribute(
15277                Attribute::NoUnwind) &&
15278            "Function should be nounwind in insertCopiesSplitCSR!");
15279     Entry->addLiveIn(*I);
15280     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15281         .addReg(*I);
15282 
15283     // Insert the copy-back instructions right before the terminator.
15284     for (auto *Exit : Exits)
15285       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15286               TII->get(TargetOpcode::COPY), *I)
15287           .addReg(NewVR);
15288   }
15289 }
15290 
15291 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
15292   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15293   TargetLoweringBase::finalizeLowering(MF);
15294 }
15295