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 void ARMTargetLowering::addMVEVectorTypes() {
225   // We 'support' these types up to bitcast/load/store level, regardless of
226   // MVE integer-only / float support. Only doing FP data processing on the FP
227   // vector types is inhibited at integer-only level.
228 
229   const MVT VecTypes[] = {
230       MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8,
231       MVT::v2f64, MVT::v4f32, MVT::v8f16,
232   };
233 
234   for (auto VT : VecTypes) {
235     addRegisterClass(VT, &ARM::QPRRegClass);
236     for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
237       setOperationAction(Opc, VT, Expand);
238     setOperationAction(ISD::BITCAST, VT, Legal);
239     setOperationAction(ISD::LOAD, VT, Legal);
240     setOperationAction(ISD::STORE, VT, Legal);
241   }
242 }
243 
244 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
245                                      const ARMSubtarget &STI)
246     : TargetLowering(TM), Subtarget(&STI) {
247   RegInfo = Subtarget->getRegisterInfo();
248   Itins = Subtarget->getInstrItineraryData();
249 
250   setBooleanContents(ZeroOrOneBooleanContent);
251   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
252 
253   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
254       !Subtarget->isTargetWatchOS()) {
255     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
256     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
257       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
258                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
259                                        : CallingConv::ARM_AAPCS);
260   }
261 
262   if (Subtarget->isTargetMachO()) {
263     // Uses VFP for Thumb libfuncs if available.
264     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
265         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
266       static const struct {
267         const RTLIB::Libcall Op;
268         const char * const Name;
269         const ISD::CondCode Cond;
270       } LibraryCalls[] = {
271         // Single-precision floating-point arithmetic.
272         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
273         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
274         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
275         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
276 
277         // Double-precision floating-point arithmetic.
278         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
279         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
280         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
281         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
282 
283         // Single-precision comparisons.
284         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
285         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
286         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
287         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
288         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
289         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
290         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
291         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
292 
293         // Double-precision comparisons.
294         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
295         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
296         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
297         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
298         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
299         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
300         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
301         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
302 
303         // Floating-point to integer conversions.
304         // i64 conversions are done via library routines even when generating VFP
305         // instructions, so use the same ones.
306         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
307         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
308         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
309         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
310 
311         // Conversions between floating types.
312         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
313         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
314 
315         // Integer to floating-point conversions.
316         // i64 conversions are done via library routines even when generating VFP
317         // instructions, so use the same ones.
318         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
319         // e.g., __floatunsidf vs. __floatunssidfvfp.
320         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
321         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
322         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
323         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
324       };
325 
326       for (const auto &LC : LibraryCalls) {
327         setLibcallName(LC.Op, LC.Name);
328         if (LC.Cond != ISD::SETCC_INVALID)
329           setCmpLibcallCC(LC.Op, LC.Cond);
330       }
331     }
332   }
333 
334   // These libcalls are not available in 32-bit.
335   setLibcallName(RTLIB::SHL_I128, nullptr);
336   setLibcallName(RTLIB::SRL_I128, nullptr);
337   setLibcallName(RTLIB::SRA_I128, nullptr);
338 
339   // RTLIB
340   if (Subtarget->isAAPCS_ABI() &&
341       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
342        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
343     static const struct {
344       const RTLIB::Libcall Op;
345       const char * const Name;
346       const CallingConv::ID CC;
347       const ISD::CondCode Cond;
348     } LibraryCalls[] = {
349       // Double-precision floating-point arithmetic helper functions
350       // RTABI chapter 4.1.2, Table 2
351       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
355 
356       // Double-precision floating-point comparison helper functions
357       // RTABI chapter 4.1.2, Table 3
358       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
359       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
360       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
361       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
362       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
363       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
364       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
365       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
366 
367       // Single-precision floating-point arithmetic helper functions
368       // RTABI chapter 4.1.2, Table 4
369       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373 
374       // Single-precision floating-point comparison helper functions
375       // RTABI chapter 4.1.2, Table 5
376       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
377       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
378       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
379       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
380       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
381       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
382       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
383       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
384 
385       // Floating-point to integer conversions.
386       // RTABI chapter 4.1.2, Table 6
387       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395 
396       // Conversions between floating types.
397       // RTABI chapter 4.1.2, Table 7
398       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401 
402       // Integer to floating-point conversions.
403       // RTABI chapter 4.1.2, Table 8
404       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412 
413       // Long long helper functions
414       // RTABI chapter 4.2, Table 9
415       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
419 
420       // Integer division functions
421       // RTABI chapter 4.3.1
422       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
423       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
424       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
425       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
426       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
427       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
428       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
429       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
430     };
431 
432     for (const auto &LC : LibraryCalls) {
433       setLibcallName(LC.Op, LC.Name);
434       setLibcallCallingConv(LC.Op, LC.CC);
435       if (LC.Cond != ISD::SETCC_INVALID)
436         setCmpLibcallCC(LC.Op, LC.Cond);
437     }
438 
439     // EABI dependent RTLIB
440     if (TM.Options.EABIVersion == EABI::EABI4 ||
441         TM.Options.EABIVersion == EABI::EABI5) {
442       static const struct {
443         const RTLIB::Libcall Op;
444         const char *const Name;
445         const CallingConv::ID CC;
446         const ISD::CondCode Cond;
447       } MemOpsLibraryCalls[] = {
448         // Memory operations
449         // RTABI chapter 4.3.4
450         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
451         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
452         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
453       };
454 
455       for (const auto &LC : MemOpsLibraryCalls) {
456         setLibcallName(LC.Op, LC.Name);
457         setLibcallCallingConv(LC.Op, LC.CC);
458         if (LC.Cond != ISD::SETCC_INVALID)
459           setCmpLibcallCC(LC.Op, LC.Cond);
460       }
461     }
462   }
463 
464   if (Subtarget->isTargetWindows()) {
465     static const struct {
466       const RTLIB::Libcall Op;
467       const char * const Name;
468       const CallingConv::ID CC;
469     } LibraryCalls[] = {
470       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
471       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
472       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
473       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
474       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
475       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
476       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
477       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
478     };
479 
480     for (const auto &LC : LibraryCalls) {
481       setLibcallName(LC.Op, LC.Name);
482       setLibcallCallingConv(LC.Op, LC.CC);
483     }
484   }
485 
486   // Use divmod compiler-rt calls for iOS 5.0 and later.
487   if (Subtarget->isTargetMachO() &&
488       !(Subtarget->isTargetIOS() &&
489         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
490     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
491     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
492   }
493 
494   // The half <-> float conversion functions are always soft-float on
495   // non-watchos platforms, but are needed for some targets which use a
496   // hard-float calling convention by default.
497   if (!Subtarget->isTargetWatchABI()) {
498     if (Subtarget->isAAPCS_ABI()) {
499       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
500       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
501       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
502     } else {
503       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
504       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
505       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
506     }
507   }
508 
509   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
510   // a __gnu_ prefix (which is the default).
511   if (Subtarget->isTargetAEABI()) {
512     static const struct {
513       const RTLIB::Libcall Op;
514       const char * const Name;
515       const CallingConv::ID CC;
516     } LibraryCalls[] = {
517       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
518       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
519       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
520     };
521 
522     for (const auto &LC : LibraryCalls) {
523       setLibcallName(LC.Op, LC.Name);
524       setLibcallCallingConv(LC.Op, LC.CC);
525     }
526   }
527 
528   if (Subtarget->isThumb1Only())
529     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
530   else
531     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
532 
533   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
534       !Subtarget->isThumb1Only()) {
535     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
536     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
537   }
538 
539   if (Subtarget->hasFullFP16()) {
540     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
541     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
542     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
543     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
544 
545     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
546     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
547   }
548 
549   for (MVT VT : MVT::vector_valuetypes()) {
550     for (MVT InnerVT : MVT::vector_valuetypes()) {
551       setTruncStoreAction(VT, InnerVT, Expand);
552       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
553       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
554       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
555     }
556 
557     setOperationAction(ISD::MULHS, VT, Expand);
558     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
559     setOperationAction(ISD::MULHU, VT, Expand);
560     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
561 
562     setOperationAction(ISD::BSWAP, VT, Expand);
563   }
564 
565   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
566   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
567 
568   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
569   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
570 
571   if (Subtarget->hasMVEIntegerOps())
572     addMVEVectorTypes();
573 
574   if (Subtarget->hasNEON()) {
575     addDRTypeForNEON(MVT::v2f32);
576     addDRTypeForNEON(MVT::v8i8);
577     addDRTypeForNEON(MVT::v4i16);
578     addDRTypeForNEON(MVT::v2i32);
579     addDRTypeForNEON(MVT::v1i64);
580 
581     addQRTypeForNEON(MVT::v4f32);
582     addQRTypeForNEON(MVT::v2f64);
583     addQRTypeForNEON(MVT::v16i8);
584     addQRTypeForNEON(MVT::v8i16);
585     addQRTypeForNEON(MVT::v4i32);
586     addQRTypeForNEON(MVT::v2i64);
587 
588     if (Subtarget->hasFullFP16()) {
589       addQRTypeForNEON(MVT::v8f16);
590       addDRTypeForNEON(MVT::v4f16);
591     }
592   }
593 
594   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
595     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
596     // none of Neon, MVE or VFP supports any arithmetic operations on it.
597     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
598     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
599     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
600     // FIXME: Code duplication: FDIV and FREM are expanded always, see
601     // ARMTargetLowering::addTypeForNEON method for details.
602     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
603     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
604     // FIXME: Create unittest.
605     // In another words, find a way when "copysign" appears in DAG with vector
606     // operands.
607     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
608     // FIXME: Code duplication: SETCC has custom operation action, see
609     // ARMTargetLowering::addTypeForNEON method for details.
610     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
611     // FIXME: Create unittest for FNEG and for FABS.
612     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
613     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
614     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
615     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
616     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
617     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
618     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
619     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
620     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
621     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
622     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
623     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
624     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
625     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
626     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
627     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
628     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
629     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
630   }
631 
632   if (Subtarget->hasNEON()) {
633     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
634     // supported for v4f32.
635     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
636     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
637     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
638     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
639     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
640     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
641     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
642     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
643     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
644     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
645     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
646     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
647     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
648     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
649 
650     // Mark v2f32 intrinsics.
651     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
652     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
653     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
654     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
655     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
656     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
657     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
658     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
659     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
660     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
661     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
662     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
663     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
664     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
665 
666     // Neon does not support some operations on v1i64 and v2i64 types.
667     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
668     // Custom handling for some quad-vector types to detect VMULL.
669     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
670     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
671     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
672     // Custom handling for some vector types to avoid expensive expansions
673     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
674     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
675     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
676     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
677     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
678     // a destination type that is wider than the source, and nor does
679     // it have a FP_TO_[SU]INT instruction with a narrower destination than
680     // source.
681     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
682     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
683     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
684     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
685     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
686     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
687     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
688     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
689 
690     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
691     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
692 
693     // NEON does not have single instruction CTPOP for vectors with element
694     // types wider than 8-bits.  However, custom lowering can leverage the
695     // v8i8/v16i8 vcnt instruction.
696     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
697     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
698     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
699     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
700     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
701     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
702 
703     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
704     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
705 
706     // NEON does not have single instruction CTTZ for vectors.
707     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
708     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
709     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
710     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
711 
712     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
713     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
714     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
715     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
716 
717     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
718     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
719     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
720     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
721 
722     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
723     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
724     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
725     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
726 
727     // NEON only has FMA instructions as of VFP4.
728     if (!Subtarget->hasVFP4Base()) {
729       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
730       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
731     }
732 
733     setTargetDAGCombine(ISD::INTRINSIC_VOID);
734     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
735     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
736     setTargetDAGCombine(ISD::SHL);
737     setTargetDAGCombine(ISD::SRL);
738     setTargetDAGCombine(ISD::SRA);
739     setTargetDAGCombine(ISD::SIGN_EXTEND);
740     setTargetDAGCombine(ISD::ZERO_EXTEND);
741     setTargetDAGCombine(ISD::ANY_EXTEND);
742     setTargetDAGCombine(ISD::BUILD_VECTOR);
743     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
744     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
745     setTargetDAGCombine(ISD::STORE);
746     setTargetDAGCombine(ISD::FP_TO_SINT);
747     setTargetDAGCombine(ISD::FP_TO_UINT);
748     setTargetDAGCombine(ISD::FDIV);
749     setTargetDAGCombine(ISD::LOAD);
750 
751     // It is legal to extload from v4i8 to v4i16 or v4i32.
752     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
753                    MVT::v2i32}) {
754       for (MVT VT : MVT::integer_vector_valuetypes()) {
755         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
756         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
757         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
758       }
759     }
760   }
761 
762   if (!Subtarget->hasFP64()) {
763     // When targeting a floating-point unit with only single-precision
764     // operations, f64 is legal for the few double-precision instructions which
765     // are present However, no double-precision operations other than moves,
766     // loads and stores are provided by the hardware.
767     setOperationAction(ISD::FADD,       MVT::f64, Expand);
768     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
769     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
770     setOperationAction(ISD::FMA,        MVT::f64, Expand);
771     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
772     setOperationAction(ISD::FREM,       MVT::f64, Expand);
773     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
774     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
775     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
776     setOperationAction(ISD::FABS,       MVT::f64, Expand);
777     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
778     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
779     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
780     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
781     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
782     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
783     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
784     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
785     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
786     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
787     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
788     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
789     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
790     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
791     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
792     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
793     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
794     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
795     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
796     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
797     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
798   }
799 
800   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()){
801     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
802     setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
803   }
804 
805   if (!Subtarget->hasFP16())
806     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
807 
808   if (!Subtarget->hasFP64())
809     setOperationAction(ISD::FP_ROUND,  MVT::f32, Custom);
810 
811   computeRegisterProperties(Subtarget->getRegisterInfo());
812 
813   // ARM does not have floating-point extending loads.
814   for (MVT VT : MVT::fp_valuetypes()) {
815     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
816     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
817   }
818 
819   // ... or truncating stores
820   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
821   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
822   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
823 
824   // ARM does not have i1 sign extending load.
825   for (MVT VT : MVT::integer_valuetypes())
826     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
827 
828   // ARM supports all 4 flavors of integer indexed load / store.
829   if (!Subtarget->isThumb1Only()) {
830     for (unsigned im = (unsigned)ISD::PRE_INC;
831          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
832       setIndexedLoadAction(im,  MVT::i1,  Legal);
833       setIndexedLoadAction(im,  MVT::i8,  Legal);
834       setIndexedLoadAction(im,  MVT::i16, Legal);
835       setIndexedLoadAction(im,  MVT::i32, Legal);
836       setIndexedStoreAction(im, MVT::i1,  Legal);
837       setIndexedStoreAction(im, MVT::i8,  Legal);
838       setIndexedStoreAction(im, MVT::i16, Legal);
839       setIndexedStoreAction(im, MVT::i32, Legal);
840     }
841   } else {
842     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
843     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
844     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
845   }
846 
847   setOperationAction(ISD::SADDO, MVT::i32, Custom);
848   setOperationAction(ISD::UADDO, MVT::i32, Custom);
849   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
850   setOperationAction(ISD::USUBO, MVT::i32, Custom);
851 
852   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
853   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
854 
855   // i64 operation support.
856   setOperationAction(ISD::MUL,     MVT::i64, Expand);
857   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
858   if (Subtarget->isThumb1Only()) {
859     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
860     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
861   }
862   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
863       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
864     setOperationAction(ISD::MULHS, MVT::i32, Expand);
865 
866   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
867   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
868   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
869   setOperationAction(ISD::SRL,       MVT::i64, Custom);
870   setOperationAction(ISD::SRA,       MVT::i64, Custom);
871   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
872 
873   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
874   if (Subtarget->isThumb1Only()) {
875     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
876     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
877     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
878   }
879 
880   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
881     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
882 
883   // ARM does not have ROTL.
884   setOperationAction(ISD::ROTL, MVT::i32, Expand);
885   for (MVT VT : MVT::vector_valuetypes()) {
886     setOperationAction(ISD::ROTL, VT, Expand);
887     setOperationAction(ISD::ROTR, VT, Expand);
888   }
889   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
890   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
891   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
892     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
893     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
894   }
895 
896   // @llvm.readcyclecounter requires the Performance Monitors extension.
897   // Default to the 0 expansion on unsupported platforms.
898   // FIXME: Technically there are older ARM CPUs that have
899   // implementation-specific ways of obtaining this information.
900   if (Subtarget->hasPerfMon())
901     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
902 
903   // Only ARMv6 has BSWAP.
904   if (!Subtarget->hasV6Ops())
905     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
906 
907   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
908                                         : Subtarget->hasDivideInARMMode();
909   if (!hasDivide) {
910     // These are expanded into libcalls if the cpu doesn't have HW divider.
911     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
912     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
913   }
914 
915   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
916     setOperationAction(ISD::SDIV, MVT::i32, Custom);
917     setOperationAction(ISD::UDIV, MVT::i32, Custom);
918 
919     setOperationAction(ISD::SDIV, MVT::i64, Custom);
920     setOperationAction(ISD::UDIV, MVT::i64, Custom);
921   }
922 
923   setOperationAction(ISD::SREM,  MVT::i32, Expand);
924   setOperationAction(ISD::UREM,  MVT::i32, Expand);
925 
926   // Register based DivRem for AEABI (RTABI 4.2)
927   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
928       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
929       Subtarget->isTargetWindows()) {
930     setOperationAction(ISD::SREM, MVT::i64, Custom);
931     setOperationAction(ISD::UREM, MVT::i64, Custom);
932     HasStandaloneRem = false;
933 
934     if (Subtarget->isTargetWindows()) {
935       const struct {
936         const RTLIB::Libcall Op;
937         const char * const Name;
938         const CallingConv::ID CC;
939       } LibraryCalls[] = {
940         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
941         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
942         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
943         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
944 
945         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
946         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
947         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
948         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
949       };
950 
951       for (const auto &LC : LibraryCalls) {
952         setLibcallName(LC.Op, LC.Name);
953         setLibcallCallingConv(LC.Op, LC.CC);
954       }
955     } else {
956       const struct {
957         const RTLIB::Libcall Op;
958         const char * const Name;
959         const CallingConv::ID CC;
960       } LibraryCalls[] = {
961         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
962         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
963         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
964         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
965 
966         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
967         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
968         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
969         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
970       };
971 
972       for (const auto &LC : LibraryCalls) {
973         setLibcallName(LC.Op, LC.Name);
974         setLibcallCallingConv(LC.Op, LC.CC);
975       }
976     }
977 
978     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
979     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
980     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
981     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
982   } else {
983     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
984     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
985   }
986 
987   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
988     for (auto &VT : {MVT::f32, MVT::f64})
989       setOperationAction(ISD::FPOWI, VT, Custom);
990 
991   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
992   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
993   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
994   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
995 
996   setOperationAction(ISD::TRAP, MVT::Other, Legal);
997   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
998 
999   // Use the default implementation.
1000   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1001   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1002   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1003   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1004   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1005   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1006 
1007   if (Subtarget->isTargetWindows())
1008     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1009   else
1010     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1011 
1012   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1013   // the default expansion.
1014   InsertFencesForAtomic = false;
1015   if (Subtarget->hasAnyDataBarrier() &&
1016       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1017     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1018     // to ldrex/strex loops already.
1019     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1020     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1021       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1022 
1023     // On v8, we have particularly efficient implementations of atomic fences
1024     // if they can be combined with nearby atomic loads and stores.
1025     if (!Subtarget->hasAcquireRelease() ||
1026         getTargetMachine().getOptLevel() == 0) {
1027       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1028       InsertFencesForAtomic = true;
1029     }
1030   } else {
1031     // If there's anything we can use as a barrier, go through custom lowering
1032     // for ATOMIC_FENCE.
1033     // If target has DMB in thumb, Fences can be inserted.
1034     if (Subtarget->hasDataBarrier())
1035       InsertFencesForAtomic = true;
1036 
1037     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1038                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1039 
1040     // Set them all for expansion, which will force libcalls.
1041     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1042     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1043     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1044     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1045     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1046     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1047     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1048     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1049     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1050     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1051     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1052     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1053     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1054     // Unordered/Monotonic case.
1055     if (!InsertFencesForAtomic) {
1056       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1057       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1058     }
1059   }
1060 
1061   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1062 
1063   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1064   if (!Subtarget->hasV6Ops()) {
1065     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1066     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1067   }
1068   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1069 
1070   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1071       !Subtarget->isThumb1Only()) {
1072     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1073     // iff target supports vfp2.
1074     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1075     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1076   }
1077 
1078   // We want to custom lower some of our intrinsics.
1079   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1080   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1081   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1082   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1083   if (Subtarget->useSjLjEH())
1084     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1085 
1086   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1087   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1088   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1089   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1090   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1091   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1092   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1093   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1094   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1095   if (Subtarget->hasFullFP16()) {
1096     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1097     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1098     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1099   }
1100 
1101   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1102 
1103   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1104   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1105   if (Subtarget->hasFullFP16())
1106       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1107   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1108   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1109   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1110 
1111   // We don't support sin/cos/fmod/copysign/pow
1112   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1113   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1114   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1115   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1116   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1117   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1118   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1119   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1120   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1121       !Subtarget->isThumb1Only()) {
1122     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1123     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1124   }
1125   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1126   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1127 
1128   if (!Subtarget->hasVFP4Base()) {
1129     setOperationAction(ISD::FMA, MVT::f64, Expand);
1130     setOperationAction(ISD::FMA, MVT::f32, Expand);
1131   }
1132 
1133   // Various VFP goodness
1134   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1135     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1136     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1137       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1138       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1139     }
1140 
1141     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1142     if (!Subtarget->hasFP16()) {
1143       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1144       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1145     }
1146   }
1147 
1148   // Use __sincos_stret if available.
1149   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1150       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1151     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1152     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1153   }
1154 
1155   // FP-ARMv8 implements a lot of rounding-like FP operations.
1156   if (Subtarget->hasFPARMv8Base()) {
1157     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1158     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1159     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1160     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1161     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1162     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1163     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1164     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1165     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1166     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1167     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1168     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1169 
1170     if (Subtarget->hasFP64()) {
1171       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1172       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1173       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1174       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1175       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1176       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1177       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1178       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1179     }
1180   }
1181 
1182   // FP16 often need to be promoted to call lib functions
1183   if (Subtarget->hasFullFP16()) {
1184     setOperationAction(ISD::FREM, MVT::f16, Promote);
1185     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1186     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1187     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1188     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1189     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1190     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1191     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1192     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1193     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1194     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1195     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1196 
1197     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1198   }
1199 
1200   if (Subtarget->hasNEON()) {
1201     // vmin and vmax aren't available in a scalar form, so we use
1202     // a NEON instruction with an undef lane instead.
1203     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1204     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1205     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1206     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1207     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1208     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1209     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1210     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1211 
1212     if (Subtarget->hasFullFP16()) {
1213       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1214       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1215       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1216       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1217 
1218       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1219       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1220       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1221       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1222     }
1223   }
1224 
1225   // We have target-specific dag combine patterns for the following nodes:
1226   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1227   setTargetDAGCombine(ISD::ADD);
1228   setTargetDAGCombine(ISD::SUB);
1229   setTargetDAGCombine(ISD::MUL);
1230   setTargetDAGCombine(ISD::AND);
1231   setTargetDAGCombine(ISD::OR);
1232   setTargetDAGCombine(ISD::XOR);
1233 
1234   if (Subtarget->hasV6Ops())
1235     setTargetDAGCombine(ISD::SRL);
1236   if (Subtarget->isThumb1Only())
1237     setTargetDAGCombine(ISD::SHL);
1238 
1239   setStackPointerRegisterToSaveRestore(ARM::SP);
1240 
1241   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1242       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1243     setSchedulingPreference(Sched::RegPressure);
1244   else
1245     setSchedulingPreference(Sched::Hybrid);
1246 
1247   //// temporary - rewrite interface to use type
1248   MaxStoresPerMemset = 8;
1249   MaxStoresPerMemsetOptSize = 4;
1250   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1251   MaxStoresPerMemcpyOptSize = 2;
1252   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1253   MaxStoresPerMemmoveOptSize = 2;
1254 
1255   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1256   // are at least 4 bytes aligned.
1257   setMinStackArgumentAlignment(4);
1258 
1259   // Prefer likely predicted branches to selects on out-of-order cores.
1260   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1261 
1262   setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1263 
1264   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1265 
1266   if (Subtarget->isThumb() || Subtarget->isThumb2())
1267     setTargetDAGCombine(ISD::ABS);
1268 }
1269 
1270 bool ARMTargetLowering::useSoftFloat() const {
1271   return Subtarget->useSoftFloat();
1272 }
1273 
1274 // FIXME: It might make sense to define the representative register class as the
1275 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1276 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1277 // SPR's representative would be DPR_VFP2. This should work well if register
1278 // pressure tracking were modified such that a register use would increment the
1279 // pressure of the register class's representative and all of it's super
1280 // classes' representatives transitively. We have not implemented this because
1281 // of the difficulty prior to coalescing of modeling operand register classes
1282 // due to the common occurrence of cross class copies and subregister insertions
1283 // and extractions.
1284 std::pair<const TargetRegisterClass *, uint8_t>
1285 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1286                                            MVT VT) const {
1287   const TargetRegisterClass *RRC = nullptr;
1288   uint8_t Cost = 1;
1289   switch (VT.SimpleTy) {
1290   default:
1291     return TargetLowering::findRepresentativeClass(TRI, VT);
1292   // Use DPR as representative register class for all floating point
1293   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1294   // the cost is 1 for both f32 and f64.
1295   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1296   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1297     RRC = &ARM::DPRRegClass;
1298     // When NEON is used for SP, only half of the register file is available
1299     // because operations that define both SP and DP results will be constrained
1300     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1301     // coalescing by double-counting the SP regs. See the FIXME above.
1302     if (Subtarget->useNEONForSinglePrecisionFP())
1303       Cost = 2;
1304     break;
1305   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1306   case MVT::v4f32: case MVT::v2f64:
1307     RRC = &ARM::DPRRegClass;
1308     Cost = 2;
1309     break;
1310   case MVT::v4i64:
1311     RRC = &ARM::DPRRegClass;
1312     Cost = 4;
1313     break;
1314   case MVT::v8i64:
1315     RRC = &ARM::DPRRegClass;
1316     Cost = 8;
1317     break;
1318   }
1319   return std::make_pair(RRC, Cost);
1320 }
1321 
1322 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1323   switch ((ARMISD::NodeType)Opcode) {
1324   case ARMISD::FIRST_NUMBER:  break;
1325   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1326   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1327   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1328   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1329   case ARMISD::CALL:          return "ARMISD::CALL";
1330   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1331   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1332   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1333   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1334   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1335   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1336   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1337   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1338   case ARMISD::CMP:           return "ARMISD::CMP";
1339   case ARMISD::CMN:           return "ARMISD::CMN";
1340   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1341   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1342   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1343   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1344   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1345 
1346   case ARMISD::CMOV:          return "ARMISD::CMOV";
1347   case ARMISD::SUBS:          return "ARMISD::SUBS";
1348 
1349   case ARMISD::SSAT:          return "ARMISD::SSAT";
1350   case ARMISD::USAT:          return "ARMISD::USAT";
1351 
1352   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1353   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1354   case ARMISD::RRX:           return "ARMISD::RRX";
1355 
1356   case ARMISD::ADDC:          return "ARMISD::ADDC";
1357   case ARMISD::ADDE:          return "ARMISD::ADDE";
1358   case ARMISD::SUBC:          return "ARMISD::SUBC";
1359   case ARMISD::SUBE:          return "ARMISD::SUBE";
1360 
1361   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1362   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1363   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1364   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1365   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1366 
1367   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1368   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1369   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1370 
1371   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1372 
1373   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1374 
1375   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1376 
1377   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1378 
1379   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1380 
1381   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1382   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1383 
1384   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1385   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1386   case ARMISD::VCGE:          return "ARMISD::VCGE";
1387   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1388   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1389   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1390   case ARMISD::VCGT:          return "ARMISD::VCGT";
1391   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1392   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1393   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1394   case ARMISD::VTST:          return "ARMISD::VTST";
1395 
1396   case ARMISD::VSHL:          return "ARMISD::VSHL";
1397   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1398   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1399   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1400   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1401   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1402   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1403   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1404   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1405   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1406   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1407   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1408   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1409   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1410   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1411   case ARMISD::VSLI:          return "ARMISD::VSLI";
1412   case ARMISD::VSRI:          return "ARMISD::VSRI";
1413   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1414   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1415   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1416   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1417   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1418   case ARMISD::VDUP:          return "ARMISD::VDUP";
1419   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1420   case ARMISD::VEXT:          return "ARMISD::VEXT";
1421   case ARMISD::VREV64:        return "ARMISD::VREV64";
1422   case ARMISD::VREV32:        return "ARMISD::VREV32";
1423   case ARMISD::VREV16:        return "ARMISD::VREV16";
1424   case ARMISD::VZIP:          return "ARMISD::VZIP";
1425   case ARMISD::VUZP:          return "ARMISD::VUZP";
1426   case ARMISD::VTRN:          return "ARMISD::VTRN";
1427   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1428   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1429   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1430   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1431   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1432   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1433   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1434   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1435   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1436   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1437   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1438   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1439   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1440   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1441   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1442   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1443   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1444   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1445   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1446   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1447   case ARMISD::BFI:           return "ARMISD::BFI";
1448   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1449   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1450   case ARMISD::VBSL:          return "ARMISD::VBSL";
1451   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1452   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1453   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1454   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1455   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1456   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1457   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1458   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1459   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1460   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1461   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1462   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1463   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1464   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1465   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1466   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1467   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1468   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1469   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1470   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1471   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1472   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1473   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1474   }
1475   return nullptr;
1476 }
1477 
1478 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1479                                           EVT VT) const {
1480   if (!VT.isVector())
1481     return getPointerTy(DL);
1482   return VT.changeVectorElementTypeToInteger();
1483 }
1484 
1485 /// getRegClassFor - Return the register class that should be used for the
1486 /// specified value type.
1487 const TargetRegisterClass *
1488 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1489   (void)isDivergent;
1490   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1491   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1492   // load / store 4 to 8 consecutive D registers.
1493   if (Subtarget->hasNEON()) {
1494     if (VT == MVT::v4i64)
1495       return &ARM::QQPRRegClass;
1496     if (VT == MVT::v8i64)
1497       return &ARM::QQQQPRRegClass;
1498   }
1499   return TargetLowering::getRegClassFor(VT);
1500 }
1501 
1502 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1503 // source/dest is aligned and the copy size is large enough. We therefore want
1504 // to align such objects passed to memory intrinsics.
1505 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1506                                                unsigned &PrefAlign) const {
1507   if (!isa<MemIntrinsic>(CI))
1508     return false;
1509   MinSize = 8;
1510   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1511   // cycle faster than 4-byte aligned LDM.
1512   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1513   return true;
1514 }
1515 
1516 // Create a fast isel object.
1517 FastISel *
1518 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1519                                   const TargetLibraryInfo *libInfo) const {
1520   return ARM::createFastISel(funcInfo, libInfo);
1521 }
1522 
1523 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1524   unsigned NumVals = N->getNumValues();
1525   if (!NumVals)
1526     return Sched::RegPressure;
1527 
1528   for (unsigned i = 0; i != NumVals; ++i) {
1529     EVT VT = N->getValueType(i);
1530     if (VT == MVT::Glue || VT == MVT::Other)
1531       continue;
1532     if (VT.isFloatingPoint() || VT.isVector())
1533       return Sched::ILP;
1534   }
1535 
1536   if (!N->isMachineOpcode())
1537     return Sched::RegPressure;
1538 
1539   // Load are scheduled for latency even if there instruction itinerary
1540   // is not available.
1541   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1542   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1543 
1544   if (MCID.getNumDefs() == 0)
1545     return Sched::RegPressure;
1546   if (!Itins->isEmpty() &&
1547       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1548     return Sched::ILP;
1549 
1550   return Sched::RegPressure;
1551 }
1552 
1553 //===----------------------------------------------------------------------===//
1554 // Lowering Code
1555 //===----------------------------------------------------------------------===//
1556 
1557 static bool isSRL16(const SDValue &Op) {
1558   if (Op.getOpcode() != ISD::SRL)
1559     return false;
1560   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1561     return Const->getZExtValue() == 16;
1562   return false;
1563 }
1564 
1565 static bool isSRA16(const SDValue &Op) {
1566   if (Op.getOpcode() != ISD::SRA)
1567     return false;
1568   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1569     return Const->getZExtValue() == 16;
1570   return false;
1571 }
1572 
1573 static bool isSHL16(const SDValue &Op) {
1574   if (Op.getOpcode() != ISD::SHL)
1575     return false;
1576   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1577     return Const->getZExtValue() == 16;
1578   return false;
1579 }
1580 
1581 // Check for a signed 16-bit value. We special case SRA because it makes it
1582 // more simple when also looking for SRAs that aren't sign extending a
1583 // smaller value. Without the check, we'd need to take extra care with
1584 // checking order for some operations.
1585 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1586   if (isSRA16(Op))
1587     return isSHL16(Op.getOperand(0));
1588   return DAG.ComputeNumSignBits(Op) == 17;
1589 }
1590 
1591 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1592 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1593   switch (CC) {
1594   default: llvm_unreachable("Unknown condition code!");
1595   case ISD::SETNE:  return ARMCC::NE;
1596   case ISD::SETEQ:  return ARMCC::EQ;
1597   case ISD::SETGT:  return ARMCC::GT;
1598   case ISD::SETGE:  return ARMCC::GE;
1599   case ISD::SETLT:  return ARMCC::LT;
1600   case ISD::SETLE:  return ARMCC::LE;
1601   case ISD::SETUGT: return ARMCC::HI;
1602   case ISD::SETUGE: return ARMCC::HS;
1603   case ISD::SETULT: return ARMCC::LO;
1604   case ISD::SETULE: return ARMCC::LS;
1605   }
1606 }
1607 
1608 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1609 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1610                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1611   CondCode2 = ARMCC::AL;
1612   InvalidOnQNaN = true;
1613   switch (CC) {
1614   default: llvm_unreachable("Unknown FP condition!");
1615   case ISD::SETEQ:
1616   case ISD::SETOEQ:
1617     CondCode = ARMCC::EQ;
1618     InvalidOnQNaN = false;
1619     break;
1620   case ISD::SETGT:
1621   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1622   case ISD::SETGE:
1623   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1624   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1625   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1626   case ISD::SETONE:
1627     CondCode = ARMCC::MI;
1628     CondCode2 = ARMCC::GT;
1629     InvalidOnQNaN = false;
1630     break;
1631   case ISD::SETO:   CondCode = ARMCC::VC; break;
1632   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1633   case ISD::SETUEQ:
1634     CondCode = ARMCC::EQ;
1635     CondCode2 = ARMCC::VS;
1636     InvalidOnQNaN = false;
1637     break;
1638   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1639   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1640   case ISD::SETLT:
1641   case ISD::SETULT: CondCode = ARMCC::LT; break;
1642   case ISD::SETLE:
1643   case ISD::SETULE: CondCode = ARMCC::LE; break;
1644   case ISD::SETNE:
1645   case ISD::SETUNE:
1646     CondCode = ARMCC::NE;
1647     InvalidOnQNaN = false;
1648     break;
1649   }
1650 }
1651 
1652 //===----------------------------------------------------------------------===//
1653 //                      Calling Convention Implementation
1654 //===----------------------------------------------------------------------===//
1655 
1656 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1657 /// account presence of floating point hardware and calling convention
1658 /// limitations, such as support for variadic functions.
1659 CallingConv::ID
1660 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1661                                            bool isVarArg) const {
1662   switch (CC) {
1663   default:
1664     report_fatal_error("Unsupported calling convention");
1665   case CallingConv::ARM_AAPCS:
1666   case CallingConv::ARM_APCS:
1667   case CallingConv::GHC:
1668     return CC;
1669   case CallingConv::PreserveMost:
1670     return CallingConv::PreserveMost;
1671   case CallingConv::ARM_AAPCS_VFP:
1672   case CallingConv::Swift:
1673     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1674   case CallingConv::C:
1675     if (!Subtarget->isAAPCS_ABI())
1676       return CallingConv::ARM_APCS;
1677     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1678              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1679              !isVarArg)
1680       return CallingConv::ARM_AAPCS_VFP;
1681     else
1682       return CallingConv::ARM_AAPCS;
1683   case CallingConv::Fast:
1684   case CallingConv::CXX_FAST_TLS:
1685     if (!Subtarget->isAAPCS_ABI()) {
1686       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1687         return CallingConv::Fast;
1688       return CallingConv::ARM_APCS;
1689     } else if (Subtarget->hasVFP2Base() &&
1690                !Subtarget->isThumb1Only() && !isVarArg)
1691       return CallingConv::ARM_AAPCS_VFP;
1692     else
1693       return CallingConv::ARM_AAPCS;
1694   }
1695 }
1696 
1697 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1698                                                  bool isVarArg) const {
1699   return CCAssignFnForNode(CC, false, isVarArg);
1700 }
1701 
1702 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1703                                                    bool isVarArg) const {
1704   return CCAssignFnForNode(CC, true, isVarArg);
1705 }
1706 
1707 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1708 /// CallingConvention.
1709 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1710                                                  bool Return,
1711                                                  bool isVarArg) const {
1712   switch (getEffectiveCallingConv(CC, isVarArg)) {
1713   default:
1714     report_fatal_error("Unsupported calling convention");
1715   case CallingConv::ARM_APCS:
1716     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1717   case CallingConv::ARM_AAPCS:
1718     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1719   case CallingConv::ARM_AAPCS_VFP:
1720     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1721   case CallingConv::Fast:
1722     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1723   case CallingConv::GHC:
1724     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1725   case CallingConv::PreserveMost:
1726     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1727   }
1728 }
1729 
1730 /// LowerCallResult - Lower the result values of a call into the
1731 /// appropriate copies out of appropriate physical registers.
1732 SDValue ARMTargetLowering::LowerCallResult(
1733     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1734     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1735     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1736     SDValue ThisVal) const {
1737   // Assign locations to each value returned by this call.
1738   SmallVector<CCValAssign, 16> RVLocs;
1739   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1740                  *DAG.getContext());
1741   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1742 
1743   // Copy all of the result registers out of their specified physreg.
1744   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1745     CCValAssign VA = RVLocs[i];
1746 
1747     // Pass 'this' value directly from the argument to return value, to avoid
1748     // reg unit interference
1749     if (i == 0 && isThisReturn) {
1750       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1751              "unexpected return calling convention register assignment");
1752       InVals.push_back(ThisVal);
1753       continue;
1754     }
1755 
1756     SDValue Val;
1757     if (VA.needsCustom()) {
1758       // Handle f64 or half of a v2f64.
1759       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1760                                       InFlag);
1761       Chain = Lo.getValue(1);
1762       InFlag = Lo.getValue(2);
1763       VA = RVLocs[++i]; // skip ahead to next loc
1764       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1765                                       InFlag);
1766       Chain = Hi.getValue(1);
1767       InFlag = Hi.getValue(2);
1768       if (!Subtarget->isLittle())
1769         std::swap (Lo, Hi);
1770       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1771 
1772       if (VA.getLocVT() == MVT::v2f64) {
1773         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1774         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1775                           DAG.getConstant(0, dl, MVT::i32));
1776 
1777         VA = RVLocs[++i]; // skip ahead to next loc
1778         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1779         Chain = Lo.getValue(1);
1780         InFlag = Lo.getValue(2);
1781         VA = RVLocs[++i]; // skip ahead to next loc
1782         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1783         Chain = Hi.getValue(1);
1784         InFlag = Hi.getValue(2);
1785         if (!Subtarget->isLittle())
1786           std::swap (Lo, Hi);
1787         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1788         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1789                           DAG.getConstant(1, dl, MVT::i32));
1790       }
1791     } else {
1792       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1793                                InFlag);
1794       Chain = Val.getValue(1);
1795       InFlag = Val.getValue(2);
1796     }
1797 
1798     switch (VA.getLocInfo()) {
1799     default: llvm_unreachable("Unknown loc info!");
1800     case CCValAssign::Full: break;
1801     case CCValAssign::BCvt:
1802       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1803       break;
1804     }
1805 
1806     InVals.push_back(Val);
1807   }
1808 
1809   return Chain;
1810 }
1811 
1812 /// LowerMemOpCallTo - Store the argument to the stack.
1813 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1814                                             SDValue Arg, const SDLoc &dl,
1815                                             SelectionDAG &DAG,
1816                                             const CCValAssign &VA,
1817                                             ISD::ArgFlagsTy Flags) const {
1818   unsigned LocMemOffset = VA.getLocMemOffset();
1819   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1820   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1821                        StackPtr, PtrOff);
1822   return DAG.getStore(
1823       Chain, dl, Arg, PtrOff,
1824       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1825 }
1826 
1827 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1828                                          SDValue Chain, SDValue &Arg,
1829                                          RegsToPassVector &RegsToPass,
1830                                          CCValAssign &VA, CCValAssign &NextVA,
1831                                          SDValue &StackPtr,
1832                                          SmallVectorImpl<SDValue> &MemOpChains,
1833                                          ISD::ArgFlagsTy Flags) const {
1834   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1835                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1836   unsigned id = Subtarget->isLittle() ? 0 : 1;
1837   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1838 
1839   if (NextVA.isRegLoc())
1840     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1841   else {
1842     assert(NextVA.isMemLoc());
1843     if (!StackPtr.getNode())
1844       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1845                                     getPointerTy(DAG.getDataLayout()));
1846 
1847     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1848                                            dl, DAG, NextVA,
1849                                            Flags));
1850   }
1851 }
1852 
1853 /// LowerCall - Lowering a call into a callseq_start <-
1854 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1855 /// nodes.
1856 SDValue
1857 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1858                              SmallVectorImpl<SDValue> &InVals) const {
1859   SelectionDAG &DAG                     = CLI.DAG;
1860   SDLoc &dl                             = CLI.DL;
1861   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1862   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1863   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1864   SDValue Chain                         = CLI.Chain;
1865   SDValue Callee                        = CLI.Callee;
1866   bool &isTailCall                      = CLI.IsTailCall;
1867   CallingConv::ID CallConv              = CLI.CallConv;
1868   bool doesNotRet                       = CLI.DoesNotReturn;
1869   bool isVarArg                         = CLI.IsVarArg;
1870 
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1873   bool isThisReturn = false;
1874   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1875   bool PreferIndirect = false;
1876 
1877   // Disable tail calls if they're not supported.
1878   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1879     isTailCall = false;
1880 
1881   if (isa<GlobalAddressSDNode>(Callee)) {
1882     // If we're optimizing for minimum size and the function is called three or
1883     // more times in this block, we can improve codesize by calling indirectly
1884     // as BLXr has a 16-bit encoding.
1885     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1886     auto *BB = CLI.CS.getParent();
1887     PreferIndirect =
1888         Subtarget->isThumb() && Subtarget->hasMinSize() &&
1889         count_if(GV->users(), [&BB](const User *U) {
1890           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
1891         }) > 2;
1892   }
1893   if (isTailCall) {
1894     // Check if it's really possible to do a tail call.
1895     isTailCall = IsEligibleForTailCallOptimization(
1896         Callee, CallConv, isVarArg, isStructRet,
1897         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
1898         PreferIndirect);
1899     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1900       report_fatal_error("failed to perform tail call elimination on a call "
1901                          "site marked musttail");
1902     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1903     // detected sibcalls.
1904     if (isTailCall)
1905       ++NumTailCalls;
1906   }
1907 
1908   // Analyze operands of the call, assigning locations to each operand.
1909   SmallVector<CCValAssign, 16> ArgLocs;
1910   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1911                  *DAG.getContext());
1912   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1913 
1914   // Get a count of how many bytes are to be pushed on the stack.
1915   unsigned NumBytes = CCInfo.getNextStackOffset();
1916 
1917   if (isTailCall) {
1918     // For tail calls, memory operands are available in our caller's stack.
1919     NumBytes = 0;
1920   } else {
1921     // Adjust the stack pointer for the new arguments...
1922     // These operations are automatically eliminated by the prolog/epilog pass
1923     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1924   }
1925 
1926   SDValue StackPtr =
1927       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1928 
1929   RegsToPassVector RegsToPass;
1930   SmallVector<SDValue, 8> MemOpChains;
1931 
1932   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1933   // of tail call optimization, arguments are handled later.
1934   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1935        i != e;
1936        ++i, ++realArgIdx) {
1937     CCValAssign &VA = ArgLocs[i];
1938     SDValue Arg = OutVals[realArgIdx];
1939     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1940     bool isByVal = Flags.isByVal();
1941 
1942     // Promote the value if needed.
1943     switch (VA.getLocInfo()) {
1944     default: llvm_unreachable("Unknown loc info!");
1945     case CCValAssign::Full: break;
1946     case CCValAssign::SExt:
1947       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1948       break;
1949     case CCValAssign::ZExt:
1950       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1951       break;
1952     case CCValAssign::AExt:
1953       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1954       break;
1955     case CCValAssign::BCvt:
1956       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1957       break;
1958     }
1959 
1960     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1961     if (VA.needsCustom()) {
1962       if (VA.getLocVT() == MVT::v2f64) {
1963         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1964                                   DAG.getConstant(0, dl, MVT::i32));
1965         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1966                                   DAG.getConstant(1, dl, MVT::i32));
1967 
1968         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1969                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1970 
1971         VA = ArgLocs[++i]; // skip ahead to next loc
1972         if (VA.isRegLoc()) {
1973           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1974                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1975         } else {
1976           assert(VA.isMemLoc());
1977 
1978           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1979                                                  dl, DAG, VA, Flags));
1980         }
1981       } else {
1982         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1983                          StackPtr, MemOpChains, Flags);
1984       }
1985     } else if (VA.isRegLoc()) {
1986       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1987           Outs[0].VT == MVT::i32) {
1988         assert(VA.getLocVT() == MVT::i32 &&
1989                "unexpected calling convention register assignment");
1990         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1991                "unexpected use of 'returned'");
1992         isThisReturn = true;
1993       }
1994       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1995     } else if (isByVal) {
1996       assert(VA.isMemLoc());
1997       unsigned offset = 0;
1998 
1999       // True if this byval aggregate will be split between registers
2000       // and memory.
2001       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2002       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2003 
2004       if (CurByValIdx < ByValArgsCount) {
2005 
2006         unsigned RegBegin, RegEnd;
2007         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2008 
2009         EVT PtrVT =
2010             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2011         unsigned int i, j;
2012         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2013           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2014           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2015           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2016                                      MachinePointerInfo(),
2017                                      DAG.InferPtrAlignment(AddArg));
2018           MemOpChains.push_back(Load.getValue(1));
2019           RegsToPass.push_back(std::make_pair(j, Load));
2020         }
2021 
2022         // If parameter size outsides register area, "offset" value
2023         // helps us to calculate stack slot for remained part properly.
2024         offset = RegEnd - RegBegin;
2025 
2026         CCInfo.nextInRegsParam();
2027       }
2028 
2029       if (Flags.getByValSize() > 4*offset) {
2030         auto PtrVT = getPointerTy(DAG.getDataLayout());
2031         unsigned LocMemOffset = VA.getLocMemOffset();
2032         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2033         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2034         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2035         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2036         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2037                                            MVT::i32);
2038         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2039                                             MVT::i32);
2040 
2041         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2042         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2043         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2044                                           Ops));
2045       }
2046     } else if (!isTailCall) {
2047       assert(VA.isMemLoc());
2048 
2049       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2050                                              dl, DAG, VA, Flags));
2051     }
2052   }
2053 
2054   if (!MemOpChains.empty())
2055     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2056 
2057   // Build a sequence of copy-to-reg nodes chained together with token chain
2058   // and flag operands which copy the outgoing args into the appropriate regs.
2059   SDValue InFlag;
2060   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2061     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2062                              RegsToPass[i].second, InFlag);
2063     InFlag = Chain.getValue(1);
2064   }
2065 
2066   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2067   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2068   // node so that legalize doesn't hack it.
2069   bool isDirect = false;
2070 
2071   const TargetMachine &TM = getTargetMachine();
2072   const Module *Mod = MF.getFunction().getParent();
2073   const GlobalValue *GV = nullptr;
2074   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2075     GV = G->getGlobal();
2076   bool isStub =
2077       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2078 
2079   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2080   bool isLocalARMFunc = false;
2081   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2082   auto PtrVt = getPointerTy(DAG.getDataLayout());
2083 
2084   if (Subtarget->genLongCalls()) {
2085     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2086            "long-calls codegen is not position independent!");
2087     // Handle a global address or an external symbol. If it's not one of
2088     // those, the target's already in a register, so we don't need to do
2089     // anything extra.
2090     if (isa<GlobalAddressSDNode>(Callee)) {
2091       // Create a constant pool entry for the callee address
2092       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2093       ARMConstantPoolValue *CPV =
2094         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2095 
2096       // Get the address of the callee into a register
2097       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2098       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2099       Callee = DAG.getLoad(
2100           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2101           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2102     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2103       const char *Sym = S->getSymbol();
2104 
2105       // Create a constant pool entry for the callee address
2106       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2107       ARMConstantPoolValue *CPV =
2108         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2109                                       ARMPCLabelIndex, 0);
2110       // Get the address of the callee into a register
2111       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2112       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2113       Callee = DAG.getLoad(
2114           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2115           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2116     }
2117   } else if (isa<GlobalAddressSDNode>(Callee)) {
2118     if (!PreferIndirect) {
2119       isDirect = true;
2120       bool isDef = GV->isStrongDefinitionForLinker();
2121 
2122       // ARM call to a local ARM function is predicable.
2123       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2124       // tBX takes a register source operand.
2125       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2126         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2127         Callee = DAG.getNode(
2128             ARMISD::WrapperPIC, dl, PtrVt,
2129             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2130         Callee = DAG.getLoad(
2131             PtrVt, dl, DAG.getEntryNode(), Callee,
2132             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2133             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2134                                      MachineMemOperand::MOInvariant);
2135       } else if (Subtarget->isTargetCOFF()) {
2136         assert(Subtarget->isTargetWindows() &&
2137                "Windows is the only supported COFF target");
2138         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2139                                    ? ARMII::MO_DLLIMPORT
2140                                    : ARMII::MO_NO_FLAG;
2141         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2142                                             TargetFlags);
2143         if (GV->hasDLLImportStorageClass())
2144           Callee =
2145               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2146                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2147                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2148       } else {
2149         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2150       }
2151     }
2152   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2153     isDirect = true;
2154     // tBX takes a register source operand.
2155     const char *Sym = S->getSymbol();
2156     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2157       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2158       ARMConstantPoolValue *CPV =
2159         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2160                                       ARMPCLabelIndex, 4);
2161       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2162       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2163       Callee = DAG.getLoad(
2164           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2165           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2166       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2167       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2168     } else {
2169       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2170     }
2171   }
2172 
2173   // FIXME: handle tail calls differently.
2174   unsigned CallOpc;
2175   if (Subtarget->isThumb()) {
2176     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2177       CallOpc = ARMISD::CALL_NOLINK;
2178     else
2179       CallOpc = ARMISD::CALL;
2180   } else {
2181     if (!isDirect && !Subtarget->hasV5TOps())
2182       CallOpc = ARMISD::CALL_NOLINK;
2183     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2184              // Emit regular call when code size is the priority
2185              !Subtarget->hasMinSize())
2186       // "mov lr, pc; b _foo" to avoid confusing the RSP
2187       CallOpc = ARMISD::CALL_NOLINK;
2188     else
2189       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2190   }
2191 
2192   std::vector<SDValue> Ops;
2193   Ops.push_back(Chain);
2194   Ops.push_back(Callee);
2195 
2196   // Add argument registers to the end of the list so that they are known live
2197   // into the call.
2198   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2199     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2200                                   RegsToPass[i].second.getValueType()));
2201 
2202   // Add a register mask operand representing the call-preserved registers.
2203   if (!isTailCall) {
2204     const uint32_t *Mask;
2205     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2206     if (isThisReturn) {
2207       // For 'this' returns, use the R0-preserving mask if applicable
2208       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2209       if (!Mask) {
2210         // Set isThisReturn to false if the calling convention is not one that
2211         // allows 'returned' to be modeled in this way, so LowerCallResult does
2212         // not try to pass 'this' straight through
2213         isThisReturn = false;
2214         Mask = ARI->getCallPreservedMask(MF, CallConv);
2215       }
2216     } else
2217       Mask = ARI->getCallPreservedMask(MF, CallConv);
2218 
2219     assert(Mask && "Missing call preserved mask for calling convention");
2220     Ops.push_back(DAG.getRegisterMask(Mask));
2221   }
2222 
2223   if (InFlag.getNode())
2224     Ops.push_back(InFlag);
2225 
2226   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2227   if (isTailCall) {
2228     MF.getFrameInfo().setHasTailCall();
2229     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2230   }
2231 
2232   // Returns a chain and a flag for retval copy to use.
2233   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2234   InFlag = Chain.getValue(1);
2235 
2236   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2237                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2238   if (!Ins.empty())
2239     InFlag = Chain.getValue(1);
2240 
2241   // Handle result values, copying them out of physregs into vregs that we
2242   // return.
2243   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2244                          InVals, isThisReturn,
2245                          isThisReturn ? OutVals[0] : SDValue());
2246 }
2247 
2248 /// HandleByVal - Every parameter *after* a byval parameter is passed
2249 /// on the stack.  Remember the next parameter register to allocate,
2250 /// and then confiscate the rest of the parameter registers to insure
2251 /// this.
2252 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2253                                     unsigned Align) const {
2254   // Byval (as with any stack) slots are always at least 4 byte aligned.
2255   Align = std::max(Align, 4U);
2256 
2257   unsigned Reg = State->AllocateReg(GPRArgRegs);
2258   if (!Reg)
2259     return;
2260 
2261   unsigned AlignInRegs = Align / 4;
2262   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2263   for (unsigned i = 0; i < Waste; ++i)
2264     Reg = State->AllocateReg(GPRArgRegs);
2265 
2266   if (!Reg)
2267     return;
2268 
2269   unsigned Excess = 4 * (ARM::R4 - Reg);
2270 
2271   // Special case when NSAA != SP and parameter size greater than size of
2272   // all remained GPR regs. In that case we can't split parameter, we must
2273   // send it to stack. We also must set NCRN to R4, so waste all
2274   // remained registers.
2275   const unsigned NSAAOffset = State->getNextStackOffset();
2276   if (NSAAOffset != 0 && Size > Excess) {
2277     while (State->AllocateReg(GPRArgRegs))
2278       ;
2279     return;
2280   }
2281 
2282   // First register for byval parameter is the first register that wasn't
2283   // allocated before this method call, so it would be "reg".
2284   // If parameter is small enough to be saved in range [reg, r4), then
2285   // the end (first after last) register would be reg + param-size-in-regs,
2286   // else parameter would be splitted between registers and stack,
2287   // end register would be r4 in this case.
2288   unsigned ByValRegBegin = Reg;
2289   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2290   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2291   // Note, first register is allocated in the beginning of function already,
2292   // allocate remained amount of registers we need.
2293   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2294     State->AllocateReg(GPRArgRegs);
2295   // A byval parameter that is split between registers and memory needs its
2296   // size truncated here.
2297   // In the case where the entire structure fits in registers, we set the
2298   // size in memory to zero.
2299   Size = std::max<int>(Size - Excess, 0);
2300 }
2301 
2302 /// MatchingStackOffset - Return true if the given stack call argument is
2303 /// already available in the same position (relatively) of the caller's
2304 /// incoming argument stack.
2305 static
2306 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2307                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2308                          const TargetInstrInfo *TII) {
2309   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2310   int FI = std::numeric_limits<int>::max();
2311   if (Arg.getOpcode() == ISD::CopyFromReg) {
2312     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2313     if (!TargetRegisterInfo::isVirtualRegister(VR))
2314       return false;
2315     MachineInstr *Def = MRI->getVRegDef(VR);
2316     if (!Def)
2317       return false;
2318     if (!Flags.isByVal()) {
2319       if (!TII->isLoadFromStackSlot(*Def, FI))
2320         return false;
2321     } else {
2322       return false;
2323     }
2324   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2325     if (Flags.isByVal())
2326       // ByVal argument is passed in as a pointer but it's now being
2327       // dereferenced. e.g.
2328       // define @foo(%struct.X* %A) {
2329       //   tail call @bar(%struct.X* byval %A)
2330       // }
2331       return false;
2332     SDValue Ptr = Ld->getBasePtr();
2333     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2334     if (!FINode)
2335       return false;
2336     FI = FINode->getIndex();
2337   } else
2338     return false;
2339 
2340   assert(FI != std::numeric_limits<int>::max());
2341   if (!MFI.isFixedObjectIndex(FI))
2342     return false;
2343   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2344 }
2345 
2346 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2347 /// for tail call optimization. Targets which want to do tail call
2348 /// optimization should implement this function.
2349 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2350     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2351     bool isCalleeStructRet, bool isCallerStructRet,
2352     const SmallVectorImpl<ISD::OutputArg> &Outs,
2353     const SmallVectorImpl<SDValue> &OutVals,
2354     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2355     const bool isIndirect) const {
2356   MachineFunction &MF = DAG.getMachineFunction();
2357   const Function &CallerF = MF.getFunction();
2358   CallingConv::ID CallerCC = CallerF.getCallingConv();
2359 
2360   assert(Subtarget->supportsTailCall());
2361 
2362   // Indirect tail calls cannot be optimized for Thumb1 if the args
2363   // to the call take up r0-r3. The reason is that there are no legal registers
2364   // left to hold the pointer to the function to be called.
2365   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2366       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2367     return false;
2368 
2369   // Look for obvious safe cases to perform tail call optimization that do not
2370   // require ABI changes. This is what gcc calls sibcall.
2371 
2372   // Exception-handling functions need a special set of instructions to indicate
2373   // a return to the hardware. Tail-calling another function would probably
2374   // break this.
2375   if (CallerF.hasFnAttribute("interrupt"))
2376     return false;
2377 
2378   // Also avoid sibcall optimization if either caller or callee uses struct
2379   // return semantics.
2380   if (isCalleeStructRet || isCallerStructRet)
2381     return false;
2382 
2383   // Externally-defined functions with weak linkage should not be
2384   // tail-called on ARM when the OS does not support dynamic
2385   // pre-emption of symbols, as the AAELF spec requires normal calls
2386   // to undefined weak functions to be replaced with a NOP or jump to the
2387   // next instruction. The behaviour of branch instructions in this
2388   // situation (as used for tail calls) is implementation-defined, so we
2389   // cannot rely on the linker replacing the tail call with a return.
2390   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2391     const GlobalValue *GV = G->getGlobal();
2392     const Triple &TT = getTargetMachine().getTargetTriple();
2393     if (GV->hasExternalWeakLinkage() &&
2394         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2395       return false;
2396   }
2397 
2398   // Check that the call results are passed in the same way.
2399   LLVMContext &C = *DAG.getContext();
2400   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2401                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2402                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2403     return false;
2404   // The callee has to preserve all registers the caller needs to preserve.
2405   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2406   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2407   if (CalleeCC != CallerCC) {
2408     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2409     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2410       return false;
2411   }
2412 
2413   // If Caller's vararg or byval argument has been split between registers and
2414   // stack, do not perform tail call, since part of the argument is in caller's
2415   // local frame.
2416   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2417   if (AFI_Caller->getArgRegsSaveSize())
2418     return false;
2419 
2420   // If the callee takes no arguments then go on to check the results of the
2421   // call.
2422   if (!Outs.empty()) {
2423     // Check if stack adjustment is needed. For now, do not do this if any
2424     // argument is passed on the stack.
2425     SmallVector<CCValAssign, 16> ArgLocs;
2426     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2427     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2428     if (CCInfo.getNextStackOffset()) {
2429       // Check if the arguments are already laid out in the right way as
2430       // the caller's fixed stack objects.
2431       MachineFrameInfo &MFI = MF.getFrameInfo();
2432       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2433       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2434       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2435            i != e;
2436            ++i, ++realArgIdx) {
2437         CCValAssign &VA = ArgLocs[i];
2438         EVT RegVT = VA.getLocVT();
2439         SDValue Arg = OutVals[realArgIdx];
2440         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2441         if (VA.getLocInfo() == CCValAssign::Indirect)
2442           return false;
2443         if (VA.needsCustom()) {
2444           // f64 and vector types are split into multiple registers or
2445           // register/stack-slot combinations.  The types will not match
2446           // the registers; give up on memory f64 refs until we figure
2447           // out what to do about this.
2448           if (!VA.isRegLoc())
2449             return false;
2450           if (!ArgLocs[++i].isRegLoc())
2451             return false;
2452           if (RegVT == MVT::v2f64) {
2453             if (!ArgLocs[++i].isRegLoc())
2454               return false;
2455             if (!ArgLocs[++i].isRegLoc())
2456               return false;
2457           }
2458         } else if (!VA.isRegLoc()) {
2459           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2460                                    MFI, MRI, TII))
2461             return false;
2462         }
2463       }
2464     }
2465 
2466     const MachineRegisterInfo &MRI = MF.getRegInfo();
2467     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2468       return false;
2469   }
2470 
2471   return true;
2472 }
2473 
2474 bool
2475 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2476                                   MachineFunction &MF, bool isVarArg,
2477                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2478                                   LLVMContext &Context) const {
2479   SmallVector<CCValAssign, 16> RVLocs;
2480   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2481   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2482 }
2483 
2484 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2485                                     const SDLoc &DL, SelectionDAG &DAG) {
2486   const MachineFunction &MF = DAG.getMachineFunction();
2487   const Function &F = MF.getFunction();
2488 
2489   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2490 
2491   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2492   // version of the "preferred return address". These offsets affect the return
2493   // instruction if this is a return from PL1 without hypervisor extensions.
2494   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2495   //    SWI:     0      "subs pc, lr, #0"
2496   //    ABORT:   +4     "subs pc, lr, #4"
2497   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2498   // UNDEF varies depending on where the exception came from ARM or Thumb
2499   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2500 
2501   int64_t LROffset;
2502   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2503       IntKind == "ABORT")
2504     LROffset = 4;
2505   else if (IntKind == "SWI" || IntKind == "UNDEF")
2506     LROffset = 0;
2507   else
2508     report_fatal_error("Unsupported interrupt attribute. If present, value "
2509                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2510 
2511   RetOps.insert(RetOps.begin() + 1,
2512                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2513 
2514   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2515 }
2516 
2517 SDValue
2518 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2519                                bool isVarArg,
2520                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2521                                const SmallVectorImpl<SDValue> &OutVals,
2522                                const SDLoc &dl, SelectionDAG &DAG) const {
2523   // CCValAssign - represent the assignment of the return value to a location.
2524   SmallVector<CCValAssign, 16> RVLocs;
2525 
2526   // CCState - Info about the registers and stack slots.
2527   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2528                  *DAG.getContext());
2529 
2530   // Analyze outgoing return values.
2531   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2532 
2533   SDValue Flag;
2534   SmallVector<SDValue, 4> RetOps;
2535   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2536   bool isLittleEndian = Subtarget->isLittle();
2537 
2538   MachineFunction &MF = DAG.getMachineFunction();
2539   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2540   AFI->setReturnRegsCount(RVLocs.size());
2541 
2542   // Copy the result values into the output registers.
2543   for (unsigned i = 0, realRVLocIdx = 0;
2544        i != RVLocs.size();
2545        ++i, ++realRVLocIdx) {
2546     CCValAssign &VA = RVLocs[i];
2547     assert(VA.isRegLoc() && "Can only return in registers!");
2548 
2549     SDValue Arg = OutVals[realRVLocIdx];
2550     bool ReturnF16 = false;
2551 
2552     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2553       // Half-precision return values can be returned like this:
2554       //
2555       // t11 f16 = fadd ...
2556       // t12: i16 = bitcast t11
2557       //   t13: i32 = zero_extend t12
2558       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2559       //
2560       // to avoid code generation for bitcasts, we simply set Arg to the node
2561       // that produces the f16 value, t11 in this case.
2562       //
2563       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2564         SDValue ZE = Arg.getOperand(0);
2565         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2566           SDValue BC = ZE.getOperand(0);
2567           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2568             Arg = BC.getOperand(0);
2569             ReturnF16 = true;
2570           }
2571         }
2572       }
2573     }
2574 
2575     switch (VA.getLocInfo()) {
2576     default: llvm_unreachable("Unknown loc info!");
2577     case CCValAssign::Full: break;
2578     case CCValAssign::BCvt:
2579       if (!ReturnF16)
2580         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2581       break;
2582     }
2583 
2584     if (VA.needsCustom()) {
2585       if (VA.getLocVT() == MVT::v2f64) {
2586         // Extract the first half and return it in two registers.
2587         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2588                                    DAG.getConstant(0, dl, MVT::i32));
2589         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2590                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2591 
2592         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2593                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2594                                  Flag);
2595         Flag = Chain.getValue(1);
2596         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2597         VA = RVLocs[++i]; // skip ahead to next loc
2598         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2599                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2600                                  Flag);
2601         Flag = Chain.getValue(1);
2602         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2603         VA = RVLocs[++i]; // skip ahead to next loc
2604 
2605         // Extract the 2nd half and fall through to handle it as an f64 value.
2606         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2607                           DAG.getConstant(1, dl, MVT::i32));
2608       }
2609       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2610       // available.
2611       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2612                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2613       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2614                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2615                                Flag);
2616       Flag = Chain.getValue(1);
2617       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2618       VA = RVLocs[++i]; // skip ahead to next loc
2619       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2620                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2621                                Flag);
2622     } else
2623       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2624 
2625     // Guarantee that all emitted copies are
2626     // stuck together, avoiding something bad.
2627     Flag = Chain.getValue(1);
2628     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2629                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2630   }
2631   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2632   const MCPhysReg *I =
2633       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2634   if (I) {
2635     for (; *I; ++I) {
2636       if (ARM::GPRRegClass.contains(*I))
2637         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2638       else if (ARM::DPRRegClass.contains(*I))
2639         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2640       else
2641         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2642     }
2643   }
2644 
2645   // Update chain and glue.
2646   RetOps[0] = Chain;
2647   if (Flag.getNode())
2648     RetOps.push_back(Flag);
2649 
2650   // CPUs which aren't M-class use a special sequence to return from
2651   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2652   // though we use "subs pc, lr, #N").
2653   //
2654   // M-class CPUs actually use a normal return sequence with a special
2655   // (hardware-provided) value in LR, so the normal code path works.
2656   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2657       !Subtarget->isMClass()) {
2658     if (Subtarget->isThumb1Only())
2659       report_fatal_error("interrupt attribute is not supported in Thumb1");
2660     return LowerInterruptReturn(RetOps, dl, DAG);
2661   }
2662 
2663   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2664 }
2665 
2666 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2667   if (N->getNumValues() != 1)
2668     return false;
2669   if (!N->hasNUsesOfValue(1, 0))
2670     return false;
2671 
2672   SDValue TCChain = Chain;
2673   SDNode *Copy = *N->use_begin();
2674   if (Copy->getOpcode() == ISD::CopyToReg) {
2675     // If the copy has a glue operand, we conservatively assume it isn't safe to
2676     // perform a tail call.
2677     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2678       return false;
2679     TCChain = Copy->getOperand(0);
2680   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2681     SDNode *VMov = Copy;
2682     // f64 returned in a pair of GPRs.
2683     SmallPtrSet<SDNode*, 2> Copies;
2684     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2685          UI != UE; ++UI) {
2686       if (UI->getOpcode() != ISD::CopyToReg)
2687         return false;
2688       Copies.insert(*UI);
2689     }
2690     if (Copies.size() > 2)
2691       return false;
2692 
2693     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2694          UI != UE; ++UI) {
2695       SDValue UseChain = UI->getOperand(0);
2696       if (Copies.count(UseChain.getNode()))
2697         // Second CopyToReg
2698         Copy = *UI;
2699       else {
2700         // We are at the top of this chain.
2701         // If the copy has a glue operand, we conservatively assume it
2702         // isn't safe to perform a tail call.
2703         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2704           return false;
2705         // First CopyToReg
2706         TCChain = UseChain;
2707       }
2708     }
2709   } else if (Copy->getOpcode() == ISD::BITCAST) {
2710     // f32 returned in a single GPR.
2711     if (!Copy->hasOneUse())
2712       return false;
2713     Copy = *Copy->use_begin();
2714     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2715       return false;
2716     // If the copy has a glue operand, we conservatively assume it isn't safe to
2717     // perform a tail call.
2718     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2719       return false;
2720     TCChain = Copy->getOperand(0);
2721   } else {
2722     return false;
2723   }
2724 
2725   bool HasRet = false;
2726   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2727        UI != UE; ++UI) {
2728     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2729         UI->getOpcode() != ARMISD::INTRET_FLAG)
2730       return false;
2731     HasRet = true;
2732   }
2733 
2734   if (!HasRet)
2735     return false;
2736 
2737   Chain = TCChain;
2738   return true;
2739 }
2740 
2741 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2742   if (!Subtarget->supportsTailCall())
2743     return false;
2744 
2745   auto Attr =
2746       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2747   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2748     return false;
2749 
2750   return true;
2751 }
2752 
2753 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2754 // and pass the lower and high parts through.
2755 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2756   SDLoc DL(Op);
2757   SDValue WriteValue = Op->getOperand(2);
2758 
2759   // This function is only supposed to be called for i64 type argument.
2760   assert(WriteValue.getValueType() == MVT::i64
2761           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2762 
2763   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2764                            DAG.getConstant(0, DL, MVT::i32));
2765   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2766                            DAG.getConstant(1, DL, MVT::i32));
2767   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2768   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2769 }
2770 
2771 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2772 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2773 // one of the above mentioned nodes. It has to be wrapped because otherwise
2774 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2775 // be used to form addressing mode. These wrapped nodes will be selected
2776 // into MOVi.
2777 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2778                                              SelectionDAG &DAG) const {
2779   EVT PtrVT = Op.getValueType();
2780   // FIXME there is no actual debug info here
2781   SDLoc dl(Op);
2782   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2783   SDValue Res;
2784 
2785   // When generating execute-only code Constant Pools must be promoted to the
2786   // global data section. It's a bit ugly that we can't share them across basic
2787   // blocks, but this way we guarantee that execute-only behaves correct with
2788   // position-independent addressing modes.
2789   if (Subtarget->genExecuteOnly()) {
2790     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2791     auto T = const_cast<Type*>(CP->getType());
2792     auto C = const_cast<Constant*>(CP->getConstVal());
2793     auto M = const_cast<Module*>(DAG.getMachineFunction().
2794                                  getFunction().getParent());
2795     auto GV = new GlobalVariable(
2796                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2797                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2798                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2799                     Twine(AFI->createPICLabelUId())
2800                   );
2801     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2802                                             dl, PtrVT);
2803     return LowerGlobalAddress(GA, DAG);
2804   }
2805 
2806   if (CP->isMachineConstantPoolEntry())
2807     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2808                                     CP->getAlignment());
2809   else
2810     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2811                                     CP->getAlignment());
2812   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2813 }
2814 
2815 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2816   return MachineJumpTableInfo::EK_Inline;
2817 }
2818 
2819 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2820                                              SelectionDAG &DAG) const {
2821   MachineFunction &MF = DAG.getMachineFunction();
2822   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2823   unsigned ARMPCLabelIndex = 0;
2824   SDLoc DL(Op);
2825   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2826   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2827   SDValue CPAddr;
2828   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2829   if (!IsPositionIndependent) {
2830     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2831   } else {
2832     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2833     ARMPCLabelIndex = AFI->createPICLabelUId();
2834     ARMConstantPoolValue *CPV =
2835       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2836                                       ARMCP::CPBlockAddress, PCAdj);
2837     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2838   }
2839   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2840   SDValue Result = DAG.getLoad(
2841       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2842       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2843   if (!IsPositionIndependent)
2844     return Result;
2845   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2846   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2847 }
2848 
2849 /// Convert a TLS address reference into the correct sequence of loads
2850 /// and calls to compute the variable's address for Darwin, and return an
2851 /// SDValue containing the final node.
2852 
2853 /// Darwin only has one TLS scheme which must be capable of dealing with the
2854 /// fully general situation, in the worst case. This means:
2855 ///     + "extern __thread" declaration.
2856 ///     + Defined in a possibly unknown dynamic library.
2857 ///
2858 /// The general system is that each __thread variable has a [3 x i32] descriptor
2859 /// which contains information used by the runtime to calculate the address. The
2860 /// only part of this the compiler needs to know about is the first word, which
2861 /// contains a function pointer that must be called with the address of the
2862 /// entire descriptor in "r0".
2863 ///
2864 /// Since this descriptor may be in a different unit, in general access must
2865 /// proceed along the usual ARM rules. A common sequence to produce is:
2866 ///
2867 ///     movw rT1, :lower16:_var$non_lazy_ptr
2868 ///     movt rT1, :upper16:_var$non_lazy_ptr
2869 ///     ldr r0, [rT1]
2870 ///     ldr rT2, [r0]
2871 ///     blx rT2
2872 ///     [...address now in r0...]
2873 SDValue
2874 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2875                                                SelectionDAG &DAG) const {
2876   assert(Subtarget->isTargetDarwin() &&
2877          "This function expects a Darwin target");
2878   SDLoc DL(Op);
2879 
2880   // First step is to get the address of the actua global symbol. This is where
2881   // the TLS descriptor lives.
2882   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2883 
2884   // The first entry in the descriptor is a function pointer that we must call
2885   // to obtain the address of the variable.
2886   SDValue Chain = DAG.getEntryNode();
2887   SDValue FuncTLVGet = DAG.getLoad(
2888       MVT::i32, DL, Chain, DescAddr,
2889       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2890       /* Alignment = */ 4,
2891       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2892           MachineMemOperand::MOInvariant);
2893   Chain = FuncTLVGet.getValue(1);
2894 
2895   MachineFunction &F = DAG.getMachineFunction();
2896   MachineFrameInfo &MFI = F.getFrameInfo();
2897   MFI.setAdjustsStack(true);
2898 
2899   // TLS calls preserve all registers except those that absolutely must be
2900   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2901   // silly).
2902   auto TRI =
2903       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2904   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2905   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2906 
2907   // Finally, we can make the call. This is just a degenerate version of a
2908   // normal AArch64 call node: r0 takes the address of the descriptor, and
2909   // returns the address of the variable in this thread.
2910   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2911   Chain =
2912       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2913                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2914                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2915   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2916 }
2917 
2918 SDValue
2919 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2920                                                 SelectionDAG &DAG) const {
2921   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2922 
2923   SDValue Chain = DAG.getEntryNode();
2924   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2925   SDLoc DL(Op);
2926 
2927   // Load the current TEB (thread environment block)
2928   SDValue Ops[] = {Chain,
2929                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2930                    DAG.getConstant(15, DL, MVT::i32),
2931                    DAG.getConstant(0, DL, MVT::i32),
2932                    DAG.getConstant(13, DL, MVT::i32),
2933                    DAG.getConstant(0, DL, MVT::i32),
2934                    DAG.getConstant(2, DL, MVT::i32)};
2935   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2936                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2937 
2938   SDValue TEB = CurrentTEB.getValue(0);
2939   Chain = CurrentTEB.getValue(1);
2940 
2941   // Load the ThreadLocalStoragePointer from the TEB
2942   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2943   SDValue TLSArray =
2944       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2945   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2946 
2947   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2948   // offset into the TLSArray.
2949 
2950   // Load the TLS index from the C runtime
2951   SDValue TLSIndex =
2952       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2953   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2954   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2955 
2956   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2957                               DAG.getConstant(2, DL, MVT::i32));
2958   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2959                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2960                             MachinePointerInfo());
2961 
2962   // Get the offset of the start of the .tls section (section base)
2963   const auto *GA = cast<GlobalAddressSDNode>(Op);
2964   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2965   SDValue Offset = DAG.getLoad(
2966       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2967                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2968       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2969 
2970   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2971 }
2972 
2973 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2974 SDValue
2975 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2976                                                  SelectionDAG &DAG) const {
2977   SDLoc dl(GA);
2978   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2979   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2980   MachineFunction &MF = DAG.getMachineFunction();
2981   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2982   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2983   ARMConstantPoolValue *CPV =
2984     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2985                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2986   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2987   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2988   Argument = DAG.getLoad(
2989       PtrVT, dl, DAG.getEntryNode(), Argument,
2990       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2991   SDValue Chain = Argument.getValue(1);
2992 
2993   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2994   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2995 
2996   // call __tls_get_addr.
2997   ArgListTy Args;
2998   ArgListEntry Entry;
2999   Entry.Node = Argument;
3000   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3001   Args.push_back(Entry);
3002 
3003   // FIXME: is there useful debug info available here?
3004   TargetLowering::CallLoweringInfo CLI(DAG);
3005   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3006       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3007       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3008 
3009   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3010   return CallResult.first;
3011 }
3012 
3013 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3014 // "local exec" model.
3015 SDValue
3016 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3017                                         SelectionDAG &DAG,
3018                                         TLSModel::Model model) const {
3019   const GlobalValue *GV = GA->getGlobal();
3020   SDLoc dl(GA);
3021   SDValue Offset;
3022   SDValue Chain = DAG.getEntryNode();
3023   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3024   // Get the Thread Pointer
3025   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3026 
3027   if (model == TLSModel::InitialExec) {
3028     MachineFunction &MF = DAG.getMachineFunction();
3029     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3030     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3031     // Initial exec model.
3032     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3033     ARMConstantPoolValue *CPV =
3034       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3035                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3036                                       true);
3037     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3038     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3039     Offset = DAG.getLoad(
3040         PtrVT, dl, Chain, Offset,
3041         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3042     Chain = Offset.getValue(1);
3043 
3044     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3045     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3046 
3047     Offset = DAG.getLoad(
3048         PtrVT, dl, Chain, Offset,
3049         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3050   } else {
3051     // local exec model
3052     assert(model == TLSModel::LocalExec);
3053     ARMConstantPoolValue *CPV =
3054       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3055     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3056     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3057     Offset = DAG.getLoad(
3058         PtrVT, dl, Chain, Offset,
3059         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3060   }
3061 
3062   // The address of the thread local variable is the add of the thread
3063   // pointer with the offset of the variable.
3064   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3065 }
3066 
3067 SDValue
3068 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3069   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3070   if (DAG.getTarget().useEmulatedTLS())
3071     return LowerToTLSEmulatedModel(GA, DAG);
3072 
3073   if (Subtarget->isTargetDarwin())
3074     return LowerGlobalTLSAddressDarwin(Op, DAG);
3075 
3076   if (Subtarget->isTargetWindows())
3077     return LowerGlobalTLSAddressWindows(Op, DAG);
3078 
3079   // TODO: implement the "local dynamic" model
3080   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3081   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3082 
3083   switch (model) {
3084     case TLSModel::GeneralDynamic:
3085     case TLSModel::LocalDynamic:
3086       return LowerToTLSGeneralDynamicModel(GA, DAG);
3087     case TLSModel::InitialExec:
3088     case TLSModel::LocalExec:
3089       return LowerToTLSExecModels(GA, DAG, model);
3090   }
3091   llvm_unreachable("bogus TLS model");
3092 }
3093 
3094 /// Return true if all users of V are within function F, looking through
3095 /// ConstantExprs.
3096 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3097   SmallVector<const User*,4> Worklist;
3098   for (auto *U : V->users())
3099     Worklist.push_back(U);
3100   while (!Worklist.empty()) {
3101     auto *U = Worklist.pop_back_val();
3102     if (isa<ConstantExpr>(U)) {
3103       for (auto *UU : U->users())
3104         Worklist.push_back(UU);
3105       continue;
3106     }
3107 
3108     auto *I = dyn_cast<Instruction>(U);
3109     if (!I || I->getParent()->getParent() != F)
3110       return false;
3111   }
3112   return true;
3113 }
3114 
3115 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3116                                      const GlobalValue *GV, SelectionDAG &DAG,
3117                                      EVT PtrVT, const SDLoc &dl) {
3118   // If we're creating a pool entry for a constant global with unnamed address,
3119   // and the global is small enough, we can emit it inline into the constant pool
3120   // to save ourselves an indirection.
3121   //
3122   // This is a win if the constant is only used in one function (so it doesn't
3123   // need to be duplicated) or duplicating the constant wouldn't increase code
3124   // size (implying the constant is no larger than 4 bytes).
3125   const Function &F = DAG.getMachineFunction().getFunction();
3126 
3127   // We rely on this decision to inline being idemopotent and unrelated to the
3128   // use-site. We know that if we inline a variable at one use site, we'll
3129   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3130   // doesn't know about this optimization, so bail out if it's enabled else
3131   // we could decide to inline here (and thus never emit the GV) but require
3132   // the GV from fast-isel generated code.
3133   if (!EnableConstpoolPromotion ||
3134       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3135       return SDValue();
3136 
3137   auto *GVar = dyn_cast<GlobalVariable>(GV);
3138   if (!GVar || !GVar->hasInitializer() ||
3139       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3140       !GVar->hasLocalLinkage())
3141     return SDValue();
3142 
3143   // If we inline a value that contains relocations, we move the relocations
3144   // from .data to .text. This is not allowed in position-independent code.
3145   auto *Init = GVar->getInitializer();
3146   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3147       Init->needsRelocation())
3148     return SDValue();
3149 
3150   // The constant islands pass can only really deal with alignment requests
3151   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3152   // any type wanting greater alignment requirements than 4 bytes. We also
3153   // can only promote constants that are multiples of 4 bytes in size or
3154   // are paddable to a multiple of 4. Currently we only try and pad constants
3155   // that are strings for simplicity.
3156   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3157   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3158   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3159   unsigned RequiredPadding = 4 - (Size % 4);
3160   bool PaddingPossible =
3161     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3162   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3163       Size == 0)
3164     return SDValue();
3165 
3166   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3167   MachineFunction &MF = DAG.getMachineFunction();
3168   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3169 
3170   // We can't bloat the constant pool too much, else the ConstantIslands pass
3171   // may fail to converge. If we haven't promoted this global yet (it may have
3172   // multiple uses), and promoting it would increase the constant pool size (Sz
3173   // > 4), ensure we have space to do so up to MaxTotal.
3174   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3175     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3176         ConstpoolPromotionMaxTotal)
3177       return SDValue();
3178 
3179   // This is only valid if all users are in a single function; we can't clone
3180   // the constant in general. The LLVM IR unnamed_addr allows merging
3181   // constants, but not cloning them.
3182   //
3183   // We could potentially allow cloning if we could prove all uses of the
3184   // constant in the current function don't care about the address, like
3185   // printf format strings. But that isn't implemented for now.
3186   if (!allUsersAreInFunction(GVar, &F))
3187     return SDValue();
3188 
3189   // We're going to inline this global. Pad it out if needed.
3190   if (RequiredPadding != 4) {
3191     StringRef S = CDAInit->getAsString();
3192 
3193     SmallVector<uint8_t,16> V(S.size());
3194     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3195     while (RequiredPadding--)
3196       V.push_back(0);
3197     Init = ConstantDataArray::get(*DAG.getContext(), V);
3198   }
3199 
3200   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3201   SDValue CPAddr =
3202     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3203   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3204     AFI->markGlobalAsPromotedToConstantPool(GVar);
3205     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3206                                       PaddedSize - 4);
3207   }
3208   ++NumConstpoolPromoted;
3209   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3210 }
3211 
3212 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3213   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3214     if (!(GV = GA->getBaseObject()))
3215       return false;
3216   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3217     return V->isConstant();
3218   return isa<Function>(GV);
3219 }
3220 
3221 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3222                                               SelectionDAG &DAG) const {
3223   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3224   default: llvm_unreachable("unknown object format");
3225   case Triple::COFF:
3226     return LowerGlobalAddressWindows(Op, DAG);
3227   case Triple::ELF:
3228     return LowerGlobalAddressELF(Op, DAG);
3229   case Triple::MachO:
3230     return LowerGlobalAddressDarwin(Op, DAG);
3231   }
3232 }
3233 
3234 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3235                                                  SelectionDAG &DAG) const {
3236   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3237   SDLoc dl(Op);
3238   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3239   const TargetMachine &TM = getTargetMachine();
3240   bool IsRO = isReadOnly(GV);
3241 
3242   // promoteToConstantPool only if not generating XO text section
3243   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3244     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3245       return V;
3246 
3247   if (isPositionIndependent()) {
3248     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3249     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3250                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3251     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3252     if (UseGOT_PREL)
3253       Result =
3254           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3255                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3256     return Result;
3257   } else if (Subtarget->isROPI() && IsRO) {
3258     // PC-relative.
3259     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3260     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3261     return Result;
3262   } else if (Subtarget->isRWPI() && !IsRO) {
3263     // SB-relative.
3264     SDValue RelAddr;
3265     if (Subtarget->useMovt()) {
3266       ++NumMovwMovt;
3267       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3268       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3269     } else { // use literal pool for address constant
3270       ARMConstantPoolValue *CPV =
3271         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3272       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3273       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3274       RelAddr = DAG.getLoad(
3275           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3276           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3277     }
3278     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3279     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3280     return Result;
3281   }
3282 
3283   // If we have T2 ops, we can materialize the address directly via movt/movw
3284   // pair. This is always cheaper.
3285   if (Subtarget->useMovt()) {
3286     ++NumMovwMovt;
3287     // FIXME: Once remat is capable of dealing with instructions with register
3288     // operands, expand this into two nodes.
3289     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3290                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3291   } else {
3292     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3293     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3294     return DAG.getLoad(
3295         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3296         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3297   }
3298 }
3299 
3300 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3301                                                     SelectionDAG &DAG) const {
3302   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3303          "ROPI/RWPI not currently supported for Darwin");
3304   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3305   SDLoc dl(Op);
3306   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3307 
3308   if (Subtarget->useMovt())
3309     ++NumMovwMovt;
3310 
3311   // FIXME: Once remat is capable of dealing with instructions with register
3312   // operands, expand this into multiple nodes
3313   unsigned Wrapper =
3314       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3315 
3316   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3317   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3318 
3319   if (Subtarget->isGVIndirectSymbol(GV))
3320     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3321                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3322   return Result;
3323 }
3324 
3325 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3326                                                      SelectionDAG &DAG) const {
3327   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3328   assert(Subtarget->useMovt() &&
3329          "Windows on ARM expects to use movw/movt");
3330   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3331          "ROPI/RWPI not currently supported for Windows");
3332 
3333   const TargetMachine &TM = getTargetMachine();
3334   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3335   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3336   if (GV->hasDLLImportStorageClass())
3337     TargetFlags = ARMII::MO_DLLIMPORT;
3338   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3339     TargetFlags = ARMII::MO_COFFSTUB;
3340   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3341   SDValue Result;
3342   SDLoc DL(Op);
3343 
3344   ++NumMovwMovt;
3345 
3346   // FIXME: Once remat is capable of dealing with instructions with register
3347   // operands, expand this into two nodes.
3348   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3349                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3350                                                   TargetFlags));
3351   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3352     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3353                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3354   return Result;
3355 }
3356 
3357 SDValue
3358 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3359   SDLoc dl(Op);
3360   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3361   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3362                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3363                      Op.getOperand(1), Val);
3364 }
3365 
3366 SDValue
3367 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3368   SDLoc dl(Op);
3369   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3370                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3371 }
3372 
3373 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3374                                                       SelectionDAG &DAG) const {
3375   SDLoc dl(Op);
3376   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3377                      Op.getOperand(0));
3378 }
3379 
3380 SDValue
3381 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3382                                           const ARMSubtarget *Subtarget) const {
3383   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3384   SDLoc dl(Op);
3385   switch (IntNo) {
3386   default: return SDValue();    // Don't custom lower most intrinsics.
3387   case Intrinsic::thread_pointer: {
3388     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3389     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3390   }
3391   case Intrinsic::eh_sjlj_lsda: {
3392     MachineFunction &MF = DAG.getMachineFunction();
3393     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3394     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3395     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3396     SDValue CPAddr;
3397     bool IsPositionIndependent = isPositionIndependent();
3398     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3399     ARMConstantPoolValue *CPV =
3400       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3401                                       ARMCP::CPLSDA, PCAdj);
3402     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3403     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3404     SDValue Result = DAG.getLoad(
3405         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3406         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3407 
3408     if (IsPositionIndependent) {
3409       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3410       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3411     }
3412     return Result;
3413   }
3414   case Intrinsic::arm_neon_vabs:
3415     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3416                         Op.getOperand(1));
3417   case Intrinsic::arm_neon_vmulls:
3418   case Intrinsic::arm_neon_vmullu: {
3419     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3420       ? ARMISD::VMULLs : ARMISD::VMULLu;
3421     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3422                        Op.getOperand(1), Op.getOperand(2));
3423   }
3424   case Intrinsic::arm_neon_vminnm:
3425   case Intrinsic::arm_neon_vmaxnm: {
3426     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3427       ? ISD::FMINNUM : ISD::FMAXNUM;
3428     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3429                        Op.getOperand(1), Op.getOperand(2));
3430   }
3431   case Intrinsic::arm_neon_vminu:
3432   case Intrinsic::arm_neon_vmaxu: {
3433     if (Op.getValueType().isFloatingPoint())
3434       return SDValue();
3435     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3436       ? ISD::UMIN : ISD::UMAX;
3437     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3438                          Op.getOperand(1), Op.getOperand(2));
3439   }
3440   case Intrinsic::arm_neon_vmins:
3441   case Intrinsic::arm_neon_vmaxs: {
3442     // v{min,max}s is overloaded between signed integers and floats.
3443     if (!Op.getValueType().isFloatingPoint()) {
3444       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3445         ? ISD::SMIN : ISD::SMAX;
3446       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3447                          Op.getOperand(1), Op.getOperand(2));
3448     }
3449     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3450       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3451     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3452                        Op.getOperand(1), Op.getOperand(2));
3453   }
3454   case Intrinsic::arm_neon_vtbl1:
3455     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3456                        Op.getOperand(1), Op.getOperand(2));
3457   case Intrinsic::arm_neon_vtbl2:
3458     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3459                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3460   }
3461 }
3462 
3463 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3464                                  const ARMSubtarget *Subtarget) {
3465   SDLoc dl(Op);
3466   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3467   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3468   if (SSID == SyncScope::SingleThread)
3469     return Op;
3470 
3471   if (!Subtarget->hasDataBarrier()) {
3472     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3473     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3474     // here.
3475     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3476            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3477     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3478                        DAG.getConstant(0, dl, MVT::i32));
3479   }
3480 
3481   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3482   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3483   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3484   if (Subtarget->isMClass()) {
3485     // Only a full system barrier exists in the M-class architectures.
3486     Domain = ARM_MB::SY;
3487   } else if (Subtarget->preferISHSTBarriers() &&
3488              Ord == AtomicOrdering::Release) {
3489     // Swift happens to implement ISHST barriers in a way that's compatible with
3490     // Release semantics but weaker than ISH so we'd be fools not to use
3491     // it. Beware: other processors probably don't!
3492     Domain = ARM_MB::ISHST;
3493   }
3494 
3495   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3496                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3497                      DAG.getConstant(Domain, dl, MVT::i32));
3498 }
3499 
3500 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3501                              const ARMSubtarget *Subtarget) {
3502   // ARM pre v5TE and Thumb1 does not have preload instructions.
3503   if (!(Subtarget->isThumb2() ||
3504         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3505     // Just preserve the chain.
3506     return Op.getOperand(0);
3507 
3508   SDLoc dl(Op);
3509   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3510   if (!isRead &&
3511       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3512     // ARMv7 with MP extension has PLDW.
3513     return Op.getOperand(0);
3514 
3515   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3516   if (Subtarget->isThumb()) {
3517     // Invert the bits.
3518     isRead = ~isRead & 1;
3519     isData = ~isData & 1;
3520   }
3521 
3522   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3523                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3524                      DAG.getConstant(isData, dl, MVT::i32));
3525 }
3526 
3527 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3528   MachineFunction &MF = DAG.getMachineFunction();
3529   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3530 
3531   // vastart just stores the address of the VarArgsFrameIndex slot into the
3532   // memory location argument.
3533   SDLoc dl(Op);
3534   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3535   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3536   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3537   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3538                       MachinePointerInfo(SV));
3539 }
3540 
3541 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3542                                                 CCValAssign &NextVA,
3543                                                 SDValue &Root,
3544                                                 SelectionDAG &DAG,
3545                                                 const SDLoc &dl) const {
3546   MachineFunction &MF = DAG.getMachineFunction();
3547   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3548 
3549   const TargetRegisterClass *RC;
3550   if (AFI->isThumb1OnlyFunction())
3551     RC = &ARM::tGPRRegClass;
3552   else
3553     RC = &ARM::GPRRegClass;
3554 
3555   // Transform the arguments stored in physical registers into virtual ones.
3556   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3557   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3558 
3559   SDValue ArgValue2;
3560   if (NextVA.isMemLoc()) {
3561     MachineFrameInfo &MFI = MF.getFrameInfo();
3562     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3563 
3564     // Create load node to retrieve arguments from the stack.
3565     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3566     ArgValue2 = DAG.getLoad(
3567         MVT::i32, dl, Root, FIN,
3568         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3569   } else {
3570     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3571     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3572   }
3573   if (!Subtarget->isLittle())
3574     std::swap (ArgValue, ArgValue2);
3575   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3576 }
3577 
3578 // The remaining GPRs hold either the beginning of variable-argument
3579 // data, or the beginning of an aggregate passed by value (usually
3580 // byval).  Either way, we allocate stack slots adjacent to the data
3581 // provided by our caller, and store the unallocated registers there.
3582 // If this is a variadic function, the va_list pointer will begin with
3583 // these values; otherwise, this reassembles a (byval) structure that
3584 // was split between registers and memory.
3585 // Return: The frame index registers were stored into.
3586 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3587                                       const SDLoc &dl, SDValue &Chain,
3588                                       const Value *OrigArg,
3589                                       unsigned InRegsParamRecordIdx,
3590                                       int ArgOffset, unsigned ArgSize) const {
3591   // Currently, two use-cases possible:
3592   // Case #1. Non-var-args function, and we meet first byval parameter.
3593   //          Setup first unallocated register as first byval register;
3594   //          eat all remained registers
3595   //          (these two actions are performed by HandleByVal method).
3596   //          Then, here, we initialize stack frame with
3597   //          "store-reg" instructions.
3598   // Case #2. Var-args function, that doesn't contain byval parameters.
3599   //          The same: eat all remained unallocated registers,
3600   //          initialize stack frame.
3601 
3602   MachineFunction &MF = DAG.getMachineFunction();
3603   MachineFrameInfo &MFI = MF.getFrameInfo();
3604   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3605   unsigned RBegin, REnd;
3606   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3607     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3608   } else {
3609     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3610     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3611     REnd = ARM::R4;
3612   }
3613 
3614   if (REnd != RBegin)
3615     ArgOffset = -4 * (ARM::R4 - RBegin);
3616 
3617   auto PtrVT = getPointerTy(DAG.getDataLayout());
3618   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3619   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3620 
3621   SmallVector<SDValue, 4> MemOps;
3622   const TargetRegisterClass *RC =
3623       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3624 
3625   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3626     unsigned VReg = MF.addLiveIn(Reg, RC);
3627     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3628     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3629                                  MachinePointerInfo(OrigArg, 4 * i));
3630     MemOps.push_back(Store);
3631     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3632   }
3633 
3634   if (!MemOps.empty())
3635     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3636   return FrameIndex;
3637 }
3638 
3639 // Setup stack frame, the va_list pointer will start from.
3640 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3641                                              const SDLoc &dl, SDValue &Chain,
3642                                              unsigned ArgOffset,
3643                                              unsigned TotalArgRegsSaveSize,
3644                                              bool ForceMutable) const {
3645   MachineFunction &MF = DAG.getMachineFunction();
3646   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3647 
3648   // Try to store any remaining integer argument regs
3649   // to their spots on the stack so that they may be loaded by dereferencing
3650   // the result of va_next.
3651   // If there is no regs to be stored, just point address after last
3652   // argument passed via stack.
3653   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3654                                   CCInfo.getInRegsParamsCount(),
3655                                   CCInfo.getNextStackOffset(),
3656                                   std::max(4U, TotalArgRegsSaveSize));
3657   AFI->setVarArgsFrameIndex(FrameIndex);
3658 }
3659 
3660 SDValue ARMTargetLowering::LowerFormalArguments(
3661     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3662     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3663     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3664   MachineFunction &MF = DAG.getMachineFunction();
3665   MachineFrameInfo &MFI = MF.getFrameInfo();
3666 
3667   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3668 
3669   // Assign locations to all of the incoming arguments.
3670   SmallVector<CCValAssign, 16> ArgLocs;
3671   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3672                  *DAG.getContext());
3673   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3674 
3675   SmallVector<SDValue, 16> ArgValues;
3676   SDValue ArgValue;
3677   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3678   unsigned CurArgIdx = 0;
3679 
3680   // Initially ArgRegsSaveSize is zero.
3681   // Then we increase this value each time we meet byval parameter.
3682   // We also increase this value in case of varargs function.
3683   AFI->setArgRegsSaveSize(0);
3684 
3685   // Calculate the amount of stack space that we need to allocate to store
3686   // byval and variadic arguments that are passed in registers.
3687   // We need to know this before we allocate the first byval or variadic
3688   // argument, as they will be allocated a stack slot below the CFA (Canonical
3689   // Frame Address, the stack pointer at entry to the function).
3690   unsigned ArgRegBegin = ARM::R4;
3691   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3692     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3693       break;
3694 
3695     CCValAssign &VA = ArgLocs[i];
3696     unsigned Index = VA.getValNo();
3697     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3698     if (!Flags.isByVal())
3699       continue;
3700 
3701     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3702     unsigned RBegin, REnd;
3703     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3704     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3705 
3706     CCInfo.nextInRegsParam();
3707   }
3708   CCInfo.rewindByValRegsInfo();
3709 
3710   int lastInsIndex = -1;
3711   if (isVarArg && MFI.hasVAStart()) {
3712     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3713     if (RegIdx != array_lengthof(GPRArgRegs))
3714       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3715   }
3716 
3717   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3718   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3719   auto PtrVT = getPointerTy(DAG.getDataLayout());
3720 
3721   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3722     CCValAssign &VA = ArgLocs[i];
3723     if (Ins[VA.getValNo()].isOrigArg()) {
3724       std::advance(CurOrigArg,
3725                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3726       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3727     }
3728     // Arguments stored in registers.
3729     if (VA.isRegLoc()) {
3730       EVT RegVT = VA.getLocVT();
3731 
3732       if (VA.needsCustom()) {
3733         // f64 and vector types are split up into multiple registers or
3734         // combinations of registers and stack slots.
3735         if (VA.getLocVT() == MVT::v2f64) {
3736           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3737                                                    Chain, DAG, dl);
3738           VA = ArgLocs[++i]; // skip ahead to next loc
3739           SDValue ArgValue2;
3740           if (VA.isMemLoc()) {
3741             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3742             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3743             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3744                                     MachinePointerInfo::getFixedStack(
3745                                         DAG.getMachineFunction(), FI));
3746           } else {
3747             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3748                                              Chain, DAG, dl);
3749           }
3750           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3751           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3752                                  ArgValue, ArgValue1,
3753                                  DAG.getIntPtrConstant(0, dl));
3754           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3755                                  ArgValue, ArgValue2,
3756                                  DAG.getIntPtrConstant(1, dl));
3757         } else
3758           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3759       } else {
3760         const TargetRegisterClass *RC;
3761 
3762 
3763         if (RegVT == MVT::f16)
3764           RC = &ARM::HPRRegClass;
3765         else if (RegVT == MVT::f32)
3766           RC = &ARM::SPRRegClass;
3767         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3768           RC = &ARM::DPRRegClass;
3769         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3770           RC = &ARM::QPRRegClass;
3771         else if (RegVT == MVT::i32)
3772           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3773                                            : &ARM::GPRRegClass;
3774         else
3775           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3776 
3777         // Transform the arguments in physical registers into virtual ones.
3778         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3779         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3780       }
3781 
3782       // If this is an 8 or 16-bit value, it is really passed promoted
3783       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3784       // truncate to the right size.
3785       switch (VA.getLocInfo()) {
3786       default: llvm_unreachable("Unknown loc info!");
3787       case CCValAssign::Full: break;
3788       case CCValAssign::BCvt:
3789         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3790         break;
3791       case CCValAssign::SExt:
3792         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3793                                DAG.getValueType(VA.getValVT()));
3794         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3795         break;
3796       case CCValAssign::ZExt:
3797         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3798                                DAG.getValueType(VA.getValVT()));
3799         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3800         break;
3801       }
3802 
3803       InVals.push_back(ArgValue);
3804     } else { // VA.isRegLoc()
3805       // sanity check
3806       assert(VA.isMemLoc());
3807       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3808 
3809       int index = VA.getValNo();
3810 
3811       // Some Ins[] entries become multiple ArgLoc[] entries.
3812       // Process them only once.
3813       if (index != lastInsIndex)
3814         {
3815           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3816           // FIXME: For now, all byval parameter objects are marked mutable.
3817           // This can be changed with more analysis.
3818           // In case of tail call optimization mark all arguments mutable.
3819           // Since they could be overwritten by lowering of arguments in case of
3820           // a tail call.
3821           if (Flags.isByVal()) {
3822             assert(Ins[index].isOrigArg() &&
3823                    "Byval arguments cannot be implicit");
3824             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3825 
3826             int FrameIndex = StoreByValRegs(
3827                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3828                 VA.getLocMemOffset(), Flags.getByValSize());
3829             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3830             CCInfo.nextInRegsParam();
3831           } else {
3832             unsigned FIOffset = VA.getLocMemOffset();
3833             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3834                                            FIOffset, true);
3835 
3836             // Create load nodes to retrieve arguments from the stack.
3837             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3838             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3839                                          MachinePointerInfo::getFixedStack(
3840                                              DAG.getMachineFunction(), FI)));
3841           }
3842           lastInsIndex = index;
3843         }
3844     }
3845   }
3846 
3847   // varargs
3848   if (isVarArg && MFI.hasVAStart())
3849     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3850                          CCInfo.getNextStackOffset(),
3851                          TotalArgRegsSaveSize);
3852 
3853   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3854 
3855   return Chain;
3856 }
3857 
3858 /// isFloatingPointZero - Return true if this is +0.0.
3859 static bool isFloatingPointZero(SDValue Op) {
3860   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3861     return CFP->getValueAPF().isPosZero();
3862   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3863     // Maybe this has already been legalized into the constant pool?
3864     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3865       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3866       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3867         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3868           return CFP->getValueAPF().isPosZero();
3869     }
3870   } else if (Op->getOpcode() == ISD::BITCAST &&
3871              Op->getValueType(0) == MVT::f64) {
3872     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3873     // created by LowerConstantFP().
3874     SDValue BitcastOp = Op->getOperand(0);
3875     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3876         isNullConstant(BitcastOp->getOperand(0)))
3877       return true;
3878   }
3879   return false;
3880 }
3881 
3882 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3883 /// the given operands.
3884 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3885                                      SDValue &ARMcc, SelectionDAG &DAG,
3886                                      const SDLoc &dl) const {
3887   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3888     unsigned C = RHSC->getZExtValue();
3889     if (!isLegalICmpImmediate((int32_t)C)) {
3890       // Constant does not fit, try adjusting it by one.
3891       switch (CC) {
3892       default: break;
3893       case ISD::SETLT:
3894       case ISD::SETGE:
3895         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3896           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3897           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3898         }
3899         break;
3900       case ISD::SETULT:
3901       case ISD::SETUGE:
3902         if (C != 0 && isLegalICmpImmediate(C-1)) {
3903           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3904           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3905         }
3906         break;
3907       case ISD::SETLE:
3908       case ISD::SETGT:
3909         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3910           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3911           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3912         }
3913         break;
3914       case ISD::SETULE:
3915       case ISD::SETUGT:
3916         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3917           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3918           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3919         }
3920         break;
3921       }
3922     }
3923   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3924              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3925     // In ARM and Thumb-2, the compare instructions can shift their second
3926     // operand.
3927     CC = ISD::getSetCCSwappedOperands(CC);
3928     std::swap(LHS, RHS);
3929   }
3930 
3931   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3932   ARMISD::NodeType CompareType;
3933   switch (CondCode) {
3934   default:
3935     CompareType = ARMISD::CMP;
3936     break;
3937   case ARMCC::EQ:
3938   case ARMCC::NE:
3939     // Uses only Z Flag
3940     CompareType = ARMISD::CMPZ;
3941     break;
3942   }
3943   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3944   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3945 }
3946 
3947 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3948 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3949                                      SelectionDAG &DAG, const SDLoc &dl,
3950                                      bool InvalidOnQNaN) const {
3951   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
3952   SDValue Cmp;
3953   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3954   if (!isFloatingPointZero(RHS))
3955     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3956   else
3957     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3958   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3959 }
3960 
3961 /// duplicateCmp - Glue values can have only one use, so this function
3962 /// duplicates a comparison node.
3963 SDValue
3964 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3965   unsigned Opc = Cmp.getOpcode();
3966   SDLoc DL(Cmp);
3967   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3968     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3969 
3970   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3971   Cmp = Cmp.getOperand(0);
3972   Opc = Cmp.getOpcode();
3973   if (Opc == ARMISD::CMPFP)
3974     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3975                       Cmp.getOperand(1), Cmp.getOperand(2));
3976   else {
3977     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3978     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3979                       Cmp.getOperand(1));
3980   }
3981   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3982 }
3983 
3984 // This function returns three things: the arithmetic computation itself
3985 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3986 // comparison and the condition code define the case in which the arithmetic
3987 // computation *does not* overflow.
3988 std::pair<SDValue, SDValue>
3989 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3990                                  SDValue &ARMcc) const {
3991   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3992 
3993   SDValue Value, OverflowCmp;
3994   SDValue LHS = Op.getOperand(0);
3995   SDValue RHS = Op.getOperand(1);
3996   SDLoc dl(Op);
3997 
3998   // FIXME: We are currently always generating CMPs because we don't support
3999   // generating CMN through the backend. This is not as good as the natural
4000   // CMP case because it causes a register dependency and cannot be folded
4001   // later.
4002 
4003   switch (Op.getOpcode()) {
4004   default:
4005     llvm_unreachable("Unknown overflow instruction!");
4006   case ISD::SADDO:
4007     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4008     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4009     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4010     break;
4011   case ISD::UADDO:
4012     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4013     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4014     // We do not use it in the USUBO case as Value may not be used.
4015     Value = DAG.getNode(ARMISD::ADDC, dl,
4016                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4017                 .getValue(0);
4018     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4019     break;
4020   case ISD::SSUBO:
4021     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4022     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4023     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4024     break;
4025   case ISD::USUBO:
4026     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4027     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4028     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4029     break;
4030   case ISD::UMULO:
4031     // We generate a UMUL_LOHI and then check if the high word is 0.
4032     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4033     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4034                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4035                         LHS, RHS);
4036     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4037                               DAG.getConstant(0, dl, MVT::i32));
4038     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4039     break;
4040   case ISD::SMULO:
4041     // We generate a SMUL_LOHI and then check if all the bits of the high word
4042     // are the same as the sign bit of the low word.
4043     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4044     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4045                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4046                         LHS, RHS);
4047     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4048                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4049                                           Value.getValue(0),
4050                                           DAG.getConstant(31, dl, MVT::i32)));
4051     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4052     break;
4053   } // switch (...)
4054 
4055   return std::make_pair(Value, OverflowCmp);
4056 }
4057 
4058 SDValue
4059 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4060   // Let legalize expand this if it isn't a legal type yet.
4061   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4062     return SDValue();
4063 
4064   SDValue Value, OverflowCmp;
4065   SDValue ARMcc;
4066   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4067   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4068   SDLoc dl(Op);
4069   // We use 0 and 1 as false and true values.
4070   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4071   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4072   EVT VT = Op.getValueType();
4073 
4074   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4075                                  ARMcc, CCR, OverflowCmp);
4076 
4077   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4078   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4079 }
4080 
4081 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4082                                               SelectionDAG &DAG) {
4083   SDLoc DL(BoolCarry);
4084   EVT CarryVT = BoolCarry.getValueType();
4085 
4086   // This converts the boolean value carry into the carry flag by doing
4087   // ARMISD::SUBC Carry, 1
4088   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4089                               DAG.getVTList(CarryVT, MVT::i32),
4090                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4091   return Carry.getValue(1);
4092 }
4093 
4094 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4095                                               SelectionDAG &DAG) {
4096   SDLoc DL(Flags);
4097 
4098   // Now convert the carry flag into a boolean carry. We do this
4099   // using ARMISD:ADDE 0, 0, Carry
4100   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4101                      DAG.getConstant(0, DL, MVT::i32),
4102                      DAG.getConstant(0, DL, MVT::i32), Flags);
4103 }
4104 
4105 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4106                                              SelectionDAG &DAG) const {
4107   // Let legalize expand this if it isn't a legal type yet.
4108   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4109     return SDValue();
4110 
4111   SDValue LHS = Op.getOperand(0);
4112   SDValue RHS = Op.getOperand(1);
4113   SDLoc dl(Op);
4114 
4115   EVT VT = Op.getValueType();
4116   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4117   SDValue Value;
4118   SDValue Overflow;
4119   switch (Op.getOpcode()) {
4120   default:
4121     llvm_unreachable("Unknown overflow instruction!");
4122   case ISD::UADDO:
4123     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4124     // Convert the carry flag into a boolean value.
4125     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4126     break;
4127   case ISD::USUBO: {
4128     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4129     // Convert the carry flag into a boolean value.
4130     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4131     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4132     // value. So compute 1 - C.
4133     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4134                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4135     break;
4136   }
4137   }
4138 
4139   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4140 }
4141 
4142 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4143   SDValue Cond = Op.getOperand(0);
4144   SDValue SelectTrue = Op.getOperand(1);
4145   SDValue SelectFalse = Op.getOperand(2);
4146   SDLoc dl(Op);
4147   unsigned Opc = Cond.getOpcode();
4148 
4149   if (Cond.getResNo() == 1 &&
4150       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4151        Opc == ISD::USUBO)) {
4152     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4153       return SDValue();
4154 
4155     SDValue Value, OverflowCmp;
4156     SDValue ARMcc;
4157     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4158     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4159     EVT VT = Op.getValueType();
4160 
4161     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4162                    OverflowCmp, DAG);
4163   }
4164 
4165   // Convert:
4166   //
4167   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4168   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4169   //
4170   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4171     const ConstantSDNode *CMOVTrue =
4172       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4173     const ConstantSDNode *CMOVFalse =
4174       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4175 
4176     if (CMOVTrue && CMOVFalse) {
4177       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4178       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4179 
4180       SDValue True;
4181       SDValue False;
4182       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4183         True = SelectTrue;
4184         False = SelectFalse;
4185       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4186         True = SelectFalse;
4187         False = SelectTrue;
4188       }
4189 
4190       if (True.getNode() && False.getNode()) {
4191         EVT VT = Op.getValueType();
4192         SDValue ARMcc = Cond.getOperand(2);
4193         SDValue CCR = Cond.getOperand(3);
4194         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4195         assert(True.getValueType() == VT);
4196         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4197       }
4198     }
4199   }
4200 
4201   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4202   // undefined bits before doing a full-word comparison with zero.
4203   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4204                      DAG.getConstant(1, dl, Cond.getValueType()));
4205 
4206   return DAG.getSelectCC(dl, Cond,
4207                          DAG.getConstant(0, dl, Cond.getValueType()),
4208                          SelectTrue, SelectFalse, ISD::SETNE);
4209 }
4210 
4211 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4212                                  bool &swpCmpOps, bool &swpVselOps) {
4213   // Start by selecting the GE condition code for opcodes that return true for
4214   // 'equality'
4215   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4216       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4217     CondCode = ARMCC::GE;
4218 
4219   // and GT for opcodes that return false for 'equality'.
4220   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4221            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4222     CondCode = ARMCC::GT;
4223 
4224   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4225   // to swap the compare operands.
4226   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4227       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4228     swpCmpOps = true;
4229 
4230   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4231   // If we have an unordered opcode, we need to swap the operands to the VSEL
4232   // instruction (effectively negating the condition).
4233   //
4234   // This also has the effect of swapping which one of 'less' or 'greater'
4235   // returns true, so we also swap the compare operands. It also switches
4236   // whether we return true for 'equality', so we compensate by picking the
4237   // opposite condition code to our original choice.
4238   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4239       CC == ISD::SETUGT) {
4240     swpCmpOps = !swpCmpOps;
4241     swpVselOps = !swpVselOps;
4242     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4243   }
4244 
4245   // 'ordered' is 'anything but unordered', so use the VS condition code and
4246   // swap the VSEL operands.
4247   if (CC == ISD::SETO) {
4248     CondCode = ARMCC::VS;
4249     swpVselOps = true;
4250   }
4251 
4252   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4253   // code and swap the VSEL operands. Also do this if we don't care about the
4254   // unordered case.
4255   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4256     CondCode = ARMCC::EQ;
4257     swpVselOps = true;
4258   }
4259 }
4260 
4261 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4262                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4263                                    SDValue Cmp, SelectionDAG &DAG) const {
4264   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4265     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4266                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4267     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4268                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4269 
4270     SDValue TrueLow = TrueVal.getValue(0);
4271     SDValue TrueHigh = TrueVal.getValue(1);
4272     SDValue FalseLow = FalseVal.getValue(0);
4273     SDValue FalseHigh = FalseVal.getValue(1);
4274 
4275     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4276                               ARMcc, CCR, Cmp);
4277     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4278                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4279 
4280     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4281   } else {
4282     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4283                        Cmp);
4284   }
4285 }
4286 
4287 static bool isGTorGE(ISD::CondCode CC) {
4288   return CC == ISD::SETGT || CC == ISD::SETGE;
4289 }
4290 
4291 static bool isLTorLE(ISD::CondCode CC) {
4292   return CC == ISD::SETLT || CC == ISD::SETLE;
4293 }
4294 
4295 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4296 // All of these conditions (and their <= and >= counterparts) will do:
4297 //          x < k ? k : x
4298 //          x > k ? x : k
4299 //          k < x ? x : k
4300 //          k > x ? k : x
4301 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4302                             const SDValue TrueVal, const SDValue FalseVal,
4303                             const ISD::CondCode CC, const SDValue K) {
4304   return (isGTorGE(CC) &&
4305           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4306          (isLTorLE(CC) &&
4307           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4308 }
4309 
4310 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4311 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4312                             const SDValue TrueVal, const SDValue FalseVal,
4313                             const ISD::CondCode CC, const SDValue K) {
4314   return (isGTorGE(CC) &&
4315           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4316          (isLTorLE(CC) &&
4317           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4318 }
4319 
4320 // Check if two chained conditionals could be converted into SSAT or USAT.
4321 //
4322 // SSAT can replace a set of two conditional selectors that bound a number to an
4323 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4324 //
4325 //     x < -k ? -k : (x > k ? k : x)
4326 //     x < -k ? -k : (x < k ? x : k)
4327 //     x > -k ? (x > k ? k : x) : -k
4328 //     x < k ? (x < -k ? -k : x) : k
4329 //     etc.
4330 //
4331 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4332 // a power of 2.
4333 //
4334 // It returns true if the conversion can be done, false otherwise.
4335 // Additionally, the variable is returned in parameter V, the constant in K and
4336 // usat is set to true if the conditional represents an unsigned saturation
4337 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4338                                     uint64_t &K, bool &usat) {
4339   SDValue LHS1 = Op.getOperand(0);
4340   SDValue RHS1 = Op.getOperand(1);
4341   SDValue TrueVal1 = Op.getOperand(2);
4342   SDValue FalseVal1 = Op.getOperand(3);
4343   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4344 
4345   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4346   if (Op2.getOpcode() != ISD::SELECT_CC)
4347     return false;
4348 
4349   SDValue LHS2 = Op2.getOperand(0);
4350   SDValue RHS2 = Op2.getOperand(1);
4351   SDValue TrueVal2 = Op2.getOperand(2);
4352   SDValue FalseVal2 = Op2.getOperand(3);
4353   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4354 
4355   // Find out which are the constants and which are the variables
4356   // in each conditional
4357   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4358                                                         ? &RHS1
4359                                                         : nullptr;
4360   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4361                                                         ? &RHS2
4362                                                         : nullptr;
4363   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4364   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4365   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4366   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4367 
4368   // We must detect cases where the original operations worked with 16- or
4369   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4370   // must work with sign-extended values but the select operations return
4371   // the original non-extended value.
4372   SDValue V2TmpReg = V2Tmp;
4373   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4374     V2TmpReg = V2Tmp->getOperand(0);
4375 
4376   // Check that the registers and the constants have the correct values
4377   // in both conditionals
4378   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4379       V2TmpReg != V2)
4380     return false;
4381 
4382   // Figure out which conditional is saturating the lower/upper bound.
4383   const SDValue *LowerCheckOp =
4384       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4385           ? &Op
4386           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4387                 ? &Op2
4388                 : nullptr;
4389   const SDValue *UpperCheckOp =
4390       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4391           ? &Op
4392           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4393                 ? &Op2
4394                 : nullptr;
4395 
4396   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4397     return false;
4398 
4399   // Check that the constant in the lower-bound check is
4400   // the opposite of the constant in the upper-bound check
4401   // in 1's complement.
4402   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4403   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4404   int64_t PosVal = std::max(Val1, Val2);
4405   int64_t NegVal = std::min(Val1, Val2);
4406 
4407   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4408        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4409       isPowerOf2_64(PosVal + 1)) {
4410 
4411     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4412     if (Val1 == ~Val2)
4413       usat = false;
4414     else if (NegVal == 0)
4415       usat = true;
4416     else
4417       return false;
4418 
4419     V = V2;
4420     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4421 
4422     return true;
4423   }
4424 
4425   return false;
4426 }
4427 
4428 // Check if a condition of the type x < k ? k : x can be converted into a
4429 // bit operation instead of conditional moves.
4430 // Currently this is allowed given:
4431 // - The conditions and values match up
4432 // - k is 0 or -1 (all ones)
4433 // This function will not check the last condition, thats up to the caller
4434 // It returns true if the transformation can be made, and in such case
4435 // returns x in V, and k in SatK.
4436 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4437                                          SDValue &SatK)
4438 {
4439   SDValue LHS = Op.getOperand(0);
4440   SDValue RHS = Op.getOperand(1);
4441   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4442   SDValue TrueVal = Op.getOperand(2);
4443   SDValue FalseVal = Op.getOperand(3);
4444 
4445   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4446                                                ? &RHS
4447                                                : nullptr;
4448 
4449   // No constant operation in comparison, early out
4450   if (!K)
4451     return false;
4452 
4453   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4454   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4455   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4456 
4457   // If the constant on left and right side, or variable on left and right,
4458   // does not match, early out
4459   if (*K != KTmp || V != VTmp)
4460     return false;
4461 
4462   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4463     SatK = *K;
4464     return true;
4465   }
4466 
4467   return false;
4468 }
4469 
4470 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4471   EVT VT = Op.getValueType();
4472   SDLoc dl(Op);
4473 
4474   // Try to convert two saturating conditional selects into a single SSAT
4475   SDValue SatValue;
4476   uint64_t SatConstant;
4477   bool SatUSat;
4478   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4479       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4480     if (SatUSat)
4481       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4482                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4483     else
4484       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4485                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4486   }
4487 
4488   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4489   // into more efficient bit operations, which is possible when k is 0 or -1
4490   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4491   // single instructions. On Thumb the shift and the bit operation will be two
4492   // instructions.
4493   // Only allow this transformation on full-width (32-bit) operations
4494   SDValue LowerSatConstant;
4495   if (VT == MVT::i32 &&
4496       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4497     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4498                                  DAG.getConstant(31, dl, VT));
4499     if (isNullConstant(LowerSatConstant)) {
4500       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4501                                       DAG.getAllOnesConstant(dl, VT));
4502       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4503     } else if (isAllOnesConstant(LowerSatConstant))
4504       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4505   }
4506 
4507   SDValue LHS = Op.getOperand(0);
4508   SDValue RHS = Op.getOperand(1);
4509   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4510   SDValue TrueVal = Op.getOperand(2);
4511   SDValue FalseVal = Op.getOperand(3);
4512 
4513   if (!Subtarget->hasFP64() && LHS.getValueType() == MVT::f64) {
4514     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4515                                                     dl);
4516 
4517     // If softenSetCCOperands only returned one value, we should compare it to
4518     // zero.
4519     if (!RHS.getNode()) {
4520       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4521       CC = ISD::SETNE;
4522     }
4523   }
4524 
4525   if (LHS.getValueType() == MVT::i32) {
4526     // Try to generate VSEL on ARMv8.
4527     // The VSEL instruction can't use all the usual ARM condition
4528     // codes: it only has two bits to select the condition code, so it's
4529     // constrained to use only GE, GT, VS and EQ.
4530     //
4531     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4532     // swap the operands of the previous compare instruction (effectively
4533     // inverting the compare condition, swapping 'less' and 'greater') and
4534     // sometimes need to swap the operands to the VSEL (which inverts the
4535     // condition in the sense of firing whenever the previous condition didn't)
4536     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4537                                         TrueVal.getValueType() == MVT::f32 ||
4538                                         TrueVal.getValueType() == MVT::f64)) {
4539       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4540       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4541           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4542         CC = ISD::getSetCCInverse(CC, true);
4543         std::swap(TrueVal, FalseVal);
4544       }
4545     }
4546 
4547     SDValue ARMcc;
4548     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4549     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4550     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4551   }
4552 
4553   ARMCC::CondCodes CondCode, CondCode2;
4554   bool InvalidOnQNaN;
4555   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4556 
4557   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4558   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4559   // must use VSEL (limited condition codes), due to not having conditional f16
4560   // moves.
4561   if (Subtarget->hasFPARMv8Base() &&
4562       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4563       (TrueVal.getValueType() == MVT::f16 ||
4564        TrueVal.getValueType() == MVT::f32 ||
4565        TrueVal.getValueType() == MVT::f64)) {
4566     bool swpCmpOps = false;
4567     bool swpVselOps = false;
4568     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4569 
4570     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4571         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4572       if (swpCmpOps)
4573         std::swap(LHS, RHS);
4574       if (swpVselOps)
4575         std::swap(TrueVal, FalseVal);
4576     }
4577   }
4578 
4579   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4580   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4581   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4582   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4583   if (CondCode2 != ARMCC::AL) {
4584     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4585     // FIXME: Needs another CMP because flag can have but one use.
4586     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4587     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4588   }
4589   return Result;
4590 }
4591 
4592 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4593 /// to morph to an integer compare sequence.
4594 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4595                            const ARMSubtarget *Subtarget) {
4596   SDNode *N = Op.getNode();
4597   if (!N->hasOneUse())
4598     // Otherwise it requires moving the value from fp to integer registers.
4599     return false;
4600   if (!N->getNumValues())
4601     return false;
4602   EVT VT = Op.getValueType();
4603   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4604     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4605     // vmrs are very slow, e.g. cortex-a8.
4606     return false;
4607 
4608   if (isFloatingPointZero(Op)) {
4609     SeenZero = true;
4610     return true;
4611   }
4612   return ISD::isNormalLoad(N);
4613 }
4614 
4615 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4616   if (isFloatingPointZero(Op))
4617     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4618 
4619   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4620     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4621                        Ld->getPointerInfo(), Ld->getAlignment(),
4622                        Ld->getMemOperand()->getFlags());
4623 
4624   llvm_unreachable("Unknown VFP cmp argument!");
4625 }
4626 
4627 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4628                            SDValue &RetVal1, SDValue &RetVal2) {
4629   SDLoc dl(Op);
4630 
4631   if (isFloatingPointZero(Op)) {
4632     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4633     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4634     return;
4635   }
4636 
4637   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4638     SDValue Ptr = Ld->getBasePtr();
4639     RetVal1 =
4640         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4641                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4642 
4643     EVT PtrType = Ptr.getValueType();
4644     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4645     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4646                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4647     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4648                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4649                           Ld->getMemOperand()->getFlags());
4650     return;
4651   }
4652 
4653   llvm_unreachable("Unknown VFP cmp argument!");
4654 }
4655 
4656 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4657 /// f32 and even f64 comparisons to integer ones.
4658 SDValue
4659 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4660   SDValue Chain = Op.getOperand(0);
4661   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4662   SDValue LHS = Op.getOperand(2);
4663   SDValue RHS = Op.getOperand(3);
4664   SDValue Dest = Op.getOperand(4);
4665   SDLoc dl(Op);
4666 
4667   bool LHSSeenZero = false;
4668   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4669   bool RHSSeenZero = false;
4670   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4671   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4672     // If unsafe fp math optimization is enabled and there are no other uses of
4673     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4674     // to an integer comparison.
4675     if (CC == ISD::SETOEQ)
4676       CC = ISD::SETEQ;
4677     else if (CC == ISD::SETUNE)
4678       CC = ISD::SETNE;
4679 
4680     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4681     SDValue ARMcc;
4682     if (LHS.getValueType() == MVT::f32) {
4683       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4684                         bitcastf32Toi32(LHS, DAG), Mask);
4685       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4686                         bitcastf32Toi32(RHS, DAG), Mask);
4687       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4688       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4689       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4690                          Chain, Dest, ARMcc, CCR, Cmp);
4691     }
4692 
4693     SDValue LHS1, LHS2;
4694     SDValue RHS1, RHS2;
4695     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4696     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4697     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4698     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4699     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4700     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4701     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4702     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4703     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4704   }
4705 
4706   return SDValue();
4707 }
4708 
4709 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4710   SDValue Chain = Op.getOperand(0);
4711   SDValue Cond = Op.getOperand(1);
4712   SDValue Dest = Op.getOperand(2);
4713   SDLoc dl(Op);
4714 
4715   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4716   // instruction.
4717   unsigned Opc = Cond.getOpcode();
4718   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4719                       !Subtarget->isThumb1Only();
4720   if (Cond.getResNo() == 1 &&
4721       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4722        Opc == ISD::USUBO || OptimizeMul)) {
4723     // Only lower legal XALUO ops.
4724     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4725       return SDValue();
4726 
4727     // The actual operation with overflow check.
4728     SDValue Value, OverflowCmp;
4729     SDValue ARMcc;
4730     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4731 
4732     // Reverse the condition code.
4733     ARMCC::CondCodes CondCode =
4734         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4735     CondCode = ARMCC::getOppositeCondition(CondCode);
4736     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4737     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4738 
4739     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4740                        OverflowCmp);
4741   }
4742 
4743   return SDValue();
4744 }
4745 
4746 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4747   SDValue Chain = Op.getOperand(0);
4748   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4749   SDValue LHS = Op.getOperand(2);
4750   SDValue RHS = Op.getOperand(3);
4751   SDValue Dest = Op.getOperand(4);
4752   SDLoc dl(Op);
4753 
4754   if (!Subtarget->hasFP64() && LHS.getValueType() == MVT::f64) {
4755     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4756                                                     dl);
4757 
4758     // If softenSetCCOperands only returned one value, we should compare it to
4759     // zero.
4760     if (!RHS.getNode()) {
4761       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4762       CC = ISD::SETNE;
4763     }
4764   }
4765 
4766   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4767   // instruction.
4768   unsigned Opc = LHS.getOpcode();
4769   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4770                       !Subtarget->isThumb1Only();
4771   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4772       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4773        Opc == ISD::USUBO || OptimizeMul) &&
4774       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4775     // Only lower legal XALUO ops.
4776     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4777       return SDValue();
4778 
4779     // The actual operation with overflow check.
4780     SDValue Value, OverflowCmp;
4781     SDValue ARMcc;
4782     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4783 
4784     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4785       // Reverse the condition code.
4786       ARMCC::CondCodes CondCode =
4787           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4788       CondCode = ARMCC::getOppositeCondition(CondCode);
4789       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4790     }
4791     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4792 
4793     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4794                        OverflowCmp);
4795   }
4796 
4797   if (LHS.getValueType() == MVT::i32) {
4798     SDValue ARMcc;
4799     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4800     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4801     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4802                        Chain, Dest, ARMcc, CCR, Cmp);
4803   }
4804 
4805   if (getTargetMachine().Options.UnsafeFPMath &&
4806       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4807        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4808     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4809       return Result;
4810   }
4811 
4812   ARMCC::CondCodes CondCode, CondCode2;
4813   bool InvalidOnQNaN;
4814   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4815 
4816   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4817   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4818   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4819   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4820   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4821   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4822   if (CondCode2 != ARMCC::AL) {
4823     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4824     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4825     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4826   }
4827   return Res;
4828 }
4829 
4830 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4831   SDValue Chain = Op.getOperand(0);
4832   SDValue Table = Op.getOperand(1);
4833   SDValue Index = Op.getOperand(2);
4834   SDLoc dl(Op);
4835 
4836   EVT PTy = getPointerTy(DAG.getDataLayout());
4837   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4838   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4839   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4840   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4841   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4842   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4843     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4844     // which does another jump to the destination. This also makes it easier
4845     // to translate it to TBB / TBH later (Thumb2 only).
4846     // FIXME: This might not work if the function is extremely large.
4847     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4848                        Addr, Op.getOperand(2), JTI);
4849   }
4850   if (isPositionIndependent() || Subtarget->isROPI()) {
4851     Addr =
4852         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4853                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4854     Chain = Addr.getValue(1);
4855     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4856     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4857   } else {
4858     Addr =
4859         DAG.getLoad(PTy, dl, Chain, Addr,
4860                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4861     Chain = Addr.getValue(1);
4862     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4863   }
4864 }
4865 
4866 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4867   EVT VT = Op.getValueType();
4868   SDLoc dl(Op);
4869 
4870   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4871     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4872       return Op;
4873     return DAG.UnrollVectorOp(Op.getNode());
4874   }
4875 
4876   const bool HasFullFP16 =
4877     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4878 
4879   EVT NewTy;
4880   const EVT OpTy = Op.getOperand(0).getValueType();
4881   if (OpTy == MVT::v4f32)
4882     NewTy = MVT::v4i32;
4883   else if (OpTy == MVT::v4f16 && HasFullFP16)
4884     NewTy = MVT::v4i16;
4885   else if (OpTy == MVT::v8f16 && HasFullFP16)
4886     NewTy = MVT::v8i16;
4887   else
4888     llvm_unreachable("Invalid type for custom lowering!");
4889 
4890   if (VT != MVT::v4i16 && VT != MVT::v8i16)
4891     return DAG.UnrollVectorOp(Op.getNode());
4892 
4893   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
4894   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4895 }
4896 
4897 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4898   EVT VT = Op.getValueType();
4899   if (VT.isVector())
4900     return LowerVectorFP_TO_INT(Op, DAG);
4901   if (!Subtarget->hasFP64() && Op.getOperand(0).getValueType() == MVT::f64) {
4902     RTLIB::Libcall LC;
4903     if (Op.getOpcode() == ISD::FP_TO_SINT)
4904       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4905                               Op.getValueType());
4906     else
4907       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4908                               Op.getValueType());
4909     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4910                        /*isSigned*/ false, SDLoc(Op)).first;
4911   }
4912 
4913   return Op;
4914 }
4915 
4916 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4917   EVT VT = Op.getValueType();
4918   SDLoc dl(Op);
4919 
4920   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4921     if (VT.getVectorElementType() == MVT::f32)
4922       return Op;
4923     return DAG.UnrollVectorOp(Op.getNode());
4924   }
4925 
4926   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
4927           Op.getOperand(0).getValueType() == MVT::v8i16) &&
4928          "Invalid type for custom lowering!");
4929 
4930   const bool HasFullFP16 =
4931     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4932 
4933   EVT DestVecType;
4934   if (VT == MVT::v4f32)
4935     DestVecType = MVT::v4i32;
4936   else if (VT == MVT::v4f16 && HasFullFP16)
4937     DestVecType = MVT::v4i16;
4938   else if (VT == MVT::v8f16 && HasFullFP16)
4939     DestVecType = MVT::v8i16;
4940   else
4941     return DAG.UnrollVectorOp(Op.getNode());
4942 
4943   unsigned CastOpc;
4944   unsigned Opc;
4945   switch (Op.getOpcode()) {
4946   default: llvm_unreachable("Invalid opcode!");
4947   case ISD::SINT_TO_FP:
4948     CastOpc = ISD::SIGN_EXTEND;
4949     Opc = ISD::SINT_TO_FP;
4950     break;
4951   case ISD::UINT_TO_FP:
4952     CastOpc = ISD::ZERO_EXTEND;
4953     Opc = ISD::UINT_TO_FP;
4954     break;
4955   }
4956 
4957   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
4958   return DAG.getNode(Opc, dl, VT, Op);
4959 }
4960 
4961 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4962   EVT VT = Op.getValueType();
4963   if (VT.isVector())
4964     return LowerVectorINT_TO_FP(Op, DAG);
4965   if (!Subtarget->hasFP64() && Op.getValueType() == MVT::f64) {
4966     RTLIB::Libcall LC;
4967     if (Op.getOpcode() == ISD::SINT_TO_FP)
4968       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4969                               Op.getValueType());
4970     else
4971       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4972                               Op.getValueType());
4973     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4974                        /*isSigned*/ false, SDLoc(Op)).first;
4975   }
4976 
4977   return Op;
4978 }
4979 
4980 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4981   // Implement fcopysign with a fabs and a conditional fneg.
4982   SDValue Tmp0 = Op.getOperand(0);
4983   SDValue Tmp1 = Op.getOperand(1);
4984   SDLoc dl(Op);
4985   EVT VT = Op.getValueType();
4986   EVT SrcVT = Tmp1.getValueType();
4987   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4988     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4989   bool UseNEON = !InGPR && Subtarget->hasNEON();
4990 
4991   if (UseNEON) {
4992     // Use VBSL to copy the sign bit.
4993     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4994     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4995                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4996     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4997     if (VT == MVT::f64)
4998       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4999                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5000                          DAG.getConstant(32, dl, MVT::i32));
5001     else /*if (VT == MVT::f32)*/
5002       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5003     if (SrcVT == MVT::f32) {
5004       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5005       if (VT == MVT::f64)
5006         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
5007                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5008                            DAG.getConstant(32, dl, MVT::i32));
5009     } else if (VT == MVT::f32)
5010       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
5011                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5012                          DAG.getConstant(32, dl, MVT::i32));
5013     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5014     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5015 
5016     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
5017                                             dl, MVT::i32);
5018     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5019     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5020                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5021 
5022     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5023                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5024                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5025     if (VT == MVT::f32) {
5026       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5027       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5028                         DAG.getConstant(0, dl, MVT::i32));
5029     } else {
5030       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5031     }
5032 
5033     return Res;
5034   }
5035 
5036   // Bitcast operand 1 to i32.
5037   if (SrcVT == MVT::f64)
5038     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5039                        Tmp1).getValue(1);
5040   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5041 
5042   // Or in the signbit with integer operations.
5043   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5044   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5045   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5046   if (VT == MVT::f32) {
5047     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5048                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5049     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5050                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5051   }
5052 
5053   // f64: Or the high part with signbit and then combine two parts.
5054   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5055                      Tmp0);
5056   SDValue Lo = Tmp0.getValue(0);
5057   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5058   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5059   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5060 }
5061 
5062 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5063   MachineFunction &MF = DAG.getMachineFunction();
5064   MachineFrameInfo &MFI = MF.getFrameInfo();
5065   MFI.setReturnAddressIsTaken(true);
5066 
5067   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5068     return SDValue();
5069 
5070   EVT VT = Op.getValueType();
5071   SDLoc dl(Op);
5072   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5073   if (Depth) {
5074     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5075     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5076     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5077                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5078                        MachinePointerInfo());
5079   }
5080 
5081   // Return LR, which contains the return address. Mark it an implicit live-in.
5082   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5083   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5084 }
5085 
5086 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5087   const ARMBaseRegisterInfo &ARI =
5088     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5089   MachineFunction &MF = DAG.getMachineFunction();
5090   MachineFrameInfo &MFI = MF.getFrameInfo();
5091   MFI.setFrameAddressIsTaken(true);
5092 
5093   EVT VT = Op.getValueType();
5094   SDLoc dl(Op);  // FIXME probably not meaningful
5095   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5096   unsigned FrameReg = ARI.getFrameRegister(MF);
5097   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5098   while (Depth--)
5099     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5100                             MachinePointerInfo());
5101   return FrameAddr;
5102 }
5103 
5104 // FIXME? Maybe this could be a TableGen attribute on some registers and
5105 // this table could be generated automatically from RegInfo.
5106 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5107                                               SelectionDAG &DAG) const {
5108   unsigned Reg = StringSwitch<unsigned>(RegName)
5109                        .Case("sp", ARM::SP)
5110                        .Default(0);
5111   if (Reg)
5112     return Reg;
5113   report_fatal_error(Twine("Invalid register name \""
5114                               + StringRef(RegName)  + "\"."));
5115 }
5116 
5117 // Result is 64 bit value so split into two 32 bit values and return as a
5118 // pair of values.
5119 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5120                                 SelectionDAG &DAG) {
5121   SDLoc DL(N);
5122 
5123   // This function is only supposed to be called for i64 type destination.
5124   assert(N->getValueType(0) == MVT::i64
5125           && "ExpandREAD_REGISTER called for non-i64 type result.");
5126 
5127   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5128                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5129                              N->getOperand(0),
5130                              N->getOperand(1));
5131 
5132   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5133                     Read.getValue(1)));
5134   Results.push_back(Read.getOperand(0));
5135 }
5136 
5137 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5138 /// When \p DstVT, the destination type of \p BC, is on the vector
5139 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5140 /// it might be possible to combine them, such that everything stays on the
5141 /// vector register bank.
5142 /// \p return The node that would replace \p BT, if the combine
5143 /// is possible.
5144 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5145                                                 SelectionDAG &DAG) {
5146   SDValue Op = BC->getOperand(0);
5147   EVT DstVT = BC->getValueType(0);
5148 
5149   // The only vector instruction that can produce a scalar (remember,
5150   // since the bitcast was about to be turned into VMOVDRR, the source
5151   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5152   // Moreover, we can do this combine only if there is one use.
5153   // Finally, if the destination type is not a vector, there is not
5154   // much point on forcing everything on the vector bank.
5155   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5156       !Op.hasOneUse())
5157     return SDValue();
5158 
5159   // If the index is not constant, we will introduce an additional
5160   // multiply that will stick.
5161   // Give up in that case.
5162   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5163   if (!Index)
5164     return SDValue();
5165   unsigned DstNumElt = DstVT.getVectorNumElements();
5166 
5167   // Compute the new index.
5168   const APInt &APIntIndex = Index->getAPIntValue();
5169   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5170   NewIndex *= APIntIndex;
5171   // Check if the new constant index fits into i32.
5172   if (NewIndex.getBitWidth() > 32)
5173     return SDValue();
5174 
5175   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5176   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5177   SDLoc dl(Op);
5178   SDValue ExtractSrc = Op.getOperand(0);
5179   EVT VecVT = EVT::getVectorVT(
5180       *DAG.getContext(), DstVT.getScalarType(),
5181       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5182   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5183   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5184                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5185 }
5186 
5187 /// ExpandBITCAST - If the target supports VFP, this function is called to
5188 /// expand a bit convert where either the source or destination type is i64 to
5189 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5190 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5191 /// vectors), since the legalizer won't know what to do with that.
5192 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5193                              const ARMSubtarget *Subtarget) {
5194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5195   SDLoc dl(N);
5196   SDValue Op = N->getOperand(0);
5197 
5198   // This function is only supposed to be called for i64 types, either as the
5199   // source or destination of the bit convert.
5200   EVT SrcVT = Op.getValueType();
5201   EVT DstVT = N->getValueType(0);
5202   const bool HasFullFP16 = Subtarget->hasFullFP16();
5203 
5204   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5205      // FullFP16: half values are passed in S-registers, and we don't
5206      // need any of the bitcast and moves:
5207      //
5208      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5209      //   t5: i32 = bitcast t2
5210      // t18: f16 = ARMISD::VMOVhr t5
5211      if (Op.getOpcode() != ISD::CopyFromReg ||
5212          Op.getValueType() != MVT::f32)
5213        return SDValue();
5214 
5215      auto Move = N->use_begin();
5216      if (Move->getOpcode() != ARMISD::VMOVhr)
5217        return SDValue();
5218 
5219      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5220      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5221      DAG.ReplaceAllUsesWith(*Move, &Copy);
5222      return Copy;
5223   }
5224 
5225   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5226     if (!HasFullFP16)
5227       return SDValue();
5228     // SoftFP: read half-precision arguments:
5229     //
5230     // t2: i32,ch = ...
5231     //        t7: i16 = truncate t2 <~~~~ Op
5232     //      t8: f16 = bitcast t7    <~~~~ N
5233     //
5234     if (Op.getOperand(0).getValueType() == MVT::i32)
5235       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5236                          MVT::f16, Op.getOperand(0));
5237 
5238     return SDValue();
5239   }
5240 
5241   // Half-precision return values
5242   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5243     if (!HasFullFP16)
5244       return SDValue();
5245     //
5246     //          t11: f16 = fadd t8, t10
5247     //        t12: i16 = bitcast t11       <~~~ SDNode N
5248     //      t13: i32 = zero_extend t12
5249     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5250     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5251     //
5252     // transform this into:
5253     //
5254     //    t20: i32 = ARMISD::VMOVrh t11
5255     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5256     //
5257     auto ZeroExtend = N->use_begin();
5258     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5259         ZeroExtend->getValueType(0) != MVT::i32)
5260       return SDValue();
5261 
5262     auto Copy = ZeroExtend->use_begin();
5263     if (Copy->getOpcode() == ISD::CopyToReg &&
5264         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5265       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5266       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5267       return Cvt;
5268     }
5269     return SDValue();
5270   }
5271 
5272   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5273     return SDValue();
5274 
5275   // Turn i64->f64 into VMOVDRR.
5276   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5277     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5278     // if we can combine the bitcast with its source.
5279     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5280       return Val;
5281 
5282     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5283                              DAG.getConstant(0, dl, MVT::i32));
5284     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5285                              DAG.getConstant(1, dl, MVT::i32));
5286     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5287                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5288   }
5289 
5290   // Turn f64->i64 into VMOVRRD.
5291   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5292     SDValue Cvt;
5293     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5294         SrcVT.getVectorNumElements() > 1)
5295       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5296                         DAG.getVTList(MVT::i32, MVT::i32),
5297                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5298     else
5299       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5300                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5301     // Merge the pieces into a single i64 value.
5302     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5303   }
5304 
5305   return SDValue();
5306 }
5307 
5308 /// getZeroVector - Returns a vector of specified type with all zero elements.
5309 /// Zero vectors are used to represent vector negation and in those cases
5310 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5311 /// not support i64 elements, so sometimes the zero vectors will need to be
5312 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5313 /// zero vector.
5314 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5315   assert(VT.isVector() && "Expected a vector type");
5316   // The canonical modified immediate encoding of a zero vector is....0!
5317   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5318   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5319   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5320   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5321 }
5322 
5323 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5324 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5325 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5326                                                 SelectionDAG &DAG) const {
5327   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5328   EVT VT = Op.getValueType();
5329   unsigned VTBits = VT.getSizeInBits();
5330   SDLoc dl(Op);
5331   SDValue ShOpLo = Op.getOperand(0);
5332   SDValue ShOpHi = Op.getOperand(1);
5333   SDValue ShAmt  = Op.getOperand(2);
5334   SDValue ARMcc;
5335   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5336   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5337 
5338   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5339 
5340   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5341                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5342   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5343   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5344                                    DAG.getConstant(VTBits, dl, MVT::i32));
5345   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5346   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5347   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5348   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5349                             ISD::SETGE, ARMcc, DAG, dl);
5350   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5351                            ARMcc, CCR, CmpLo);
5352 
5353   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5354   SDValue HiBigShift = Opc == ISD::SRA
5355                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5356                                          DAG.getConstant(VTBits - 1, dl, VT))
5357                            : DAG.getConstant(0, dl, VT);
5358   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5359                             ISD::SETGE, ARMcc, DAG, dl);
5360   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5361                            ARMcc, CCR, CmpHi);
5362 
5363   SDValue Ops[2] = { Lo, Hi };
5364   return DAG.getMergeValues(Ops, dl);
5365 }
5366 
5367 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5368 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5369 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5370                                                SelectionDAG &DAG) const {
5371   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5372   EVT VT = Op.getValueType();
5373   unsigned VTBits = VT.getSizeInBits();
5374   SDLoc dl(Op);
5375   SDValue ShOpLo = Op.getOperand(0);
5376   SDValue ShOpHi = Op.getOperand(1);
5377   SDValue ShAmt  = Op.getOperand(2);
5378   SDValue ARMcc;
5379   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5380 
5381   assert(Op.getOpcode() == ISD::SHL_PARTS);
5382   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5383                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5384   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5385   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5386   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5387 
5388   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5389                                    DAG.getConstant(VTBits, dl, MVT::i32));
5390   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5391   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5392                             ISD::SETGE, ARMcc, DAG, dl);
5393   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5394                            ARMcc, CCR, CmpHi);
5395 
5396   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5397                           ISD::SETGE, ARMcc, DAG, dl);
5398   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5399   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5400                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5401 
5402   SDValue Ops[2] = { Lo, Hi };
5403   return DAG.getMergeValues(Ops, dl);
5404 }
5405 
5406 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5407                                             SelectionDAG &DAG) const {
5408   // The rounding mode is in bits 23:22 of the FPSCR.
5409   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5410   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5411   // so that the shift + and get folded into a bitfield extract.
5412   SDLoc dl(Op);
5413   SDValue Ops[] = { DAG.getEntryNode(),
5414                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5415 
5416   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5417   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5418                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5419   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5420                               DAG.getConstant(22, dl, MVT::i32));
5421   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5422                      DAG.getConstant(3, dl, MVT::i32));
5423 }
5424 
5425 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5426                          const ARMSubtarget *ST) {
5427   SDLoc dl(N);
5428   EVT VT = N->getValueType(0);
5429   if (VT.isVector()) {
5430     assert(ST->hasNEON());
5431 
5432     // Compute the least significant set bit: LSB = X & -X
5433     SDValue X = N->getOperand(0);
5434     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5435     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5436 
5437     EVT ElemTy = VT.getVectorElementType();
5438 
5439     if (ElemTy == MVT::i8) {
5440       // Compute with: cttz(x) = ctpop(lsb - 1)
5441       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5442                                 DAG.getTargetConstant(1, dl, ElemTy));
5443       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5444       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5445     }
5446 
5447     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5448         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5449       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5450       unsigned NumBits = ElemTy.getSizeInBits();
5451       SDValue WidthMinus1 =
5452           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5453                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5454       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5455       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5456     }
5457 
5458     // Compute with: cttz(x) = ctpop(lsb - 1)
5459 
5460     // Compute LSB - 1.
5461     SDValue Bits;
5462     if (ElemTy == MVT::i64) {
5463       // Load constant 0xffff'ffff'ffff'ffff to register.
5464       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5465                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5466       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5467     } else {
5468       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5469                                 DAG.getTargetConstant(1, dl, ElemTy));
5470       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5471     }
5472     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5473   }
5474 
5475   if (!ST->hasV6T2Ops())
5476     return SDValue();
5477 
5478   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5479   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5480 }
5481 
5482 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5483                           const ARMSubtarget *ST) {
5484   EVT VT = N->getValueType(0);
5485   SDLoc DL(N);
5486 
5487   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5488   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5489           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5490          "Unexpected type for custom ctpop lowering");
5491 
5492   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5493   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5494   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5495   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5496 
5497   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5498   unsigned EltSize = 8;
5499   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5500   while (EltSize != VT.getScalarSizeInBits()) {
5501     SmallVector<SDValue, 8> Ops;
5502     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5503                                   TLI.getPointerTy(DAG.getDataLayout())));
5504     Ops.push_back(Res);
5505 
5506     EltSize *= 2;
5507     NumElts /= 2;
5508     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5509     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5510   }
5511 
5512   return Res;
5513 }
5514 
5515 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5516                           const ARMSubtarget *ST) {
5517   EVT VT = N->getValueType(0);
5518   SDLoc dl(N);
5519 
5520   if (!VT.isVector())
5521     return SDValue();
5522 
5523   // Lower vector shifts on NEON to use VSHL.
5524   assert(ST->hasNEON() && "unexpected vector shift");
5525 
5526   // Left shifts translate directly to the vshiftu intrinsic.
5527   if (N->getOpcode() == ISD::SHL)
5528     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5529                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5530                                        MVT::i32),
5531                        N->getOperand(0), N->getOperand(1));
5532 
5533   assert((N->getOpcode() == ISD::SRA ||
5534           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5535 
5536   // NEON uses the same intrinsics for both left and right shifts.  For
5537   // right shifts, the shift amounts are negative, so negate the vector of
5538   // shift amounts.
5539   EVT ShiftVT = N->getOperand(1).getValueType();
5540   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5541                                      getZeroVector(ShiftVT, DAG, dl),
5542                                      N->getOperand(1));
5543   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5544                              Intrinsic::arm_neon_vshifts :
5545                              Intrinsic::arm_neon_vshiftu);
5546   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5547                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5548                      N->getOperand(0), NegatedCount);
5549 }
5550 
5551 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5552                                 const ARMSubtarget *ST) {
5553   EVT VT = N->getValueType(0);
5554   SDLoc dl(N);
5555 
5556   // We can get here for a node like i32 = ISD::SHL i32, i64
5557   if (VT != MVT::i64)
5558     return SDValue();
5559 
5560   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5561          "Unknown shift to lower!");
5562 
5563   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5564   if (!isOneConstant(N->getOperand(1)))
5565     return SDValue();
5566 
5567   // If we are in thumb mode, we don't have RRX.
5568   if (ST->isThumb1Only())
5569     return SDValue();
5570 
5571   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5572   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5573                            DAG.getConstant(0, dl, MVT::i32));
5574   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5575                            DAG.getConstant(1, dl, MVT::i32));
5576 
5577   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5578   // captures the result into a carry flag.
5579   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5580   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5581 
5582   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5583   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5584 
5585   // Merge the pieces into a single i64 value.
5586  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5587 }
5588 
5589 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5590   SDValue TmpOp0, TmpOp1;
5591   bool Invert = false;
5592   bool Swap = false;
5593   unsigned Opc = 0;
5594 
5595   SDValue Op0 = Op.getOperand(0);
5596   SDValue Op1 = Op.getOperand(1);
5597   SDValue CC = Op.getOperand(2);
5598   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5599   EVT VT = Op.getValueType();
5600   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5601   SDLoc dl(Op);
5602 
5603   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5604       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5605     // Special-case integer 64-bit equality comparisons. They aren't legal,
5606     // but they can be lowered with a few vector instructions.
5607     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5608     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5609     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5610     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5611     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5612                               DAG.getCondCode(ISD::SETEQ));
5613     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5614     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5615     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5616     if (SetCCOpcode == ISD::SETNE)
5617       Merged = DAG.getNOT(dl, Merged, CmpVT);
5618     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5619     return Merged;
5620   }
5621 
5622   if (CmpVT.getVectorElementType() == MVT::i64)
5623     // 64-bit comparisons are not legal in general.
5624     return SDValue();
5625 
5626   if (Op1.getValueType().isFloatingPoint()) {
5627     switch (SetCCOpcode) {
5628     default: llvm_unreachable("Illegal FP comparison");
5629     case ISD::SETUNE:
5630     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5631     case ISD::SETOEQ:
5632     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5633     case ISD::SETOLT:
5634     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5635     case ISD::SETOGT:
5636     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5637     case ISD::SETOLE:
5638     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5639     case ISD::SETOGE:
5640     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5641     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5642     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5643     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5644     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5645     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5646     case ISD::SETONE:
5647       // Expand this to (OLT | OGT).
5648       TmpOp0 = Op0;
5649       TmpOp1 = Op1;
5650       Opc = ISD::OR;
5651       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5652       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5653       break;
5654     case ISD::SETUO:
5655       Invert = true;
5656       LLVM_FALLTHROUGH;
5657     case ISD::SETO:
5658       // Expand this to (OLT | OGE).
5659       TmpOp0 = Op0;
5660       TmpOp1 = Op1;
5661       Opc = ISD::OR;
5662       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5663       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5664       break;
5665     }
5666   } else {
5667     // Integer comparisons.
5668     switch (SetCCOpcode) {
5669     default: llvm_unreachable("Illegal integer comparison");
5670     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5671     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5672     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5673     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5674     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5675     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5676     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5677     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5678     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5679     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5680     }
5681 
5682     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5683     if (Opc == ARMISD::VCEQ) {
5684       SDValue AndOp;
5685       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5686         AndOp = Op0;
5687       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5688         AndOp = Op1;
5689 
5690       // Ignore bitconvert.
5691       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5692         AndOp = AndOp.getOperand(0);
5693 
5694       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5695         Opc = ARMISD::VTST;
5696         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5697         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5698         Invert = !Invert;
5699       }
5700     }
5701   }
5702 
5703   if (Swap)
5704     std::swap(Op0, Op1);
5705 
5706   // If one of the operands is a constant vector zero, attempt to fold the
5707   // comparison to a specialized compare-against-zero form.
5708   SDValue SingleOp;
5709   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5710     SingleOp = Op0;
5711   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5712     if (Opc == ARMISD::VCGE)
5713       Opc = ARMISD::VCLEZ;
5714     else if (Opc == ARMISD::VCGT)
5715       Opc = ARMISD::VCLTZ;
5716     SingleOp = Op1;
5717   }
5718 
5719   SDValue Result;
5720   if (SingleOp.getNode()) {
5721     switch (Opc) {
5722     case ARMISD::VCEQ:
5723       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5724     case ARMISD::VCGE:
5725       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5726     case ARMISD::VCLEZ:
5727       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5728     case ARMISD::VCGT:
5729       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5730     case ARMISD::VCLTZ:
5731       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5732     default:
5733       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5734     }
5735   } else {
5736      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5737   }
5738 
5739   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5740 
5741   if (Invert)
5742     Result = DAG.getNOT(dl, Result, VT);
5743 
5744   return Result;
5745 }
5746 
5747 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
5748   SDValue LHS = Op.getOperand(0);
5749   SDValue RHS = Op.getOperand(1);
5750   SDValue Carry = Op.getOperand(2);
5751   SDValue Cond = Op.getOperand(3);
5752   SDLoc DL(Op);
5753 
5754   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
5755 
5756   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
5757   // have to invert the carry first.
5758   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
5759                       DAG.getConstant(1, DL, MVT::i32), Carry);
5760   // This converts the boolean value carry into the carry flag.
5761   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
5762 
5763   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5764   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5765 
5766   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5767   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5768   SDValue ARMcc = DAG.getConstant(
5769       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5770   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5771   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5772                                    Cmp.getValue(1), SDValue());
5773   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5774                      CCR, Chain.getValue(1));
5775 }
5776 
5777 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5778 /// valid vector constant for a NEON instruction with a "modified immediate"
5779 /// operand (e.g., VMOV).  If so, return the encoded value.
5780 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5781                                  unsigned SplatBitSize, SelectionDAG &DAG,
5782                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5783                                  NEONModImmType type) {
5784   unsigned OpCmode, Imm;
5785 
5786   // SplatBitSize is set to the smallest size that splats the vector, so a
5787   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5788   // immediate instructions others than VMOV do not support the 8-bit encoding
5789   // of a zero vector, and the default encoding of zero is supposed to be the
5790   // 32-bit version.
5791   if (SplatBits == 0)
5792     SplatBitSize = 32;
5793 
5794   switch (SplatBitSize) {
5795   case 8:
5796     if (type != VMOVModImm)
5797       return SDValue();
5798     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5799     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5800     OpCmode = 0xe;
5801     Imm = SplatBits;
5802     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5803     break;
5804 
5805   case 16:
5806     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5807     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5808     if ((SplatBits & ~0xff) == 0) {
5809       // Value = 0x00nn: Op=x, Cmode=100x.
5810       OpCmode = 0x8;
5811       Imm = SplatBits;
5812       break;
5813     }
5814     if ((SplatBits & ~0xff00) == 0) {
5815       // Value = 0xnn00: Op=x, Cmode=101x.
5816       OpCmode = 0xa;
5817       Imm = SplatBits >> 8;
5818       break;
5819     }
5820     return SDValue();
5821 
5822   case 32:
5823     // NEON's 32-bit VMOV supports splat values where:
5824     // * only one byte is nonzero, or
5825     // * the least significant byte is 0xff and the second byte is nonzero, or
5826     // * the least significant 2 bytes are 0xff and the third is nonzero.
5827     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5828     if ((SplatBits & ~0xff) == 0) {
5829       // Value = 0x000000nn: Op=x, Cmode=000x.
5830       OpCmode = 0;
5831       Imm = SplatBits;
5832       break;
5833     }
5834     if ((SplatBits & ~0xff00) == 0) {
5835       // Value = 0x0000nn00: Op=x, Cmode=001x.
5836       OpCmode = 0x2;
5837       Imm = SplatBits >> 8;
5838       break;
5839     }
5840     if ((SplatBits & ~0xff0000) == 0) {
5841       // Value = 0x00nn0000: Op=x, Cmode=010x.
5842       OpCmode = 0x4;
5843       Imm = SplatBits >> 16;
5844       break;
5845     }
5846     if ((SplatBits & ~0xff000000) == 0) {
5847       // Value = 0xnn000000: Op=x, Cmode=011x.
5848       OpCmode = 0x6;
5849       Imm = SplatBits >> 24;
5850       break;
5851     }
5852 
5853     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5854     if (type == OtherModImm) return SDValue();
5855 
5856     if ((SplatBits & ~0xffff) == 0 &&
5857         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5858       // Value = 0x0000nnff: Op=x, Cmode=1100.
5859       OpCmode = 0xc;
5860       Imm = SplatBits >> 8;
5861       break;
5862     }
5863 
5864     if ((SplatBits & ~0xffffff) == 0 &&
5865         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5866       // Value = 0x00nnffff: Op=x, Cmode=1101.
5867       OpCmode = 0xd;
5868       Imm = SplatBits >> 16;
5869       break;
5870     }
5871 
5872     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5873     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5874     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5875     // and fall through here to test for a valid 64-bit splat.  But, then the
5876     // caller would also need to check and handle the change in size.
5877     return SDValue();
5878 
5879   case 64: {
5880     if (type != VMOVModImm)
5881       return SDValue();
5882     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5883     uint64_t BitMask = 0xff;
5884     uint64_t Val = 0;
5885     unsigned ImmMask = 1;
5886     Imm = 0;
5887     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5888       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5889         Val |= BitMask;
5890         Imm |= ImmMask;
5891       } else if ((SplatBits & BitMask) != 0) {
5892         return SDValue();
5893       }
5894       BitMask <<= 8;
5895       ImmMask <<= 1;
5896     }
5897 
5898     if (DAG.getDataLayout().isBigEndian())
5899       // swap higher and lower 32 bit word
5900       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5901 
5902     // Op=1, Cmode=1110.
5903     OpCmode = 0x1e;
5904     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5905     break;
5906   }
5907 
5908   default:
5909     llvm_unreachable("unexpected size for isNEONModifiedImm");
5910   }
5911 
5912   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5913   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5914 }
5915 
5916 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5917                                            const ARMSubtarget *ST) const {
5918   EVT VT = Op.getValueType();
5919   bool IsDouble = (VT == MVT::f64);
5920   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5921   const APFloat &FPVal = CFP->getValueAPF();
5922 
5923   // Prevent floating-point constants from using literal loads
5924   // when execute-only is enabled.
5925   if (ST->genExecuteOnly()) {
5926     // If we can represent the constant as an immediate, don't lower it
5927     if (isFPImmLegal(FPVal, VT))
5928       return Op;
5929     // Otherwise, construct as integer, and move to float register
5930     APInt INTVal = FPVal.bitcastToAPInt();
5931     SDLoc DL(CFP);
5932     switch (VT.getSimpleVT().SimpleTy) {
5933       default:
5934         llvm_unreachable("Unknown floating point type!");
5935         break;
5936       case MVT::f64: {
5937         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5938         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5939         if (!ST->isLittle())
5940           std::swap(Lo, Hi);
5941         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5942       }
5943       case MVT::f32:
5944           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
5945               DAG.getConstant(INTVal, DL, MVT::i32));
5946     }
5947   }
5948 
5949   if (!ST->hasVFP3Base())
5950     return SDValue();
5951 
5952   // Use the default (constant pool) lowering for double constants when we have
5953   // an SP-only FPU
5954   if (IsDouble && !Subtarget->hasFP64())
5955     return SDValue();
5956 
5957   // Try splatting with a VMOV.f32...
5958   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5959 
5960   if (ImmVal != -1) {
5961     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5962       // We have code in place to select a valid ConstantFP already, no need to
5963       // do any mangling.
5964       return Op;
5965     }
5966 
5967     // It's a float and we are trying to use NEON operations where
5968     // possible. Lower it to a splat followed by an extract.
5969     SDLoc DL(Op);
5970     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5971     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5972                                       NewVal);
5973     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5974                        DAG.getConstant(0, DL, MVT::i32));
5975   }
5976 
5977   // The rest of our options are NEON only, make sure that's allowed before
5978   // proceeding..
5979   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5980     return SDValue();
5981 
5982   EVT VMovVT;
5983   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5984 
5985   // It wouldn't really be worth bothering for doubles except for one very
5986   // important value, which does happen to match: 0.0. So make sure we don't do
5987   // anything stupid.
5988   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5989     return SDValue();
5990 
5991   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5992   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5993                                      VMovVT, false, VMOVModImm);
5994   if (NewVal != SDValue()) {
5995     SDLoc DL(Op);
5996     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5997                                       NewVal);
5998     if (IsDouble)
5999       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6000 
6001     // It's a float: cast and extract a vector element.
6002     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6003                                        VecConstant);
6004     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6005                        DAG.getConstant(0, DL, MVT::i32));
6006   }
6007 
6008   // Finally, try a VMVN.i32
6009   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6010                              false, VMVNModImm);
6011   if (NewVal != SDValue()) {
6012     SDLoc DL(Op);
6013     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6014 
6015     if (IsDouble)
6016       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6017 
6018     // It's a float: cast and extract a vector element.
6019     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6020                                        VecConstant);
6021     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6022                        DAG.getConstant(0, DL, MVT::i32));
6023   }
6024 
6025   return SDValue();
6026 }
6027 
6028 // check if an VEXT instruction can handle the shuffle mask when the
6029 // vector sources of the shuffle are the same.
6030 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6031   unsigned NumElts = VT.getVectorNumElements();
6032 
6033   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6034   if (M[0] < 0)
6035     return false;
6036 
6037   Imm = M[0];
6038 
6039   // If this is a VEXT shuffle, the immediate value is the index of the first
6040   // element.  The other shuffle indices must be the successive elements after
6041   // the first one.
6042   unsigned ExpectedElt = Imm;
6043   for (unsigned i = 1; i < NumElts; ++i) {
6044     // Increment the expected index.  If it wraps around, just follow it
6045     // back to index zero and keep going.
6046     ++ExpectedElt;
6047     if (ExpectedElt == NumElts)
6048       ExpectedElt = 0;
6049 
6050     if (M[i] < 0) continue; // ignore UNDEF indices
6051     if (ExpectedElt != static_cast<unsigned>(M[i]))
6052       return false;
6053   }
6054 
6055   return true;
6056 }
6057 
6058 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6059                        bool &ReverseVEXT, unsigned &Imm) {
6060   unsigned NumElts = VT.getVectorNumElements();
6061   ReverseVEXT = false;
6062 
6063   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6064   if (M[0] < 0)
6065     return false;
6066 
6067   Imm = M[0];
6068 
6069   // If this is a VEXT shuffle, the immediate value is the index of the first
6070   // element.  The other shuffle indices must be the successive elements after
6071   // the first one.
6072   unsigned ExpectedElt = Imm;
6073   for (unsigned i = 1; i < NumElts; ++i) {
6074     // Increment the expected index.  If it wraps around, it may still be
6075     // a VEXT but the source vectors must be swapped.
6076     ExpectedElt += 1;
6077     if (ExpectedElt == NumElts * 2) {
6078       ExpectedElt = 0;
6079       ReverseVEXT = true;
6080     }
6081 
6082     if (M[i] < 0) continue; // ignore UNDEF indices
6083     if (ExpectedElt != static_cast<unsigned>(M[i]))
6084       return false;
6085   }
6086 
6087   // Adjust the index value if the source operands will be swapped.
6088   if (ReverseVEXT)
6089     Imm -= NumElts;
6090 
6091   return true;
6092 }
6093 
6094 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6095 /// instruction with the specified blocksize.  (The order of the elements
6096 /// within each block of the vector is reversed.)
6097 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6098   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6099          "Only possible block sizes for VREV are: 16, 32, 64");
6100 
6101   unsigned EltSz = VT.getScalarSizeInBits();
6102   if (EltSz == 64)
6103     return false;
6104 
6105   unsigned NumElts = VT.getVectorNumElements();
6106   unsigned BlockElts = M[0] + 1;
6107   // If the first shuffle index is UNDEF, be optimistic.
6108   if (M[0] < 0)
6109     BlockElts = BlockSize / EltSz;
6110 
6111   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6112     return false;
6113 
6114   for (unsigned i = 0; i < NumElts; ++i) {
6115     if (M[i] < 0) continue; // ignore UNDEF indices
6116     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6117       return false;
6118   }
6119 
6120   return true;
6121 }
6122 
6123 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6124   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6125   // range, then 0 is placed into the resulting vector. So pretty much any mask
6126   // of 8 elements can work here.
6127   return VT == MVT::v8i8 && M.size() == 8;
6128 }
6129 
6130 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6131                                unsigned Index) {
6132   if (Mask.size() == Elements * 2)
6133     return Index / Elements;
6134   return Mask[Index] == 0 ? 0 : 1;
6135 }
6136 
6137 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6138 // checking that pairs of elements in the shuffle mask represent the same index
6139 // in each vector, incrementing the expected index by 2 at each step.
6140 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6141 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6142 //  v2={e,f,g,h}
6143 // WhichResult gives the offset for each element in the mask based on which
6144 // of the two results it belongs to.
6145 //
6146 // The transpose can be represented either as:
6147 // result1 = shufflevector v1, v2, result1_shuffle_mask
6148 // result2 = shufflevector v1, v2, result2_shuffle_mask
6149 // where v1/v2 and the shuffle masks have the same number of elements
6150 // (here WhichResult (see below) indicates which result is being checked)
6151 //
6152 // or as:
6153 // results = shufflevector v1, v2, shuffle_mask
6154 // where both results are returned in one vector and the shuffle mask has twice
6155 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6156 // want to check the low half and high half of the shuffle mask as if it were
6157 // the other case
6158 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6159   unsigned EltSz = VT.getScalarSizeInBits();
6160   if (EltSz == 64)
6161     return false;
6162 
6163   unsigned NumElts = VT.getVectorNumElements();
6164   if (M.size() != NumElts && M.size() != NumElts*2)
6165     return false;
6166 
6167   // If the mask is twice as long as the input vector then we need to check the
6168   // upper and lower parts of the mask with a matching value for WhichResult
6169   // FIXME: A mask with only even values will be rejected in case the first
6170   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6171   // M[0] is used to determine WhichResult
6172   for (unsigned i = 0; i < M.size(); i += NumElts) {
6173     WhichResult = SelectPairHalf(NumElts, M, i);
6174     for (unsigned j = 0; j < NumElts; j += 2) {
6175       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6176           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6177         return false;
6178     }
6179   }
6180 
6181   if (M.size() == NumElts*2)
6182     WhichResult = 0;
6183 
6184   return true;
6185 }
6186 
6187 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6188 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6189 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6190 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6191   unsigned EltSz = VT.getScalarSizeInBits();
6192   if (EltSz == 64)
6193     return false;
6194 
6195   unsigned NumElts = VT.getVectorNumElements();
6196   if (M.size() != NumElts && M.size() != NumElts*2)
6197     return false;
6198 
6199   for (unsigned i = 0; i < M.size(); i += NumElts) {
6200     WhichResult = SelectPairHalf(NumElts, M, i);
6201     for (unsigned j = 0; j < NumElts; j += 2) {
6202       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6203           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6204         return false;
6205     }
6206   }
6207 
6208   if (M.size() == NumElts*2)
6209     WhichResult = 0;
6210 
6211   return true;
6212 }
6213 
6214 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6215 // that the mask elements are either all even and in steps of size 2 or all odd
6216 // and in steps of size 2.
6217 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6218 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6219 //  v2={e,f,g,h}
6220 // Requires similar checks to that of isVTRNMask with
6221 // respect the how results are returned.
6222 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6223   unsigned EltSz = VT.getScalarSizeInBits();
6224   if (EltSz == 64)
6225     return false;
6226 
6227   unsigned NumElts = VT.getVectorNumElements();
6228   if (M.size() != NumElts && M.size() != NumElts*2)
6229     return false;
6230 
6231   for (unsigned i = 0; i < M.size(); i += NumElts) {
6232     WhichResult = SelectPairHalf(NumElts, M, i);
6233     for (unsigned j = 0; j < NumElts; ++j) {
6234       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6235         return false;
6236     }
6237   }
6238 
6239   if (M.size() == NumElts*2)
6240     WhichResult = 0;
6241 
6242   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6243   if (VT.is64BitVector() && EltSz == 32)
6244     return false;
6245 
6246   return true;
6247 }
6248 
6249 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6250 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6251 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6252 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6253   unsigned EltSz = VT.getScalarSizeInBits();
6254   if (EltSz == 64)
6255     return false;
6256 
6257   unsigned NumElts = VT.getVectorNumElements();
6258   if (M.size() != NumElts && M.size() != NumElts*2)
6259     return false;
6260 
6261   unsigned Half = NumElts / 2;
6262   for (unsigned i = 0; i < M.size(); i += NumElts) {
6263     WhichResult = SelectPairHalf(NumElts, M, i);
6264     for (unsigned j = 0; j < NumElts; j += Half) {
6265       unsigned Idx = WhichResult;
6266       for (unsigned k = 0; k < Half; ++k) {
6267         int MIdx = M[i + j + k];
6268         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6269           return false;
6270         Idx += 2;
6271       }
6272     }
6273   }
6274 
6275   if (M.size() == NumElts*2)
6276     WhichResult = 0;
6277 
6278   // VUZP.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 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6286 // that pairs of elements of the shufflemask represent the same index in each
6287 // vector incrementing sequentially through the vectors.
6288 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6289 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6290 //  v2={e,f,g,h}
6291 // Requires similar checks to that of isVTRNMask with respect the how results
6292 // are returned.
6293 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6294   unsigned EltSz = VT.getScalarSizeInBits();
6295   if (EltSz == 64)
6296     return false;
6297 
6298   unsigned NumElts = VT.getVectorNumElements();
6299   if (M.size() != NumElts && M.size() != NumElts*2)
6300     return false;
6301 
6302   for (unsigned i = 0; i < M.size(); i += NumElts) {
6303     WhichResult = SelectPairHalf(NumElts, M, i);
6304     unsigned Idx = WhichResult * NumElts / 2;
6305     for (unsigned j = 0; j < NumElts; j += 2) {
6306       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6307           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6308         return false;
6309       Idx += 1;
6310     }
6311   }
6312 
6313   if (M.size() == NumElts*2)
6314     WhichResult = 0;
6315 
6316   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6317   if (VT.is64BitVector() && EltSz == 32)
6318     return false;
6319 
6320   return true;
6321 }
6322 
6323 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6324 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6325 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6326 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6327   unsigned EltSz = VT.getScalarSizeInBits();
6328   if (EltSz == 64)
6329     return false;
6330 
6331   unsigned NumElts = VT.getVectorNumElements();
6332   if (M.size() != NumElts && M.size() != NumElts*2)
6333     return false;
6334 
6335   for (unsigned i = 0; i < M.size(); i += NumElts) {
6336     WhichResult = SelectPairHalf(NumElts, M, i);
6337     unsigned Idx = WhichResult * NumElts / 2;
6338     for (unsigned j = 0; j < NumElts; j += 2) {
6339       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6340           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6341         return false;
6342       Idx += 1;
6343     }
6344   }
6345 
6346   if (M.size() == NumElts*2)
6347     WhichResult = 0;
6348 
6349   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6350   if (VT.is64BitVector() && EltSz == 32)
6351     return false;
6352 
6353   return true;
6354 }
6355 
6356 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6357 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6358 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6359                                            unsigned &WhichResult,
6360                                            bool &isV_UNDEF) {
6361   isV_UNDEF = false;
6362   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6363     return ARMISD::VTRN;
6364   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6365     return ARMISD::VUZP;
6366   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6367     return ARMISD::VZIP;
6368 
6369   isV_UNDEF = true;
6370   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6371     return ARMISD::VTRN;
6372   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6373     return ARMISD::VUZP;
6374   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6375     return ARMISD::VZIP;
6376 
6377   return 0;
6378 }
6379 
6380 /// \return true if this is a reverse operation on an vector.
6381 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6382   unsigned NumElts = VT.getVectorNumElements();
6383   // Make sure the mask has the right size.
6384   if (NumElts != M.size())
6385       return false;
6386 
6387   // Look for <15, ..., 3, -1, 1, 0>.
6388   for (unsigned i = 0; i != NumElts; ++i)
6389     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6390       return false;
6391 
6392   return true;
6393 }
6394 
6395 // If N is an integer constant that can be moved into a register in one
6396 // instruction, return an SDValue of such a constant (will become a MOV
6397 // instruction).  Otherwise return null.
6398 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6399                                      const ARMSubtarget *ST, const SDLoc &dl) {
6400   uint64_t Val;
6401   if (!isa<ConstantSDNode>(N))
6402     return SDValue();
6403   Val = cast<ConstantSDNode>(N)->getZExtValue();
6404 
6405   if (ST->isThumb1Only()) {
6406     if (Val <= 255 || ~Val <= 255)
6407       return DAG.getConstant(Val, dl, MVT::i32);
6408   } else {
6409     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6410       return DAG.getConstant(Val, dl, MVT::i32);
6411   }
6412   return SDValue();
6413 }
6414 
6415 // If this is a case we can't handle, return null and let the default
6416 // expansion code take care of it.
6417 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6418                                              const ARMSubtarget *ST) const {
6419   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6420   SDLoc dl(Op);
6421   EVT VT = Op.getValueType();
6422 
6423   APInt SplatBits, SplatUndef;
6424   unsigned SplatBitSize;
6425   bool HasAnyUndefs;
6426   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6427     if (SplatUndef.isAllOnesValue())
6428       return DAG.getUNDEF(VT);
6429 
6430     if (SplatBitSize <= 64) {
6431       // Check if an immediate VMOV works.
6432       EVT VmovVT;
6433       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6434                                       SplatUndef.getZExtValue(), SplatBitSize,
6435                                       DAG, dl, VmovVT, VT.is128BitVector(),
6436                                       VMOVModImm);
6437       if (Val.getNode()) {
6438         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6439         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6440       }
6441 
6442       // Try an immediate VMVN.
6443       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6444       Val = isNEONModifiedImm(NegatedImm,
6445                                       SplatUndef.getZExtValue(), SplatBitSize,
6446                                       DAG, dl, VmovVT, VT.is128BitVector(),
6447                                       VMVNModImm);
6448       if (Val.getNode()) {
6449         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6450         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6451       }
6452 
6453       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6454       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6455         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6456         if (ImmVal != -1) {
6457           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6458           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6459         }
6460       }
6461     }
6462   }
6463 
6464   // Scan through the operands to see if only one value is used.
6465   //
6466   // As an optimisation, even if more than one value is used it may be more
6467   // profitable to splat with one value then change some lanes.
6468   //
6469   // Heuristically we decide to do this if the vector has a "dominant" value,
6470   // defined as splatted to more than half of the lanes.
6471   unsigned NumElts = VT.getVectorNumElements();
6472   bool isOnlyLowElement = true;
6473   bool usesOnlyOneValue = true;
6474   bool hasDominantValue = false;
6475   bool isConstant = true;
6476 
6477   // Map of the number of times a particular SDValue appears in the
6478   // element list.
6479   DenseMap<SDValue, unsigned> ValueCounts;
6480   SDValue Value;
6481   for (unsigned i = 0; i < NumElts; ++i) {
6482     SDValue V = Op.getOperand(i);
6483     if (V.isUndef())
6484       continue;
6485     if (i > 0)
6486       isOnlyLowElement = false;
6487     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6488       isConstant = false;
6489 
6490     ValueCounts.insert(std::make_pair(V, 0));
6491     unsigned &Count = ValueCounts[V];
6492 
6493     // Is this value dominant? (takes up more than half of the lanes)
6494     if (++Count > (NumElts / 2)) {
6495       hasDominantValue = true;
6496       Value = V;
6497     }
6498   }
6499   if (ValueCounts.size() != 1)
6500     usesOnlyOneValue = false;
6501   if (!Value.getNode() && !ValueCounts.empty())
6502     Value = ValueCounts.begin()->first;
6503 
6504   if (ValueCounts.empty())
6505     return DAG.getUNDEF(VT);
6506 
6507   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6508   // Keep going if we are hitting this case.
6509   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6510     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6511 
6512   unsigned EltSize = VT.getScalarSizeInBits();
6513 
6514   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6515   // i32 and try again.
6516   if (hasDominantValue && EltSize <= 32) {
6517     if (!isConstant) {
6518       SDValue N;
6519 
6520       // If we are VDUPing a value that comes directly from a vector, that will
6521       // cause an unnecessary move to and from a GPR, where instead we could
6522       // just use VDUPLANE. We can only do this if the lane being extracted
6523       // is at a constant index, as the VDUP from lane instructions only have
6524       // constant-index forms.
6525       ConstantSDNode *constIndex;
6526       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6527           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6528         // We need to create a new undef vector to use for the VDUPLANE if the
6529         // size of the vector from which we get the value is different than the
6530         // size of the vector that we need to create. We will insert the element
6531         // such that the register coalescer will remove unnecessary copies.
6532         if (VT != Value->getOperand(0).getValueType()) {
6533           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6534                              VT.getVectorNumElements();
6535           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6536                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6537                         Value, DAG.getConstant(index, dl, MVT::i32)),
6538                            DAG.getConstant(index, dl, MVT::i32));
6539         } else
6540           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6541                         Value->getOperand(0), Value->getOperand(1));
6542       } else
6543         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6544 
6545       if (!usesOnlyOneValue) {
6546         // The dominant value was splatted as 'N', but we now have to insert
6547         // all differing elements.
6548         for (unsigned I = 0; I < NumElts; ++I) {
6549           if (Op.getOperand(I) == Value)
6550             continue;
6551           SmallVector<SDValue, 3> Ops;
6552           Ops.push_back(N);
6553           Ops.push_back(Op.getOperand(I));
6554           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6555           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6556         }
6557       }
6558       return N;
6559     }
6560     if (VT.getVectorElementType().isFloatingPoint()) {
6561       SmallVector<SDValue, 8> Ops;
6562       for (unsigned i = 0; i < NumElts; ++i)
6563         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6564                                   Op.getOperand(i)));
6565       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6566       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6567       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6568       if (Val.getNode())
6569         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6570     }
6571     if (usesOnlyOneValue) {
6572       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6573       if (isConstant && Val.getNode())
6574         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6575     }
6576   }
6577 
6578   // If all elements are constants and the case above didn't get hit, fall back
6579   // to the default expansion, which will generate a load from the constant
6580   // pool.
6581   if (isConstant)
6582     return SDValue();
6583 
6584   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6585   if (NumElts >= 4) {
6586     SDValue shuffle = ReconstructShuffle(Op, DAG);
6587     if (shuffle != SDValue())
6588       return shuffle;
6589   }
6590 
6591   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6592     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6593     // into two 64-bit vectors; we might discover a better way to lower it.
6594     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6595     EVT ExtVT = VT.getVectorElementType();
6596     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6597     SDValue Lower =
6598         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6599     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6600       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6601     SDValue Upper = DAG.getBuildVector(
6602         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6603     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6604       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6605     if (Lower && Upper)
6606       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6607   }
6608 
6609   // Vectors with 32- or 64-bit elements can be built by directly assigning
6610   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6611   // will be legalized.
6612   if (EltSize >= 32) {
6613     // Do the expansion with floating-point types, since that is what the VFP
6614     // registers are defined to use, and since i64 is not legal.
6615     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6616     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6617     SmallVector<SDValue, 8> Ops;
6618     for (unsigned i = 0; i < NumElts; ++i)
6619       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6620     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6621     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6622   }
6623 
6624   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6625   // know the default expansion would otherwise fall back on something even
6626   // worse. For a vector with one or two non-undef values, that's
6627   // scalar_to_vector for the elements followed by a shuffle (provided the
6628   // shuffle is valid for the target) and materialization element by element
6629   // on the stack followed by a load for everything else.
6630   if (!isConstant && !usesOnlyOneValue) {
6631     SDValue Vec = DAG.getUNDEF(VT);
6632     for (unsigned i = 0 ; i < NumElts; ++i) {
6633       SDValue V = Op.getOperand(i);
6634       if (V.isUndef())
6635         continue;
6636       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6637       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6638     }
6639     return Vec;
6640   }
6641 
6642   return SDValue();
6643 }
6644 
6645 // Gather data to see if the operation can be modelled as a
6646 // shuffle in combination with VEXTs.
6647 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6648                                               SelectionDAG &DAG) const {
6649   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6650   SDLoc dl(Op);
6651   EVT VT = Op.getValueType();
6652   unsigned NumElts = VT.getVectorNumElements();
6653 
6654   struct ShuffleSourceInfo {
6655     SDValue Vec;
6656     unsigned MinElt = std::numeric_limits<unsigned>::max();
6657     unsigned MaxElt = 0;
6658 
6659     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6660     // be compatible with the shuffle we intend to construct. As a result
6661     // ShuffleVec will be some sliding window into the original Vec.
6662     SDValue ShuffleVec;
6663 
6664     // Code should guarantee that element i in Vec starts at element "WindowBase
6665     // + i * WindowScale in ShuffleVec".
6666     int WindowBase = 0;
6667     int WindowScale = 1;
6668 
6669     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6670 
6671     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6672   };
6673 
6674   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6675   // node.
6676   SmallVector<ShuffleSourceInfo, 2> Sources;
6677   for (unsigned i = 0; i < NumElts; ++i) {
6678     SDValue V = Op.getOperand(i);
6679     if (V.isUndef())
6680       continue;
6681     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6682       // A shuffle can only come from building a vector from various
6683       // elements of other vectors.
6684       return SDValue();
6685     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6686       // Furthermore, shuffles require a constant mask, whereas extractelts
6687       // accept variable indices.
6688       return SDValue();
6689     }
6690 
6691     // Add this element source to the list if it's not already there.
6692     SDValue SourceVec = V.getOperand(0);
6693     auto Source = llvm::find(Sources, SourceVec);
6694     if (Source == Sources.end())
6695       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6696 
6697     // Update the minimum and maximum lane number seen.
6698     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6699     Source->MinElt = std::min(Source->MinElt, EltNo);
6700     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6701   }
6702 
6703   // Currently only do something sane when at most two source vectors
6704   // are involved.
6705   if (Sources.size() > 2)
6706     return SDValue();
6707 
6708   // Find out the smallest element size among result and two sources, and use
6709   // it as element size to build the shuffle_vector.
6710   EVT SmallestEltTy = VT.getVectorElementType();
6711   for (auto &Source : Sources) {
6712     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6713     if (SrcEltTy.bitsLT(SmallestEltTy))
6714       SmallestEltTy = SrcEltTy;
6715   }
6716   unsigned ResMultiplier =
6717       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6718   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6719   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6720 
6721   // If the source vector is too wide or too narrow, we may nevertheless be able
6722   // to construct a compatible shuffle either by concatenating it with UNDEF or
6723   // extracting a suitable range of elements.
6724   for (auto &Src : Sources) {
6725     EVT SrcVT = Src.ShuffleVec.getValueType();
6726 
6727     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6728       continue;
6729 
6730     // This stage of the search produces a source with the same element type as
6731     // the original, but with a total width matching the BUILD_VECTOR output.
6732     EVT EltVT = SrcVT.getVectorElementType();
6733     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6734     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6735 
6736     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6737       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6738         return SDValue();
6739       // We can pad out the smaller vector for free, so if it's part of a
6740       // shuffle...
6741       Src.ShuffleVec =
6742           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6743                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6744       continue;
6745     }
6746 
6747     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6748       return SDValue();
6749 
6750     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6751       // Span too large for a VEXT to cope
6752       return SDValue();
6753     }
6754 
6755     if (Src.MinElt >= NumSrcElts) {
6756       // The extraction can just take the second half
6757       Src.ShuffleVec =
6758           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6759                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6760       Src.WindowBase = -NumSrcElts;
6761     } else if (Src.MaxElt < NumSrcElts) {
6762       // The extraction can just take the first half
6763       Src.ShuffleVec =
6764           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6765                       DAG.getConstant(0, dl, MVT::i32));
6766     } else {
6767       // An actual VEXT is needed
6768       SDValue VEXTSrc1 =
6769           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6770                       DAG.getConstant(0, dl, MVT::i32));
6771       SDValue VEXTSrc2 =
6772           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6773                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6774 
6775       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6776                                    VEXTSrc2,
6777                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6778       Src.WindowBase = -Src.MinElt;
6779     }
6780   }
6781 
6782   // Another possible incompatibility occurs from the vector element types. We
6783   // can fix this by bitcasting the source vectors to the same type we intend
6784   // for the shuffle.
6785   for (auto &Src : Sources) {
6786     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6787     if (SrcEltTy == SmallestEltTy)
6788       continue;
6789     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6790     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6791     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6792     Src.WindowBase *= Src.WindowScale;
6793   }
6794 
6795   // Final sanity check before we try to actually produce a shuffle.
6796   LLVM_DEBUG(for (auto Src
6797                   : Sources)
6798                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6799 
6800   // The stars all align, our next step is to produce the mask for the shuffle.
6801   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6802   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6803   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6804     SDValue Entry = Op.getOperand(i);
6805     if (Entry.isUndef())
6806       continue;
6807 
6808     auto Src = llvm::find(Sources, Entry.getOperand(0));
6809     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6810 
6811     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6812     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6813     // segment.
6814     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6815     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6816                                VT.getScalarSizeInBits());
6817     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6818 
6819     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6820     // starting at the appropriate offset.
6821     int *LaneMask = &Mask[i * ResMultiplier];
6822 
6823     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6824     ExtractBase += NumElts * (Src - Sources.begin());
6825     for (int j = 0; j < LanesDefined; ++j)
6826       LaneMask[j] = ExtractBase + j;
6827   }
6828 
6829   // Final check before we try to produce nonsense...
6830   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6831     return SDValue();
6832 
6833   // We can't handle more than two sources. This should have already
6834   // been checked before this point.
6835   assert(Sources.size() <= 2 && "Too many sources!");
6836 
6837   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6838   for (unsigned i = 0; i < Sources.size(); ++i)
6839     ShuffleOps[i] = Sources[i].ShuffleVec;
6840 
6841   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6842                                          ShuffleOps[1], Mask);
6843   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6844 }
6845 
6846 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6847 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6848 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6849 /// are assumed to be legal.
6850 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6851   if (VT.getVectorNumElements() == 4 &&
6852       (VT.is128BitVector() || VT.is64BitVector())) {
6853     unsigned PFIndexes[4];
6854     for (unsigned i = 0; i != 4; ++i) {
6855       if (M[i] < 0)
6856         PFIndexes[i] = 8;
6857       else
6858         PFIndexes[i] = M[i];
6859     }
6860 
6861     // Compute the index in the perfect shuffle table.
6862     unsigned PFTableIndex =
6863       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6864     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6865     unsigned Cost = (PFEntry >> 30);
6866 
6867     if (Cost <= 4)
6868       return true;
6869   }
6870 
6871   bool ReverseVEXT, isV_UNDEF;
6872   unsigned Imm, WhichResult;
6873 
6874   unsigned EltSize = VT.getScalarSizeInBits();
6875   return (EltSize >= 32 ||
6876           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6877           isVREVMask(M, VT, 64) ||
6878           isVREVMask(M, VT, 32) ||
6879           isVREVMask(M, VT, 16) ||
6880           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6881           isVTBLMask(M, VT) ||
6882           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6883           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6884 }
6885 
6886 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6887 /// the specified operations to build the shuffle.
6888 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6889                                       SDValue RHS, SelectionDAG &DAG,
6890                                       const SDLoc &dl) {
6891   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6892   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6893   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6894 
6895   enum {
6896     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6897     OP_VREV,
6898     OP_VDUP0,
6899     OP_VDUP1,
6900     OP_VDUP2,
6901     OP_VDUP3,
6902     OP_VEXT1,
6903     OP_VEXT2,
6904     OP_VEXT3,
6905     OP_VUZPL, // VUZP, left result
6906     OP_VUZPR, // VUZP, right result
6907     OP_VZIPL, // VZIP, left result
6908     OP_VZIPR, // VZIP, right result
6909     OP_VTRNL, // VTRN, left result
6910     OP_VTRNR  // VTRN, right result
6911   };
6912 
6913   if (OpNum == OP_COPY) {
6914     if (LHSID == (1*9+2)*9+3) return LHS;
6915     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6916     return RHS;
6917   }
6918 
6919   SDValue OpLHS, OpRHS;
6920   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6921   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6922   EVT VT = OpLHS.getValueType();
6923 
6924   switch (OpNum) {
6925   default: llvm_unreachable("Unknown shuffle opcode!");
6926   case OP_VREV:
6927     // VREV divides the vector in half and swaps within the half.
6928     if (VT.getVectorElementType() == MVT::i32 ||
6929         VT.getVectorElementType() == MVT::f32)
6930       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6931     // vrev <4 x i16> -> VREV32
6932     if (VT.getVectorElementType() == MVT::i16)
6933       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6934     // vrev <4 x i8> -> VREV16
6935     assert(VT.getVectorElementType() == MVT::i8);
6936     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6937   case OP_VDUP0:
6938   case OP_VDUP1:
6939   case OP_VDUP2:
6940   case OP_VDUP3:
6941     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6942                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6943   case OP_VEXT1:
6944   case OP_VEXT2:
6945   case OP_VEXT3:
6946     return DAG.getNode(ARMISD::VEXT, dl, VT,
6947                        OpLHS, OpRHS,
6948                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6949   case OP_VUZPL:
6950   case OP_VUZPR:
6951     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6952                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6953   case OP_VZIPL:
6954   case OP_VZIPR:
6955     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6956                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6957   case OP_VTRNL:
6958   case OP_VTRNR:
6959     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6960                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6961   }
6962 }
6963 
6964 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6965                                        ArrayRef<int> ShuffleMask,
6966                                        SelectionDAG &DAG) {
6967   // Check to see if we can use the VTBL instruction.
6968   SDValue V1 = Op.getOperand(0);
6969   SDValue V2 = Op.getOperand(1);
6970   SDLoc DL(Op);
6971 
6972   SmallVector<SDValue, 8> VTBLMask;
6973   for (ArrayRef<int>::iterator
6974          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6975     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6976 
6977   if (V2.getNode()->isUndef())
6978     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6979                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6980 
6981   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6982                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6983 }
6984 
6985 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6986                                                       SelectionDAG &DAG) {
6987   SDLoc DL(Op);
6988   SDValue OpLHS = Op.getOperand(0);
6989   EVT VT = OpLHS.getValueType();
6990 
6991   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6992          "Expect an v8i16/v16i8 type");
6993   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6994   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6995   // extract the first 8 bytes into the top double word and the last 8 bytes
6996   // into the bottom double word. The v8i16 case is similar.
6997   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6998   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6999                      DAG.getConstant(ExtractNum, DL, MVT::i32));
7000 }
7001 
7002 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
7003   SDValue V1 = Op.getOperand(0);
7004   SDValue V2 = Op.getOperand(1);
7005   SDLoc dl(Op);
7006   EVT VT = Op.getValueType();
7007   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7008 
7009   // Convert shuffles that are directly supported on NEON to target-specific
7010   // DAG nodes, instead of keeping them as shuffles and matching them again
7011   // during code selection.  This is more efficient and avoids the possibility
7012   // of inconsistencies between legalization and selection.
7013   // FIXME: floating-point vectors should be canonicalized to integer vectors
7014   // of the same time so that they get CSEd properly.
7015   ArrayRef<int> ShuffleMask = SVN->getMask();
7016 
7017   unsigned EltSize = VT.getScalarSizeInBits();
7018   if (EltSize <= 32) {
7019     if (SVN->isSplat()) {
7020       int Lane = SVN->getSplatIndex();
7021       // If this is undef splat, generate it via "just" vdup, if possible.
7022       if (Lane == -1) Lane = 0;
7023 
7024       // Test if V1 is a SCALAR_TO_VECTOR.
7025       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7026         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7027       }
7028       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7029       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7030       // reaches it).
7031       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7032           !isa<ConstantSDNode>(V1.getOperand(0))) {
7033         bool IsScalarToVector = true;
7034         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7035           if (!V1.getOperand(i).isUndef()) {
7036             IsScalarToVector = false;
7037             break;
7038           }
7039         if (IsScalarToVector)
7040           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7041       }
7042       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7043                          DAG.getConstant(Lane, dl, MVT::i32));
7044     }
7045 
7046     bool ReverseVEXT = false;
7047     unsigned Imm = 0;
7048     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7049       if (ReverseVEXT)
7050         std::swap(V1, V2);
7051       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7052                          DAG.getConstant(Imm, dl, MVT::i32));
7053     }
7054 
7055     if (isVREVMask(ShuffleMask, VT, 64))
7056       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7057     if (isVREVMask(ShuffleMask, VT, 32))
7058       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7059     if (isVREVMask(ShuffleMask, VT, 16))
7060       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7061 
7062     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7063       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7064                          DAG.getConstant(Imm, dl, MVT::i32));
7065     }
7066 
7067     // Check for Neon shuffles that modify both input vectors in place.
7068     // If both results are used, i.e., if there are two shuffles with the same
7069     // source operands and with masks corresponding to both results of one of
7070     // these operations, DAG memoization will ensure that a single node is
7071     // used for both shuffles.
7072     unsigned WhichResult = 0;
7073     bool isV_UNDEF = false;
7074     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7075             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7076       if (isV_UNDEF)
7077         V2 = V1;
7078       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7079           .getValue(WhichResult);
7080     }
7081 
7082     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7083     // shuffles that produce a result larger than their operands with:
7084     //   shuffle(concat(v1, undef), concat(v2, undef))
7085     // ->
7086     //   shuffle(concat(v1, v2), undef)
7087     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7088     //
7089     // This is useful in the general case, but there are special cases where
7090     // native shuffles produce larger results: the two-result ops.
7091     //
7092     // Look through the concat when lowering them:
7093     //   shuffle(concat(v1, v2), undef)
7094     // ->
7095     //   concat(VZIP(v1, v2):0, :1)
7096     //
7097     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7098       SDValue SubV1 = V1->getOperand(0);
7099       SDValue SubV2 = V1->getOperand(1);
7100       EVT SubVT = SubV1.getValueType();
7101 
7102       // We expect these to have been canonicalized to -1.
7103       assert(llvm::all_of(ShuffleMask, [&](int i) {
7104         return i < (int)VT.getVectorNumElements();
7105       }) && "Unexpected shuffle index into UNDEF operand!");
7106 
7107       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7108               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7109         if (isV_UNDEF)
7110           SubV2 = SubV1;
7111         assert((WhichResult == 0) &&
7112                "In-place shuffle of concat can only have one result!");
7113         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7114                                   SubV1, SubV2);
7115         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7116                            Res.getValue(1));
7117       }
7118     }
7119   }
7120 
7121   // If the shuffle is not directly supported and it has 4 elements, use
7122   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7123   unsigned NumElts = VT.getVectorNumElements();
7124   if (NumElts == 4) {
7125     unsigned PFIndexes[4];
7126     for (unsigned i = 0; i != 4; ++i) {
7127       if (ShuffleMask[i] < 0)
7128         PFIndexes[i] = 8;
7129       else
7130         PFIndexes[i] = ShuffleMask[i];
7131     }
7132 
7133     // Compute the index in the perfect shuffle table.
7134     unsigned PFTableIndex =
7135       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7136     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7137     unsigned Cost = (PFEntry >> 30);
7138 
7139     if (Cost <= 4)
7140       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7141   }
7142 
7143   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7144   if (EltSize >= 32) {
7145     // Do the expansion with floating-point types, since that is what the VFP
7146     // registers are defined to use, and since i64 is not legal.
7147     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7148     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7149     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7150     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7151     SmallVector<SDValue, 8> Ops;
7152     for (unsigned i = 0; i < NumElts; ++i) {
7153       if (ShuffleMask[i] < 0)
7154         Ops.push_back(DAG.getUNDEF(EltVT));
7155       else
7156         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7157                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7158                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7159                                                   dl, MVT::i32)));
7160     }
7161     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7162     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7163   }
7164 
7165   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7166     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7167 
7168   if (VT == MVT::v8i8)
7169     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7170       return NewOp;
7171 
7172   return SDValue();
7173 }
7174 
7175 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7176   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7177   SDValue Lane = Op.getOperand(2);
7178   if (!isa<ConstantSDNode>(Lane))
7179     return SDValue();
7180 
7181   return Op;
7182 }
7183 
7184 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7185   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7186   SDValue Lane = Op.getOperand(1);
7187   if (!isa<ConstantSDNode>(Lane))
7188     return SDValue();
7189 
7190   SDValue Vec = Op.getOperand(0);
7191   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7192     SDLoc dl(Op);
7193     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7194   }
7195 
7196   return Op;
7197 }
7198 
7199 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7200   // The only time a CONCAT_VECTORS operation can have legal types is when
7201   // two 64-bit vectors are concatenated to a 128-bit vector.
7202   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7203          "unexpected CONCAT_VECTORS");
7204   SDLoc dl(Op);
7205   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7206   SDValue Op0 = Op.getOperand(0);
7207   SDValue Op1 = Op.getOperand(1);
7208   if (!Op0.isUndef())
7209     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7210                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7211                       DAG.getIntPtrConstant(0, dl));
7212   if (!Op1.isUndef())
7213     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7214                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7215                       DAG.getIntPtrConstant(1, dl));
7216   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7217 }
7218 
7219 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7220 /// element has been zero/sign-extended, depending on the isSigned parameter,
7221 /// from an integer type half its size.
7222 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7223                                    bool isSigned) {
7224   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7225   EVT VT = N->getValueType(0);
7226   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7227     SDNode *BVN = N->getOperand(0).getNode();
7228     if (BVN->getValueType(0) != MVT::v4i32 ||
7229         BVN->getOpcode() != ISD::BUILD_VECTOR)
7230       return false;
7231     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7232     unsigned HiElt = 1 - LoElt;
7233     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7234     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7235     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7236     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7237     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7238       return false;
7239     if (isSigned) {
7240       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7241           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7242         return true;
7243     } else {
7244       if (Hi0->isNullValue() && Hi1->isNullValue())
7245         return true;
7246     }
7247     return false;
7248   }
7249 
7250   if (N->getOpcode() != ISD::BUILD_VECTOR)
7251     return false;
7252 
7253   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7254     SDNode *Elt = N->getOperand(i).getNode();
7255     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7256       unsigned EltSize = VT.getScalarSizeInBits();
7257       unsigned HalfSize = EltSize / 2;
7258       if (isSigned) {
7259         if (!isIntN(HalfSize, C->getSExtValue()))
7260           return false;
7261       } else {
7262         if (!isUIntN(HalfSize, C->getZExtValue()))
7263           return false;
7264       }
7265       continue;
7266     }
7267     return false;
7268   }
7269 
7270   return true;
7271 }
7272 
7273 /// isSignExtended - Check if a node is a vector value that is sign-extended
7274 /// or a constant BUILD_VECTOR with sign-extended elements.
7275 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7276   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7277     return true;
7278   if (isExtendedBUILD_VECTOR(N, DAG, true))
7279     return true;
7280   return false;
7281 }
7282 
7283 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7284 /// or a constant BUILD_VECTOR with zero-extended elements.
7285 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7286   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7287     return true;
7288   if (isExtendedBUILD_VECTOR(N, DAG, false))
7289     return true;
7290   return false;
7291 }
7292 
7293 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7294   if (OrigVT.getSizeInBits() >= 64)
7295     return OrigVT;
7296 
7297   assert(OrigVT.isSimple() && "Expecting a simple value type");
7298 
7299   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7300   switch (OrigSimpleTy) {
7301   default: llvm_unreachable("Unexpected Vector Type");
7302   case MVT::v2i8:
7303   case MVT::v2i16:
7304      return MVT::v2i32;
7305   case MVT::v4i8:
7306     return  MVT::v4i16;
7307   }
7308 }
7309 
7310 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7311 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7312 /// We insert the required extension here to get the vector to fill a D register.
7313 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7314                                             const EVT &OrigTy,
7315                                             const EVT &ExtTy,
7316                                             unsigned ExtOpcode) {
7317   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7318   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7319   // 64-bits we need to insert a new extension so that it will be 64-bits.
7320   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7321   if (OrigTy.getSizeInBits() >= 64)
7322     return N;
7323 
7324   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7325   EVT NewVT = getExtensionTo64Bits(OrigTy);
7326 
7327   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7328 }
7329 
7330 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7331 /// does not do any sign/zero extension. If the original vector is less
7332 /// than 64 bits, an appropriate extension will be added after the load to
7333 /// reach a total size of 64 bits. We have to add the extension separately
7334 /// because ARM does not have a sign/zero extending load for vectors.
7335 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7336   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7337 
7338   // The load already has the right type.
7339   if (ExtendedTy == LD->getMemoryVT())
7340     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7341                        LD->getBasePtr(), LD->getPointerInfo(),
7342                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7343 
7344   // We need to create a zextload/sextload. We cannot just create a load
7345   // followed by a zext/zext node because LowerMUL is also run during normal
7346   // operation legalization where we can't create illegal types.
7347   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7348                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7349                         LD->getMemoryVT(), LD->getAlignment(),
7350                         LD->getMemOperand()->getFlags());
7351 }
7352 
7353 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7354 /// extending load, or BUILD_VECTOR with extended elements, return the
7355 /// unextended value. The unextended vector should be 64 bits so that it can
7356 /// be used as an operand to a VMULL instruction. If the original vector size
7357 /// before extension is less than 64 bits we add a an extension to resize
7358 /// the vector to 64 bits.
7359 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7360   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7361     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7362                                         N->getOperand(0)->getValueType(0),
7363                                         N->getValueType(0),
7364                                         N->getOpcode());
7365 
7366   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7367     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7368            "Expected extending load");
7369 
7370     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7371     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7372     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7373     SDValue extLoad =
7374         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7375     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7376 
7377     return newLoad;
7378   }
7379 
7380   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7381   // have been legalized as a BITCAST from v4i32.
7382   if (N->getOpcode() == ISD::BITCAST) {
7383     SDNode *BVN = N->getOperand(0).getNode();
7384     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7385            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7386     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7387     return DAG.getBuildVector(
7388         MVT::v2i32, SDLoc(N),
7389         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7390   }
7391   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7392   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7393   EVT VT = N->getValueType(0);
7394   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7395   unsigned NumElts = VT.getVectorNumElements();
7396   MVT TruncVT = MVT::getIntegerVT(EltSize);
7397   SmallVector<SDValue, 8> Ops;
7398   SDLoc dl(N);
7399   for (unsigned i = 0; i != NumElts; ++i) {
7400     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7401     const APInt &CInt = C->getAPIntValue();
7402     // Element types smaller than 32 bits are not legal, so use i32 elements.
7403     // The values are implicitly truncated so sext vs. zext doesn't matter.
7404     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7405   }
7406   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7407 }
7408 
7409 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7410   unsigned Opcode = N->getOpcode();
7411   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7412     SDNode *N0 = N->getOperand(0).getNode();
7413     SDNode *N1 = N->getOperand(1).getNode();
7414     return N0->hasOneUse() && N1->hasOneUse() &&
7415       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7416   }
7417   return false;
7418 }
7419 
7420 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7421   unsigned Opcode = N->getOpcode();
7422   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7423     SDNode *N0 = N->getOperand(0).getNode();
7424     SDNode *N1 = N->getOperand(1).getNode();
7425     return N0->hasOneUse() && N1->hasOneUse() &&
7426       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7427   }
7428   return false;
7429 }
7430 
7431 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7432   // Multiplications are only custom-lowered for 128-bit vectors so that
7433   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7434   EVT VT = Op.getValueType();
7435   assert(VT.is128BitVector() && VT.isInteger() &&
7436          "unexpected type for custom-lowering ISD::MUL");
7437   SDNode *N0 = Op.getOperand(0).getNode();
7438   SDNode *N1 = Op.getOperand(1).getNode();
7439   unsigned NewOpc = 0;
7440   bool isMLA = false;
7441   bool isN0SExt = isSignExtended(N0, DAG);
7442   bool isN1SExt = isSignExtended(N1, DAG);
7443   if (isN0SExt && isN1SExt)
7444     NewOpc = ARMISD::VMULLs;
7445   else {
7446     bool isN0ZExt = isZeroExtended(N0, DAG);
7447     bool isN1ZExt = isZeroExtended(N1, DAG);
7448     if (isN0ZExt && isN1ZExt)
7449       NewOpc = ARMISD::VMULLu;
7450     else if (isN1SExt || isN1ZExt) {
7451       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7452       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7453       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7454         NewOpc = ARMISD::VMULLs;
7455         isMLA = true;
7456       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7457         NewOpc = ARMISD::VMULLu;
7458         isMLA = true;
7459       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7460         std::swap(N0, N1);
7461         NewOpc = ARMISD::VMULLu;
7462         isMLA = true;
7463       }
7464     }
7465 
7466     if (!NewOpc) {
7467       if (VT == MVT::v2i64)
7468         // Fall through to expand this.  It is not legal.
7469         return SDValue();
7470       else
7471         // Other vector multiplications are legal.
7472         return Op;
7473     }
7474   }
7475 
7476   // Legalize to a VMULL instruction.
7477   SDLoc DL(Op);
7478   SDValue Op0;
7479   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7480   if (!isMLA) {
7481     Op0 = SkipExtensionForVMULL(N0, DAG);
7482     assert(Op0.getValueType().is64BitVector() &&
7483            Op1.getValueType().is64BitVector() &&
7484            "unexpected types for extended operands to VMULL");
7485     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7486   }
7487 
7488   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7489   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7490   //   vmull q0, d4, d6
7491   //   vmlal q0, d5, d6
7492   // is faster than
7493   //   vaddl q0, d4, d5
7494   //   vmovl q1, d6
7495   //   vmul  q0, q0, q1
7496   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7497   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7498   EVT Op1VT = Op1.getValueType();
7499   return DAG.getNode(N0->getOpcode(), DL, VT,
7500                      DAG.getNode(NewOpc, DL, VT,
7501                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7502                      DAG.getNode(NewOpc, DL, VT,
7503                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7504 }
7505 
7506 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7507                               SelectionDAG &DAG) {
7508   // TODO: Should this propagate fast-math-flags?
7509 
7510   // Convert to float
7511   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7512   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7513   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7514   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7515   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7516   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7517   // Get reciprocal estimate.
7518   // float4 recip = vrecpeq_f32(yf);
7519   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7520                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7521                    Y);
7522   // Because char has a smaller range than uchar, we can actually get away
7523   // without any newton steps.  This requires that we use a weird bias
7524   // of 0xb000, however (again, this has been exhaustively tested).
7525   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7526   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7527   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7528   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7529   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7530   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7531   // Convert back to short.
7532   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7533   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7534   return X;
7535 }
7536 
7537 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7538                                SelectionDAG &DAG) {
7539   // TODO: Should this propagate fast-math-flags?
7540 
7541   SDValue N2;
7542   // Convert to float.
7543   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7544   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7545   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7546   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7547   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7548   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7549 
7550   // Use reciprocal estimate and one refinement step.
7551   // float4 recip = vrecpeq_f32(yf);
7552   // recip *= vrecpsq_f32(yf, recip);
7553   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7554                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7555                    N1);
7556   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7557                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7558                    N1, N2);
7559   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7560   // Because short has a smaller range than ushort, we can actually get away
7561   // with only a single newton step.  This requires that we use a weird bias
7562   // of 89, however (again, this has been exhaustively tested).
7563   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7564   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7565   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7566   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7567   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7568   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7569   // Convert back to integer and return.
7570   // return vmovn_s32(vcvt_s32_f32(result));
7571   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7572   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7573   return N0;
7574 }
7575 
7576 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7577   EVT VT = Op.getValueType();
7578   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7579          "unexpected type for custom-lowering ISD::SDIV");
7580 
7581   SDLoc dl(Op);
7582   SDValue N0 = Op.getOperand(0);
7583   SDValue N1 = Op.getOperand(1);
7584   SDValue N2, N3;
7585 
7586   if (VT == MVT::v8i8) {
7587     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7588     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7589 
7590     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7591                      DAG.getIntPtrConstant(4, dl));
7592     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7593                      DAG.getIntPtrConstant(4, dl));
7594     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7595                      DAG.getIntPtrConstant(0, dl));
7596     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7597                      DAG.getIntPtrConstant(0, dl));
7598 
7599     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7600     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7601 
7602     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7603     N0 = LowerCONCAT_VECTORS(N0, DAG);
7604 
7605     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7606     return N0;
7607   }
7608   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7609 }
7610 
7611 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7612   // TODO: Should this propagate fast-math-flags?
7613   EVT VT = Op.getValueType();
7614   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7615          "unexpected type for custom-lowering ISD::UDIV");
7616 
7617   SDLoc dl(Op);
7618   SDValue N0 = Op.getOperand(0);
7619   SDValue N1 = Op.getOperand(1);
7620   SDValue N2, N3;
7621 
7622   if (VT == MVT::v8i8) {
7623     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7624     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7625 
7626     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7627                      DAG.getIntPtrConstant(4, dl));
7628     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7629                      DAG.getIntPtrConstant(4, dl));
7630     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7631                      DAG.getIntPtrConstant(0, dl));
7632     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7633                      DAG.getIntPtrConstant(0, dl));
7634 
7635     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7636     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7637 
7638     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7639     N0 = LowerCONCAT_VECTORS(N0, DAG);
7640 
7641     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7642                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7643                                      MVT::i32),
7644                      N0);
7645     return N0;
7646   }
7647 
7648   // v4i16 sdiv ... Convert to float.
7649   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7650   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7651   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7652   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7653   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7654   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7655 
7656   // Use reciprocal estimate and two refinement steps.
7657   // float4 recip = vrecpeq_f32(yf);
7658   // recip *= vrecpsq_f32(yf, recip);
7659   // recip *= vrecpsq_f32(yf, recip);
7660   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7661                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7662                    BN1);
7663   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7664                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7665                    BN1, N2);
7666   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7667   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7668                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7669                    BN1, N2);
7670   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7671   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7672   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7673   // and that it will never cause us to return an answer too large).
7674   // float4 result = as_float4(as_int4(xf*recip) + 2);
7675   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7676   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7677   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7678   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7679   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7680   // Convert back to integer and return.
7681   // return vmovn_u32(vcvt_s32_f32(result));
7682   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7683   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7684   return N0;
7685 }
7686 
7687 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7688   SDNode *N = Op.getNode();
7689   EVT VT = N->getValueType(0);
7690   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7691 
7692   SDValue Carry = Op.getOperand(2);
7693 
7694   SDLoc DL(Op);
7695 
7696   SDValue Result;
7697   if (Op.getOpcode() == ISD::ADDCARRY) {
7698     // This converts the boolean value carry into the carry flag.
7699     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7700 
7701     // Do the addition proper using the carry flag we wanted.
7702     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7703                          Op.getOperand(1), Carry);
7704 
7705     // Now convert the carry flag into a boolean value.
7706     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7707   } else {
7708     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7709     // have to invert the carry first.
7710     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7711                         DAG.getConstant(1, DL, MVT::i32), Carry);
7712     // This converts the boolean value carry into the carry flag.
7713     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7714 
7715     // Do the subtraction proper using the carry flag we wanted.
7716     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7717                          Op.getOperand(1), Carry);
7718 
7719     // Now convert the carry flag into a boolean value.
7720     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7721     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7722     // by ISD::SUBCARRY, so compute 1 - C.
7723     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7724                         DAG.getConstant(1, DL, MVT::i32), Carry);
7725   }
7726 
7727   // Return both values.
7728   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7729 }
7730 
7731 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7732   assert(Subtarget->isTargetDarwin());
7733 
7734   // For iOS, we want to call an alternative entry point: __sincos_stret,
7735   // return values are passed via sret.
7736   SDLoc dl(Op);
7737   SDValue Arg = Op.getOperand(0);
7738   EVT ArgVT = Arg.getValueType();
7739   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7740   auto PtrVT = getPointerTy(DAG.getDataLayout());
7741 
7742   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7744 
7745   // Pair of floats / doubles used to pass the result.
7746   Type *RetTy = StructType::get(ArgTy, ArgTy);
7747   auto &DL = DAG.getDataLayout();
7748 
7749   ArgListTy Args;
7750   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7751   SDValue SRet;
7752   if (ShouldUseSRet) {
7753     // Create stack object for sret.
7754     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7755     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7756     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7757     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7758 
7759     ArgListEntry Entry;
7760     Entry.Node = SRet;
7761     Entry.Ty = RetTy->getPointerTo();
7762     Entry.IsSExt = false;
7763     Entry.IsZExt = false;
7764     Entry.IsSRet = true;
7765     Args.push_back(Entry);
7766     RetTy = Type::getVoidTy(*DAG.getContext());
7767   }
7768 
7769   ArgListEntry Entry;
7770   Entry.Node = Arg;
7771   Entry.Ty = ArgTy;
7772   Entry.IsSExt = false;
7773   Entry.IsZExt = false;
7774   Args.push_back(Entry);
7775 
7776   RTLIB::Libcall LC =
7777       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7778   const char *LibcallName = getLibcallName(LC);
7779   CallingConv::ID CC = getLibcallCallingConv(LC);
7780   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7781 
7782   TargetLowering::CallLoweringInfo CLI(DAG);
7783   CLI.setDebugLoc(dl)
7784       .setChain(DAG.getEntryNode())
7785       .setCallee(CC, RetTy, Callee, std::move(Args))
7786       .setDiscardResult(ShouldUseSRet);
7787   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7788 
7789   if (!ShouldUseSRet)
7790     return CallResult.first;
7791 
7792   SDValue LoadSin =
7793       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7794 
7795   // Address of cos field.
7796   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7797                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7798   SDValue LoadCos =
7799       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7800 
7801   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7802   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7803                      LoadSin.getValue(0), LoadCos.getValue(0));
7804 }
7805 
7806 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7807                                                   bool Signed,
7808                                                   SDValue &Chain) const {
7809   EVT VT = Op.getValueType();
7810   assert((VT == MVT::i32 || VT == MVT::i64) &&
7811          "unexpected type for custom lowering DIV");
7812   SDLoc dl(Op);
7813 
7814   const auto &DL = DAG.getDataLayout();
7815   const auto &TLI = DAG.getTargetLoweringInfo();
7816 
7817   const char *Name = nullptr;
7818   if (Signed)
7819     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7820   else
7821     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7822 
7823   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7824 
7825   ARMTargetLowering::ArgListTy Args;
7826 
7827   for (auto AI : {1, 0}) {
7828     ArgListEntry Arg;
7829     Arg.Node = Op.getOperand(AI);
7830     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7831     Args.push_back(Arg);
7832   }
7833 
7834   CallLoweringInfo CLI(DAG);
7835   CLI.setDebugLoc(dl)
7836     .setChain(Chain)
7837     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7838                ES, std::move(Args));
7839 
7840   return LowerCallTo(CLI).first;
7841 }
7842 
7843 // This is a code size optimisation: return the original SDIV node to
7844 // DAGCombiner when we don't want to expand SDIV into a sequence of
7845 // instructions, and an empty node otherwise which will cause the
7846 // SDIV to be expanded in DAGCombine.
7847 SDValue
7848 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7849                                  SelectionDAG &DAG,
7850                                  SmallVectorImpl<SDNode *> &Created) const {
7851   // TODO: Support SREM
7852   if (N->getOpcode() != ISD::SDIV)
7853     return SDValue();
7854 
7855   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
7856   const bool MinSize = ST.hasMinSize();
7857   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
7858                                       : ST.hasDivideInARMMode();
7859 
7860   // Don't touch vector types; rewriting this may lead to scalarizing
7861   // the int divs.
7862   if (N->getOperand(0).getValueType().isVector())
7863     return SDValue();
7864 
7865   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
7866   // hwdiv support for this to be really profitable.
7867   if (!(MinSize && HasDivide))
7868     return SDValue();
7869 
7870   // ARM mode is a bit simpler than Thumb: we can handle large power
7871   // of 2 immediates with 1 mov instruction; no further checks required,
7872   // just return the sdiv node.
7873   if (!ST.isThumb())
7874     return SDValue(N, 0);
7875 
7876   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
7877   // and thus lose the code size benefits of a MOVS that requires only 2.
7878   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
7879   // but as it's doing exactly this, it's not worth the trouble to get TTI.
7880   if (Divisor.sgt(128))
7881     return SDValue();
7882 
7883   return SDValue(N, 0);
7884 }
7885 
7886 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7887                                             bool Signed) const {
7888   assert(Op.getValueType() == MVT::i32 &&
7889          "unexpected type for custom lowering DIV");
7890   SDLoc dl(Op);
7891 
7892   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7893                                DAG.getEntryNode(), Op.getOperand(1));
7894 
7895   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7896 }
7897 
7898 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7899   SDLoc DL(N);
7900   SDValue Op = N->getOperand(1);
7901   if (N->getValueType(0) == MVT::i32)
7902     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7903   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7904                            DAG.getConstant(0, DL, MVT::i32));
7905   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7906                            DAG.getConstant(1, DL, MVT::i32));
7907   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7908                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7909 }
7910 
7911 void ARMTargetLowering::ExpandDIV_Windows(
7912     SDValue Op, SelectionDAG &DAG, bool Signed,
7913     SmallVectorImpl<SDValue> &Results) const {
7914   const auto &DL = DAG.getDataLayout();
7915   const auto &TLI = DAG.getTargetLoweringInfo();
7916 
7917   assert(Op.getValueType() == MVT::i64 &&
7918          "unexpected type for custom lowering DIV");
7919   SDLoc dl(Op);
7920 
7921   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7922 
7923   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7924 
7925   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7926   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7927                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7928   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7929 
7930   Results.push_back(Lower);
7931   Results.push_back(Upper);
7932 }
7933 
7934 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7935   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7936     // Acquire/Release load/store is not legal for targets without a dmb or
7937     // equivalent available.
7938     return SDValue();
7939 
7940   // Monotonic load/store is legal for all targets.
7941   return Op;
7942 }
7943 
7944 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7945                                     SmallVectorImpl<SDValue> &Results,
7946                                     SelectionDAG &DAG,
7947                                     const ARMSubtarget *Subtarget) {
7948   SDLoc DL(N);
7949   // Under Power Management extensions, the cycle-count is:
7950   //    mrc p15, #0, <Rt>, c9, c13, #0
7951   SDValue Ops[] = { N->getOperand(0), // Chain
7952                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7953                     DAG.getConstant(15, DL, MVT::i32),
7954                     DAG.getConstant(0, DL, MVT::i32),
7955                     DAG.getConstant(9, DL, MVT::i32),
7956                     DAG.getConstant(13, DL, MVT::i32),
7957                     DAG.getConstant(0, DL, MVT::i32)
7958   };
7959 
7960   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7961                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7962   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7963                                 DAG.getConstant(0, DL, MVT::i32)));
7964   Results.push_back(Cycles32.getValue(1));
7965 }
7966 
7967 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7968   SDLoc dl(V.getNode());
7969   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7970   SDValue VHi = DAG.getAnyExtOrTrunc(
7971       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7972       dl, MVT::i32);
7973   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7974   if (isBigEndian)
7975     std::swap (VLo, VHi);
7976   SDValue RegClass =
7977       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7978   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7979   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7980   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7981   return SDValue(
7982       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7983 }
7984 
7985 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7986                                        SmallVectorImpl<SDValue> & Results,
7987                                        SelectionDAG &DAG) {
7988   assert(N->getValueType(0) == MVT::i64 &&
7989          "AtomicCmpSwap on types less than 64 should be legal");
7990   SDValue Ops[] = {N->getOperand(1),
7991                    createGPRPairNode(DAG, N->getOperand(2)),
7992                    createGPRPairNode(DAG, N->getOperand(3)),
7993                    N->getOperand(0)};
7994   SDNode *CmpSwap = DAG.getMachineNode(
7995       ARM::CMP_SWAP_64, SDLoc(N),
7996       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7997 
7998   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
7999   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8000 
8001   bool isBigEndian = DAG.getDataLayout().isBigEndian();
8002 
8003   Results.push_back(
8004       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8005                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8006   Results.push_back(
8007       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8008                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8009   Results.push_back(SDValue(CmpSwap, 2));
8010 }
8011 
8012 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8013                           SelectionDAG &DAG) {
8014   const auto &TLI = DAG.getTargetLoweringInfo();
8015 
8016   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8017          "Custom lowering is MSVCRT specific!");
8018 
8019   SDLoc dl(Op);
8020   SDValue Val = Op.getOperand(0);
8021   MVT Ty = Val->getSimpleValueType(0);
8022   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8023   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8024                                          TLI.getPointerTy(DAG.getDataLayout()));
8025 
8026   TargetLowering::ArgListTy Args;
8027   TargetLowering::ArgListEntry Entry;
8028 
8029   Entry.Node = Val;
8030   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8031   Entry.IsZExt = true;
8032   Args.push_back(Entry);
8033 
8034   Entry.Node = Exponent;
8035   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8036   Entry.IsZExt = true;
8037   Args.push_back(Entry);
8038 
8039   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8040 
8041   // In the in-chain to the call is the entry node  If we are emitting a
8042   // tailcall, the chain will be mutated if the node has a non-entry input
8043   // chain.
8044   SDValue InChain = DAG.getEntryNode();
8045   SDValue TCChain = InChain;
8046 
8047   const Function &F = DAG.getMachineFunction().getFunction();
8048   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8049               F.getReturnType() == LCRTy;
8050   if (IsTC)
8051     InChain = TCChain;
8052 
8053   TargetLowering::CallLoweringInfo CLI(DAG);
8054   CLI.setDebugLoc(dl)
8055       .setChain(InChain)
8056       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8057       .setTailCall(IsTC);
8058   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8059 
8060   // Return the chain (the DAG root) if it is a tail call
8061   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8062 }
8063 
8064 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8065   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8066   switch (Op.getOpcode()) {
8067   default: llvm_unreachable("Don't know how to custom lower this!");
8068   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8069   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8070   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
8071   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8072   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8073   case ISD::SELECT:        return LowerSELECT(Op, DAG);
8074   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
8075   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
8076   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
8077   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
8078   case ISD::VASTART:       return LowerVASTART(Op, DAG);
8079   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8080   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
8081   case ISD::SINT_TO_FP:
8082   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
8083   case ISD::FP_TO_SINT:
8084   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
8085   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
8086   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
8087   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
8088   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8089   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8090   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8091   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8092                                                                Subtarget);
8093   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8094   case ISD::SHL:
8095   case ISD::SRL:
8096   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8097   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8098   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8099   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8100   case ISD::SRL_PARTS:
8101   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8102   case ISD::CTTZ:
8103   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8104   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8105   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8106   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
8107   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8108   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8109   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8110   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8111   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8112   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8113   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8114   case ISD::MUL:           return LowerMUL(Op, DAG);
8115   case ISD::SDIV:
8116     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8117       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8118     return LowerSDIV(Op, DAG);
8119   case ISD::UDIV:
8120     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8121       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8122     return LowerUDIV(Op, DAG);
8123   case ISD::ADDCARRY:
8124   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8125   case ISD::SADDO:
8126   case ISD::SSUBO:
8127     return LowerSignedALUO(Op, DAG);
8128   case ISD::UADDO:
8129   case ISD::USUBO:
8130     return LowerUnsignedALUO(Op, DAG);
8131   case ISD::ATOMIC_LOAD:
8132   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8133   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8134   case ISD::SDIVREM:
8135   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8136   case ISD::DYNAMIC_STACKALLOC:
8137     if (Subtarget->isTargetWindows())
8138       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8139     llvm_unreachable("Don't know how to custom lower this!");
8140   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8141   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8142   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8143   case ARMISD::WIN__DBZCHK: return SDValue();
8144   }
8145 }
8146 
8147 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8148                                  SelectionDAG &DAG) {
8149   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8150   unsigned Opc = 0;
8151   if (IntNo == Intrinsic::arm_smlald)
8152     Opc = ARMISD::SMLALD;
8153   else if (IntNo == Intrinsic::arm_smlaldx)
8154     Opc = ARMISD::SMLALDX;
8155   else if (IntNo == Intrinsic::arm_smlsld)
8156     Opc = ARMISD::SMLSLD;
8157   else if (IntNo == Intrinsic::arm_smlsldx)
8158     Opc = ARMISD::SMLSLDX;
8159   else
8160     return;
8161 
8162   SDLoc dl(N);
8163   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8164                            N->getOperand(3),
8165                            DAG.getConstant(0, dl, MVT::i32));
8166   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8167                            N->getOperand(3),
8168                            DAG.getConstant(1, dl, MVT::i32));
8169 
8170   SDValue LongMul = DAG.getNode(Opc, dl,
8171                                 DAG.getVTList(MVT::i32, MVT::i32),
8172                                 N->getOperand(1), N->getOperand(2),
8173                                 Lo, Hi);
8174   Results.push_back(LongMul.getValue(0));
8175   Results.push_back(LongMul.getValue(1));
8176 }
8177 
8178 /// ReplaceNodeResults - Replace the results of node with an illegal result
8179 /// type with new values built out of custom code.
8180 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8181                                            SmallVectorImpl<SDValue> &Results,
8182                                            SelectionDAG &DAG) const {
8183   SDValue Res;
8184   switch (N->getOpcode()) {
8185   default:
8186     llvm_unreachable("Don't know how to custom expand this!");
8187   case ISD::READ_REGISTER:
8188     ExpandREAD_REGISTER(N, Results, DAG);
8189     break;
8190   case ISD::BITCAST:
8191     Res = ExpandBITCAST(N, DAG, Subtarget);
8192     break;
8193   case ISD::SRL:
8194   case ISD::SRA:
8195     Res = Expand64BitShift(N, DAG, Subtarget);
8196     break;
8197   case ISD::SREM:
8198   case ISD::UREM:
8199     Res = LowerREM(N, DAG);
8200     break;
8201   case ISD::SDIVREM:
8202   case ISD::UDIVREM:
8203     Res = LowerDivRem(SDValue(N, 0), DAG);
8204     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8205     Results.push_back(Res.getValue(0));
8206     Results.push_back(Res.getValue(1));
8207     return;
8208   case ISD::READCYCLECOUNTER:
8209     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8210     return;
8211   case ISD::UDIV:
8212   case ISD::SDIV:
8213     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8214     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8215                              Results);
8216   case ISD::ATOMIC_CMP_SWAP:
8217     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8218     return;
8219   case ISD::INTRINSIC_WO_CHAIN:
8220     return ReplaceLongIntrinsic(N, Results, DAG);
8221   case ISD::ABS:
8222      lowerABS(N, Results, DAG);
8223      return ;
8224 
8225   }
8226   if (Res.getNode())
8227     Results.push_back(Res);
8228 }
8229 
8230 //===----------------------------------------------------------------------===//
8231 //                           ARM Scheduler Hooks
8232 //===----------------------------------------------------------------------===//
8233 
8234 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8235 /// registers the function context.
8236 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8237                                                MachineBasicBlock *MBB,
8238                                                MachineBasicBlock *DispatchBB,
8239                                                int FI) const {
8240   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8241          "ROPI/RWPI not currently supported with SjLj");
8242   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8243   DebugLoc dl = MI.getDebugLoc();
8244   MachineFunction *MF = MBB->getParent();
8245   MachineRegisterInfo *MRI = &MF->getRegInfo();
8246   MachineConstantPool *MCP = MF->getConstantPool();
8247   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8248   const Function &F = MF->getFunction();
8249 
8250   bool isThumb = Subtarget->isThumb();
8251   bool isThumb2 = Subtarget->isThumb2();
8252 
8253   unsigned PCLabelId = AFI->createPICLabelUId();
8254   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8255   ARMConstantPoolValue *CPV =
8256     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8257   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8258 
8259   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8260                                            : &ARM::GPRRegClass;
8261 
8262   // Grab constant pool and fixed stack memory operands.
8263   MachineMemOperand *CPMMO =
8264       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8265                                MachineMemOperand::MOLoad, 4, 4);
8266 
8267   MachineMemOperand *FIMMOSt =
8268       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8269                                MachineMemOperand::MOStore, 4, 4);
8270 
8271   // Load the address of the dispatch MBB into the jump buffer.
8272   if (isThumb2) {
8273     // Incoming value: jbuf
8274     //   ldr.n  r5, LCPI1_1
8275     //   orr    r5, r5, #1
8276     //   add    r5, pc
8277     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8278     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8279     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8280         .addConstantPoolIndex(CPI)
8281         .addMemOperand(CPMMO)
8282         .add(predOps(ARMCC::AL));
8283     // Set the low bit because of thumb mode.
8284     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8285     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8286         .addReg(NewVReg1, RegState::Kill)
8287         .addImm(0x01)
8288         .add(predOps(ARMCC::AL))
8289         .add(condCodeOp());
8290     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8291     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8292       .addReg(NewVReg2, RegState::Kill)
8293       .addImm(PCLabelId);
8294     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8295         .addReg(NewVReg3, RegState::Kill)
8296         .addFrameIndex(FI)
8297         .addImm(36) // &jbuf[1] :: pc
8298         .addMemOperand(FIMMOSt)
8299         .add(predOps(ARMCC::AL));
8300   } else if (isThumb) {
8301     // Incoming value: jbuf
8302     //   ldr.n  r1, LCPI1_4
8303     //   add    r1, pc
8304     //   mov    r2, #1
8305     //   orrs   r1, r2
8306     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8307     //   str    r1, [r2]
8308     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8309     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8310         .addConstantPoolIndex(CPI)
8311         .addMemOperand(CPMMO)
8312         .add(predOps(ARMCC::AL));
8313     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8314     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8315       .addReg(NewVReg1, RegState::Kill)
8316       .addImm(PCLabelId);
8317     // Set the low bit because of thumb mode.
8318     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8319     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8320         .addReg(ARM::CPSR, RegState::Define)
8321         .addImm(1)
8322         .add(predOps(ARMCC::AL));
8323     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8324     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8325         .addReg(ARM::CPSR, RegState::Define)
8326         .addReg(NewVReg2, RegState::Kill)
8327         .addReg(NewVReg3, RegState::Kill)
8328         .add(predOps(ARMCC::AL));
8329     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8330     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8331             .addFrameIndex(FI)
8332             .addImm(36); // &jbuf[1] :: pc
8333     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8334         .addReg(NewVReg4, RegState::Kill)
8335         .addReg(NewVReg5, RegState::Kill)
8336         .addImm(0)
8337         .addMemOperand(FIMMOSt)
8338         .add(predOps(ARMCC::AL));
8339   } else {
8340     // Incoming value: jbuf
8341     //   ldr  r1, LCPI1_1
8342     //   add  r1, pc, r1
8343     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8344     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8345     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8346         .addConstantPoolIndex(CPI)
8347         .addImm(0)
8348         .addMemOperand(CPMMO)
8349         .add(predOps(ARMCC::AL));
8350     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8351     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8352         .addReg(NewVReg1, RegState::Kill)
8353         .addImm(PCLabelId)
8354         .add(predOps(ARMCC::AL));
8355     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8356         .addReg(NewVReg2, RegState::Kill)
8357         .addFrameIndex(FI)
8358         .addImm(36) // &jbuf[1] :: pc
8359         .addMemOperand(FIMMOSt)
8360         .add(predOps(ARMCC::AL));
8361   }
8362 }
8363 
8364 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8365                                               MachineBasicBlock *MBB) const {
8366   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8367   DebugLoc dl = MI.getDebugLoc();
8368   MachineFunction *MF = MBB->getParent();
8369   MachineRegisterInfo *MRI = &MF->getRegInfo();
8370   MachineFrameInfo &MFI = MF->getFrameInfo();
8371   int FI = MFI.getFunctionContextIndex();
8372 
8373   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8374                                                         : &ARM::GPRnopcRegClass;
8375 
8376   // Get a mapping of the call site numbers to all of the landing pads they're
8377   // associated with.
8378   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8379   unsigned MaxCSNum = 0;
8380   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8381        ++BB) {
8382     if (!BB->isEHPad()) continue;
8383 
8384     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8385     // pad.
8386     for (MachineBasicBlock::iterator
8387            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8388       if (!II->isEHLabel()) continue;
8389 
8390       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8391       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8392 
8393       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8394       for (SmallVectorImpl<unsigned>::iterator
8395              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8396            CSI != CSE; ++CSI) {
8397         CallSiteNumToLPad[*CSI].push_back(&*BB);
8398         MaxCSNum = std::max(MaxCSNum, *CSI);
8399       }
8400       break;
8401     }
8402   }
8403 
8404   // Get an ordered list of the machine basic blocks for the jump table.
8405   std::vector<MachineBasicBlock*> LPadList;
8406   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8407   LPadList.reserve(CallSiteNumToLPad.size());
8408   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8409     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8410     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8411            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8412       LPadList.push_back(*II);
8413       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8414     }
8415   }
8416 
8417   assert(!LPadList.empty() &&
8418          "No landing pad destinations for the dispatch jump table!");
8419 
8420   // Create the jump table and associated information.
8421   MachineJumpTableInfo *JTI =
8422     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8423   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8424 
8425   // Create the MBBs for the dispatch code.
8426 
8427   // Shove the dispatch's address into the return slot in the function context.
8428   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8429   DispatchBB->setIsEHPad();
8430 
8431   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8432   unsigned trap_opcode;
8433   if (Subtarget->isThumb())
8434     trap_opcode = ARM::tTRAP;
8435   else
8436     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8437 
8438   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8439   DispatchBB->addSuccessor(TrapBB);
8440 
8441   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8442   DispatchBB->addSuccessor(DispContBB);
8443 
8444   // Insert and MBBs.
8445   MF->insert(MF->end(), DispatchBB);
8446   MF->insert(MF->end(), DispContBB);
8447   MF->insert(MF->end(), TrapBB);
8448 
8449   // Insert code into the entry block that creates and registers the function
8450   // context.
8451   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8452 
8453   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8454       MachinePointerInfo::getFixedStack(*MF, FI),
8455       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8456 
8457   MachineInstrBuilder MIB;
8458   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8459 
8460   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8461   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8462 
8463   // Add a register mask with no preserved registers.  This results in all
8464   // registers being marked as clobbered. This can't work if the dispatch block
8465   // is in a Thumb1 function and is linked with ARM code which uses the FP
8466   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8467   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8468 
8469   bool IsPositionIndependent = isPositionIndependent();
8470   unsigned NumLPads = LPadList.size();
8471   if (Subtarget->isThumb2()) {
8472     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8473     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8474         .addFrameIndex(FI)
8475         .addImm(4)
8476         .addMemOperand(FIMMOLd)
8477         .add(predOps(ARMCC::AL));
8478 
8479     if (NumLPads < 256) {
8480       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8481           .addReg(NewVReg1)
8482           .addImm(LPadList.size())
8483           .add(predOps(ARMCC::AL));
8484     } else {
8485       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8486       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8487           .addImm(NumLPads & 0xFFFF)
8488           .add(predOps(ARMCC::AL));
8489 
8490       unsigned VReg2 = VReg1;
8491       if ((NumLPads & 0xFFFF0000) != 0) {
8492         VReg2 = MRI->createVirtualRegister(TRC);
8493         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8494             .addReg(VReg1)
8495             .addImm(NumLPads >> 16)
8496             .add(predOps(ARMCC::AL));
8497       }
8498 
8499       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8500           .addReg(NewVReg1)
8501           .addReg(VReg2)
8502           .add(predOps(ARMCC::AL));
8503     }
8504 
8505     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8506       .addMBB(TrapBB)
8507       .addImm(ARMCC::HI)
8508       .addReg(ARM::CPSR);
8509 
8510     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8511     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8512         .addJumpTableIndex(MJTI)
8513         .add(predOps(ARMCC::AL));
8514 
8515     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8516     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8517         .addReg(NewVReg3, RegState::Kill)
8518         .addReg(NewVReg1)
8519         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8520         .add(predOps(ARMCC::AL))
8521         .add(condCodeOp());
8522 
8523     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8524       .addReg(NewVReg4, RegState::Kill)
8525       .addReg(NewVReg1)
8526       .addJumpTableIndex(MJTI);
8527   } else if (Subtarget->isThumb()) {
8528     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8529     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8530         .addFrameIndex(FI)
8531         .addImm(1)
8532         .addMemOperand(FIMMOLd)
8533         .add(predOps(ARMCC::AL));
8534 
8535     if (NumLPads < 256) {
8536       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8537           .addReg(NewVReg1)
8538           .addImm(NumLPads)
8539           .add(predOps(ARMCC::AL));
8540     } else {
8541       MachineConstantPool *ConstantPool = MF->getConstantPool();
8542       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8543       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8544 
8545       // MachineConstantPool wants an explicit alignment.
8546       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8547       if (Align == 0)
8548         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8549       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8550 
8551       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8552       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8553           .addReg(VReg1, RegState::Define)
8554           .addConstantPoolIndex(Idx)
8555           .add(predOps(ARMCC::AL));
8556       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8557           .addReg(NewVReg1)
8558           .addReg(VReg1)
8559           .add(predOps(ARMCC::AL));
8560     }
8561 
8562     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8563       .addMBB(TrapBB)
8564       .addImm(ARMCC::HI)
8565       .addReg(ARM::CPSR);
8566 
8567     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8568     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8569         .addReg(ARM::CPSR, RegState::Define)
8570         .addReg(NewVReg1)
8571         .addImm(2)
8572         .add(predOps(ARMCC::AL));
8573 
8574     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8575     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8576         .addJumpTableIndex(MJTI)
8577         .add(predOps(ARMCC::AL));
8578 
8579     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8580     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8581         .addReg(ARM::CPSR, RegState::Define)
8582         .addReg(NewVReg2, RegState::Kill)
8583         .addReg(NewVReg3)
8584         .add(predOps(ARMCC::AL));
8585 
8586     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8587         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8588 
8589     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8590     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8591         .addReg(NewVReg4, RegState::Kill)
8592         .addImm(0)
8593         .addMemOperand(JTMMOLd)
8594         .add(predOps(ARMCC::AL));
8595 
8596     unsigned NewVReg6 = NewVReg5;
8597     if (IsPositionIndependent) {
8598       NewVReg6 = MRI->createVirtualRegister(TRC);
8599       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8600           .addReg(ARM::CPSR, RegState::Define)
8601           .addReg(NewVReg5, RegState::Kill)
8602           .addReg(NewVReg3)
8603           .add(predOps(ARMCC::AL));
8604     }
8605 
8606     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8607       .addReg(NewVReg6, RegState::Kill)
8608       .addJumpTableIndex(MJTI);
8609   } else {
8610     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8611     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8612         .addFrameIndex(FI)
8613         .addImm(4)
8614         .addMemOperand(FIMMOLd)
8615         .add(predOps(ARMCC::AL));
8616 
8617     if (NumLPads < 256) {
8618       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8619           .addReg(NewVReg1)
8620           .addImm(NumLPads)
8621           .add(predOps(ARMCC::AL));
8622     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8623       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8624       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8625           .addImm(NumLPads & 0xFFFF)
8626           .add(predOps(ARMCC::AL));
8627 
8628       unsigned VReg2 = VReg1;
8629       if ((NumLPads & 0xFFFF0000) != 0) {
8630         VReg2 = MRI->createVirtualRegister(TRC);
8631         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8632             .addReg(VReg1)
8633             .addImm(NumLPads >> 16)
8634             .add(predOps(ARMCC::AL));
8635       }
8636 
8637       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8638           .addReg(NewVReg1)
8639           .addReg(VReg2)
8640           .add(predOps(ARMCC::AL));
8641     } else {
8642       MachineConstantPool *ConstantPool = MF->getConstantPool();
8643       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8644       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8645 
8646       // MachineConstantPool wants an explicit alignment.
8647       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8648       if (Align == 0)
8649         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8650       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8651 
8652       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8653       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8654           .addReg(VReg1, RegState::Define)
8655           .addConstantPoolIndex(Idx)
8656           .addImm(0)
8657           .add(predOps(ARMCC::AL));
8658       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8659           .addReg(NewVReg1)
8660           .addReg(VReg1, RegState::Kill)
8661           .add(predOps(ARMCC::AL));
8662     }
8663 
8664     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8665       .addMBB(TrapBB)
8666       .addImm(ARMCC::HI)
8667       .addReg(ARM::CPSR);
8668 
8669     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8670     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8671         .addReg(NewVReg1)
8672         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8673         .add(predOps(ARMCC::AL))
8674         .add(condCodeOp());
8675     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8676     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8677         .addJumpTableIndex(MJTI)
8678         .add(predOps(ARMCC::AL));
8679 
8680     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8681         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8682     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8683     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8684         .addReg(NewVReg3, RegState::Kill)
8685         .addReg(NewVReg4)
8686         .addImm(0)
8687         .addMemOperand(JTMMOLd)
8688         .add(predOps(ARMCC::AL));
8689 
8690     if (IsPositionIndependent) {
8691       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8692         .addReg(NewVReg5, RegState::Kill)
8693         .addReg(NewVReg4)
8694         .addJumpTableIndex(MJTI);
8695     } else {
8696       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8697         .addReg(NewVReg5, RegState::Kill)
8698         .addJumpTableIndex(MJTI);
8699     }
8700   }
8701 
8702   // Add the jump table entries as successors to the MBB.
8703   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8704   for (std::vector<MachineBasicBlock*>::iterator
8705          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8706     MachineBasicBlock *CurMBB = *I;
8707     if (SeenMBBs.insert(CurMBB).second)
8708       DispContBB->addSuccessor(CurMBB);
8709   }
8710 
8711   // N.B. the order the invoke BBs are processed in doesn't matter here.
8712   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8713   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8714   for (MachineBasicBlock *BB : InvokeBBs) {
8715 
8716     // Remove the landing pad successor from the invoke block and replace it
8717     // with the new dispatch block.
8718     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8719                                                   BB->succ_end());
8720     while (!Successors.empty()) {
8721       MachineBasicBlock *SMBB = Successors.pop_back_val();
8722       if (SMBB->isEHPad()) {
8723         BB->removeSuccessor(SMBB);
8724         MBBLPads.push_back(SMBB);
8725       }
8726     }
8727 
8728     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8729     BB->normalizeSuccProbs();
8730 
8731     // Find the invoke call and mark all of the callee-saved registers as
8732     // 'implicit defined' so that they're spilled. This prevents code from
8733     // moving instructions to before the EH block, where they will never be
8734     // executed.
8735     for (MachineBasicBlock::reverse_iterator
8736            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8737       if (!II->isCall()) continue;
8738 
8739       DenseMap<unsigned, bool> DefRegs;
8740       for (MachineInstr::mop_iterator
8741              OI = II->operands_begin(), OE = II->operands_end();
8742            OI != OE; ++OI) {
8743         if (!OI->isReg()) continue;
8744         DefRegs[OI->getReg()] = true;
8745       }
8746 
8747       MachineInstrBuilder MIB(*MF, &*II);
8748 
8749       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8750         unsigned Reg = SavedRegs[i];
8751         if (Subtarget->isThumb2() &&
8752             !ARM::tGPRRegClass.contains(Reg) &&
8753             !ARM::hGPRRegClass.contains(Reg))
8754           continue;
8755         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8756           continue;
8757         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8758           continue;
8759         if (!DefRegs[Reg])
8760           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8761       }
8762 
8763       break;
8764     }
8765   }
8766 
8767   // Mark all former landing pads as non-landing pads. The dispatch is the only
8768   // landing pad now.
8769   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8770          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8771     (*I)->setIsEHPad(false);
8772 
8773   // The instruction is gone now.
8774   MI.eraseFromParent();
8775 }
8776 
8777 static
8778 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8779   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8780        E = MBB->succ_end(); I != E; ++I)
8781     if (*I != Succ)
8782       return *I;
8783   llvm_unreachable("Expecting a BB with two successors!");
8784 }
8785 
8786 /// Return the load opcode for a given load size. If load size >= 8,
8787 /// neon opcode will be returned.
8788 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8789   if (LdSize >= 8)
8790     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8791                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8792   if (IsThumb1)
8793     return LdSize == 4 ? ARM::tLDRi
8794                        : LdSize == 2 ? ARM::tLDRHi
8795                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8796   if (IsThumb2)
8797     return LdSize == 4 ? ARM::t2LDR_POST
8798                        : LdSize == 2 ? ARM::t2LDRH_POST
8799                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8800   return LdSize == 4 ? ARM::LDR_POST_IMM
8801                      : LdSize == 2 ? ARM::LDRH_POST
8802                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8803 }
8804 
8805 /// Return the store opcode for a given store size. If store size >= 8,
8806 /// neon opcode will be returned.
8807 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8808   if (StSize >= 8)
8809     return StSize == 16 ? ARM::VST1q32wb_fixed
8810                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8811   if (IsThumb1)
8812     return StSize == 4 ? ARM::tSTRi
8813                        : StSize == 2 ? ARM::tSTRHi
8814                                      : StSize == 1 ? ARM::tSTRBi : 0;
8815   if (IsThumb2)
8816     return StSize == 4 ? ARM::t2STR_POST
8817                        : StSize == 2 ? ARM::t2STRH_POST
8818                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8819   return StSize == 4 ? ARM::STR_POST_IMM
8820                      : StSize == 2 ? ARM::STRH_POST
8821                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8822 }
8823 
8824 /// Emit a post-increment load operation with given size. The instructions
8825 /// will be added to BB at Pos.
8826 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8827                        const TargetInstrInfo *TII, const DebugLoc &dl,
8828                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8829                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8830   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8831   assert(LdOpc != 0 && "Should have a load opcode");
8832   if (LdSize >= 8) {
8833     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8834         .addReg(AddrOut, RegState::Define)
8835         .addReg(AddrIn)
8836         .addImm(0)
8837         .add(predOps(ARMCC::AL));
8838   } else if (IsThumb1) {
8839     // load + update AddrIn
8840     BuildMI(*BB, Pos, dl, TII->get(LdOpc), 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(LdSize)
8848         .add(predOps(ARMCC::AL));
8849   } else if (IsThumb2) {
8850     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8851         .addReg(AddrOut, RegState::Define)
8852         .addReg(AddrIn)
8853         .addImm(LdSize)
8854         .add(predOps(ARMCC::AL));
8855   } else { // arm
8856     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8857         .addReg(AddrOut, RegState::Define)
8858         .addReg(AddrIn)
8859         .addReg(0)
8860         .addImm(LdSize)
8861         .add(predOps(ARMCC::AL));
8862   }
8863 }
8864 
8865 /// Emit a post-increment store operation with given size. The instructions
8866 /// will be added to BB at Pos.
8867 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8868                        const TargetInstrInfo *TII, const DebugLoc &dl,
8869                        unsigned StSize, unsigned Data, unsigned AddrIn,
8870                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8871   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8872   assert(StOpc != 0 && "Should have a store opcode");
8873   if (StSize >= 8) {
8874     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8875         .addReg(AddrIn)
8876         .addImm(0)
8877         .addReg(Data)
8878         .add(predOps(ARMCC::AL));
8879   } else if (IsThumb1) {
8880     // store + update AddrIn
8881     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8882         .addReg(Data)
8883         .addReg(AddrIn)
8884         .addImm(0)
8885         .add(predOps(ARMCC::AL));
8886     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8887         .add(t1CondCodeOp())
8888         .addReg(AddrIn)
8889         .addImm(StSize)
8890         .add(predOps(ARMCC::AL));
8891   } else if (IsThumb2) {
8892     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8893         .addReg(Data)
8894         .addReg(AddrIn)
8895         .addImm(StSize)
8896         .add(predOps(ARMCC::AL));
8897   } else { // arm
8898     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8899         .addReg(Data)
8900         .addReg(AddrIn)
8901         .addReg(0)
8902         .addImm(StSize)
8903         .add(predOps(ARMCC::AL));
8904   }
8905 }
8906 
8907 MachineBasicBlock *
8908 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8909                                    MachineBasicBlock *BB) const {
8910   // This pseudo instruction has 3 operands: dst, src, size
8911   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8912   // Otherwise, we will generate unrolled scalar copies.
8913   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8914   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8915   MachineFunction::iterator It = ++BB->getIterator();
8916 
8917   unsigned dest = MI.getOperand(0).getReg();
8918   unsigned src = MI.getOperand(1).getReg();
8919   unsigned SizeVal = MI.getOperand(2).getImm();
8920   unsigned Align = MI.getOperand(3).getImm();
8921   DebugLoc dl = MI.getDebugLoc();
8922 
8923   MachineFunction *MF = BB->getParent();
8924   MachineRegisterInfo &MRI = MF->getRegInfo();
8925   unsigned UnitSize = 0;
8926   const TargetRegisterClass *TRC = nullptr;
8927   const TargetRegisterClass *VecTRC = nullptr;
8928 
8929   bool IsThumb1 = Subtarget->isThumb1Only();
8930   bool IsThumb2 = Subtarget->isThumb2();
8931   bool IsThumb = Subtarget->isThumb();
8932 
8933   if (Align & 1) {
8934     UnitSize = 1;
8935   } else if (Align & 2) {
8936     UnitSize = 2;
8937   } else {
8938     // Check whether we can use NEON instructions.
8939     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8940         Subtarget->hasNEON()) {
8941       if ((Align % 16 == 0) && SizeVal >= 16)
8942         UnitSize = 16;
8943       else if ((Align % 8 == 0) && SizeVal >= 8)
8944         UnitSize = 8;
8945     }
8946     // Can't use NEON instructions.
8947     if (UnitSize == 0)
8948       UnitSize = 4;
8949   }
8950 
8951   // Select the correct opcode and register class for unit size load/store
8952   bool IsNeon = UnitSize >= 8;
8953   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8954   if (IsNeon)
8955     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8956                             : UnitSize == 8 ? &ARM::DPRRegClass
8957                                             : nullptr;
8958 
8959   unsigned BytesLeft = SizeVal % UnitSize;
8960   unsigned LoopSize = SizeVal - BytesLeft;
8961 
8962   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8963     // Use LDR and STR to copy.
8964     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8965     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8966     unsigned srcIn = src;
8967     unsigned destIn = dest;
8968     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8969       unsigned srcOut = MRI.createVirtualRegister(TRC);
8970       unsigned destOut = MRI.createVirtualRegister(TRC);
8971       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8972       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8973                  IsThumb1, IsThumb2);
8974       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8975                  IsThumb1, IsThumb2);
8976       srcIn = srcOut;
8977       destIn = destOut;
8978     }
8979 
8980     // Handle the leftover bytes with LDRB and STRB.
8981     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8982     // [destOut] = STRB_POST(scratch, destIn, 1)
8983     for (unsigned i = 0; i < BytesLeft; i++) {
8984       unsigned srcOut = MRI.createVirtualRegister(TRC);
8985       unsigned destOut = MRI.createVirtualRegister(TRC);
8986       unsigned scratch = MRI.createVirtualRegister(TRC);
8987       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8988                  IsThumb1, IsThumb2);
8989       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8990                  IsThumb1, IsThumb2);
8991       srcIn = srcOut;
8992       destIn = destOut;
8993     }
8994     MI.eraseFromParent(); // The instruction is gone now.
8995     return BB;
8996   }
8997 
8998   // Expand the pseudo op to a loop.
8999   // thisMBB:
9000   //   ...
9001   //   movw varEnd, # --> with thumb2
9002   //   movt varEnd, #
9003   //   ldrcp varEnd, idx --> without thumb2
9004   //   fallthrough --> loopMBB
9005   // loopMBB:
9006   //   PHI varPhi, varEnd, varLoop
9007   //   PHI srcPhi, src, srcLoop
9008   //   PHI destPhi, dst, destLoop
9009   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9010   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9011   //   subs varLoop, varPhi, #UnitSize
9012   //   bne loopMBB
9013   //   fallthrough --> exitMBB
9014   // exitMBB:
9015   //   epilogue to handle left-over bytes
9016   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9017   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9018   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9019   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9020   MF->insert(It, loopMBB);
9021   MF->insert(It, exitMBB);
9022 
9023   // Transfer the remainder of BB and its successor edges to exitMBB.
9024   exitMBB->splice(exitMBB->begin(), BB,
9025                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9026   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9027 
9028   // Load an immediate to varEnd.
9029   unsigned varEnd = MRI.createVirtualRegister(TRC);
9030   if (Subtarget->useMovt()) {
9031     unsigned Vtmp = varEnd;
9032     if ((LoopSize & 0xFFFF0000) != 0)
9033       Vtmp = MRI.createVirtualRegister(TRC);
9034     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9035         .addImm(LoopSize & 0xFFFF)
9036         .add(predOps(ARMCC::AL));
9037 
9038     if ((LoopSize & 0xFFFF0000) != 0)
9039       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9040           .addReg(Vtmp)
9041           .addImm(LoopSize >> 16)
9042           .add(predOps(ARMCC::AL));
9043   } else {
9044     MachineConstantPool *ConstantPool = MF->getConstantPool();
9045     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9046     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9047 
9048     // MachineConstantPool wants an explicit alignment.
9049     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9050     if (Align == 0)
9051       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9052     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9053     MachineMemOperand *CPMMO =
9054         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9055                                  MachineMemOperand::MOLoad, 4, 4);
9056 
9057     if (IsThumb)
9058       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9059           .addReg(varEnd, RegState::Define)
9060           .addConstantPoolIndex(Idx)
9061           .add(predOps(ARMCC::AL))
9062           .addMemOperand(CPMMO);
9063     else
9064       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9065           .addReg(varEnd, RegState::Define)
9066           .addConstantPoolIndex(Idx)
9067           .addImm(0)
9068           .add(predOps(ARMCC::AL))
9069           .addMemOperand(CPMMO);
9070   }
9071   BB->addSuccessor(loopMBB);
9072 
9073   // Generate the loop body:
9074   //   varPhi = PHI(varLoop, varEnd)
9075   //   srcPhi = PHI(srcLoop, src)
9076   //   destPhi = PHI(destLoop, dst)
9077   MachineBasicBlock *entryBB = BB;
9078   BB = loopMBB;
9079   unsigned varLoop = MRI.createVirtualRegister(TRC);
9080   unsigned varPhi = MRI.createVirtualRegister(TRC);
9081   unsigned srcLoop = MRI.createVirtualRegister(TRC);
9082   unsigned srcPhi = MRI.createVirtualRegister(TRC);
9083   unsigned destLoop = MRI.createVirtualRegister(TRC);
9084   unsigned destPhi = MRI.createVirtualRegister(TRC);
9085 
9086   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9087     .addReg(varLoop).addMBB(loopMBB)
9088     .addReg(varEnd).addMBB(entryBB);
9089   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9090     .addReg(srcLoop).addMBB(loopMBB)
9091     .addReg(src).addMBB(entryBB);
9092   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9093     .addReg(destLoop).addMBB(loopMBB)
9094     .addReg(dest).addMBB(entryBB);
9095 
9096   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9097   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9098   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9099   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9100              IsThumb1, IsThumb2);
9101   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9102              IsThumb1, IsThumb2);
9103 
9104   // Decrement loop variable by UnitSize.
9105   if (IsThumb1) {
9106     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9107         .add(t1CondCodeOp())
9108         .addReg(varPhi)
9109         .addImm(UnitSize)
9110         .add(predOps(ARMCC::AL));
9111   } else {
9112     MachineInstrBuilder MIB =
9113         BuildMI(*BB, BB->end(), dl,
9114                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9115     MIB.addReg(varPhi)
9116         .addImm(UnitSize)
9117         .add(predOps(ARMCC::AL))
9118         .add(condCodeOp());
9119     MIB->getOperand(5).setReg(ARM::CPSR);
9120     MIB->getOperand(5).setIsDef(true);
9121   }
9122   BuildMI(*BB, BB->end(), dl,
9123           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9124       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9125 
9126   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9127   BB->addSuccessor(loopMBB);
9128   BB->addSuccessor(exitMBB);
9129 
9130   // Add epilogue to handle BytesLeft.
9131   BB = exitMBB;
9132   auto StartOfExit = exitMBB->begin();
9133 
9134   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9135   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9136   unsigned srcIn = srcLoop;
9137   unsigned destIn = destLoop;
9138   for (unsigned i = 0; i < BytesLeft; i++) {
9139     unsigned srcOut = MRI.createVirtualRegister(TRC);
9140     unsigned destOut = MRI.createVirtualRegister(TRC);
9141     unsigned scratch = MRI.createVirtualRegister(TRC);
9142     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9143                IsThumb1, IsThumb2);
9144     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9145                IsThumb1, IsThumb2);
9146     srcIn = srcOut;
9147     destIn = destOut;
9148   }
9149 
9150   MI.eraseFromParent(); // The instruction is gone now.
9151   return BB;
9152 }
9153 
9154 MachineBasicBlock *
9155 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9156                                        MachineBasicBlock *MBB) const {
9157   const TargetMachine &TM = getTargetMachine();
9158   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9159   DebugLoc DL = MI.getDebugLoc();
9160 
9161   assert(Subtarget->isTargetWindows() &&
9162          "__chkstk is only supported on Windows");
9163   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9164 
9165   // __chkstk takes the number of words to allocate on the stack in R4, and
9166   // returns the stack adjustment in number of bytes in R4.  This will not
9167   // clober any other registers (other than the obvious lr).
9168   //
9169   // Although, technically, IP should be considered a register which may be
9170   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9171   // thumb-2 environment, so there is no interworking required.  As a result, we
9172   // do not expect a veneer to be emitted by the linker, clobbering IP.
9173   //
9174   // Each module receives its own copy of __chkstk, so no import thunk is
9175   // required, again, ensuring that IP is not clobbered.
9176   //
9177   // Finally, although some linkers may theoretically provide a trampoline for
9178   // out of range calls (which is quite common due to a 32M range limitation of
9179   // branches for Thumb), we can generate the long-call version via
9180   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9181   // IP.
9182 
9183   switch (TM.getCodeModel()) {
9184   case CodeModel::Tiny:
9185     llvm_unreachable("Tiny code model not available on ARM.");
9186   case CodeModel::Small:
9187   case CodeModel::Medium:
9188   case CodeModel::Kernel:
9189     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9190         .add(predOps(ARMCC::AL))
9191         .addExternalSymbol("__chkstk")
9192         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9193         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9194         .addReg(ARM::R12,
9195                 RegState::Implicit | RegState::Define | RegState::Dead)
9196         .addReg(ARM::CPSR,
9197                 RegState::Implicit | RegState::Define | RegState::Dead);
9198     break;
9199   case CodeModel::Large: {
9200     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9201     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9202 
9203     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9204       .addExternalSymbol("__chkstk");
9205     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9206         .add(predOps(ARMCC::AL))
9207         .addReg(Reg, RegState::Kill)
9208         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9209         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9210         .addReg(ARM::R12,
9211                 RegState::Implicit | RegState::Define | RegState::Dead)
9212         .addReg(ARM::CPSR,
9213                 RegState::Implicit | RegState::Define | RegState::Dead);
9214     break;
9215   }
9216   }
9217 
9218   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9219       .addReg(ARM::SP, RegState::Kill)
9220       .addReg(ARM::R4, RegState::Kill)
9221       .setMIFlags(MachineInstr::FrameSetup)
9222       .add(predOps(ARMCC::AL))
9223       .add(condCodeOp());
9224 
9225   MI.eraseFromParent();
9226   return MBB;
9227 }
9228 
9229 MachineBasicBlock *
9230 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9231                                        MachineBasicBlock *MBB) const {
9232   DebugLoc DL = MI.getDebugLoc();
9233   MachineFunction *MF = MBB->getParent();
9234   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9235 
9236   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9237   MF->insert(++MBB->getIterator(), ContBB);
9238   ContBB->splice(ContBB->begin(), MBB,
9239                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9240   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9241   MBB->addSuccessor(ContBB);
9242 
9243   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9244   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9245   MF->push_back(TrapBB);
9246   MBB->addSuccessor(TrapBB);
9247 
9248   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9249       .addReg(MI.getOperand(0).getReg())
9250       .addImm(0)
9251       .add(predOps(ARMCC::AL));
9252   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9253       .addMBB(TrapBB)
9254       .addImm(ARMCC::EQ)
9255       .addReg(ARM::CPSR);
9256 
9257   MI.eraseFromParent();
9258   return ContBB;
9259 }
9260 
9261 // The CPSR operand of SelectItr might be missing a kill marker
9262 // because there were multiple uses of CPSR, and ISel didn't know
9263 // which to mark. Figure out whether SelectItr should have had a
9264 // kill marker, and set it if it should. Returns the correct kill
9265 // marker value.
9266 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9267                                    MachineBasicBlock* BB,
9268                                    const TargetRegisterInfo* TRI) {
9269   // Scan forward through BB for a use/def of CPSR.
9270   MachineBasicBlock::iterator miI(std::next(SelectItr));
9271   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9272     const MachineInstr& mi = *miI;
9273     if (mi.readsRegister(ARM::CPSR))
9274       return false;
9275     if (mi.definesRegister(ARM::CPSR))
9276       break; // Should have kill-flag - update below.
9277   }
9278 
9279   // If we hit the end of the block, check whether CPSR is live into a
9280   // successor.
9281   if (miI == BB->end()) {
9282     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9283                                           sEnd = BB->succ_end();
9284          sItr != sEnd; ++sItr) {
9285       MachineBasicBlock* succ = *sItr;
9286       if (succ->isLiveIn(ARM::CPSR))
9287         return false;
9288     }
9289   }
9290 
9291   // We found a def, or hit the end of the basic block and CPSR wasn't live
9292   // out. SelectMI should have a kill flag on CPSR.
9293   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9294   return true;
9295 }
9296 
9297 MachineBasicBlock *
9298 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9299                                                MachineBasicBlock *BB) const {
9300   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9301   DebugLoc dl = MI.getDebugLoc();
9302   bool isThumb2 = Subtarget->isThumb2();
9303   switch (MI.getOpcode()) {
9304   default: {
9305     MI.print(errs());
9306     llvm_unreachable("Unexpected instr type to insert");
9307   }
9308 
9309   // Thumb1 post-indexed loads are really just single-register LDMs.
9310   case ARM::tLDR_postidx: {
9311     MachineOperand Def(MI.getOperand(1));
9312     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9313         .add(Def)  // Rn_wb
9314         .add(MI.getOperand(2))  // Rn
9315         .add(MI.getOperand(3))  // PredImm
9316         .add(MI.getOperand(4))  // PredReg
9317         .add(MI.getOperand(0))  // Rt
9318         .cloneMemRefs(MI);
9319     MI.eraseFromParent();
9320     return BB;
9321   }
9322 
9323   // The Thumb2 pre-indexed stores have the same MI operands, they just
9324   // define them differently in the .td files from the isel patterns, so
9325   // they need pseudos.
9326   case ARM::t2STR_preidx:
9327     MI.setDesc(TII->get(ARM::t2STR_PRE));
9328     return BB;
9329   case ARM::t2STRB_preidx:
9330     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9331     return BB;
9332   case ARM::t2STRH_preidx:
9333     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9334     return BB;
9335 
9336   case ARM::STRi_preidx:
9337   case ARM::STRBi_preidx: {
9338     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9339                                                          : ARM::STRB_PRE_IMM;
9340     // Decode the offset.
9341     unsigned Offset = MI.getOperand(4).getImm();
9342     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9343     Offset = ARM_AM::getAM2Offset(Offset);
9344     if (isSub)
9345       Offset = -Offset;
9346 
9347     MachineMemOperand *MMO = *MI.memoperands_begin();
9348     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9349         .add(MI.getOperand(0)) // Rn_wb
9350         .add(MI.getOperand(1)) // Rt
9351         .add(MI.getOperand(2)) // Rn
9352         .addImm(Offset)        // offset (skip GPR==zero_reg)
9353         .add(MI.getOperand(5)) // pred
9354         .add(MI.getOperand(6))
9355         .addMemOperand(MMO);
9356     MI.eraseFromParent();
9357     return BB;
9358   }
9359   case ARM::STRr_preidx:
9360   case ARM::STRBr_preidx:
9361   case ARM::STRH_preidx: {
9362     unsigned NewOpc;
9363     switch (MI.getOpcode()) {
9364     default: llvm_unreachable("unexpected opcode!");
9365     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9366     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9367     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9368     }
9369     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9370     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9371       MIB.add(MI.getOperand(i));
9372     MI.eraseFromParent();
9373     return BB;
9374   }
9375 
9376   case ARM::tMOVCCr_pseudo: {
9377     // To "insert" a SELECT_CC instruction, we actually have to insert the
9378     // diamond control-flow pattern.  The incoming instruction knows the
9379     // destination vreg to set, the condition code register to branch on, the
9380     // true/false values to select between, and a branch opcode to use.
9381     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9382     MachineFunction::iterator It = ++BB->getIterator();
9383 
9384     //  thisMBB:
9385     //  ...
9386     //   TrueVal = ...
9387     //   cmpTY ccX, r1, r2
9388     //   bCC copy1MBB
9389     //   fallthrough --> copy0MBB
9390     MachineBasicBlock *thisMBB  = BB;
9391     MachineFunction *F = BB->getParent();
9392     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9393     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9394     F->insert(It, copy0MBB);
9395     F->insert(It, sinkMBB);
9396 
9397     // Check whether CPSR is live past the tMOVCCr_pseudo.
9398     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
9399     if (!MI.killsRegister(ARM::CPSR) &&
9400         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
9401       copy0MBB->addLiveIn(ARM::CPSR);
9402       sinkMBB->addLiveIn(ARM::CPSR);
9403     }
9404 
9405     // Transfer the remainder of BB and its successor edges to sinkMBB.
9406     sinkMBB->splice(sinkMBB->begin(), BB,
9407                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9408     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9409 
9410     BB->addSuccessor(copy0MBB);
9411     BB->addSuccessor(sinkMBB);
9412 
9413     BuildMI(BB, dl, TII->get(ARM::tBcc))
9414         .addMBB(sinkMBB)
9415         .addImm(MI.getOperand(3).getImm())
9416         .addReg(MI.getOperand(4).getReg());
9417 
9418     //  copy0MBB:
9419     //   %FalseValue = ...
9420     //   # fallthrough to sinkMBB
9421     BB = copy0MBB;
9422 
9423     // Update machine-CFG edges
9424     BB->addSuccessor(sinkMBB);
9425 
9426     //  sinkMBB:
9427     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9428     //  ...
9429     BB = sinkMBB;
9430     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9431         .addReg(MI.getOperand(1).getReg())
9432         .addMBB(copy0MBB)
9433         .addReg(MI.getOperand(2).getReg())
9434         .addMBB(thisMBB);
9435 
9436     MI.eraseFromParent(); // The pseudo instruction is gone now.
9437     return BB;
9438   }
9439 
9440   case ARM::BCCi64:
9441   case ARM::BCCZi64: {
9442     // If there is an unconditional branch to the other successor, remove it.
9443     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9444 
9445     // Compare both parts that make up the double comparison separately for
9446     // equality.
9447     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9448 
9449     unsigned LHS1 = MI.getOperand(1).getReg();
9450     unsigned LHS2 = MI.getOperand(2).getReg();
9451     if (RHSisZero) {
9452       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9453           .addReg(LHS1)
9454           .addImm(0)
9455           .add(predOps(ARMCC::AL));
9456       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9457         .addReg(LHS2).addImm(0)
9458         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9459     } else {
9460       unsigned RHS1 = MI.getOperand(3).getReg();
9461       unsigned RHS2 = MI.getOperand(4).getReg();
9462       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9463           .addReg(LHS1)
9464           .addReg(RHS1)
9465           .add(predOps(ARMCC::AL));
9466       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9467         .addReg(LHS2).addReg(RHS2)
9468         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9469     }
9470 
9471     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9472     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9473     if (MI.getOperand(0).getImm() == ARMCC::NE)
9474       std::swap(destMBB, exitMBB);
9475 
9476     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9477       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9478     if (isThumb2)
9479       BuildMI(BB, dl, TII->get(ARM::t2B))
9480           .addMBB(exitMBB)
9481           .add(predOps(ARMCC::AL));
9482     else
9483       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9484 
9485     MI.eraseFromParent(); // The pseudo instruction is gone now.
9486     return BB;
9487   }
9488 
9489   case ARM::Int_eh_sjlj_setjmp:
9490   case ARM::Int_eh_sjlj_setjmp_nofp:
9491   case ARM::tInt_eh_sjlj_setjmp:
9492   case ARM::t2Int_eh_sjlj_setjmp:
9493   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9494     return BB;
9495 
9496   case ARM::Int_eh_sjlj_setup_dispatch:
9497     EmitSjLjDispatchBlock(MI, BB);
9498     return BB;
9499 
9500   case ARM::ABS:
9501   case ARM::t2ABS: {
9502     // To insert an ABS instruction, we have to insert the
9503     // diamond control-flow pattern.  The incoming instruction knows the
9504     // source vreg to test against 0, the destination vreg to set,
9505     // the condition code register to branch on, the
9506     // true/false values to select between, and a branch opcode to use.
9507     // It transforms
9508     //     V1 = ABS V0
9509     // into
9510     //     V2 = MOVS V0
9511     //     BCC                      (branch to SinkBB if V0 >= 0)
9512     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9513     //     SinkBB: V1 = PHI(V2, V3)
9514     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9515     MachineFunction::iterator BBI = ++BB->getIterator();
9516     MachineFunction *Fn = BB->getParent();
9517     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9518     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9519     Fn->insert(BBI, RSBBB);
9520     Fn->insert(BBI, SinkBB);
9521 
9522     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9523     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9524     bool ABSSrcKIll = MI.getOperand(1).isKill();
9525     bool isThumb2 = Subtarget->isThumb2();
9526     MachineRegisterInfo &MRI = Fn->getRegInfo();
9527     // In Thumb mode S must not be specified if source register is the SP or
9528     // PC and if destination register is the SP, so restrict register class
9529     unsigned NewRsbDstReg =
9530       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9531 
9532     // Transfer the remainder of BB and its successor edges to sinkMBB.
9533     SinkBB->splice(SinkBB->begin(), BB,
9534                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9535     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9536 
9537     BB->addSuccessor(RSBBB);
9538     BB->addSuccessor(SinkBB);
9539 
9540     // fall through to SinkMBB
9541     RSBBB->addSuccessor(SinkBB);
9542 
9543     // insert a cmp at the end of BB
9544     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9545         .addReg(ABSSrcReg)
9546         .addImm(0)
9547         .add(predOps(ARMCC::AL));
9548 
9549     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9550     BuildMI(BB, dl,
9551       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9552       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9553 
9554     // insert rsbri in RSBBB
9555     // Note: BCC and rsbri will be converted into predicated rsbmi
9556     // by if-conversion pass
9557     BuildMI(*RSBBB, RSBBB->begin(), dl,
9558             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9559         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9560         .addImm(0)
9561         .add(predOps(ARMCC::AL))
9562         .add(condCodeOp());
9563 
9564     // insert PHI in SinkBB,
9565     // reuse ABSDstReg to not change uses of ABS instruction
9566     BuildMI(*SinkBB, SinkBB->begin(), dl,
9567       TII->get(ARM::PHI), ABSDstReg)
9568       .addReg(NewRsbDstReg).addMBB(RSBBB)
9569       .addReg(ABSSrcReg).addMBB(BB);
9570 
9571     // remove ABS instruction
9572     MI.eraseFromParent();
9573 
9574     // return last added BB
9575     return SinkBB;
9576   }
9577   case ARM::COPY_STRUCT_BYVAL_I32:
9578     ++NumLoopByVals;
9579     return EmitStructByval(MI, BB);
9580   case ARM::WIN__CHKSTK:
9581     return EmitLowered__chkstk(MI, BB);
9582   case ARM::WIN__DBZCHK:
9583     return EmitLowered__dbzchk(MI, BB);
9584   }
9585 }
9586 
9587 /// Attaches vregs to MEMCPY that it will use as scratch registers
9588 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9589 /// instead of as a custom inserter because we need the use list from the SDNode.
9590 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9591                                     MachineInstr &MI, const SDNode *Node) {
9592   bool isThumb1 = Subtarget->isThumb1Only();
9593 
9594   DebugLoc DL = MI.getDebugLoc();
9595   MachineFunction *MF = MI.getParent()->getParent();
9596   MachineRegisterInfo &MRI = MF->getRegInfo();
9597   MachineInstrBuilder MIB(*MF, MI);
9598 
9599   // If the new dst/src is unused mark it as dead.
9600   if (!Node->hasAnyUseOfValue(0)) {
9601     MI.getOperand(0).setIsDead(true);
9602   }
9603   if (!Node->hasAnyUseOfValue(1)) {
9604     MI.getOperand(1).setIsDead(true);
9605   }
9606 
9607   // The MEMCPY both defines and kills the scratch registers.
9608   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9609     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9610                                                          : &ARM::GPRRegClass);
9611     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9612   }
9613 }
9614 
9615 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9616                                                       SDNode *Node) const {
9617   if (MI.getOpcode() == ARM::MEMCPY) {
9618     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9619     return;
9620   }
9621 
9622   const MCInstrDesc *MCID = &MI.getDesc();
9623   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9624   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9625   // operand is still set to noreg. If needed, set the optional operand's
9626   // register to CPSR, and remove the redundant implicit def.
9627   //
9628   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9629 
9630   // Rename pseudo opcodes.
9631   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9632   unsigned ccOutIdx;
9633   if (NewOpc) {
9634     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9635     MCID = &TII->get(NewOpc);
9636 
9637     assert(MCID->getNumOperands() ==
9638            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9639         && "converted opcode should be the same except for cc_out"
9640            " (and, on Thumb1, pred)");
9641 
9642     MI.setDesc(*MCID);
9643 
9644     // Add the optional cc_out operand
9645     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9646 
9647     // On Thumb1, move all input operands to the end, then add the predicate
9648     if (Subtarget->isThumb1Only()) {
9649       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9650         MI.addOperand(MI.getOperand(1));
9651         MI.RemoveOperand(1);
9652       }
9653 
9654       // Restore the ties
9655       for (unsigned i = MI.getNumOperands(); i--;) {
9656         const MachineOperand& op = MI.getOperand(i);
9657         if (op.isReg() && op.isUse()) {
9658           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9659           if (DefIdx != -1)
9660             MI.tieOperands(DefIdx, i);
9661         }
9662       }
9663 
9664       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9665       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9666       ccOutIdx = 1;
9667     } else
9668       ccOutIdx = MCID->getNumOperands() - 1;
9669   } else
9670     ccOutIdx = MCID->getNumOperands() - 1;
9671 
9672   // Any ARM instruction that sets the 's' bit should specify an optional
9673   // "cc_out" operand in the last operand position.
9674   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9675     assert(!NewOpc && "Optional cc_out operand required");
9676     return;
9677   }
9678   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9679   // since we already have an optional CPSR def.
9680   bool definesCPSR = false;
9681   bool deadCPSR = false;
9682   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9683        ++i) {
9684     const MachineOperand &MO = MI.getOperand(i);
9685     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9686       definesCPSR = true;
9687       if (MO.isDead())
9688         deadCPSR = true;
9689       MI.RemoveOperand(i);
9690       break;
9691     }
9692   }
9693   if (!definesCPSR) {
9694     assert(!NewOpc && "Optional cc_out operand required");
9695     return;
9696   }
9697   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9698   if (deadCPSR) {
9699     assert(!MI.getOperand(ccOutIdx).getReg() &&
9700            "expect uninitialized optional cc_out operand");
9701     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9702     if (!Subtarget->isThumb1Only())
9703       return;
9704   }
9705 
9706   // If this instruction was defined with an optional CPSR def and its dag node
9707   // had a live implicit CPSR def, then activate the optional CPSR def.
9708   MachineOperand &MO = MI.getOperand(ccOutIdx);
9709   MO.setReg(ARM::CPSR);
9710   MO.setIsDef(true);
9711 }
9712 
9713 //===----------------------------------------------------------------------===//
9714 //                           ARM Optimization Hooks
9715 //===----------------------------------------------------------------------===//
9716 
9717 // Helper function that checks if N is a null or all ones constant.
9718 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9719   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9720 }
9721 
9722 // Return true if N is conditionally 0 or all ones.
9723 // Detects these expressions where cc is an i1 value:
9724 //
9725 //   (select cc 0, y)   [AllOnes=0]
9726 //   (select cc y, 0)   [AllOnes=0]
9727 //   (zext cc)          [AllOnes=0]
9728 //   (sext cc)          [AllOnes=0/1]
9729 //   (select cc -1, y)  [AllOnes=1]
9730 //   (select cc y, -1)  [AllOnes=1]
9731 //
9732 // Invert is set when N is the null/all ones constant when CC is false.
9733 // OtherOp is set to the alternative value of N.
9734 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9735                                        SDValue &CC, bool &Invert,
9736                                        SDValue &OtherOp,
9737                                        SelectionDAG &DAG) {
9738   switch (N->getOpcode()) {
9739   default: return false;
9740   case ISD::SELECT: {
9741     CC = N->getOperand(0);
9742     SDValue N1 = N->getOperand(1);
9743     SDValue N2 = N->getOperand(2);
9744     if (isZeroOrAllOnes(N1, AllOnes)) {
9745       Invert = false;
9746       OtherOp = N2;
9747       return true;
9748     }
9749     if (isZeroOrAllOnes(N2, AllOnes)) {
9750       Invert = true;
9751       OtherOp = N1;
9752       return true;
9753     }
9754     return false;
9755   }
9756   case ISD::ZERO_EXTEND:
9757     // (zext cc) can never be the all ones value.
9758     if (AllOnes)
9759       return false;
9760     LLVM_FALLTHROUGH;
9761   case ISD::SIGN_EXTEND: {
9762     SDLoc dl(N);
9763     EVT VT = N->getValueType(0);
9764     CC = N->getOperand(0);
9765     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9766       return false;
9767     Invert = !AllOnes;
9768     if (AllOnes)
9769       // When looking for an AllOnes constant, N is an sext, and the 'other'
9770       // value is 0.
9771       OtherOp = DAG.getConstant(0, dl, VT);
9772     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9773       // When looking for a 0 constant, N can be zext or sext.
9774       OtherOp = DAG.getConstant(1, dl, VT);
9775     else
9776       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9777                                 VT);
9778     return true;
9779   }
9780   }
9781 }
9782 
9783 // Combine a constant select operand into its use:
9784 //
9785 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9786 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9787 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9788 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9789 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9790 //
9791 // The transform is rejected if the select doesn't have a constant operand that
9792 // is null, or all ones when AllOnes is set.
9793 //
9794 // Also recognize sext/zext from i1:
9795 //
9796 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9797 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9798 //
9799 // These transformations eventually create predicated instructions.
9800 //
9801 // @param N       The node to transform.
9802 // @param Slct    The N operand that is a select.
9803 // @param OtherOp The other N operand (x above).
9804 // @param DCI     Context.
9805 // @param AllOnes Require the select constant to be all ones instead of null.
9806 // @returns The new node, or SDValue() on failure.
9807 static
9808 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9809                             TargetLowering::DAGCombinerInfo &DCI,
9810                             bool AllOnes = false) {
9811   SelectionDAG &DAG = DCI.DAG;
9812   EVT VT = N->getValueType(0);
9813   SDValue NonConstantVal;
9814   SDValue CCOp;
9815   bool SwapSelectOps;
9816   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9817                                   NonConstantVal, DAG))
9818     return SDValue();
9819 
9820   // Slct is now know to be the desired identity constant when CC is true.
9821   SDValue TrueVal = OtherOp;
9822   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9823                                  OtherOp, NonConstantVal);
9824   // Unless SwapSelectOps says CC should be false.
9825   if (SwapSelectOps)
9826     std::swap(TrueVal, FalseVal);
9827 
9828   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9829                      CCOp, TrueVal, FalseVal);
9830 }
9831 
9832 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9833 static
9834 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9835                                        TargetLowering::DAGCombinerInfo &DCI) {
9836   SDValue N0 = N->getOperand(0);
9837   SDValue N1 = N->getOperand(1);
9838   if (N0.getNode()->hasOneUse())
9839     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9840       return Result;
9841   if (N1.getNode()->hasOneUse())
9842     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9843       return Result;
9844   return SDValue();
9845 }
9846 
9847 static bool IsVUZPShuffleNode(SDNode *N) {
9848   // VUZP shuffle node.
9849   if (N->getOpcode() == ARMISD::VUZP)
9850     return true;
9851 
9852   // "VUZP" on i32 is an alias for VTRN.
9853   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9854     return true;
9855 
9856   return false;
9857 }
9858 
9859 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9860                                  TargetLowering::DAGCombinerInfo &DCI,
9861                                  const ARMSubtarget *Subtarget) {
9862   // Look for ADD(VUZP.0, VUZP.1).
9863   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9864       N0 == N1)
9865    return SDValue();
9866 
9867   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9868   if (!N->getValueType(0).is64BitVector())
9869     return SDValue();
9870 
9871   // Generate vpadd.
9872   SelectionDAG &DAG = DCI.DAG;
9873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9874   SDLoc dl(N);
9875   SDNode *Unzip = N0.getNode();
9876   EVT VT = N->getValueType(0);
9877 
9878   SmallVector<SDValue, 8> Ops;
9879   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9880                                 TLI.getPointerTy(DAG.getDataLayout())));
9881   Ops.push_back(Unzip->getOperand(0));
9882   Ops.push_back(Unzip->getOperand(1));
9883 
9884   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9885 }
9886 
9887 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9888                                       TargetLowering::DAGCombinerInfo &DCI,
9889                                       const ARMSubtarget *Subtarget) {
9890   // Check for two extended operands.
9891   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9892         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9893       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9894         N1.getOpcode() == ISD::ZERO_EXTEND))
9895     return SDValue();
9896 
9897   SDValue N00 = N0.getOperand(0);
9898   SDValue N10 = N1.getOperand(0);
9899 
9900   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9901   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9902       N00 == N10)
9903     return SDValue();
9904 
9905   // We only recognize Q register paddl here; this can't be reached until
9906   // after type legalization.
9907   if (!N00.getValueType().is64BitVector() ||
9908       !N0.getValueType().is128BitVector())
9909     return SDValue();
9910 
9911   // Generate vpaddl.
9912   SelectionDAG &DAG = DCI.DAG;
9913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9914   SDLoc dl(N);
9915   EVT VT = N->getValueType(0);
9916 
9917   SmallVector<SDValue, 8> Ops;
9918   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9919   unsigned Opcode;
9920   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9921     Opcode = Intrinsic::arm_neon_vpaddls;
9922   else
9923     Opcode = Intrinsic::arm_neon_vpaddlu;
9924   Ops.push_back(DAG.getConstant(Opcode, dl,
9925                                 TLI.getPointerTy(DAG.getDataLayout())));
9926   EVT ElemTy = N00.getValueType().getVectorElementType();
9927   unsigned NumElts = VT.getVectorNumElements();
9928   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9929   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9930                                N00.getOperand(0), N00.getOperand(1));
9931   Ops.push_back(Concat);
9932 
9933   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9934 }
9935 
9936 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9937 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9938 // much easier to match.
9939 static SDValue
9940 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9941                                TargetLowering::DAGCombinerInfo &DCI,
9942                                const ARMSubtarget *Subtarget) {
9943   // Only perform optimization if after legalize, and if NEON is available. We
9944   // also expected both operands to be BUILD_VECTORs.
9945   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9946       || N0.getOpcode() != ISD::BUILD_VECTOR
9947       || N1.getOpcode() != ISD::BUILD_VECTOR)
9948     return SDValue();
9949 
9950   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9951   EVT VT = N->getValueType(0);
9952   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9953     return SDValue();
9954 
9955   // Check that the vector operands are of the right form.
9956   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9957   // operands, where N is the size of the formed vector.
9958   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9959   // index such that we have a pair wise add pattern.
9960 
9961   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9962   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9963     return SDValue();
9964   SDValue Vec = N0->getOperand(0)->getOperand(0);
9965   SDNode *V = Vec.getNode();
9966   unsigned nextIndex = 0;
9967 
9968   // For each operands to the ADD which are BUILD_VECTORs,
9969   // check to see if each of their operands are an EXTRACT_VECTOR with
9970   // the same vector and appropriate index.
9971   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9972     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9973         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9974 
9975       SDValue ExtVec0 = N0->getOperand(i);
9976       SDValue ExtVec1 = N1->getOperand(i);
9977 
9978       // First operand is the vector, verify its the same.
9979       if (V != ExtVec0->getOperand(0).getNode() ||
9980           V != ExtVec1->getOperand(0).getNode())
9981         return SDValue();
9982 
9983       // Second is the constant, verify its correct.
9984       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9985       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9986 
9987       // For the constant, we want to see all the even or all the odd.
9988       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9989           || C1->getZExtValue() != nextIndex+1)
9990         return SDValue();
9991 
9992       // Increment index.
9993       nextIndex+=2;
9994     } else
9995       return SDValue();
9996   }
9997 
9998   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9999   // we're using the entire input vector, otherwise there's a size/legality
10000   // mismatch somewhere.
10001   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10002       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10003     return SDValue();
10004 
10005   // Create VPADDL node.
10006   SelectionDAG &DAG = DCI.DAG;
10007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10008 
10009   SDLoc dl(N);
10010 
10011   // Build operand list.
10012   SmallVector<SDValue, 8> Ops;
10013   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10014                                 TLI.getPointerTy(DAG.getDataLayout())));
10015 
10016   // Input is the vector.
10017   Ops.push_back(Vec);
10018 
10019   // Get widened type and narrowed type.
10020   MVT widenType;
10021   unsigned numElem = VT.getVectorNumElements();
10022 
10023   EVT inputLaneType = Vec.getValueType().getVectorElementType();
10024   switch (inputLaneType.getSimpleVT().SimpleTy) {
10025     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10026     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10027     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10028     default:
10029       llvm_unreachable("Invalid vector element type for padd optimization.");
10030   }
10031 
10032   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10033   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10034   return DAG.getNode(ExtOp, dl, VT, tmp);
10035 }
10036 
10037 static SDValue findMUL_LOHI(SDValue V) {
10038   if (V->getOpcode() == ISD::UMUL_LOHI ||
10039       V->getOpcode() == ISD::SMUL_LOHI)
10040     return V;
10041   return SDValue();
10042 }
10043 
10044 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10045                                         TargetLowering::DAGCombinerInfo &DCI,
10046                                         const ARMSubtarget *Subtarget) {
10047   if (Subtarget->isThumb()) {
10048     if (!Subtarget->hasDSP())
10049       return SDValue();
10050   } else if (!Subtarget->hasV5TEOps())
10051     return SDValue();
10052 
10053   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10054   // accumulates the product into a 64-bit value. The 16-bit values will
10055   // be sign extended somehow or SRA'd into 32-bit values
10056   // (addc (adde (mul 16bit, 16bit), lo), hi)
10057   SDValue Mul = AddcNode->getOperand(0);
10058   SDValue Lo = AddcNode->getOperand(1);
10059   if (Mul.getOpcode() != ISD::MUL) {
10060     Lo = AddcNode->getOperand(0);
10061     Mul = AddcNode->getOperand(1);
10062     if (Mul.getOpcode() != ISD::MUL)
10063       return SDValue();
10064   }
10065 
10066   SDValue SRA = AddeNode->getOperand(0);
10067   SDValue Hi = AddeNode->getOperand(1);
10068   if (SRA.getOpcode() != ISD::SRA) {
10069     SRA = AddeNode->getOperand(1);
10070     Hi = AddeNode->getOperand(0);
10071     if (SRA.getOpcode() != ISD::SRA)
10072       return SDValue();
10073   }
10074   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10075     if (Const->getZExtValue() != 31)
10076       return SDValue();
10077   } else
10078     return SDValue();
10079 
10080   if (SRA.getOperand(0) != Mul)
10081     return SDValue();
10082 
10083   SelectionDAG &DAG = DCI.DAG;
10084   SDLoc dl(AddcNode);
10085   unsigned Opcode = 0;
10086   SDValue Op0;
10087   SDValue Op1;
10088 
10089   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10090     Opcode = ARMISD::SMLALBB;
10091     Op0 = Mul.getOperand(0);
10092     Op1 = Mul.getOperand(1);
10093   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10094     Opcode = ARMISD::SMLALBT;
10095     Op0 = Mul.getOperand(0);
10096     Op1 = Mul.getOperand(1).getOperand(0);
10097   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10098     Opcode = ARMISD::SMLALTB;
10099     Op0 = Mul.getOperand(0).getOperand(0);
10100     Op1 = Mul.getOperand(1);
10101   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10102     Opcode = ARMISD::SMLALTT;
10103     Op0 = Mul->getOperand(0).getOperand(0);
10104     Op1 = Mul->getOperand(1).getOperand(0);
10105   }
10106 
10107   if (!Op0 || !Op1)
10108     return SDValue();
10109 
10110   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10111                               Op0, Op1, Lo, Hi);
10112   // Replace the ADDs' nodes uses by the MLA node's values.
10113   SDValue HiMLALResult(SMLAL.getNode(), 1);
10114   SDValue LoMLALResult(SMLAL.getNode(), 0);
10115 
10116   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10117   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10118 
10119   // Return original node to notify the driver to stop replacing.
10120   SDValue resNode(AddcNode, 0);
10121   return resNode;
10122 }
10123 
10124 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10125                                      TargetLowering::DAGCombinerInfo &DCI,
10126                                      const ARMSubtarget *Subtarget) {
10127   // Look for multiply add opportunities.
10128   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10129   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10130   // a glue link from the first add to the second add.
10131   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10132   // a S/UMLAL instruction.
10133   //                  UMUL_LOHI
10134   //                 / :lo    \ :hi
10135   //                V          \          [no multiline comment]
10136   //    loAdd ->  ADDC         |
10137   //                 \ :carry /
10138   //                  V      V
10139   //                    ADDE   <- hiAdd
10140   //
10141   // In the special case where only the higher part of a signed result is used
10142   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10143   // a constant with the exact value of 0x80000000, we recognize we are dealing
10144   // with a "rounded multiply and add" (or subtract) and transform it into
10145   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10146 
10147   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10148           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10149          "Expect an ADDE or SUBE");
10150 
10151   assert(AddeSubeNode->getNumOperands() == 3 &&
10152          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10153          "ADDE node has the wrong inputs");
10154 
10155   // Check that we are chained to the right ADDC or SUBC node.
10156   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10157   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10158        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10159       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10160        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10161     return SDValue();
10162 
10163   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10164   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10165 
10166   // Check if the two operands are from the same mul_lohi node.
10167   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10168     return SDValue();
10169 
10170   assert(AddcSubcNode->getNumValues() == 2 &&
10171          AddcSubcNode->getValueType(0) == MVT::i32 &&
10172          "Expect ADDC with two result values. First: i32");
10173 
10174   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10175   // maybe a SMLAL which multiplies two 16-bit values.
10176   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10177       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10178       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10179       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10180       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10181     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10182 
10183   // Check for the triangle shape.
10184   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10185   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10186 
10187   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10188   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10189     return SDValue();
10190 
10191   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10192   bool IsLeftOperandMUL = false;
10193   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10194   if (MULOp == SDValue())
10195     MULOp = findMUL_LOHI(AddeSubeOp1);
10196   else
10197     IsLeftOperandMUL = true;
10198   if (MULOp == SDValue())
10199     return SDValue();
10200 
10201   // Figure out the right opcode.
10202   unsigned Opc = MULOp->getOpcode();
10203   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10204 
10205   // Figure out the high and low input values to the MLAL node.
10206   SDValue *HiAddSub = nullptr;
10207   SDValue *LoMul = nullptr;
10208   SDValue *LowAddSub = nullptr;
10209 
10210   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10211   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10212     return SDValue();
10213 
10214   if (IsLeftOperandMUL)
10215     HiAddSub = &AddeSubeOp1;
10216   else
10217     HiAddSub = &AddeSubeOp0;
10218 
10219   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10220   // whose low result is fed to the ADDC/SUBC we are checking.
10221 
10222   if (AddcSubcOp0 == MULOp.getValue(0)) {
10223     LoMul = &AddcSubcOp0;
10224     LowAddSub = &AddcSubcOp1;
10225   }
10226   if (AddcSubcOp1 == MULOp.getValue(0)) {
10227     LoMul = &AddcSubcOp1;
10228     LowAddSub = &AddcSubcOp0;
10229   }
10230 
10231   if (!LoMul)
10232     return SDValue();
10233 
10234   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10235   // the replacement below will create a cycle.
10236   if (AddcSubcNode == HiAddSub->getNode() ||
10237       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10238     return SDValue();
10239 
10240   // Create the merged node.
10241   SelectionDAG &DAG = DCI.DAG;
10242 
10243   // Start building operand list.
10244   SmallVector<SDValue, 8> Ops;
10245   Ops.push_back(LoMul->getOperand(0));
10246   Ops.push_back(LoMul->getOperand(1));
10247 
10248   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10249   // the case, we must be doing signed multiplication and only use the higher
10250   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10251   // addition or subtraction with the value of 0x800000.
10252   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10253       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10254       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10255       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10256           0x80000000) {
10257     Ops.push_back(*HiAddSub);
10258     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10259       FinalOpc = ARMISD::SMMLSR;
10260     } else {
10261       FinalOpc = ARMISD::SMMLAR;
10262     }
10263     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10264     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10265 
10266     return SDValue(AddeSubeNode, 0);
10267   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10268     // SMMLS is generated during instruction selection and the rest of this
10269     // function can not handle the case where AddcSubcNode is a SUBC.
10270     return SDValue();
10271 
10272   // Finish building the operand list for {U/S}MLAL
10273   Ops.push_back(*LowAddSub);
10274   Ops.push_back(*HiAddSub);
10275 
10276   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10277                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10278 
10279   // Replace the ADDs' nodes uses by the MLA node's values.
10280   SDValue HiMLALResult(MLALNode.getNode(), 1);
10281   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10282 
10283   SDValue LoMLALResult(MLALNode.getNode(), 0);
10284   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10285 
10286   // Return original node to notify the driver to stop replacing.
10287   return SDValue(AddeSubeNode, 0);
10288 }
10289 
10290 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10291                                       TargetLowering::DAGCombinerInfo &DCI,
10292                                       const ARMSubtarget *Subtarget) {
10293   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10294   // While trying to combine for the other MLAL nodes, first search for the
10295   // chance to use UMAAL. Check if Addc uses a node which has already
10296   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10297   // as the addend, and it's handled in PerformUMLALCombine.
10298 
10299   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10300     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10301 
10302   // Check that we have a glued ADDC node.
10303   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10304   if (AddcNode->getOpcode() != ARMISD::ADDC)
10305     return SDValue();
10306 
10307   // Find the converted UMAAL or quit if it doesn't exist.
10308   SDNode *UmlalNode = nullptr;
10309   SDValue AddHi;
10310   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10311     UmlalNode = AddcNode->getOperand(0).getNode();
10312     AddHi = AddcNode->getOperand(1);
10313   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10314     UmlalNode = AddcNode->getOperand(1).getNode();
10315     AddHi = AddcNode->getOperand(0);
10316   } else {
10317     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10318   }
10319 
10320   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10321   // the ADDC as well as Zero.
10322   if (!isNullConstant(UmlalNode->getOperand(3)))
10323     return SDValue();
10324 
10325   if ((isNullConstant(AddeNode->getOperand(0)) &&
10326        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10327       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10328        isNullConstant(AddeNode->getOperand(1)))) {
10329     SelectionDAG &DAG = DCI.DAG;
10330     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10331                       UmlalNode->getOperand(2), AddHi };
10332     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10333                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10334 
10335     // Replace the ADDs' nodes uses by the UMAAL node's values.
10336     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10337     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10338 
10339     // Return original node to notify the driver to stop replacing.
10340     return SDValue(AddeNode, 0);
10341   }
10342   return SDValue();
10343 }
10344 
10345 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10346                                    const ARMSubtarget *Subtarget) {
10347   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10348     return SDValue();
10349 
10350   // Check that we have a pair of ADDC and ADDE as operands.
10351   // Both addends of the ADDE must be zero.
10352   SDNode* AddcNode = N->getOperand(2).getNode();
10353   SDNode* AddeNode = N->getOperand(3).getNode();
10354   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10355       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10356       isNullConstant(AddeNode->getOperand(0)) &&
10357       isNullConstant(AddeNode->getOperand(1)) &&
10358       (AddeNode->getOperand(2).getNode() == AddcNode))
10359     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10360                        DAG.getVTList(MVT::i32, MVT::i32),
10361                        {N->getOperand(0), N->getOperand(1),
10362                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10363   else
10364     return SDValue();
10365 }
10366 
10367 static SDValue PerformAddcSubcCombine(SDNode *N,
10368                                       TargetLowering::DAGCombinerInfo &DCI,
10369                                       const ARMSubtarget *Subtarget) {
10370   SelectionDAG &DAG(DCI.DAG);
10371 
10372   if (N->getOpcode() == ARMISD::SUBC) {
10373     // (SUBC (ADDE 0, 0, C), 1) -> C
10374     SDValue LHS = N->getOperand(0);
10375     SDValue RHS = N->getOperand(1);
10376     if (LHS->getOpcode() == ARMISD::ADDE &&
10377         isNullConstant(LHS->getOperand(0)) &&
10378         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10379       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10380     }
10381   }
10382 
10383   if (Subtarget->isThumb1Only()) {
10384     SDValue RHS = N->getOperand(1);
10385     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10386       int32_t imm = C->getSExtValue();
10387       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10388         SDLoc DL(N);
10389         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10390         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10391                                                            : ARMISD::ADDC;
10392         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10393       }
10394     }
10395   }
10396 
10397   return SDValue();
10398 }
10399 
10400 static SDValue PerformAddeSubeCombine(SDNode *N,
10401                                       TargetLowering::DAGCombinerInfo &DCI,
10402                                       const ARMSubtarget *Subtarget) {
10403   if (Subtarget->isThumb1Only()) {
10404     SelectionDAG &DAG = DCI.DAG;
10405     SDValue RHS = N->getOperand(1);
10406     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10407       int64_t imm = C->getSExtValue();
10408       if (imm < 0) {
10409         SDLoc DL(N);
10410 
10411         // The with-carry-in form matches bitwise not instead of the negation.
10412         // Effectively, the inverse interpretation of the carry flag already
10413         // accounts for part of the negation.
10414         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10415 
10416         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10417                                                            : ARMISD::ADDE;
10418         return DAG.getNode(Opcode, DL, N->getVTList(),
10419                            N->getOperand(0), RHS, N->getOperand(2));
10420       }
10421     }
10422   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10423     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10424   }
10425   return SDValue();
10426 }
10427 
10428 static SDValue PerformABSCombine(SDNode *N,
10429                                   TargetLowering::DAGCombinerInfo &DCI,
10430                                   const ARMSubtarget *Subtarget) {
10431   SDValue res;
10432   SelectionDAG &DAG = DCI.DAG;
10433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10434 
10435   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
10436     return SDValue();
10437 
10438   if (!TLI.expandABS(N, res, DAG))
10439       return SDValue();
10440 
10441   return res;
10442 }
10443 
10444 /// PerformADDECombine - Target-specific dag combine transform from
10445 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10446 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10447 static SDValue PerformADDECombine(SDNode *N,
10448                                   TargetLowering::DAGCombinerInfo &DCI,
10449                                   const ARMSubtarget *Subtarget) {
10450   // Only ARM and Thumb2 support UMLAL/SMLAL.
10451   if (Subtarget->isThumb1Only())
10452     return PerformAddeSubeCombine(N, DCI, Subtarget);
10453 
10454   // Only perform the checks after legalize when the pattern is available.
10455   if (DCI.isBeforeLegalize()) return SDValue();
10456 
10457   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10458 }
10459 
10460 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10461 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10462 /// called with the default operands, and if that fails, with commuted
10463 /// operands.
10464 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10465                                           TargetLowering::DAGCombinerInfo &DCI,
10466                                           const ARMSubtarget *Subtarget){
10467   // Attempt to create vpadd for this add.
10468   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10469     return Result;
10470 
10471   // Attempt to create vpaddl for this add.
10472   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10473     return Result;
10474   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10475                                                       Subtarget))
10476     return Result;
10477 
10478   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10479   if (N0.getNode()->hasOneUse())
10480     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10481       return Result;
10482   return SDValue();
10483 }
10484 
10485 bool
10486 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10487                                                  CombineLevel Level) const {
10488   if (Level == BeforeLegalizeTypes)
10489     return true;
10490 
10491   if (N->getOpcode() != ISD::SHL)
10492     return true;
10493 
10494   if (Subtarget->isThumb1Only()) {
10495     // Avoid making expensive immediates by commuting shifts. (This logic
10496     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
10497     // for free.)
10498     if (N->getOpcode() != ISD::SHL)
10499       return true;
10500     SDValue N1 = N->getOperand(0);
10501     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
10502         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
10503       return true;
10504     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
10505       if (Const->getAPIntValue().ult(256))
10506         return false;
10507       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
10508           Const->getAPIntValue().sgt(-256))
10509         return false;
10510     }
10511     return true;
10512   }
10513 
10514   // Turn off commute-with-shift transform after legalization, so it doesn't
10515   // conflict with PerformSHLSimplify.  (We could try to detect when
10516   // PerformSHLSimplify would trigger more precisely, but it isn't
10517   // really necessary.)
10518   return false;
10519 }
10520 
10521 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
10522     const SDNode *N, CombineLevel Level) const {
10523   if (!Subtarget->isThumb1Only())
10524     return true;
10525 
10526   if (Level == BeforeLegalizeTypes)
10527     return true;
10528 
10529   return false;
10530 }
10531 
10532 static SDValue PerformSHLSimplify(SDNode *N,
10533                                 TargetLowering::DAGCombinerInfo &DCI,
10534                                 const ARMSubtarget *ST) {
10535   // Allow the generic combiner to identify potential bswaps.
10536   if (DCI.isBeforeLegalize())
10537     return SDValue();
10538 
10539   // DAG combiner will fold:
10540   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10541   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10542   // Other code patterns that can be also be modified have the following form:
10543   // b + ((a << 1) | 510)
10544   // b + ((a << 1) & 510)
10545   // b + ((a << 1) ^ 510)
10546   // b + ((a << 1) + 510)
10547 
10548   // Many instructions can  perform the shift for free, but it requires both
10549   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10550   // instruction will needed. So, unfold back to the original pattern if:
10551   // - if c1 and c2 are small enough that they don't require mov imms.
10552   // - the user(s) of the node can perform an shl
10553 
10554   // No shifted operands for 16-bit instructions.
10555   if (ST->isThumb() && ST->isThumb1Only())
10556     return SDValue();
10557 
10558   // Check that all the users could perform the shl themselves.
10559   for (auto U : N->uses()) {
10560     switch(U->getOpcode()) {
10561     default:
10562       return SDValue();
10563     case ISD::SUB:
10564     case ISD::ADD:
10565     case ISD::AND:
10566     case ISD::OR:
10567     case ISD::XOR:
10568     case ISD::SETCC:
10569     case ARMISD::CMP:
10570       // Check that the user isn't already using a constant because there
10571       // aren't any instructions that support an immediate operand and a
10572       // shifted operand.
10573       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10574           isa<ConstantSDNode>(U->getOperand(1)))
10575         return SDValue();
10576 
10577       // Check that it's not already using a shift.
10578       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10579           U->getOperand(1).getOpcode() == ISD::SHL)
10580         return SDValue();
10581       break;
10582     }
10583   }
10584 
10585   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10586       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10587     return SDValue();
10588 
10589   if (N->getOperand(0).getOpcode() != ISD::SHL)
10590     return SDValue();
10591 
10592   SDValue SHL = N->getOperand(0);
10593 
10594   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10595   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10596   if (!C1ShlC2 || !C2)
10597     return SDValue();
10598 
10599   APInt C2Int = C2->getAPIntValue();
10600   APInt C1Int = C1ShlC2->getAPIntValue();
10601 
10602   // Check that performing a lshr will not lose any information.
10603   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10604                                      C2Int.getBitWidth() - C2->getZExtValue());
10605   if ((C1Int & Mask) != C1Int)
10606     return SDValue();
10607 
10608   // Shift the first constant.
10609   C1Int.lshrInPlace(C2Int);
10610 
10611   // The immediates are encoded as an 8-bit value that can be rotated.
10612   auto LargeImm = [](const APInt &Imm) {
10613     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10614     return Imm.getBitWidth() - Zeros > 8;
10615   };
10616 
10617   if (LargeImm(C1Int) || LargeImm(C2Int))
10618     return SDValue();
10619 
10620   SelectionDAG &DAG = DCI.DAG;
10621   SDLoc dl(N);
10622   SDValue X = SHL.getOperand(0);
10623   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10624                               DAG.getConstant(C1Int, dl, MVT::i32));
10625   // Shift left to compensate for the lshr of C1Int.
10626   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10627 
10628   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
10629              SHL.dump(); N->dump());
10630   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10631   return Res;
10632 }
10633 
10634 
10635 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10636 ///
10637 static SDValue PerformADDCombine(SDNode *N,
10638                                  TargetLowering::DAGCombinerInfo &DCI,
10639                                  const ARMSubtarget *Subtarget) {
10640   SDValue N0 = N->getOperand(0);
10641   SDValue N1 = N->getOperand(1);
10642 
10643   // Only works one way, because it needs an immediate operand.
10644   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10645     return Result;
10646 
10647   // First try with the default operand order.
10648   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10649     return Result;
10650 
10651   // If that didn't work, try again with the operands commuted.
10652   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10653 }
10654 
10655 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10656 ///
10657 static SDValue PerformSUBCombine(SDNode *N,
10658                                  TargetLowering::DAGCombinerInfo &DCI) {
10659   SDValue N0 = N->getOperand(0);
10660   SDValue N1 = N->getOperand(1);
10661 
10662   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10663   if (N1.getNode()->hasOneUse())
10664     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10665       return Result;
10666 
10667   return SDValue();
10668 }
10669 
10670 /// PerformVMULCombine
10671 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10672 /// special multiplier accumulator forwarding.
10673 ///   vmul d3, d0, d2
10674 ///   vmla d3, d1, d2
10675 /// is faster than
10676 ///   vadd d3, d0, d1
10677 ///   vmul d3, d3, d2
10678 //  However, for (A + B) * (A + B),
10679 //    vadd d2, d0, d1
10680 //    vmul d3, d0, d2
10681 //    vmla d3, d1, d2
10682 //  is slower than
10683 //    vadd d2, d0, d1
10684 //    vmul d3, d2, d2
10685 static SDValue PerformVMULCombine(SDNode *N,
10686                                   TargetLowering::DAGCombinerInfo &DCI,
10687                                   const ARMSubtarget *Subtarget) {
10688   if (!Subtarget->hasVMLxForwarding())
10689     return SDValue();
10690 
10691   SelectionDAG &DAG = DCI.DAG;
10692   SDValue N0 = N->getOperand(0);
10693   SDValue N1 = N->getOperand(1);
10694   unsigned Opcode = N0.getOpcode();
10695   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10696       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10697     Opcode = N1.getOpcode();
10698     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10699         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10700       return SDValue();
10701     std::swap(N0, N1);
10702   }
10703 
10704   if (N0 == N1)
10705     return SDValue();
10706 
10707   EVT VT = N->getValueType(0);
10708   SDLoc DL(N);
10709   SDValue N00 = N0->getOperand(0);
10710   SDValue N01 = N0->getOperand(1);
10711   return DAG.getNode(Opcode, DL, VT,
10712                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10713                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10714 }
10715 
10716 static SDValue PerformMULCombine(SDNode *N,
10717                                  TargetLowering::DAGCombinerInfo &DCI,
10718                                  const ARMSubtarget *Subtarget) {
10719   SelectionDAG &DAG = DCI.DAG;
10720 
10721   if (Subtarget->isThumb1Only())
10722     return SDValue();
10723 
10724   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10725     return SDValue();
10726 
10727   EVT VT = N->getValueType(0);
10728   if (VT.is64BitVector() || VT.is128BitVector())
10729     return PerformVMULCombine(N, DCI, Subtarget);
10730   if (VT != MVT::i32)
10731     return SDValue();
10732 
10733   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10734   if (!C)
10735     return SDValue();
10736 
10737   int64_t MulAmt = C->getSExtValue();
10738   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10739 
10740   ShiftAmt = ShiftAmt & (32 - 1);
10741   SDValue V = N->getOperand(0);
10742   SDLoc DL(N);
10743 
10744   SDValue Res;
10745   MulAmt >>= ShiftAmt;
10746 
10747   if (MulAmt >= 0) {
10748     if (isPowerOf2_32(MulAmt - 1)) {
10749       // (mul x, 2^N + 1) => (add (shl x, N), x)
10750       Res = DAG.getNode(ISD::ADD, DL, VT,
10751                         V,
10752                         DAG.getNode(ISD::SHL, DL, VT,
10753                                     V,
10754                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10755                                                     MVT::i32)));
10756     } else if (isPowerOf2_32(MulAmt + 1)) {
10757       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10758       Res = DAG.getNode(ISD::SUB, DL, VT,
10759                         DAG.getNode(ISD::SHL, DL, VT,
10760                                     V,
10761                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10762                                                     MVT::i32)),
10763                         V);
10764     } else
10765       return SDValue();
10766   } else {
10767     uint64_t MulAmtAbs = -MulAmt;
10768     if (isPowerOf2_32(MulAmtAbs + 1)) {
10769       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10770       Res = DAG.getNode(ISD::SUB, DL, VT,
10771                         V,
10772                         DAG.getNode(ISD::SHL, DL, VT,
10773                                     V,
10774                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10775                                                     MVT::i32)));
10776     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10777       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10778       Res = DAG.getNode(ISD::ADD, DL, VT,
10779                         V,
10780                         DAG.getNode(ISD::SHL, DL, VT,
10781                                     V,
10782                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10783                                                     MVT::i32)));
10784       Res = DAG.getNode(ISD::SUB, DL, VT,
10785                         DAG.getConstant(0, DL, MVT::i32), Res);
10786     } else
10787       return SDValue();
10788   }
10789 
10790   if (ShiftAmt != 0)
10791     Res = DAG.getNode(ISD::SHL, DL, VT,
10792                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10793 
10794   // Do not add new nodes to DAG combiner worklist.
10795   DCI.CombineTo(N, Res, false);
10796   return SDValue();
10797 }
10798 
10799 static SDValue CombineANDShift(SDNode *N,
10800                                TargetLowering::DAGCombinerInfo &DCI,
10801                                const ARMSubtarget *Subtarget) {
10802   // Allow DAGCombine to pattern-match before we touch the canonical form.
10803   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10804     return SDValue();
10805 
10806   if (N->getValueType(0) != MVT::i32)
10807     return SDValue();
10808 
10809   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10810   if (!N1C)
10811     return SDValue();
10812 
10813   uint32_t C1 = (uint32_t)N1C->getZExtValue();
10814   // Don't transform uxtb/uxth.
10815   if (C1 == 255 || C1 == 65535)
10816     return SDValue();
10817 
10818   SDNode *N0 = N->getOperand(0).getNode();
10819   if (!N0->hasOneUse())
10820     return SDValue();
10821 
10822   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
10823     return SDValue();
10824 
10825   bool LeftShift = N0->getOpcode() == ISD::SHL;
10826 
10827   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10828   if (!N01C)
10829     return SDValue();
10830 
10831   uint32_t C2 = (uint32_t)N01C->getZExtValue();
10832   if (!C2 || C2 >= 32)
10833     return SDValue();
10834 
10835   // Clear irrelevant bits in the mask.
10836   if (LeftShift)
10837     C1 &= (-1U << C2);
10838   else
10839     C1 &= (-1U >> C2);
10840 
10841   SelectionDAG &DAG = DCI.DAG;
10842   SDLoc DL(N);
10843 
10844   // We have a pattern of the form "(and (shl x, c2) c1)" or
10845   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
10846   // transform to a pair of shifts, to save materializing c1.
10847 
10848   // First pattern: right shift, then mask off leading bits.
10849   // FIXME: Use demanded bits?
10850   if (!LeftShift && isMask_32(C1)) {
10851     uint32_t C3 = countLeadingZeros(C1);
10852     if (C2 < C3) {
10853       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10854                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10855       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10856                          DAG.getConstant(C3, DL, MVT::i32));
10857     }
10858   }
10859 
10860   // First pattern, reversed: left shift, then mask off trailing bits.
10861   if (LeftShift && isMask_32(~C1)) {
10862     uint32_t C3 = countTrailingZeros(C1);
10863     if (C2 < C3) {
10864       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
10865                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10866       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
10867                          DAG.getConstant(C3, DL, MVT::i32));
10868     }
10869   }
10870 
10871   // Second pattern: left shift, then mask off leading bits.
10872   // FIXME: Use demanded bits?
10873   if (LeftShift && isShiftedMask_32(C1)) {
10874     uint32_t Trailing = countTrailingZeros(C1);
10875     uint32_t C3 = countLeadingZeros(C1);
10876     if (Trailing == C2 && C2 + C3 < 32) {
10877       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10878                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10879       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10880                         DAG.getConstant(C3, DL, MVT::i32));
10881     }
10882   }
10883 
10884   // Second pattern, reversed: right shift, then mask off trailing bits.
10885   // FIXME: Handle other patterns of known/demanded bits.
10886   if (!LeftShift && isShiftedMask_32(C1)) {
10887     uint32_t Leading = countLeadingZeros(C1);
10888     uint32_t C3 = countTrailingZeros(C1);
10889     if (Leading == C2 && C2 + C3 < 32) {
10890       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
10891                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10892       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
10893                          DAG.getConstant(C3, DL, MVT::i32));
10894     }
10895   }
10896 
10897   // FIXME: Transform "(and (shl x, c2) c1)" ->
10898   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
10899   // c1.
10900   return SDValue();
10901 }
10902 
10903 static SDValue PerformANDCombine(SDNode *N,
10904                                  TargetLowering::DAGCombinerInfo &DCI,
10905                                  const ARMSubtarget *Subtarget) {
10906   // Attempt to use immediate-form VBIC
10907   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10908   SDLoc dl(N);
10909   EVT VT = N->getValueType(0);
10910   SelectionDAG &DAG = DCI.DAG;
10911 
10912   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10913     return SDValue();
10914 
10915   APInt SplatBits, SplatUndef;
10916   unsigned SplatBitSize;
10917   bool HasAnyUndefs;
10918   if (BVN &&
10919       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10920     if (SplatBitSize <= 64) {
10921       EVT VbicVT;
10922       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10923                                       SplatUndef.getZExtValue(), SplatBitSize,
10924                                       DAG, dl, VbicVT, VT.is128BitVector(),
10925                                       OtherModImm);
10926       if (Val.getNode()) {
10927         SDValue Input =
10928           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10929         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10930         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10931       }
10932     }
10933   }
10934 
10935   if (!Subtarget->isThumb1Only()) {
10936     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10937     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10938       return Result;
10939 
10940     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10941       return Result;
10942   }
10943 
10944   if (Subtarget->isThumb1Only())
10945     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
10946       return Result;
10947 
10948   return SDValue();
10949 }
10950 
10951 // Try combining OR nodes to SMULWB, SMULWT.
10952 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10953                                          TargetLowering::DAGCombinerInfo &DCI,
10954                                          const ARMSubtarget *Subtarget) {
10955   if (!Subtarget->hasV6Ops() ||
10956       (Subtarget->isThumb() &&
10957        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10958     return SDValue();
10959 
10960   SDValue SRL = OR->getOperand(0);
10961   SDValue SHL = OR->getOperand(1);
10962 
10963   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10964     SRL = OR->getOperand(1);
10965     SHL = OR->getOperand(0);
10966   }
10967   if (!isSRL16(SRL) || !isSHL16(SHL))
10968     return SDValue();
10969 
10970   // The first operands to the shifts need to be the two results from the
10971   // same smul_lohi node.
10972   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10973        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10974     return SDValue();
10975 
10976   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10977   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10978       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10979     return SDValue();
10980 
10981   // Now we have:
10982   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10983   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10984   // For SMUWB the 16-bit value will signed extended somehow.
10985   // For SMULWT only the SRA is required.
10986   // Check both sides of SMUL_LOHI
10987   SDValue OpS16 = SMULLOHI->getOperand(0);
10988   SDValue OpS32 = SMULLOHI->getOperand(1);
10989 
10990   SelectionDAG &DAG = DCI.DAG;
10991   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10992     OpS16 = OpS32;
10993     OpS32 = SMULLOHI->getOperand(0);
10994   }
10995 
10996   SDLoc dl(OR);
10997   unsigned Opcode = 0;
10998   if (isS16(OpS16, DAG))
10999     Opcode = ARMISD::SMULWB;
11000   else if (isSRA16(OpS16)) {
11001     Opcode = ARMISD::SMULWT;
11002     OpS16 = OpS16->getOperand(0);
11003   }
11004   else
11005     return SDValue();
11006 
11007   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11008   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11009   return SDValue(OR, 0);
11010 }
11011 
11012 static SDValue PerformORCombineToBFI(SDNode *N,
11013                                      TargetLowering::DAGCombinerInfo &DCI,
11014                                      const ARMSubtarget *Subtarget) {
11015   // BFI is only available on V6T2+
11016   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11017     return SDValue();
11018 
11019   EVT VT = N->getValueType(0);
11020   SDValue N0 = N->getOperand(0);
11021   SDValue N1 = N->getOperand(1);
11022   SelectionDAG &DAG = DCI.DAG;
11023   SDLoc DL(N);
11024   // 1) or (and A, mask), val => ARMbfi A, val, mask
11025   //      iff (val & mask) == val
11026   //
11027   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11028   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11029   //          && mask == ~mask2
11030   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11031   //          && ~mask == mask2
11032   //  (i.e., copy a bitfield value into another bitfield of the same width)
11033 
11034   if (VT != MVT::i32)
11035     return SDValue();
11036 
11037   SDValue N00 = N0.getOperand(0);
11038 
11039   // The value and the mask need to be constants so we can verify this is
11040   // actually a bitfield set. If the mask is 0xffff, we can do better
11041   // via a movt instruction, so don't use BFI in that case.
11042   SDValue MaskOp = N0.getOperand(1);
11043   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11044   if (!MaskC)
11045     return SDValue();
11046   unsigned Mask = MaskC->getZExtValue();
11047   if (Mask == 0xffff)
11048     return SDValue();
11049   SDValue Res;
11050   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11051   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11052   if (N1C) {
11053     unsigned Val = N1C->getZExtValue();
11054     if ((Val & ~Mask) != Val)
11055       return SDValue();
11056 
11057     if (ARM::isBitFieldInvertedMask(Mask)) {
11058       Val >>= countTrailingZeros(~Mask);
11059 
11060       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11061                         DAG.getConstant(Val, DL, MVT::i32),
11062                         DAG.getConstant(Mask, DL, MVT::i32));
11063 
11064       DCI.CombineTo(N, Res, false);
11065       // Return value from the original node to inform the combiner than N is
11066       // now dead.
11067       return SDValue(N, 0);
11068     }
11069   } else if (N1.getOpcode() == ISD::AND) {
11070     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11071     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11072     if (!N11C)
11073       return SDValue();
11074     unsigned Mask2 = N11C->getZExtValue();
11075 
11076     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11077     // as is to match.
11078     if (ARM::isBitFieldInvertedMask(Mask) &&
11079         (Mask == ~Mask2)) {
11080       // The pack halfword instruction works better for masks that fit it,
11081       // so use that when it's available.
11082       if (Subtarget->hasDSP() &&
11083           (Mask == 0xffff || Mask == 0xffff0000))
11084         return SDValue();
11085       // 2a
11086       unsigned amt = countTrailingZeros(Mask2);
11087       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11088                         DAG.getConstant(amt, DL, MVT::i32));
11089       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11090                         DAG.getConstant(Mask, DL, MVT::i32));
11091       DCI.CombineTo(N, Res, false);
11092       // Return value from the original node to inform the combiner than N is
11093       // now dead.
11094       return SDValue(N, 0);
11095     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11096                (~Mask == Mask2)) {
11097       // The pack halfword instruction works better for masks that fit it,
11098       // so use that when it's available.
11099       if (Subtarget->hasDSP() &&
11100           (Mask2 == 0xffff || Mask2 == 0xffff0000))
11101         return SDValue();
11102       // 2b
11103       unsigned lsb = countTrailingZeros(Mask);
11104       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11105                         DAG.getConstant(lsb, DL, MVT::i32));
11106       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11107                         DAG.getConstant(Mask2, DL, MVT::i32));
11108       DCI.CombineTo(N, Res, false);
11109       // Return value from the original node to inform the combiner than N is
11110       // now dead.
11111       return SDValue(N, 0);
11112     }
11113   }
11114 
11115   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11116       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11117       ARM::isBitFieldInvertedMask(~Mask)) {
11118     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11119     // where lsb(mask) == #shamt and masked bits of B are known zero.
11120     SDValue ShAmt = N00.getOperand(1);
11121     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11122     unsigned LSB = countTrailingZeros(Mask);
11123     if (ShAmtC != LSB)
11124       return SDValue();
11125 
11126     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11127                       DAG.getConstant(~Mask, DL, MVT::i32));
11128 
11129     DCI.CombineTo(N, Res, false);
11130     // Return value from the original node to inform the combiner than N is
11131     // now dead.
11132     return SDValue(N, 0);
11133   }
11134 
11135   return SDValue();
11136 }
11137 
11138 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11139 static SDValue PerformORCombine(SDNode *N,
11140                                 TargetLowering::DAGCombinerInfo &DCI,
11141                                 const ARMSubtarget *Subtarget) {
11142   // Attempt to use immediate-form VORR
11143   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11144   SDLoc dl(N);
11145   EVT VT = N->getValueType(0);
11146   SelectionDAG &DAG = DCI.DAG;
11147 
11148   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11149     return SDValue();
11150 
11151   APInt SplatBits, SplatUndef;
11152   unsigned SplatBitSize;
11153   bool HasAnyUndefs;
11154   if (BVN && Subtarget->hasNEON() &&
11155       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11156     if (SplatBitSize <= 64) {
11157       EVT VorrVT;
11158       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
11159                                       SplatUndef.getZExtValue(), SplatBitSize,
11160                                       DAG, dl, VorrVT, VT.is128BitVector(),
11161                                       OtherModImm);
11162       if (Val.getNode()) {
11163         SDValue Input =
11164           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11165         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11166         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11167       }
11168     }
11169   }
11170 
11171   if (!Subtarget->isThumb1Only()) {
11172     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11173     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11174       return Result;
11175     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11176       return Result;
11177   }
11178 
11179   SDValue N0 = N->getOperand(0);
11180   SDValue N1 = N->getOperand(1);
11181 
11182   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11183   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11184       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11185 
11186     // The code below optimizes (or (and X, Y), Z).
11187     // The AND operand needs to have a single user to make these optimizations
11188     // profitable.
11189     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11190       return SDValue();
11191 
11192     APInt SplatUndef;
11193     unsigned SplatBitSize;
11194     bool HasAnyUndefs;
11195 
11196     APInt SplatBits0, SplatBits1;
11197     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11198     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11199     // Ensure that the second operand of both ands are constants
11200     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11201                                       HasAnyUndefs) && !HasAnyUndefs) {
11202         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11203                                           HasAnyUndefs) && !HasAnyUndefs) {
11204             // Ensure that the bit width of the constants are the same and that
11205             // the splat arguments are logical inverses as per the pattern we
11206             // are trying to simplify.
11207             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11208                 SplatBits0 == ~SplatBits1) {
11209                 // Canonicalize the vector type to make instruction selection
11210                 // simpler.
11211                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11212                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11213                                              N0->getOperand(1),
11214                                              N0->getOperand(0),
11215                                              N1->getOperand(0));
11216                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11217             }
11218         }
11219     }
11220   }
11221 
11222   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11223   // reasonable.
11224   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11225     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11226       return Res;
11227   }
11228 
11229   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11230     return Result;
11231 
11232   return SDValue();
11233 }
11234 
11235 static SDValue PerformXORCombine(SDNode *N,
11236                                  TargetLowering::DAGCombinerInfo &DCI,
11237                                  const ARMSubtarget *Subtarget) {
11238   EVT VT = N->getValueType(0);
11239   SelectionDAG &DAG = DCI.DAG;
11240 
11241   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11242     return SDValue();
11243 
11244   if (!Subtarget->isThumb1Only()) {
11245     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11246     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11247       return Result;
11248 
11249     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11250       return Result;
11251   }
11252 
11253   return SDValue();
11254 }
11255 
11256 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11257 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11258 // their position in "to" (Rd).
11259 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11260   assert(N->getOpcode() == ARMISD::BFI);
11261 
11262   SDValue From = N->getOperand(1);
11263   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11264   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11265 
11266   // If the Base came from a SHR #C, we can deduce that it is really testing bit
11267   // #C in the base of the SHR.
11268   if (From->getOpcode() == ISD::SRL &&
11269       isa<ConstantSDNode>(From->getOperand(1))) {
11270     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11271     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11272     FromMask <<= Shift.getLimitedValue(31);
11273     From = From->getOperand(0);
11274   }
11275 
11276   return From;
11277 }
11278 
11279 // If A and B contain one contiguous set of bits, does A | B == A . B?
11280 //
11281 // Neither A nor B must be zero.
11282 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11283   unsigned LastActiveBitInA =  A.countTrailingZeros();
11284   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11285   return LastActiveBitInA - 1 == FirstActiveBitInB;
11286 }
11287 
11288 static SDValue FindBFIToCombineWith(SDNode *N) {
11289   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11290   // if one exists.
11291   APInt ToMask, FromMask;
11292   SDValue From = ParseBFI(N, ToMask, FromMask);
11293   SDValue To = N->getOperand(0);
11294 
11295   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11296   // aren't compatible, but not if they set the same bit in their destination as
11297   // we do (or that of any BFI we're going to combine with).
11298   SDValue V = To;
11299   APInt CombinedToMask = ToMask;
11300   while (V.getOpcode() == ARMISD::BFI) {
11301     APInt NewToMask, NewFromMask;
11302     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11303     if (NewFrom != From) {
11304       // This BFI has a different base. Keep going.
11305       CombinedToMask |= NewToMask;
11306       V = V.getOperand(0);
11307       continue;
11308     }
11309 
11310     // Do the written bits conflict with any we've seen so far?
11311     if ((NewToMask & CombinedToMask).getBoolValue())
11312       // Conflicting bits - bail out because going further is unsafe.
11313       return SDValue();
11314 
11315     // Are the new bits contiguous when combined with the old bits?
11316     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11317         BitsProperlyConcatenate(FromMask, NewFromMask))
11318       return V;
11319     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11320         BitsProperlyConcatenate(NewFromMask, FromMask))
11321       return V;
11322 
11323     // We've seen a write to some bits, so track it.
11324     CombinedToMask |= NewToMask;
11325     // Keep going...
11326     V = V.getOperand(0);
11327   }
11328 
11329   return SDValue();
11330 }
11331 
11332 static SDValue PerformBFICombine(SDNode *N,
11333                                  TargetLowering::DAGCombinerInfo &DCI) {
11334   SDValue N1 = N->getOperand(1);
11335   if (N1.getOpcode() == ISD::AND) {
11336     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11337     // the bits being cleared by the AND are not demanded by the BFI.
11338     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11339     if (!N11C)
11340       return SDValue();
11341     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11342     unsigned LSB = countTrailingZeros(~InvMask);
11343     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11344     assert(Width <
11345                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11346            "undefined behavior");
11347     unsigned Mask = (1u << Width) - 1;
11348     unsigned Mask2 = N11C->getZExtValue();
11349     if ((Mask & (~Mask2)) == 0)
11350       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11351                              N->getOperand(0), N1.getOperand(0),
11352                              N->getOperand(2));
11353   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11354     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11355     // Keep track of any consecutive bits set that all come from the same base
11356     // value. We can combine these together into a single BFI.
11357     SDValue CombineBFI = FindBFIToCombineWith(N);
11358     if (CombineBFI == SDValue())
11359       return SDValue();
11360 
11361     // We've found a BFI.
11362     APInt ToMask1, FromMask1;
11363     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11364 
11365     APInt ToMask2, FromMask2;
11366     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11367     assert(From1 == From2);
11368     (void)From2;
11369 
11370     // First, unlink CombineBFI.
11371     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11372     // Then create a new BFI, combining the two together.
11373     APInt NewFromMask = FromMask1 | FromMask2;
11374     APInt NewToMask = ToMask1 | ToMask2;
11375 
11376     EVT VT = N->getValueType(0);
11377     SDLoc dl(N);
11378 
11379     if (NewFromMask[0] == 0)
11380       From1 = DCI.DAG.getNode(
11381         ISD::SRL, dl, VT, From1,
11382         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11383     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11384                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11385   }
11386   return SDValue();
11387 }
11388 
11389 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11390 /// ARMISD::VMOVRRD.
11391 static SDValue PerformVMOVRRDCombine(SDNode *N,
11392                                      TargetLowering::DAGCombinerInfo &DCI,
11393                                      const ARMSubtarget *Subtarget) {
11394   // vmovrrd(vmovdrr x, y) -> x,y
11395   SDValue InDouble = N->getOperand(0);
11396   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
11397     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11398 
11399   // vmovrrd(load f64) -> (load i32), (load i32)
11400   SDNode *InNode = InDouble.getNode();
11401   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11402       InNode->getValueType(0) == MVT::f64 &&
11403       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11404       !cast<LoadSDNode>(InNode)->isVolatile()) {
11405     // TODO: Should this be done for non-FrameIndex operands?
11406     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11407 
11408     SelectionDAG &DAG = DCI.DAG;
11409     SDLoc DL(LD);
11410     SDValue BasePtr = LD->getBasePtr();
11411     SDValue NewLD1 =
11412         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11413                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11414 
11415     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11416                                     DAG.getConstant(4, DL, MVT::i32));
11417     SDValue NewLD2 = DAG.getLoad(
11418         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11419         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11420 
11421     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11422     if (DCI.DAG.getDataLayout().isBigEndian())
11423       std::swap (NewLD1, NewLD2);
11424     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11425     return Result;
11426   }
11427 
11428   return SDValue();
11429 }
11430 
11431 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11432 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11433 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11434   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11435   SDValue Op0 = N->getOperand(0);
11436   SDValue Op1 = N->getOperand(1);
11437   if (Op0.getOpcode() == ISD::BITCAST)
11438     Op0 = Op0.getOperand(0);
11439   if (Op1.getOpcode() == ISD::BITCAST)
11440     Op1 = Op1.getOperand(0);
11441   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11442       Op0.getNode() == Op1.getNode() &&
11443       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11444     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11445                        N->getValueType(0), Op0.getOperand(0));
11446   return SDValue();
11447 }
11448 
11449 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11450 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11451 /// i64 vector to have f64 elements, since the value can then be loaded
11452 /// directly into a VFP register.
11453 static bool hasNormalLoadOperand(SDNode *N) {
11454   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11455   for (unsigned i = 0; i < NumElts; ++i) {
11456     SDNode *Elt = N->getOperand(i).getNode();
11457     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11458       return true;
11459   }
11460   return false;
11461 }
11462 
11463 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11464 /// ISD::BUILD_VECTOR.
11465 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11466                                           TargetLowering::DAGCombinerInfo &DCI,
11467                                           const ARMSubtarget *Subtarget) {
11468   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11469   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11470   // into a pair of GPRs, which is fine when the value is used as a scalar,
11471   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11472   SelectionDAG &DAG = DCI.DAG;
11473   if (N->getNumOperands() == 2)
11474     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11475       return RV;
11476 
11477   // Load i64 elements as f64 values so that type legalization does not split
11478   // them up into i32 values.
11479   EVT VT = N->getValueType(0);
11480   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11481     return SDValue();
11482   SDLoc dl(N);
11483   SmallVector<SDValue, 8> Ops;
11484   unsigned NumElts = VT.getVectorNumElements();
11485   for (unsigned i = 0; i < NumElts; ++i) {
11486     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11487     Ops.push_back(V);
11488     // Make the DAGCombiner fold the bitcast.
11489     DCI.AddToWorklist(V.getNode());
11490   }
11491   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11492   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11493   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11494 }
11495 
11496 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11497 static SDValue
11498 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11499   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11500   // At that time, we may have inserted bitcasts from integer to float.
11501   // If these bitcasts have survived DAGCombine, change the lowering of this
11502   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11503   // force to use floating point types.
11504 
11505   // Make sure we can change the type of the vector.
11506   // This is possible iff:
11507   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11508   //    1.1. Vector is used only once.
11509   //    1.2. Use is a bit convert to an integer type.
11510   // 2. The size of its operands are 32-bits (64-bits are not legal).
11511   EVT VT = N->getValueType(0);
11512   EVT EltVT = VT.getVectorElementType();
11513 
11514   // Check 1.1. and 2.
11515   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11516     return SDValue();
11517 
11518   // By construction, the input type must be float.
11519   assert(EltVT == MVT::f32 && "Unexpected type!");
11520 
11521   // Check 1.2.
11522   SDNode *Use = *N->use_begin();
11523   if (Use->getOpcode() != ISD::BITCAST ||
11524       Use->getValueType(0).isFloatingPoint())
11525     return SDValue();
11526 
11527   // Check profitability.
11528   // Model is, if more than half of the relevant operands are bitcast from
11529   // i32, turn the build_vector into a sequence of insert_vector_elt.
11530   // Relevant operands are everything that is not statically
11531   // (i.e., at compile time) bitcasted.
11532   unsigned NumOfBitCastedElts = 0;
11533   unsigned NumElts = VT.getVectorNumElements();
11534   unsigned NumOfRelevantElts = NumElts;
11535   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11536     SDValue Elt = N->getOperand(Idx);
11537     if (Elt->getOpcode() == ISD::BITCAST) {
11538       // Assume only bit cast to i32 will go away.
11539       if (Elt->getOperand(0).getValueType() == MVT::i32)
11540         ++NumOfBitCastedElts;
11541     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11542       // Constants are statically casted, thus do not count them as
11543       // relevant operands.
11544       --NumOfRelevantElts;
11545   }
11546 
11547   // Check if more than half of the elements require a non-free bitcast.
11548   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11549     return SDValue();
11550 
11551   SelectionDAG &DAG = DCI.DAG;
11552   // Create the new vector type.
11553   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11554   // Check if the type is legal.
11555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11556   if (!TLI.isTypeLegal(VecVT))
11557     return SDValue();
11558 
11559   // Combine:
11560   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11561   // => BITCAST INSERT_VECTOR_ELT
11562   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11563   //                      (BITCAST EN), N.
11564   SDValue Vec = DAG.getUNDEF(VecVT);
11565   SDLoc dl(N);
11566   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11567     SDValue V = N->getOperand(Idx);
11568     if (V.isUndef())
11569       continue;
11570     if (V.getOpcode() == ISD::BITCAST &&
11571         V->getOperand(0).getValueType() == MVT::i32)
11572       // Fold obvious case.
11573       V = V.getOperand(0);
11574     else {
11575       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11576       // Make the DAGCombiner fold the bitcasts.
11577       DCI.AddToWorklist(V.getNode());
11578     }
11579     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11580     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11581   }
11582   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11583   // Make the DAGCombiner fold the bitcasts.
11584   DCI.AddToWorklist(Vec.getNode());
11585   return Vec;
11586 }
11587 
11588 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11589 /// ISD::INSERT_VECTOR_ELT.
11590 static SDValue PerformInsertEltCombine(SDNode *N,
11591                                        TargetLowering::DAGCombinerInfo &DCI) {
11592   // Bitcast an i64 load inserted into a vector to f64.
11593   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11594   EVT VT = N->getValueType(0);
11595   SDNode *Elt = N->getOperand(1).getNode();
11596   if (VT.getVectorElementType() != MVT::i64 ||
11597       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11598     return SDValue();
11599 
11600   SelectionDAG &DAG = DCI.DAG;
11601   SDLoc dl(N);
11602   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11603                                  VT.getVectorNumElements());
11604   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11605   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11606   // Make the DAGCombiner fold the bitcasts.
11607   DCI.AddToWorklist(Vec.getNode());
11608   DCI.AddToWorklist(V.getNode());
11609   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11610                                Vec, V, N->getOperand(2));
11611   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11612 }
11613 
11614 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11615 /// ISD::VECTOR_SHUFFLE.
11616 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11617   // The LLVM shufflevector instruction does not require the shuffle mask
11618   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11619   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11620   // operands do not match the mask length, they are extended by concatenating
11621   // them with undef vectors.  That is probably the right thing for other
11622   // targets, but for NEON it is better to concatenate two double-register
11623   // size vector operands into a single quad-register size vector.  Do that
11624   // transformation here:
11625   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11626   //   shuffle(concat(v1, v2), undef)
11627   SDValue Op0 = N->getOperand(0);
11628   SDValue Op1 = N->getOperand(1);
11629   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11630       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11631       Op0.getNumOperands() != 2 ||
11632       Op1.getNumOperands() != 2)
11633     return SDValue();
11634   SDValue Concat0Op1 = Op0.getOperand(1);
11635   SDValue Concat1Op1 = Op1.getOperand(1);
11636   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11637     return SDValue();
11638   // Skip the transformation if any of the types are illegal.
11639   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11640   EVT VT = N->getValueType(0);
11641   if (!TLI.isTypeLegal(VT) ||
11642       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11643       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11644     return SDValue();
11645 
11646   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11647                                   Op0.getOperand(0), Op1.getOperand(0));
11648   // Translate the shuffle mask.
11649   SmallVector<int, 16> NewMask;
11650   unsigned NumElts = VT.getVectorNumElements();
11651   unsigned HalfElts = NumElts/2;
11652   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11653   for (unsigned n = 0; n < NumElts; ++n) {
11654     int MaskElt = SVN->getMaskElt(n);
11655     int NewElt = -1;
11656     if (MaskElt < (int)HalfElts)
11657       NewElt = MaskElt;
11658     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11659       NewElt = HalfElts + MaskElt - NumElts;
11660     NewMask.push_back(NewElt);
11661   }
11662   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11663                               DAG.getUNDEF(VT), NewMask);
11664 }
11665 
11666 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11667 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11668 /// base address updates.
11669 /// For generic load/stores, the memory type is assumed to be a vector.
11670 /// The caller is assumed to have checked legality.
11671 static SDValue CombineBaseUpdate(SDNode *N,
11672                                  TargetLowering::DAGCombinerInfo &DCI) {
11673   SelectionDAG &DAG = DCI.DAG;
11674   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11675                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11676   const bool isStore = N->getOpcode() == ISD::STORE;
11677   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11678   SDValue Addr = N->getOperand(AddrOpIdx);
11679   MemSDNode *MemN = cast<MemSDNode>(N);
11680   SDLoc dl(N);
11681 
11682   // Search for a use of the address operand that is an increment.
11683   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11684          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11685     SDNode *User = *UI;
11686     if (User->getOpcode() != ISD::ADD ||
11687         UI.getUse().getResNo() != Addr.getResNo())
11688       continue;
11689 
11690     // Check that the add is independent of the load/store.  Otherwise, folding
11691     // it would create a cycle. We can avoid searching through Addr as it's a
11692     // predecessor to both.
11693     SmallPtrSet<const SDNode *, 32> Visited;
11694     SmallVector<const SDNode *, 16> Worklist;
11695     Visited.insert(Addr.getNode());
11696     Worklist.push_back(N);
11697     Worklist.push_back(User);
11698     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11699         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11700       continue;
11701 
11702     // Find the new opcode for the updating load/store.
11703     bool isLoadOp = true;
11704     bool isLaneOp = false;
11705     unsigned NewOpc = 0;
11706     unsigned NumVecs = 0;
11707     if (isIntrinsic) {
11708       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11709       switch (IntNo) {
11710       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11711       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11712         NumVecs = 1; break;
11713       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11714         NumVecs = 2; break;
11715       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11716         NumVecs = 3; break;
11717       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11718         NumVecs = 4; break;
11719       case Intrinsic::arm_neon_vld2dup:
11720       case Intrinsic::arm_neon_vld3dup:
11721       case Intrinsic::arm_neon_vld4dup:
11722         // TODO: Support updating VLDxDUP nodes. For now, we just skip
11723         // combining base updates for such intrinsics.
11724         continue;
11725       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11726         NumVecs = 2; isLaneOp = true; break;
11727       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11728         NumVecs = 3; isLaneOp = true; break;
11729       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11730         NumVecs = 4; isLaneOp = true; break;
11731       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11732         NumVecs = 1; isLoadOp = false; break;
11733       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11734         NumVecs = 2; isLoadOp = false; break;
11735       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11736         NumVecs = 3; isLoadOp = false; break;
11737       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11738         NumVecs = 4; isLoadOp = false; break;
11739       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11740         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11741       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11742         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11743       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11744         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11745       }
11746     } else {
11747       isLaneOp = true;
11748       switch (N->getOpcode()) {
11749       default: llvm_unreachable("unexpected opcode for Neon base update");
11750       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11751       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11752       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11753       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11754       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11755         NumVecs = 1; isLaneOp = false; break;
11756       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11757         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11758       }
11759     }
11760 
11761     // Find the size of memory referenced by the load/store.
11762     EVT VecTy;
11763     if (isLoadOp) {
11764       VecTy = N->getValueType(0);
11765     } else if (isIntrinsic) {
11766       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11767     } else {
11768       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11769       VecTy = N->getOperand(1).getValueType();
11770     }
11771 
11772     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11773     if (isLaneOp)
11774       NumBytes /= VecTy.getVectorNumElements();
11775 
11776     // If the increment is a constant, it must match the memory ref size.
11777     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11778     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11779     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11780       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11781       // separate instructions that make it harder to use a non-constant update.
11782       continue;
11783     }
11784 
11785     // OK, we found an ADD we can fold into the base update.
11786     // Now, create a _UPD node, taking care of not breaking alignment.
11787 
11788     EVT AlignedVecTy = VecTy;
11789     unsigned Alignment = MemN->getAlignment();
11790 
11791     // If this is a less-than-standard-aligned load/store, change the type to
11792     // match the standard alignment.
11793     // The alignment is overlooked when selecting _UPD variants; and it's
11794     // easier to introduce bitcasts here than fix that.
11795     // There are 3 ways to get to this base-update combine:
11796     // - intrinsics: they are assumed to be properly aligned (to the standard
11797     //   alignment of the memory type), so we don't need to do anything.
11798     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11799     //   intrinsics, so, likewise, there's nothing to do.
11800     // - generic load/store instructions: the alignment is specified as an
11801     //   explicit operand, rather than implicitly as the standard alignment
11802     //   of the memory type (like the intrisics).  We need to change the
11803     //   memory type to match the explicit alignment.  That way, we don't
11804     //   generate non-standard-aligned ARMISD::VLDx nodes.
11805     if (isa<LSBaseSDNode>(N)) {
11806       if (Alignment == 0)
11807         Alignment = 1;
11808       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11809         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11810         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11811         assert(!isLaneOp && "Unexpected generic load/store lane.");
11812         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11813         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11814       }
11815       // Don't set an explicit alignment on regular load/stores that we want
11816       // to transform to VLD/VST 1_UPD nodes.
11817       // This matches the behavior of regular load/stores, which only get an
11818       // explicit alignment if the MMO alignment is larger than the standard
11819       // alignment of the memory type.
11820       // Intrinsics, however, always get an explicit alignment, set to the
11821       // alignment of the MMO.
11822       Alignment = 1;
11823     }
11824 
11825     // Create the new updating load/store node.
11826     // First, create an SDVTList for the new updating node's results.
11827     EVT Tys[6];
11828     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11829     unsigned n;
11830     for (n = 0; n < NumResultVecs; ++n)
11831       Tys[n] = AlignedVecTy;
11832     Tys[n++] = MVT::i32;
11833     Tys[n] = MVT::Other;
11834     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11835 
11836     // Then, gather the new node's operands.
11837     SmallVector<SDValue, 8> Ops;
11838     Ops.push_back(N->getOperand(0)); // incoming chain
11839     Ops.push_back(N->getOperand(AddrOpIdx));
11840     Ops.push_back(Inc);
11841 
11842     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11843       // Try to match the intrinsic's signature
11844       Ops.push_back(StN->getValue());
11845     } else {
11846       // Loads (and of course intrinsics) match the intrinsics' signature,
11847       // so just add all but the alignment operand.
11848       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11849         Ops.push_back(N->getOperand(i));
11850     }
11851 
11852     // For all node types, the alignment operand is always the last one.
11853     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11854 
11855     // If this is a non-standard-aligned STORE, the penultimate operand is the
11856     // stored value.  Bitcast it to the aligned type.
11857     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11858       SDValue &StVal = Ops[Ops.size()-2];
11859       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11860     }
11861 
11862     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11863     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11864                                            MemN->getMemOperand());
11865 
11866     // Update the uses.
11867     SmallVector<SDValue, 5> NewResults;
11868     for (unsigned i = 0; i < NumResultVecs; ++i)
11869       NewResults.push_back(SDValue(UpdN.getNode(), i));
11870 
11871     // If this is an non-standard-aligned LOAD, the first result is the loaded
11872     // value.  Bitcast it to the expected result type.
11873     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11874       SDValue &LdVal = NewResults[0];
11875       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11876     }
11877 
11878     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11879     DCI.CombineTo(N, NewResults);
11880     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11881 
11882     break;
11883   }
11884   return SDValue();
11885 }
11886 
11887 static SDValue PerformVLDCombine(SDNode *N,
11888                                  TargetLowering::DAGCombinerInfo &DCI) {
11889   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11890     return SDValue();
11891 
11892   return CombineBaseUpdate(N, DCI);
11893 }
11894 
11895 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11896 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11897 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11898 /// return true.
11899 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11900   SelectionDAG &DAG = DCI.DAG;
11901   EVT VT = N->getValueType(0);
11902   // vldN-dup instructions only support 64-bit vectors for N > 1.
11903   if (!VT.is64BitVector())
11904     return false;
11905 
11906   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11907   SDNode *VLD = N->getOperand(0).getNode();
11908   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11909     return false;
11910   unsigned NumVecs = 0;
11911   unsigned NewOpc = 0;
11912   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11913   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11914     NumVecs = 2;
11915     NewOpc = ARMISD::VLD2DUP;
11916   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11917     NumVecs = 3;
11918     NewOpc = ARMISD::VLD3DUP;
11919   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11920     NumVecs = 4;
11921     NewOpc = ARMISD::VLD4DUP;
11922   } else {
11923     return false;
11924   }
11925 
11926   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11927   // numbers match the load.
11928   unsigned VLDLaneNo =
11929     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11930   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11931        UI != UE; ++UI) {
11932     // Ignore uses of the chain result.
11933     if (UI.getUse().getResNo() == NumVecs)
11934       continue;
11935     SDNode *User = *UI;
11936     if (User->getOpcode() != ARMISD::VDUPLANE ||
11937         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11938       return false;
11939   }
11940 
11941   // Create the vldN-dup node.
11942   EVT Tys[5];
11943   unsigned n;
11944   for (n = 0; n < NumVecs; ++n)
11945     Tys[n] = VT;
11946   Tys[n] = MVT::Other;
11947   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11948   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11949   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11950   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11951                                            Ops, VLDMemInt->getMemoryVT(),
11952                                            VLDMemInt->getMemOperand());
11953 
11954   // Update the uses.
11955   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11956        UI != UE; ++UI) {
11957     unsigned ResNo = UI.getUse().getResNo();
11958     // Ignore uses of the chain result.
11959     if (ResNo == NumVecs)
11960       continue;
11961     SDNode *User = *UI;
11962     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11963   }
11964 
11965   // Now the vldN-lane intrinsic is dead except for its chain result.
11966   // Update uses of the chain.
11967   std::vector<SDValue> VLDDupResults;
11968   for (unsigned n = 0; n < NumVecs; ++n)
11969     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11970   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11971   DCI.CombineTo(VLD, VLDDupResults);
11972 
11973   return true;
11974 }
11975 
11976 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11977 /// ARMISD::VDUPLANE.
11978 static SDValue PerformVDUPLANECombine(SDNode *N,
11979                                       TargetLowering::DAGCombinerInfo &DCI) {
11980   SDValue Op = N->getOperand(0);
11981 
11982   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11983   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11984   if (CombineVLDDUP(N, DCI))
11985     return SDValue(N, 0);
11986 
11987   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11988   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11989   while (Op.getOpcode() == ISD::BITCAST)
11990     Op = Op.getOperand(0);
11991   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11992     return SDValue();
11993 
11994   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11995   unsigned EltSize = Op.getScalarValueSizeInBits();
11996   // The canonical VMOV for a zero vector uses a 32-bit element size.
11997   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11998   unsigned EltBits;
11999   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
12000     EltSize = 8;
12001   EVT VT = N->getValueType(0);
12002   if (EltSize > VT.getScalarSizeInBits())
12003     return SDValue();
12004 
12005   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12006 }
12007 
12008 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12009 static SDValue PerformVDUPCombine(SDNode *N,
12010                                   TargetLowering::DAGCombinerInfo &DCI) {
12011   SelectionDAG &DAG = DCI.DAG;
12012   SDValue Op = N->getOperand(0);
12013 
12014   // Match VDUP(LOAD) -> VLD1DUP.
12015   // We match this pattern here rather than waiting for isel because the
12016   // transform is only legal for unindexed loads.
12017   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12018   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12019       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12020     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12021                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12022     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12023     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12024                                              Ops, LD->getMemoryVT(),
12025                                              LD->getMemOperand());
12026     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12027     return VLDDup;
12028   }
12029 
12030   return SDValue();
12031 }
12032 
12033 static SDValue PerformLOADCombine(SDNode *N,
12034                                   TargetLowering::DAGCombinerInfo &DCI) {
12035   EVT VT = N->getValueType(0);
12036 
12037   // If this is a legal vector load, try to combine it into a VLD1_UPD.
12038   if (ISD::isNormalLoad(N) && VT.isVector() &&
12039       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12040     return CombineBaseUpdate(N, DCI);
12041 
12042   return SDValue();
12043 }
12044 
12045 /// PerformSTORECombine - Target-specific dag combine xforms for
12046 /// ISD::STORE.
12047 static SDValue PerformSTORECombine(SDNode *N,
12048                                    TargetLowering::DAGCombinerInfo &DCI) {
12049   StoreSDNode *St = cast<StoreSDNode>(N);
12050   if (St->isVolatile())
12051     return SDValue();
12052 
12053   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
12054   // pack all of the elements in one place.  Next, store to memory in fewer
12055   // chunks.
12056   SDValue StVal = St->getValue();
12057   EVT VT = StVal.getValueType();
12058   if (St->isTruncatingStore() && VT.isVector()) {
12059     SelectionDAG &DAG = DCI.DAG;
12060     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12061     EVT StVT = St->getMemoryVT();
12062     unsigned NumElems = VT.getVectorNumElements();
12063     assert(StVT != VT && "Cannot truncate to the same type");
12064     unsigned FromEltSz = VT.getScalarSizeInBits();
12065     unsigned ToEltSz = StVT.getScalarSizeInBits();
12066 
12067     // From, To sizes and ElemCount must be pow of two
12068     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
12069 
12070     // We are going to use the original vector elt for storing.
12071     // Accumulated smaller vector elements must be a multiple of the store size.
12072     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
12073 
12074     unsigned SizeRatio  = FromEltSz / ToEltSz;
12075     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
12076 
12077     // Create a type on which we perform the shuffle.
12078     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
12079                                      NumElems*SizeRatio);
12080     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
12081 
12082     SDLoc DL(St);
12083     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
12084     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
12085     for (unsigned i = 0; i < NumElems; ++i)
12086       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
12087                           ? (i + 1) * SizeRatio - 1
12088                           : i * SizeRatio;
12089 
12090     // Can't shuffle using an illegal type.
12091     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
12092 
12093     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
12094                                 DAG.getUNDEF(WideVec.getValueType()),
12095                                 ShuffleVec);
12096     // At this point all of the data is stored at the bottom of the
12097     // register. We now need to save it to mem.
12098 
12099     // Find the largest store unit
12100     MVT StoreType = MVT::i8;
12101     for (MVT Tp : MVT::integer_valuetypes()) {
12102       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
12103         StoreType = Tp;
12104     }
12105     // Didn't find a legal store type.
12106     if (!TLI.isTypeLegal(StoreType))
12107       return SDValue();
12108 
12109     // Bitcast the original vector into a vector of store-size units
12110     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
12111             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
12112     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
12113     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
12114     SmallVector<SDValue, 8> Chains;
12115     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
12116                                         TLI.getPointerTy(DAG.getDataLayout()));
12117     SDValue BasePtr = St->getBasePtr();
12118 
12119     // Perform one or more big stores into memory.
12120     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
12121     for (unsigned I = 0; I < E; I++) {
12122       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
12123                                    StoreType, ShuffWide,
12124                                    DAG.getIntPtrConstant(I, DL));
12125       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12126                                 St->getPointerInfo(), St->getAlignment(),
12127                                 St->getMemOperand()->getFlags());
12128       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12129                             Increment);
12130       Chains.push_back(Ch);
12131     }
12132     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12133   }
12134 
12135   if (!ISD::isNormalStore(St))
12136     return SDValue();
12137 
12138   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12139   // ARM stores of arguments in the same cache line.
12140   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12141       StVal.getNode()->hasOneUse()) {
12142     SelectionDAG  &DAG = DCI.DAG;
12143     bool isBigEndian = DAG.getDataLayout().isBigEndian();
12144     SDLoc DL(St);
12145     SDValue BasePtr = St->getBasePtr();
12146     SDValue NewST1 = DAG.getStore(
12147         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12148         BasePtr, St->getPointerInfo(), St->getAlignment(),
12149         St->getMemOperand()->getFlags());
12150 
12151     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12152                                     DAG.getConstant(4, DL, MVT::i32));
12153     return DAG.getStore(NewST1.getValue(0), DL,
12154                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12155                         OffsetPtr, St->getPointerInfo(),
12156                         std::min(4U, St->getAlignment() / 2),
12157                         St->getMemOperand()->getFlags());
12158   }
12159 
12160   if (StVal.getValueType() == MVT::i64 &&
12161       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12162 
12163     // Bitcast an i64 store extracted from a vector to f64.
12164     // Otherwise, the i64 value will be legalized to a pair of i32 values.
12165     SelectionDAG &DAG = DCI.DAG;
12166     SDLoc dl(StVal);
12167     SDValue IntVec = StVal.getOperand(0);
12168     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12169                                    IntVec.getValueType().getVectorNumElements());
12170     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12171     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12172                                  Vec, StVal.getOperand(1));
12173     dl = SDLoc(N);
12174     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12175     // Make the DAGCombiner fold the bitcasts.
12176     DCI.AddToWorklist(Vec.getNode());
12177     DCI.AddToWorklist(ExtElt.getNode());
12178     DCI.AddToWorklist(V.getNode());
12179     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12180                         St->getPointerInfo(), St->getAlignment(),
12181                         St->getMemOperand()->getFlags(), St->getAAInfo());
12182   }
12183 
12184   // If this is a legal vector store, try to combine it into a VST1_UPD.
12185   if (ISD::isNormalStore(N) && VT.isVector() &&
12186       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12187     return CombineBaseUpdate(N, DCI);
12188 
12189   return SDValue();
12190 }
12191 
12192 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12193 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12194 /// when the VMUL has a constant operand that is a power of 2.
12195 ///
12196 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12197 ///  vmul.f32        d16, d17, d16
12198 ///  vcvt.s32.f32    d16, d16
12199 /// becomes:
12200 ///  vcvt.s32.f32    d16, d16, #3
12201 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12202                                   const ARMSubtarget *Subtarget) {
12203   if (!Subtarget->hasNEON())
12204     return SDValue();
12205 
12206   SDValue Op = N->getOperand(0);
12207   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12208       Op.getOpcode() != ISD::FMUL)
12209     return SDValue();
12210 
12211   SDValue ConstVec = Op->getOperand(1);
12212   if (!isa<BuildVectorSDNode>(ConstVec))
12213     return SDValue();
12214 
12215   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12216   uint32_t FloatBits = FloatTy.getSizeInBits();
12217   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12218   uint32_t IntBits = IntTy.getSizeInBits();
12219   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12220   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
12221     // These instructions only exist converting from f32 to i32. We can handle
12222     // smaller integers by generating an extra truncate, but larger ones would
12223     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
12224     // these intructions only support v2i32/v4i32 types.
12225     return SDValue();
12226   }
12227 
12228   BitVector UndefElements;
12229   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12230   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12231   if (C == -1 || C == 0 || C > 32)
12232     return SDValue();
12233 
12234   SDLoc dl(N);
12235   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12236   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12237     Intrinsic::arm_neon_vcvtfp2fxu;
12238   SDValue FixConv = DAG.getNode(
12239       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12240       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12241       DAG.getConstant(C, dl, MVT::i32));
12242 
12243   if (IntBits < FloatBits)
12244     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12245 
12246   return FixConv;
12247 }
12248 
12249 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12250 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12251 /// when the VDIV has a constant operand that is a power of 2.
12252 ///
12253 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12254 ///  vcvt.f32.s32    d16, d16
12255 ///  vdiv.f32        d16, d17, d16
12256 /// becomes:
12257 ///  vcvt.f32.s32    d16, d16, #3
12258 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12259                                   const ARMSubtarget *Subtarget) {
12260   if (!Subtarget->hasNEON())
12261     return SDValue();
12262 
12263   SDValue Op = N->getOperand(0);
12264   unsigned OpOpcode = Op.getNode()->getOpcode();
12265   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12266       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12267     return SDValue();
12268 
12269   SDValue ConstVec = N->getOperand(1);
12270   if (!isa<BuildVectorSDNode>(ConstVec))
12271     return SDValue();
12272 
12273   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12274   uint32_t FloatBits = FloatTy.getSizeInBits();
12275   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12276   uint32_t IntBits = IntTy.getSizeInBits();
12277   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12278   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
12279     // These instructions only exist converting from i32 to f32. We can handle
12280     // smaller integers by generating an extra extend, but larger ones would
12281     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
12282     // these intructions only support v2i32/v4i32 types.
12283     return SDValue();
12284   }
12285 
12286   BitVector UndefElements;
12287   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12288   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12289   if (C == -1 || C == 0 || C > 32)
12290     return SDValue();
12291 
12292   SDLoc dl(N);
12293   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12294   SDValue ConvInput = Op.getOperand(0);
12295   if (IntBits < FloatBits)
12296     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12297                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12298                             ConvInput);
12299 
12300   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12301     Intrinsic::arm_neon_vcvtfxu2fp;
12302   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12303                      Op.getValueType(),
12304                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12305                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
12306 }
12307 
12308 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12309 /// operand of a vector shift operation, where all the elements of the
12310 /// build_vector must have the same constant integer value.
12311 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12312   // Ignore bit_converts.
12313   while (Op.getOpcode() == ISD::BITCAST)
12314     Op = Op.getOperand(0);
12315   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12316   APInt SplatBits, SplatUndef;
12317   unsigned SplatBitSize;
12318   bool HasAnyUndefs;
12319   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12320                                       HasAnyUndefs, ElementBits) ||
12321       SplatBitSize > ElementBits)
12322     return false;
12323   Cnt = SplatBits.getSExtValue();
12324   return true;
12325 }
12326 
12327 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12328 /// operand of a vector shift left operation.  That value must be in the range:
12329 ///   0 <= Value < ElementBits for a left shift; or
12330 ///   0 <= Value <= ElementBits for a long left shift.
12331 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12332   assert(VT.isVector() && "vector shift count is not a vector type");
12333   int64_t ElementBits = VT.getScalarSizeInBits();
12334   if (! getVShiftImm(Op, ElementBits, Cnt))
12335     return false;
12336   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12337 }
12338 
12339 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12340 /// operand of a vector shift right operation.  For a shift opcode, the value
12341 /// is positive, but for an intrinsic the value count must be negative. The
12342 /// absolute value must be in the range:
12343 ///   1 <= |Value| <= ElementBits for a right shift; or
12344 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12345 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12346                          int64_t &Cnt) {
12347   assert(VT.isVector() && "vector shift count is not a vector type");
12348   int64_t ElementBits = VT.getScalarSizeInBits();
12349   if (! getVShiftImm(Op, ElementBits, Cnt))
12350     return false;
12351   if (!isIntrinsic)
12352     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12353   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12354     Cnt = -Cnt;
12355     return true;
12356   }
12357   return false;
12358 }
12359 
12360 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12361 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12362   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12363   switch (IntNo) {
12364   default:
12365     // Don't do anything for most intrinsics.
12366     break;
12367 
12368   // Vector shifts: check for immediate versions and lower them.
12369   // Note: This is done during DAG combining instead of DAG legalizing because
12370   // the build_vectors for 64-bit vector element shift counts are generally
12371   // not legal, and it is hard to see their values after they get legalized to
12372   // loads from a constant pool.
12373   case Intrinsic::arm_neon_vshifts:
12374   case Intrinsic::arm_neon_vshiftu:
12375   case Intrinsic::arm_neon_vrshifts:
12376   case Intrinsic::arm_neon_vrshiftu:
12377   case Intrinsic::arm_neon_vrshiftn:
12378   case Intrinsic::arm_neon_vqshifts:
12379   case Intrinsic::arm_neon_vqshiftu:
12380   case Intrinsic::arm_neon_vqshiftsu:
12381   case Intrinsic::arm_neon_vqshiftns:
12382   case Intrinsic::arm_neon_vqshiftnu:
12383   case Intrinsic::arm_neon_vqshiftnsu:
12384   case Intrinsic::arm_neon_vqrshiftns:
12385   case Intrinsic::arm_neon_vqrshiftnu:
12386   case Intrinsic::arm_neon_vqrshiftnsu: {
12387     EVT VT = N->getOperand(1).getValueType();
12388     int64_t Cnt;
12389     unsigned VShiftOpc = 0;
12390 
12391     switch (IntNo) {
12392     case Intrinsic::arm_neon_vshifts:
12393     case Intrinsic::arm_neon_vshiftu:
12394       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12395         VShiftOpc = ARMISD::VSHL;
12396         break;
12397       }
12398       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12399         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12400                      ARMISD::VSHRs : ARMISD::VSHRu);
12401         break;
12402       }
12403       return SDValue();
12404 
12405     case Intrinsic::arm_neon_vrshifts:
12406     case Intrinsic::arm_neon_vrshiftu:
12407       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12408         break;
12409       return SDValue();
12410 
12411     case Intrinsic::arm_neon_vqshifts:
12412     case Intrinsic::arm_neon_vqshiftu:
12413       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12414         break;
12415       return SDValue();
12416 
12417     case Intrinsic::arm_neon_vqshiftsu:
12418       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12419         break;
12420       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12421 
12422     case Intrinsic::arm_neon_vrshiftn:
12423     case Intrinsic::arm_neon_vqshiftns:
12424     case Intrinsic::arm_neon_vqshiftnu:
12425     case Intrinsic::arm_neon_vqshiftnsu:
12426     case Intrinsic::arm_neon_vqrshiftns:
12427     case Intrinsic::arm_neon_vqrshiftnu:
12428     case Intrinsic::arm_neon_vqrshiftnsu:
12429       // Narrowing shifts require an immediate right shift.
12430       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12431         break;
12432       llvm_unreachable("invalid shift count for narrowing vector shift "
12433                        "intrinsic");
12434 
12435     default:
12436       llvm_unreachable("unhandled vector shift");
12437     }
12438 
12439     switch (IntNo) {
12440     case Intrinsic::arm_neon_vshifts:
12441     case Intrinsic::arm_neon_vshiftu:
12442       // Opcode already set above.
12443       break;
12444     case Intrinsic::arm_neon_vrshifts:
12445       VShiftOpc = ARMISD::VRSHRs; break;
12446     case Intrinsic::arm_neon_vrshiftu:
12447       VShiftOpc = ARMISD::VRSHRu; break;
12448     case Intrinsic::arm_neon_vrshiftn:
12449       VShiftOpc = ARMISD::VRSHRN; break;
12450     case Intrinsic::arm_neon_vqshifts:
12451       VShiftOpc = ARMISD::VQSHLs; break;
12452     case Intrinsic::arm_neon_vqshiftu:
12453       VShiftOpc = ARMISD::VQSHLu; break;
12454     case Intrinsic::arm_neon_vqshiftsu:
12455       VShiftOpc = ARMISD::VQSHLsu; break;
12456     case Intrinsic::arm_neon_vqshiftns:
12457       VShiftOpc = ARMISD::VQSHRNs; break;
12458     case Intrinsic::arm_neon_vqshiftnu:
12459       VShiftOpc = ARMISD::VQSHRNu; break;
12460     case Intrinsic::arm_neon_vqshiftnsu:
12461       VShiftOpc = ARMISD::VQSHRNsu; break;
12462     case Intrinsic::arm_neon_vqrshiftns:
12463       VShiftOpc = ARMISD::VQRSHRNs; break;
12464     case Intrinsic::arm_neon_vqrshiftnu:
12465       VShiftOpc = ARMISD::VQRSHRNu; break;
12466     case Intrinsic::arm_neon_vqrshiftnsu:
12467       VShiftOpc = ARMISD::VQRSHRNsu; break;
12468     }
12469 
12470     SDLoc dl(N);
12471     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12472                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12473   }
12474 
12475   case Intrinsic::arm_neon_vshiftins: {
12476     EVT VT = N->getOperand(1).getValueType();
12477     int64_t Cnt;
12478     unsigned VShiftOpc = 0;
12479 
12480     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12481       VShiftOpc = ARMISD::VSLI;
12482     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12483       VShiftOpc = ARMISD::VSRI;
12484     else {
12485       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12486     }
12487 
12488     SDLoc dl(N);
12489     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12490                        N->getOperand(1), N->getOperand(2),
12491                        DAG.getConstant(Cnt, dl, MVT::i32));
12492   }
12493 
12494   case Intrinsic::arm_neon_vqrshifts:
12495   case Intrinsic::arm_neon_vqrshiftu:
12496     // No immediate versions of these to check for.
12497     break;
12498   }
12499 
12500   return SDValue();
12501 }
12502 
12503 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12504 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12505 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12506 /// vector element shift counts are generally not legal, and it is hard to see
12507 /// their values after they get legalized to loads from a constant pool.
12508 static SDValue PerformShiftCombine(SDNode *N,
12509                                    TargetLowering::DAGCombinerInfo &DCI,
12510                                    const ARMSubtarget *ST) {
12511   SelectionDAG &DAG = DCI.DAG;
12512   EVT VT = N->getValueType(0);
12513   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12514     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12515     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12516     SDValue N1 = N->getOperand(1);
12517     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12518       SDValue N0 = N->getOperand(0);
12519       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12520           DAG.MaskedValueIsZero(N0.getOperand(0),
12521                                 APInt::getHighBitsSet(32, 16)))
12522         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12523     }
12524   }
12525 
12526   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
12527       N->getOperand(0)->getOpcode() == ISD::AND &&
12528       N->getOperand(0)->hasOneUse()) {
12529     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12530       return SDValue();
12531     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
12532     // usually show up because instcombine prefers to canonicalize it to
12533     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
12534     // out of GEP lowering in some cases.
12535     SDValue N0 = N->getOperand(0);
12536     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
12537     if (!ShiftAmtNode)
12538       return SDValue();
12539     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
12540     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12541     if (!AndMaskNode)
12542       return SDValue();
12543     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
12544     // Don't transform uxtb/uxth.
12545     if (AndMask == 255 || AndMask == 65535)
12546       return SDValue();
12547     if (isMask_32(AndMask)) {
12548       uint32_t MaskedBits = countLeadingZeros(AndMask);
12549       if (MaskedBits > ShiftAmt) {
12550         SDLoc DL(N);
12551         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12552                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
12553         return DAG.getNode(
12554             ISD::SRL, DL, MVT::i32, SHL,
12555             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
12556       }
12557     }
12558   }
12559 
12560   // Nothing to be done for scalar shifts.
12561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12562   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12563     return SDValue();
12564 
12565   assert(ST->hasNEON() && "unexpected vector shift");
12566   int64_t Cnt;
12567 
12568   switch (N->getOpcode()) {
12569   default: llvm_unreachable("unexpected shift opcode");
12570 
12571   case ISD::SHL:
12572     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12573       SDLoc dl(N);
12574       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12575                          DAG.getConstant(Cnt, dl, MVT::i32));
12576     }
12577     break;
12578 
12579   case ISD::SRA:
12580   case ISD::SRL:
12581     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12582       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12583                             ARMISD::VSHRs : ARMISD::VSHRu);
12584       SDLoc dl(N);
12585       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12586                          DAG.getConstant(Cnt, dl, MVT::i32));
12587     }
12588   }
12589   return SDValue();
12590 }
12591 
12592 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12593 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12594 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12595                                     const ARMSubtarget *ST) {
12596   SDValue N0 = N->getOperand(0);
12597 
12598   // Check for sign- and zero-extensions of vector extract operations of 8-
12599   // and 16-bit vector elements.  NEON supports these directly.  They are
12600   // handled during DAG combining because type legalization will promote them
12601   // to 32-bit types and it is messy to recognize the operations after that.
12602   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12603     SDValue Vec = N0.getOperand(0);
12604     SDValue Lane = N0.getOperand(1);
12605     EVT VT = N->getValueType(0);
12606     EVT EltVT = N0.getValueType();
12607     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12608 
12609     if (VT == MVT::i32 &&
12610         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12611         TLI.isTypeLegal(Vec.getValueType()) &&
12612         isa<ConstantSDNode>(Lane)) {
12613 
12614       unsigned Opc = 0;
12615       switch (N->getOpcode()) {
12616       default: llvm_unreachable("unexpected opcode");
12617       case ISD::SIGN_EXTEND:
12618         Opc = ARMISD::VGETLANEs;
12619         break;
12620       case ISD::ZERO_EXTEND:
12621       case ISD::ANY_EXTEND:
12622         Opc = ARMISD::VGETLANEu;
12623         break;
12624       }
12625       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12626     }
12627   }
12628 
12629   return SDValue();
12630 }
12631 
12632 static const APInt *isPowerOf2Constant(SDValue V) {
12633   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12634   if (!C)
12635     return nullptr;
12636   const APInt *CV = &C->getAPIntValue();
12637   return CV->isPowerOf2() ? CV : nullptr;
12638 }
12639 
12640 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12641   // If we have a CMOV, OR and AND combination such as:
12642   //   if (x & CN)
12643   //     y |= CM;
12644   //
12645   // And:
12646   //   * CN is a single bit;
12647   //   * All bits covered by CM are known zero in y
12648   //
12649   // Then we can convert this into a sequence of BFI instructions. This will
12650   // always be a win if CM is a single bit, will always be no worse than the
12651   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12652   // three bits (due to the extra IT instruction).
12653 
12654   SDValue Op0 = CMOV->getOperand(0);
12655   SDValue Op1 = CMOV->getOperand(1);
12656   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12657   auto CC = CCNode->getAPIntValue().getLimitedValue();
12658   SDValue CmpZ = CMOV->getOperand(4);
12659 
12660   // The compare must be against zero.
12661   if (!isNullConstant(CmpZ->getOperand(1)))
12662     return SDValue();
12663 
12664   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12665   SDValue And = CmpZ->getOperand(0);
12666   if (And->getOpcode() != ISD::AND)
12667     return SDValue();
12668   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12669   if (!AndC)
12670     return SDValue();
12671   SDValue X = And->getOperand(0);
12672 
12673   if (CC == ARMCC::EQ) {
12674     // We're performing an "equal to zero" compare. Swap the operands so we
12675     // canonicalize on a "not equal to zero" compare.
12676     std::swap(Op0, Op1);
12677   } else {
12678     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12679   }
12680 
12681   if (Op1->getOpcode() != ISD::OR)
12682     return SDValue();
12683 
12684   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12685   if (!OrC)
12686     return SDValue();
12687   SDValue Y = Op1->getOperand(0);
12688 
12689   if (Op0 != Y)
12690     return SDValue();
12691 
12692   // Now, is it profitable to continue?
12693   APInt OrCI = OrC->getAPIntValue();
12694   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12695   if (OrCI.countPopulation() > Heuristic)
12696     return SDValue();
12697 
12698   // Lastly, can we determine that the bits defined by OrCI
12699   // are zero in Y?
12700   KnownBits Known = DAG.computeKnownBits(Y);
12701   if ((OrCI & Known.Zero) != OrCI)
12702     return SDValue();
12703 
12704   // OK, we can do the combine.
12705   SDValue V = Y;
12706   SDLoc dl(X);
12707   EVT VT = X.getValueType();
12708   unsigned BitInX = AndC->logBase2();
12709 
12710   if (BitInX != 0) {
12711     // We must shift X first.
12712     X = DAG.getNode(ISD::SRL, dl, VT, X,
12713                     DAG.getConstant(BitInX, dl, VT));
12714   }
12715 
12716   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12717        BitInY < NumActiveBits; ++BitInY) {
12718     if (OrCI[BitInY] == 0)
12719       continue;
12720     APInt Mask(VT.getSizeInBits(), 0);
12721     Mask.setBit(BitInY);
12722     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12723                     // Confusingly, the operand is an *inverted* mask.
12724                     DAG.getConstant(~Mask, dl, VT));
12725   }
12726 
12727   return V;
12728 }
12729 
12730 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12731 SDValue
12732 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12733   SDValue Cmp = N->getOperand(4);
12734   if (Cmp.getOpcode() != ARMISD::CMPZ)
12735     // Only looking at NE cases.
12736     return SDValue();
12737 
12738   EVT VT = N->getValueType(0);
12739   SDLoc dl(N);
12740   SDValue LHS = Cmp.getOperand(0);
12741   SDValue RHS = Cmp.getOperand(1);
12742   SDValue Chain = N->getOperand(0);
12743   SDValue BB = N->getOperand(1);
12744   SDValue ARMcc = N->getOperand(2);
12745   ARMCC::CondCodes CC =
12746     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12747 
12748   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12749   // -> (brcond Chain BB CC CPSR Cmp)
12750   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12751       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12752       LHS->getOperand(0)->hasOneUse()) {
12753     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12754     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12755     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12756     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12757     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12758         (LHS01C && LHS01C->getZExtValue() == 1) &&
12759         (LHS1C && LHS1C->getZExtValue() == 1) &&
12760         (RHSC && RHSC->getZExtValue() == 0)) {
12761       return DAG.getNode(
12762           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12763           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12764     }
12765   }
12766 
12767   return SDValue();
12768 }
12769 
12770 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12771 SDValue
12772 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12773   SDValue Cmp = N->getOperand(4);
12774   if (Cmp.getOpcode() != ARMISD::CMPZ)
12775     // Only looking at EQ and NE cases.
12776     return SDValue();
12777 
12778   EVT VT = N->getValueType(0);
12779   SDLoc dl(N);
12780   SDValue LHS = Cmp.getOperand(0);
12781   SDValue RHS = Cmp.getOperand(1);
12782   SDValue FalseVal = N->getOperand(0);
12783   SDValue TrueVal = N->getOperand(1);
12784   SDValue ARMcc = N->getOperand(2);
12785   ARMCC::CondCodes CC =
12786     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12787 
12788   // BFI is only available on V6T2+.
12789   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12790     SDValue R = PerformCMOVToBFICombine(N, DAG);
12791     if (R)
12792       return R;
12793   }
12794 
12795   // Simplify
12796   //   mov     r1, r0
12797   //   cmp     r1, x
12798   //   mov     r0, y
12799   //   moveq   r0, x
12800   // to
12801   //   cmp     r0, x
12802   //   movne   r0, y
12803   //
12804   //   mov     r1, r0
12805   //   cmp     r1, x
12806   //   mov     r0, x
12807   //   movne   r0, y
12808   // to
12809   //   cmp     r0, x
12810   //   movne   r0, y
12811   /// FIXME: Turn this into a target neutral optimization?
12812   SDValue Res;
12813   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12814     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12815                       N->getOperand(3), Cmp);
12816   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12817     SDValue ARMcc;
12818     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12819     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12820                       N->getOperand(3), NewCmp);
12821   }
12822 
12823   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12824   // -> (cmov F T CC CPSR Cmp)
12825   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12826     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12827     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12828     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12829     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12830         (LHS1C && LHS1C->getZExtValue() == 1) &&
12831         (RHSC && RHSC->getZExtValue() == 0)) {
12832       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12833                          LHS->getOperand(2), LHS->getOperand(3),
12834                          LHS->getOperand(4));
12835     }
12836   }
12837 
12838   if (!VT.isInteger())
12839       return SDValue();
12840 
12841   // Materialize a boolean comparison for integers so we can avoid branching.
12842   if (isNullConstant(FalseVal)) {
12843     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
12844       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
12845         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
12846         // right 5 bits will make that 32 be 1, otherwise it will be 0.
12847         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
12848         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12849         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
12850                           DAG.getConstant(5, dl, MVT::i32));
12851       } else {
12852         // CMOV 0, 1, ==, (CMPZ x, y) ->
12853         //     (ADDCARRY (SUB x, y), t:0, t:1)
12854         // where t = (SUBCARRY 0, (SUB x, y), 0)
12855         //
12856         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
12857         // x != y. In other words, a carry C == 1 when x == y, C == 0
12858         // otherwise.
12859         // The final ADDCARRY computes
12860         //     x - y + (0 - (x - y)) + C == C
12861         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12862         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12863         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
12864         // ISD::SUBCARRY returns a borrow but we want the carry here
12865         // actually.
12866         SDValue Carry =
12867             DAG.getNode(ISD::SUB, dl, MVT::i32,
12868                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
12869         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
12870       }
12871     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
12872                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
12873       // This seems pointless but will allow us to combine it further below.
12874       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12875       SDValue Sub =
12876           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12877       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12878                                           Sub.getValue(1), SDValue());
12879       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
12880                         N->getOperand(3), CPSRGlue.getValue(1));
12881       FalseVal = Sub;
12882     }
12883   } else if (isNullConstant(TrueVal)) {
12884     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
12885         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
12886       // This seems pointless but will allow us to combine it further below
12887       // Note that we change == for != as this is the dual for the case above.
12888       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12889       SDValue Sub =
12890           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12891       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12892                                           Sub.getValue(1), SDValue());
12893       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
12894                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
12895                         N->getOperand(3), CPSRGlue.getValue(1));
12896       FalseVal = Sub;
12897     }
12898   }
12899 
12900   // On Thumb1, the DAG above may be further combined if z is a power of 2
12901   // (z == 2 ^ K).
12902   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
12903   // t1 = (USUBO (SUB x, y), 1)
12904   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
12905   // Result = if K != 0 then (SHL t2:0, K) else t2:0
12906   //
12907   // This also handles the special case of comparing against zero; it's
12908   // essentially, the same pattern, except there's no SUBS:
12909   // CMOV x, z, !=, (CMPZ x, 0) ->
12910   // t1 = (USUBO x, 1)
12911   // t2 = (SUBCARRY x, t1:0, t1:1)
12912   // Result = if K != 0 then (SHL t2:0, K) else t2:0
12913   const APInt *TrueConst;
12914   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
12915       ((FalseVal.getOpcode() == ARMISD::SUBS &&
12916         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
12917        (FalseVal == LHS && isNullConstant(RHS))) &&
12918       (TrueConst = isPowerOf2Constant(TrueVal))) {
12919     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12920     unsigned ShiftAmount = TrueConst->logBase2();
12921     if (ShiftAmount)
12922       TrueVal = DAG.getConstant(1, dl, VT);
12923     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
12924     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
12925 
12926     if (ShiftAmount)
12927       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
12928                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
12929   }
12930 
12931   if (Res.getNode()) {
12932     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
12933     // Capture demanded bits information that would be otherwise lost.
12934     if (Known.Zero == 0xfffffffe)
12935       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12936                         DAG.getValueType(MVT::i1));
12937     else if (Known.Zero == 0xffffff00)
12938       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12939                         DAG.getValueType(MVT::i8));
12940     else if (Known.Zero == 0xffff0000)
12941       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12942                         DAG.getValueType(MVT::i16));
12943   }
12944 
12945   return Res;
12946 }
12947 
12948 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12949                                              DAGCombinerInfo &DCI) const {
12950   switch (N->getOpcode()) {
12951   default: break;
12952   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
12953   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12954   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12955   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12956   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12957   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12958   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12959   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12960   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12961   case ARMISD::ADDC:
12962   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12963   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12964   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12965   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12966   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12967   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12968   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12969   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12970   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12971   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12972   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12973   case ISD::FP_TO_SINT:
12974   case ISD::FP_TO_UINT:
12975     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12976   case ISD::FDIV:
12977     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12978   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12979   case ISD::SHL:
12980   case ISD::SRA:
12981   case ISD::SRL:
12982     return PerformShiftCombine(N, DCI, Subtarget);
12983   case ISD::SIGN_EXTEND:
12984   case ISD::ZERO_EXTEND:
12985   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12986   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12987   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12988   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12989   case ARMISD::VLD1DUP:
12990   case ARMISD::VLD2DUP:
12991   case ARMISD::VLD3DUP:
12992   case ARMISD::VLD4DUP:
12993     return PerformVLDCombine(N, DCI);
12994   case ARMISD::BUILD_VECTOR:
12995     return PerformARMBUILD_VECTORCombine(N, DCI);
12996   case ARMISD::SMULWB: {
12997     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12998     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12999     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13000       return SDValue();
13001     break;
13002   }
13003   case ARMISD::SMULWT: {
13004     unsigned BitWidth = N->getValueType(0).getSizeInBits();
13005     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13006     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13007       return SDValue();
13008     break;
13009   }
13010   case ARMISD::SMLALBB: {
13011     unsigned BitWidth = N->getValueType(0).getSizeInBits();
13012     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13013     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13014         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13015       return SDValue();
13016     break;
13017   }
13018   case ARMISD::SMLALBT: {
13019     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
13020     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13021     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
13022     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13023     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
13024         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
13025       return SDValue();
13026     break;
13027   }
13028   case ARMISD::SMLALTB: {
13029     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
13030     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13031     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
13032     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13033     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
13034         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
13035       return SDValue();
13036     break;
13037   }
13038   case ARMISD::SMLALTT: {
13039     unsigned BitWidth = N->getValueType(0).getSizeInBits();
13040     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13041     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13042         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13043       return SDValue();
13044     break;
13045   }
13046   case ISD::INTRINSIC_VOID:
13047   case ISD::INTRINSIC_W_CHAIN:
13048     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13049     case Intrinsic::arm_neon_vld1:
13050     case Intrinsic::arm_neon_vld1x2:
13051     case Intrinsic::arm_neon_vld1x3:
13052     case Intrinsic::arm_neon_vld1x4:
13053     case Intrinsic::arm_neon_vld2:
13054     case Intrinsic::arm_neon_vld3:
13055     case Intrinsic::arm_neon_vld4:
13056     case Intrinsic::arm_neon_vld2lane:
13057     case Intrinsic::arm_neon_vld3lane:
13058     case Intrinsic::arm_neon_vld4lane:
13059     case Intrinsic::arm_neon_vld2dup:
13060     case Intrinsic::arm_neon_vld3dup:
13061     case Intrinsic::arm_neon_vld4dup:
13062     case Intrinsic::arm_neon_vst1:
13063     case Intrinsic::arm_neon_vst1x2:
13064     case Intrinsic::arm_neon_vst1x3:
13065     case Intrinsic::arm_neon_vst1x4:
13066     case Intrinsic::arm_neon_vst2:
13067     case Intrinsic::arm_neon_vst3:
13068     case Intrinsic::arm_neon_vst4:
13069     case Intrinsic::arm_neon_vst2lane:
13070     case Intrinsic::arm_neon_vst3lane:
13071     case Intrinsic::arm_neon_vst4lane:
13072       return PerformVLDCombine(N, DCI);
13073     default: break;
13074     }
13075     break;
13076   }
13077   return SDValue();
13078 }
13079 
13080 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
13081                                                           EVT VT) const {
13082   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
13083 }
13084 
13085 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
13086                                                        unsigned,
13087                                                        MachineMemOperand::Flags,
13088                                                        bool *Fast) const {
13089   // Depends what it gets converted into if the type is weird.
13090   if (!VT.isSimple())
13091     return false;
13092 
13093   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
13094   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
13095 
13096   switch (VT.getSimpleVT().SimpleTy) {
13097   default:
13098     return false;
13099   case MVT::i8:
13100   case MVT::i16:
13101   case MVT::i32: {
13102     // Unaligned access can use (for example) LRDB, LRDH, LDR
13103     if (AllowsUnaligned) {
13104       if (Fast)
13105         *Fast = Subtarget->hasV7Ops();
13106       return true;
13107     }
13108     return false;
13109   }
13110   case MVT::f64:
13111   case MVT::v2f64: {
13112     // For any little-endian targets with neon, we can support unaligned ld/st
13113     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
13114     // A big-endian target may also explicitly support unaligned accesses
13115     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
13116       if (Fast)
13117         *Fast = true;
13118       return true;
13119     }
13120     return false;
13121   }
13122   }
13123 }
13124 
13125 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
13126                        unsigned AlignCheck) {
13127   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
13128           (DstAlign == 0 || DstAlign % AlignCheck == 0));
13129 }
13130 
13131 EVT ARMTargetLowering::getOptimalMemOpType(
13132     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
13133     bool ZeroMemset, bool MemcpyStrSrc,
13134     const AttributeList &FuncAttributes) const {
13135   // See if we can use NEON instructions for this...
13136   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
13137       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
13138     bool Fast;
13139     if (Size >= 16 &&
13140         (memOpAlign(SrcAlign, DstAlign, 16) ||
13141          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
13142                                          MachineMemOperand::MONone, &Fast) &&
13143           Fast))) {
13144       return MVT::v2f64;
13145     } else if (Size >= 8 &&
13146                (memOpAlign(SrcAlign, DstAlign, 8) ||
13147                 (allowsMisalignedMemoryAccesses(
13148                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
13149                  Fast))) {
13150       return MVT::f64;
13151     }
13152   }
13153 
13154   // Let the target-independent logic figure it out.
13155   return MVT::Other;
13156 }
13157 
13158 // 64-bit integers are split into their high and low parts and held in two
13159 // different registers, so the trunc is free since the low register can just
13160 // be used.
13161 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
13162   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
13163     return false;
13164   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
13165   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
13166   return (SrcBits == 64 && DestBits == 32);
13167 }
13168 
13169 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
13170   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
13171       !DstVT.isInteger())
13172     return false;
13173   unsigned SrcBits = SrcVT.getSizeInBits();
13174   unsigned DestBits = DstVT.getSizeInBits();
13175   return (SrcBits == 64 && DestBits == 32);
13176 }
13177 
13178 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13179   if (Val.getOpcode() != ISD::LOAD)
13180     return false;
13181 
13182   EVT VT1 = Val.getValueType();
13183   if (!VT1.isSimple() || !VT1.isInteger() ||
13184       !VT2.isSimple() || !VT2.isInteger())
13185     return false;
13186 
13187   switch (VT1.getSimpleVT().SimpleTy) {
13188   default: break;
13189   case MVT::i1:
13190   case MVT::i8:
13191   case MVT::i16:
13192     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
13193     return true;
13194   }
13195 
13196   return false;
13197 }
13198 
13199 bool ARMTargetLowering::isFNegFree(EVT VT) const {
13200   if (!VT.isSimple())
13201     return false;
13202 
13203   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
13204   // negate values directly (fneg is free). So, we don't want to let the DAG
13205   // combiner rewrite fneg into xors and some other instructions.  For f16 and
13206   // FullFP16 argument passing, some bitcast nodes may be introduced,
13207   // triggering this DAG combine rewrite, so we are avoiding that with this.
13208   switch (VT.getSimpleVT().SimpleTy) {
13209   default: break;
13210   case MVT::f16:
13211     return Subtarget->hasFullFP16();
13212   }
13213 
13214   return false;
13215 }
13216 
13217 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
13218 /// of the vector elements.
13219 static bool areExtractExts(Value *Ext1, Value *Ext2) {
13220   auto areExtDoubled = [](Instruction *Ext) {
13221     return Ext->getType()->getScalarSizeInBits() ==
13222            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
13223   };
13224 
13225   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
13226       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
13227       !areExtDoubled(cast<Instruction>(Ext1)) ||
13228       !areExtDoubled(cast<Instruction>(Ext2)))
13229     return false;
13230 
13231   return true;
13232 }
13233 
13234 /// Check if sinking \p I's operands to I's basic block is profitable, because
13235 /// the operands can be folded into a target instruction, e.g.
13236 /// sext/zext can be folded into vsubl.
13237 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
13238                                            SmallVectorImpl<Use *> &Ops) const {
13239   if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
13240     return false;
13241 
13242   switch (I->getOpcode()) {
13243   case Instruction::Sub:
13244   case Instruction::Add: {
13245     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
13246       return false;
13247     Ops.push_back(&I->getOperandUse(0));
13248     Ops.push_back(&I->getOperandUse(1));
13249     return true;
13250   }
13251   default:
13252     return false;
13253   }
13254   return false;
13255 }
13256 
13257 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
13258   EVT VT = ExtVal.getValueType();
13259 
13260   if (!isTypeLegal(VT))
13261     return false;
13262 
13263   // Don't create a loadext if we can fold the extension into a wide/long
13264   // instruction.
13265   // If there's more than one user instruction, the loadext is desirable no
13266   // matter what.  There can be two uses by the same instruction.
13267   if (ExtVal->use_empty() ||
13268       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
13269     return true;
13270 
13271   SDNode *U = *ExtVal->use_begin();
13272   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
13273        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
13274     return false;
13275 
13276   return true;
13277 }
13278 
13279 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13280   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13281     return false;
13282 
13283   if (!isTypeLegal(EVT::getEVT(Ty1)))
13284     return false;
13285 
13286   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13287 
13288   // Assuming the caller doesn't have a zeroext or signext return parameter,
13289   // truncation all the way down to i1 is valid.
13290   return true;
13291 }
13292 
13293 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
13294                                                 const AddrMode &AM, Type *Ty,
13295                                                 unsigned AS) const {
13296   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
13297     if (Subtarget->hasFPAO())
13298       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
13299     return 0;
13300   }
13301   return -1;
13302 }
13303 
13304 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
13305   if (V < 0)
13306     return false;
13307 
13308   unsigned Scale = 1;
13309   switch (VT.getSimpleVT().SimpleTy) {
13310   case MVT::i1:
13311   case MVT::i8:
13312     // Scale == 1;
13313     break;
13314   case MVT::i16:
13315     // Scale == 2;
13316     Scale = 2;
13317     break;
13318   default:
13319     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
13320     // Scale == 4;
13321     Scale = 4;
13322     break;
13323   }
13324 
13325   if ((V & (Scale - 1)) != 0)
13326     return false;
13327   return isUInt<5>(V / Scale);
13328 }
13329 
13330 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
13331                                       const ARMSubtarget *Subtarget) {
13332   if (!VT.isInteger() && !VT.isFloatingPoint())
13333     return false;
13334   if (VT.isVector() && Subtarget->hasNEON())
13335     return false;
13336   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
13337       !Subtarget->hasMVEFloatOps())
13338     return false;
13339 
13340   bool IsNeg = false;
13341   if (V < 0) {
13342     IsNeg = true;
13343     V = -V;
13344   }
13345 
13346   unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
13347 
13348   // MVE: size * imm7
13349   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
13350     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
13351     case MVT::i32:
13352     case MVT::f32:
13353       return isShiftedUInt<7,2>(V);
13354     case MVT::i16:
13355     case MVT::f16:
13356       return isShiftedUInt<7,1>(V);
13357     case MVT::i8:
13358       return isUInt<7>(V);
13359     default:
13360       return false;
13361     }
13362   }
13363 
13364   // half VLDR: 2 * imm8
13365   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
13366     return isShiftedUInt<8, 1>(V);
13367   // VLDR and LDRD: 4 * imm8
13368   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
13369     return isShiftedUInt<8, 2>(V);
13370 
13371   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
13372     // + imm12 or - imm8
13373     if (IsNeg)
13374       return isUInt<8>(V);
13375     return isUInt<12>(V);
13376   }
13377 
13378   return false;
13379 }
13380 
13381 /// isLegalAddressImmediate - Return true if the integer value can be used
13382 /// as the offset of the target addressing mode for load / store of the
13383 /// given type.
13384 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13385                                     const ARMSubtarget *Subtarget) {
13386   if (V == 0)
13387     return true;
13388 
13389   if (!VT.isSimple())
13390     return false;
13391 
13392   if (Subtarget->isThumb1Only())
13393     return isLegalT1AddressImmediate(V, VT);
13394   else if (Subtarget->isThumb2())
13395     return isLegalT2AddressImmediate(V, VT, Subtarget);
13396 
13397   // ARM mode.
13398   if (V < 0)
13399     V = - V;
13400   switch (VT.getSimpleVT().SimpleTy) {
13401   default: return false;
13402   case MVT::i1:
13403   case MVT::i8:
13404   case MVT::i32:
13405     // +- imm12
13406     return isUInt<12>(V);
13407   case MVT::i16:
13408     // +- imm8
13409     return isUInt<8>(V);
13410   case MVT::f32:
13411   case MVT::f64:
13412     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
13413       return false;
13414     return isShiftedUInt<8, 2>(V);
13415   }
13416 }
13417 
13418 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13419                                                       EVT VT) const {
13420   int Scale = AM.Scale;
13421   if (Scale < 0)
13422     return false;
13423 
13424   switch (VT.getSimpleVT().SimpleTy) {
13425   default: return false;
13426   case MVT::i1:
13427   case MVT::i8:
13428   case MVT::i16:
13429   case MVT::i32:
13430     if (Scale == 1)
13431       return true;
13432     // r + r << imm
13433     Scale = Scale & ~1;
13434     return Scale == 2 || Scale == 4 || Scale == 8;
13435   case MVT::i64:
13436     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13437     // version in Thumb mode.
13438     // r + r
13439     if (Scale == 1)
13440       return true;
13441     // r * 2 (this can be lowered to r + r).
13442     if (!AM.HasBaseReg && Scale == 2)
13443       return true;
13444     return false;
13445   case MVT::isVoid:
13446     // Note, we allow "void" uses (basically, uses that aren't loads or
13447     // stores), because arm allows folding a scale into many arithmetic
13448     // operations.  This should be made more precise and revisited later.
13449 
13450     // Allow r << imm, but the imm has to be a multiple of two.
13451     if (Scale & 1) return false;
13452     return isPowerOf2_32(Scale);
13453   }
13454 }
13455 
13456 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13457                                                       EVT VT) const {
13458   const int Scale = AM.Scale;
13459 
13460   // Negative scales are not supported in Thumb1.
13461   if (Scale < 0)
13462     return false;
13463 
13464   // Thumb1 addressing modes do not support register scaling excepting the
13465   // following cases:
13466   // 1. Scale == 1 means no scaling.
13467   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13468   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13469 }
13470 
13471 /// isLegalAddressingMode - Return true if the addressing mode represented
13472 /// by AM is legal for this target, for a load/store of the specified type.
13473 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13474                                               const AddrMode &AM, Type *Ty,
13475                                               unsigned AS, Instruction *I) const {
13476   EVT VT = getValueType(DL, Ty, true);
13477   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13478     return false;
13479 
13480   // Can never fold addr of global into load/store.
13481   if (AM.BaseGV)
13482     return false;
13483 
13484   switch (AM.Scale) {
13485   case 0:  // no scale reg, must be "r+i" or "r", or "i".
13486     break;
13487   default:
13488     // ARM doesn't support any R+R*scale+imm addr modes.
13489     if (AM.BaseOffs)
13490       return false;
13491 
13492     if (!VT.isSimple())
13493       return false;
13494 
13495     if (Subtarget->isThumb1Only())
13496       return isLegalT1ScaledAddressingMode(AM, VT);
13497 
13498     if (Subtarget->isThumb2())
13499       return isLegalT2ScaledAddressingMode(AM, VT);
13500 
13501     int Scale = AM.Scale;
13502     switch (VT.getSimpleVT().SimpleTy) {
13503     default: return false;
13504     case MVT::i1:
13505     case MVT::i8:
13506     case MVT::i32:
13507       if (Scale < 0) Scale = -Scale;
13508       if (Scale == 1)
13509         return true;
13510       // r + r << imm
13511       return isPowerOf2_32(Scale & ~1);
13512     case MVT::i16:
13513     case MVT::i64:
13514       // r +/- r
13515       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13516         return true;
13517       // r * 2 (this can be lowered to r + r).
13518       if (!AM.HasBaseReg && Scale == 2)
13519         return true;
13520       return false;
13521 
13522     case MVT::isVoid:
13523       // Note, we allow "void" uses (basically, uses that aren't loads or
13524       // stores), because arm allows folding a scale into many arithmetic
13525       // operations.  This should be made more precise and revisited later.
13526 
13527       // Allow r << imm, but the imm has to be a multiple of two.
13528       if (Scale & 1) return false;
13529       return isPowerOf2_32(Scale);
13530     }
13531   }
13532   return true;
13533 }
13534 
13535 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13536 /// icmp immediate, that is the target has icmp instructions which can compare
13537 /// a register against the immediate without having to materialize the
13538 /// immediate into a register.
13539 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13540   // Thumb2 and ARM modes can use cmn for negative immediates.
13541   if (!Subtarget->isThumb())
13542     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
13543            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
13544   if (Subtarget->isThumb2())
13545     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
13546            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
13547   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13548   return Imm >= 0 && Imm <= 255;
13549 }
13550 
13551 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13552 /// *or sub* immediate, that is the target has add or sub instructions which can
13553 /// add a register with the immediate without having to materialize the
13554 /// immediate into a register.
13555 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13556   // Same encoding for add/sub, just flip the sign.
13557   int64_t AbsImm = std::abs(Imm);
13558   if (!Subtarget->isThumb())
13559     return ARM_AM::getSOImmVal(AbsImm) != -1;
13560   if (Subtarget->isThumb2())
13561     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13562   // Thumb1 only has 8-bit unsigned immediate.
13563   return AbsImm >= 0 && AbsImm <= 255;
13564 }
13565 
13566 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13567                                       bool isSEXTLoad, SDValue &Base,
13568                                       SDValue &Offset, bool &isInc,
13569                                       SelectionDAG &DAG) {
13570   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13571     return false;
13572 
13573   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13574     // AddressingMode 3
13575     Base = Ptr->getOperand(0);
13576     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13577       int RHSC = (int)RHS->getZExtValue();
13578       if (RHSC < 0 && RHSC > -256) {
13579         assert(Ptr->getOpcode() == ISD::ADD);
13580         isInc = false;
13581         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13582         return true;
13583       }
13584     }
13585     isInc = (Ptr->getOpcode() == ISD::ADD);
13586     Offset = Ptr->getOperand(1);
13587     return true;
13588   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13589     // AddressingMode 2
13590     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13591       int RHSC = (int)RHS->getZExtValue();
13592       if (RHSC < 0 && RHSC > -0x1000) {
13593         assert(Ptr->getOpcode() == ISD::ADD);
13594         isInc = false;
13595         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13596         Base = Ptr->getOperand(0);
13597         return true;
13598       }
13599     }
13600 
13601     if (Ptr->getOpcode() == ISD::ADD) {
13602       isInc = true;
13603       ARM_AM::ShiftOpc ShOpcVal=
13604         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13605       if (ShOpcVal != ARM_AM::no_shift) {
13606         Base = Ptr->getOperand(1);
13607         Offset = Ptr->getOperand(0);
13608       } else {
13609         Base = Ptr->getOperand(0);
13610         Offset = Ptr->getOperand(1);
13611       }
13612       return true;
13613     }
13614 
13615     isInc = (Ptr->getOpcode() == ISD::ADD);
13616     Base = Ptr->getOperand(0);
13617     Offset = Ptr->getOperand(1);
13618     return true;
13619   }
13620 
13621   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13622   return false;
13623 }
13624 
13625 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13626                                      bool isSEXTLoad, SDValue &Base,
13627                                      SDValue &Offset, bool &isInc,
13628                                      SelectionDAG &DAG) {
13629   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13630     return false;
13631 
13632   Base = Ptr->getOperand(0);
13633   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13634     int RHSC = (int)RHS->getZExtValue();
13635     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13636       assert(Ptr->getOpcode() == ISD::ADD);
13637       isInc = false;
13638       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13639       return true;
13640     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13641       isInc = Ptr->getOpcode() == ISD::ADD;
13642       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13643       return true;
13644     }
13645   }
13646 
13647   return false;
13648 }
13649 
13650 /// getPreIndexedAddressParts - returns true by value, base pointer and
13651 /// offset pointer and addressing mode by reference if the node's address
13652 /// can be legally represented as pre-indexed load / store address.
13653 bool
13654 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13655                                              SDValue &Offset,
13656                                              ISD::MemIndexedMode &AM,
13657                                              SelectionDAG &DAG) const {
13658   if (Subtarget->isThumb1Only())
13659     return false;
13660 
13661   EVT VT;
13662   SDValue Ptr;
13663   bool isSEXTLoad = false;
13664   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13665     Ptr = LD->getBasePtr();
13666     VT  = LD->getMemoryVT();
13667     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13668   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13669     Ptr = ST->getBasePtr();
13670     VT  = ST->getMemoryVT();
13671   } else
13672     return false;
13673 
13674   bool isInc;
13675   bool isLegal = false;
13676   if (Subtarget->isThumb2())
13677     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13678                                        Offset, isInc, DAG);
13679   else
13680     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13681                                         Offset, isInc, DAG);
13682   if (!isLegal)
13683     return false;
13684 
13685   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13686   return true;
13687 }
13688 
13689 /// getPostIndexedAddressParts - returns true by value, base pointer and
13690 /// offset pointer and addressing mode by reference if this node can be
13691 /// combined with a load / store to form a post-indexed load / store.
13692 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13693                                                    SDValue &Base,
13694                                                    SDValue &Offset,
13695                                                    ISD::MemIndexedMode &AM,
13696                                                    SelectionDAG &DAG) const {
13697   EVT VT;
13698   SDValue Ptr;
13699   bool isSEXTLoad = false, isNonExt;
13700   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13701     VT  = LD->getMemoryVT();
13702     Ptr = LD->getBasePtr();
13703     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13704     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13705   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13706     VT  = ST->getMemoryVT();
13707     Ptr = ST->getBasePtr();
13708     isNonExt = !ST->isTruncatingStore();
13709   } else
13710     return false;
13711 
13712   if (Subtarget->isThumb1Only()) {
13713     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13714     // must be non-extending/truncating, i32, with an offset of 4.
13715     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13716     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13717       return false;
13718     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13719     if (!RHS || RHS->getZExtValue() != 4)
13720       return false;
13721 
13722     Offset = Op->getOperand(1);
13723     Base = Op->getOperand(0);
13724     AM = ISD::POST_INC;
13725     return true;
13726   }
13727 
13728   bool isInc;
13729   bool isLegal = false;
13730   if (Subtarget->isThumb2())
13731     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13732                                        isInc, DAG);
13733   else
13734     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13735                                         isInc, DAG);
13736   if (!isLegal)
13737     return false;
13738 
13739   if (Ptr != Base) {
13740     // Swap base ptr and offset to catch more post-index load / store when
13741     // it's legal. In Thumb2 mode, offset must be an immediate.
13742     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13743         !Subtarget->isThumb2())
13744       std::swap(Base, Offset);
13745 
13746     // Post-indexed load / store update the base pointer.
13747     if (Ptr != Base)
13748       return false;
13749   }
13750 
13751   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13752   return true;
13753 }
13754 
13755 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13756                                                       KnownBits &Known,
13757                                                       const APInt &DemandedElts,
13758                                                       const SelectionDAG &DAG,
13759                                                       unsigned Depth) const {
13760   unsigned BitWidth = Known.getBitWidth();
13761   Known.resetAll();
13762   switch (Op.getOpcode()) {
13763   default: break;
13764   case ARMISD::ADDC:
13765   case ARMISD::ADDE:
13766   case ARMISD::SUBC:
13767   case ARMISD::SUBE:
13768     // Special cases when we convert a carry to a boolean.
13769     if (Op.getResNo() == 0) {
13770       SDValue LHS = Op.getOperand(0);
13771       SDValue RHS = Op.getOperand(1);
13772       // (ADDE 0, 0, C) will give us a single bit.
13773       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13774           isNullConstant(RHS)) {
13775         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13776         return;
13777       }
13778     }
13779     break;
13780   case ARMISD::CMOV: {
13781     // Bits are known zero/one if known on the LHS and RHS.
13782     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
13783     if (Known.isUnknown())
13784       return;
13785 
13786     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
13787     Known.Zero &= KnownRHS.Zero;
13788     Known.One  &= KnownRHS.One;
13789     return;
13790   }
13791   case ISD::INTRINSIC_W_CHAIN: {
13792     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13793     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13794     switch (IntID) {
13795     default: return;
13796     case Intrinsic::arm_ldaex:
13797     case Intrinsic::arm_ldrex: {
13798       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13799       unsigned MemBits = VT.getScalarSizeInBits();
13800       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13801       return;
13802     }
13803     }
13804   }
13805   case ARMISD::BFI: {
13806     // Conservatively, we can recurse down the first operand
13807     // and just mask out all affected bits.
13808     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
13809 
13810     // The operand to BFI is already a mask suitable for removing the bits it
13811     // sets.
13812     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13813     const APInt &Mask = CI->getAPIntValue();
13814     Known.Zero &= Mask;
13815     Known.One &= Mask;
13816     return;
13817   }
13818   case ARMISD::VGETLANEs:
13819   case ARMISD::VGETLANEu: {
13820     const SDValue &SrcSV = Op.getOperand(0);
13821     EVT VecVT = SrcSV.getValueType();
13822     assert(VecVT.isVector() && "VGETLANE expected a vector type");
13823     const unsigned NumSrcElts = VecVT.getVectorNumElements();
13824     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
13825     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
13826            "VGETLANE index out of bounds");
13827     unsigned Idx = Pos->getZExtValue();
13828     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
13829     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
13830 
13831     EVT VT = Op.getValueType();
13832     const unsigned DstSz = VT.getScalarSizeInBits();
13833     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
13834     (void)SrcSz;
13835     assert(SrcSz == Known.getBitWidth());
13836     assert(DstSz > SrcSz);
13837     if (Op.getOpcode() == ARMISD::VGETLANEs)
13838       Known = Known.sext(DstSz);
13839     else {
13840       Known = Known.zext(DstSz, true /* extended bits are known zero */);
13841     }
13842     assert(DstSz == Known.getBitWidth());
13843     break;
13844   }
13845   }
13846 }
13847 
13848 bool
13849 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
13850                                                 const APInt &DemandedAPInt,
13851                                                 TargetLoweringOpt &TLO) const {
13852   // Delay optimization, so we don't have to deal with illegal types, or block
13853   // optimizations.
13854   if (!TLO.LegalOps)
13855     return false;
13856 
13857   // Only optimize AND for now.
13858   if (Op.getOpcode() != ISD::AND)
13859     return false;
13860 
13861   EVT VT = Op.getValueType();
13862 
13863   // Ignore vectors.
13864   if (VT.isVector())
13865     return false;
13866 
13867   assert(VT == MVT::i32 && "Unexpected integer type");
13868 
13869   // Make sure the RHS really is a constant.
13870   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13871   if (!C)
13872     return false;
13873 
13874   unsigned Mask = C->getZExtValue();
13875 
13876   unsigned Demanded = DemandedAPInt.getZExtValue();
13877   unsigned ShrunkMask = Mask & Demanded;
13878   unsigned ExpandedMask = Mask | ~Demanded;
13879 
13880   // If the mask is all zeros, let the target-independent code replace the
13881   // result with zero.
13882   if (ShrunkMask == 0)
13883     return false;
13884 
13885   // If the mask is all ones, erase the AND. (Currently, the target-independent
13886   // code won't do this, so we have to do it explicitly to avoid an infinite
13887   // loop in obscure cases.)
13888   if (ExpandedMask == ~0U)
13889     return TLO.CombineTo(Op, Op.getOperand(0));
13890 
13891   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
13892     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
13893   };
13894   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
13895     if (NewMask == Mask)
13896       return true;
13897     SDLoc DL(Op);
13898     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
13899     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
13900     return TLO.CombineTo(Op, NewOp);
13901   };
13902 
13903   // Prefer uxtb mask.
13904   if (IsLegalMask(0xFF))
13905     return UseMask(0xFF);
13906 
13907   // Prefer uxth mask.
13908   if (IsLegalMask(0xFFFF))
13909     return UseMask(0xFFFF);
13910 
13911   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
13912   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13913   if (ShrunkMask < 256)
13914     return UseMask(ShrunkMask);
13915 
13916   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
13917   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13918   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
13919     return UseMask(ExpandedMask);
13920 
13921   // Potential improvements:
13922   //
13923   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
13924   // We could try to prefer Thumb1 immediates which can be lowered to a
13925   // two-instruction sequence.
13926   // We could try to recognize more legal ARM/Thumb2 immediates here.
13927 
13928   return false;
13929 }
13930 
13931 
13932 //===----------------------------------------------------------------------===//
13933 //                           ARM Inline Assembly Support
13934 //===----------------------------------------------------------------------===//
13935 
13936 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13937   // Looking for "rev" which is V6+.
13938   if (!Subtarget->hasV6Ops())
13939     return false;
13940 
13941   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13942   std::string AsmStr = IA->getAsmString();
13943   SmallVector<StringRef, 4> AsmPieces;
13944   SplitString(AsmStr, AsmPieces, ";\n");
13945 
13946   switch (AsmPieces.size()) {
13947   default: return false;
13948   case 1:
13949     AsmStr = AsmPieces[0];
13950     AsmPieces.clear();
13951     SplitString(AsmStr, AsmPieces, " \t,");
13952 
13953     // rev $0, $1
13954     if (AsmPieces.size() == 3 &&
13955         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13956         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13957       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13958       if (Ty && Ty->getBitWidth() == 32)
13959         return IntrinsicLowering::LowerToByteSwap(CI);
13960     }
13961     break;
13962   }
13963 
13964   return false;
13965 }
13966 
13967 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13968   // At this point, we have to lower this constraint to something else, so we
13969   // lower it to an "r" or "w". However, by doing this we will force the result
13970   // to be in register, while the X constraint is much more permissive.
13971   //
13972   // Although we are correct (we are free to emit anything, without
13973   // constraints), we might break use cases that would expect us to be more
13974   // efficient and emit something else.
13975   if (!Subtarget->hasVFP2Base())
13976     return "r";
13977   if (ConstraintVT.isFloatingPoint())
13978     return "w";
13979   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13980      (ConstraintVT.getSizeInBits() == 64 ||
13981       ConstraintVT.getSizeInBits() == 128))
13982     return "w";
13983 
13984   return "r";
13985 }
13986 
13987 /// getConstraintType - Given a constraint letter, return the type of
13988 /// constraint it is for this target.
13989 ARMTargetLowering::ConstraintType
13990 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13991   if (Constraint.size() == 1) {
13992     switch (Constraint[0]) {
13993     default:  break;
13994     case 'l': return C_RegisterClass;
13995     case 'w': return C_RegisterClass;
13996     case 'h': return C_RegisterClass;
13997     case 'x': return C_RegisterClass;
13998     case 't': return C_RegisterClass;
13999     case 'j': return C_Other; // Constant for movw.
14000       // An address with a single base register. Due to the way we
14001       // currently handle addresses it is the same as an 'r' memory constraint.
14002     case 'Q': return C_Memory;
14003     }
14004   } else if (Constraint.size() == 2) {
14005     switch (Constraint[0]) {
14006     default: break;
14007     case 'T': return C_RegisterClass;
14008     // All 'U+' constraints are addresses.
14009     case 'U': return C_Memory;
14010     }
14011   }
14012   return TargetLowering::getConstraintType(Constraint);
14013 }
14014 
14015 /// Examine constraint type and operand type and determine a weight value.
14016 /// This object must already have been set up with the operand type
14017 /// and the current alternative constraint selected.
14018 TargetLowering::ConstraintWeight
14019 ARMTargetLowering::getSingleConstraintMatchWeight(
14020     AsmOperandInfo &info, const char *constraint) const {
14021   ConstraintWeight weight = CW_Invalid;
14022   Value *CallOperandVal = info.CallOperandVal;
14023     // If we don't have a value, we can't do a match,
14024     // but allow it at the lowest weight.
14025   if (!CallOperandVal)
14026     return CW_Default;
14027   Type *type = CallOperandVal->getType();
14028   // Look at the constraint type.
14029   switch (*constraint) {
14030   default:
14031     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14032     break;
14033   case 'l':
14034     if (type->isIntegerTy()) {
14035       if (Subtarget->isThumb())
14036         weight = CW_SpecificReg;
14037       else
14038         weight = CW_Register;
14039     }
14040     break;
14041   case 'w':
14042     if (type->isFloatingPointTy())
14043       weight = CW_Register;
14044     break;
14045   }
14046   return weight;
14047 }
14048 
14049 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
14050 
14051 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
14052     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
14053   switch (Constraint.size()) {
14054   case 1:
14055     // GCC ARM Constraint Letters
14056     switch (Constraint[0]) {
14057     case 'l': // Low regs or general regs.
14058       if (Subtarget->isThumb())
14059         return RCPair(0U, &ARM::tGPRRegClass);
14060       return RCPair(0U, &ARM::GPRRegClass);
14061     case 'h': // High regs or no regs.
14062       if (Subtarget->isThumb())
14063         return RCPair(0U, &ARM::hGPRRegClass);
14064       break;
14065     case 'r':
14066       if (Subtarget->isThumb1Only())
14067         return RCPair(0U, &ARM::tGPRRegClass);
14068       return RCPair(0U, &ARM::GPRRegClass);
14069     case 'w':
14070       if (VT == MVT::Other)
14071         break;
14072       if (VT == MVT::f32)
14073         return RCPair(0U, &ARM::SPRRegClass);
14074       if (VT.getSizeInBits() == 64)
14075         return RCPair(0U, &ARM::DPRRegClass);
14076       if (VT.getSizeInBits() == 128)
14077         return RCPair(0U, &ARM::QPRRegClass);
14078       break;
14079     case 'x':
14080       if (VT == MVT::Other)
14081         break;
14082       if (VT == MVT::f32)
14083         return RCPair(0U, &ARM::SPR_8RegClass);
14084       if (VT.getSizeInBits() == 64)
14085         return RCPair(0U, &ARM::DPR_8RegClass);
14086       if (VT.getSizeInBits() == 128)
14087         return RCPair(0U, &ARM::QPR_8RegClass);
14088       break;
14089     case 't':
14090       if (VT == MVT::Other)
14091         break;
14092       if (VT == MVT::f32 || VT == MVT::i32)
14093         return RCPair(0U, &ARM::SPRRegClass);
14094       if (VT.getSizeInBits() == 64)
14095         return RCPair(0U, &ARM::DPR_VFP2RegClass);
14096       if (VT.getSizeInBits() == 128)
14097         return RCPair(0U, &ARM::QPR_VFP2RegClass);
14098       break;
14099     }
14100     break;
14101 
14102   case 2:
14103     if (Constraint[0] == 'T') {
14104       switch (Constraint[1]) {
14105       default:
14106         break;
14107       case 'e':
14108         return RCPair(0U, &ARM::tGPREvenRegClass);
14109       case 'o':
14110         return RCPair(0U, &ARM::tGPROddRegClass);
14111       }
14112     }
14113     break;
14114 
14115   default:
14116     break;
14117   }
14118 
14119   if (StringRef("{cc}").equals_lower(Constraint))
14120     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
14121 
14122   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14123 }
14124 
14125 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14126 /// vector.  If it is invalid, don't add anything to Ops.
14127 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14128                                                      std::string &Constraint,
14129                                                      std::vector<SDValue>&Ops,
14130                                                      SelectionDAG &DAG) const {
14131   SDValue Result;
14132 
14133   // Currently only support length 1 constraints.
14134   if (Constraint.length() != 1) return;
14135 
14136   char ConstraintLetter = Constraint[0];
14137   switch (ConstraintLetter) {
14138   default: break;
14139   case 'j':
14140   case 'I': case 'J': case 'K': case 'L':
14141   case 'M': case 'N': case 'O':
14142     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
14143     if (!C)
14144       return;
14145 
14146     int64_t CVal64 = C->getSExtValue();
14147     int CVal = (int) CVal64;
14148     // None of these constraints allow values larger than 32 bits.  Check
14149     // that the value fits in an int.
14150     if (CVal != CVal64)
14151       return;
14152 
14153     switch (ConstraintLetter) {
14154       case 'j':
14155         // Constant suitable for movw, must be between 0 and
14156         // 65535.
14157         if (Subtarget->hasV6T2Ops())
14158           if (CVal >= 0 && CVal <= 65535)
14159             break;
14160         return;
14161       case 'I':
14162         if (Subtarget->isThumb1Only()) {
14163           // This must be a constant between 0 and 255, for ADD
14164           // immediates.
14165           if (CVal >= 0 && CVal <= 255)
14166             break;
14167         } else if (Subtarget->isThumb2()) {
14168           // A constant that can be used as an immediate value in a
14169           // data-processing instruction.
14170           if (ARM_AM::getT2SOImmVal(CVal) != -1)
14171             break;
14172         } else {
14173           // A constant that can be used as an immediate value in a
14174           // data-processing instruction.
14175           if (ARM_AM::getSOImmVal(CVal) != -1)
14176             break;
14177         }
14178         return;
14179 
14180       case 'J':
14181         if (Subtarget->isThumb1Only()) {
14182           // This must be a constant between -255 and -1, for negated ADD
14183           // immediates. This can be used in GCC with an "n" modifier that
14184           // prints the negated value, for use with SUB instructions. It is
14185           // not useful otherwise but is implemented for compatibility.
14186           if (CVal >= -255 && CVal <= -1)
14187             break;
14188         } else {
14189           // This must be a constant between -4095 and 4095. It is not clear
14190           // what this constraint is intended for. Implemented for
14191           // compatibility with GCC.
14192           if (CVal >= -4095 && CVal <= 4095)
14193             break;
14194         }
14195         return;
14196 
14197       case 'K':
14198         if (Subtarget->isThumb1Only()) {
14199           // A 32-bit value where only one byte has a nonzero value. Exclude
14200           // zero to match GCC. This constraint is used by GCC internally for
14201           // constants that can be loaded with a move/shift combination.
14202           // It is not useful otherwise but is implemented for compatibility.
14203           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
14204             break;
14205         } else if (Subtarget->isThumb2()) {
14206           // A constant whose bitwise inverse can be used as an immediate
14207           // value in a data-processing instruction. This can be used in GCC
14208           // with a "B" modifier that prints the inverted value, for use with
14209           // BIC and MVN instructions. It is not useful otherwise but is
14210           // implemented for compatibility.
14211           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
14212             break;
14213         } else {
14214           // A constant whose bitwise inverse can be used as an immediate
14215           // value in a data-processing instruction. This can be used in GCC
14216           // with a "B" modifier that prints the inverted value, for use with
14217           // BIC and MVN instructions. It is not useful otherwise but is
14218           // implemented for compatibility.
14219           if (ARM_AM::getSOImmVal(~CVal) != -1)
14220             break;
14221         }
14222         return;
14223 
14224       case 'L':
14225         if (Subtarget->isThumb1Only()) {
14226           // This must be a constant between -7 and 7,
14227           // for 3-operand ADD/SUB immediate instructions.
14228           if (CVal >= -7 && CVal < 7)
14229             break;
14230         } else if (Subtarget->isThumb2()) {
14231           // A constant whose negation can be used as an immediate value in a
14232           // data-processing instruction. This can be used in GCC with an "n"
14233           // modifier that prints the negated value, for use with SUB
14234           // instructions. It is not useful otherwise but is implemented for
14235           // compatibility.
14236           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
14237             break;
14238         } else {
14239           // A constant whose negation can be used as an immediate value in a
14240           // data-processing instruction. This can be used in GCC with an "n"
14241           // modifier that prints the negated value, for use with SUB
14242           // instructions. It is not useful otherwise but is implemented for
14243           // compatibility.
14244           if (ARM_AM::getSOImmVal(-CVal) != -1)
14245             break;
14246         }
14247         return;
14248 
14249       case 'M':
14250         if (Subtarget->isThumb1Only()) {
14251           // This must be a multiple of 4 between 0 and 1020, for
14252           // ADD sp + immediate.
14253           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
14254             break;
14255         } else {
14256           // A power of two or a constant between 0 and 32.  This is used in
14257           // GCC for the shift amount on shifted register operands, but it is
14258           // useful in general for any shift amounts.
14259           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
14260             break;
14261         }
14262         return;
14263 
14264       case 'N':
14265         if (Subtarget->isThumb()) {  // FIXME thumb2
14266           // This must be a constant between 0 and 31, for shift amounts.
14267           if (CVal >= 0 && CVal <= 31)
14268             break;
14269         }
14270         return;
14271 
14272       case 'O':
14273         if (Subtarget->isThumb()) {  // FIXME thumb2
14274           // This must be a multiple of 4 between -508 and 508, for
14275           // ADD/SUB sp = sp + immediate.
14276           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
14277             break;
14278         }
14279         return;
14280     }
14281     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
14282     break;
14283   }
14284 
14285   if (Result.getNode()) {
14286     Ops.push_back(Result);
14287     return;
14288   }
14289   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14290 }
14291 
14292 static RTLIB::Libcall getDivRemLibcall(
14293     const SDNode *N, MVT::SimpleValueType SVT) {
14294   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14295           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14296          "Unhandled Opcode in getDivRemLibcall");
14297   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14298                   N->getOpcode() == ISD::SREM;
14299   RTLIB::Libcall LC;
14300   switch (SVT) {
14301   default: llvm_unreachable("Unexpected request for libcall!");
14302   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
14303   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
14304   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
14305   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
14306   }
14307   return LC;
14308 }
14309 
14310 static TargetLowering::ArgListTy getDivRemArgList(
14311     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
14312   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14313           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14314          "Unhandled Opcode in getDivRemArgList");
14315   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14316                   N->getOpcode() == ISD::SREM;
14317   TargetLowering::ArgListTy Args;
14318   TargetLowering::ArgListEntry Entry;
14319   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14320     EVT ArgVT = N->getOperand(i).getValueType();
14321     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
14322     Entry.Node = N->getOperand(i);
14323     Entry.Ty = ArgTy;
14324     Entry.IsSExt = isSigned;
14325     Entry.IsZExt = !isSigned;
14326     Args.push_back(Entry);
14327   }
14328   if (Subtarget->isTargetWindows() && Args.size() >= 2)
14329     std::swap(Args[0], Args[1]);
14330   return Args;
14331 }
14332 
14333 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
14334   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
14335           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
14336           Subtarget->isTargetWindows()) &&
14337          "Register-based DivRem lowering only");
14338   unsigned Opcode = Op->getOpcode();
14339   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
14340          "Invalid opcode for Div/Rem lowering");
14341   bool isSigned = (Opcode == ISD::SDIVREM);
14342   EVT VT = Op->getValueType(0);
14343   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
14344   SDLoc dl(Op);
14345 
14346   // If the target has hardware divide, use divide + multiply + subtract:
14347   //     div = a / b
14348   //     rem = a - b * div
14349   //     return {div, rem}
14350   // This should be lowered into UDIV/SDIV + MLS later on.
14351   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
14352                                         : Subtarget->hasDivideInARMMode();
14353   if (hasDivide && Op->getValueType(0).isSimple() &&
14354       Op->getSimpleValueType(0) == MVT::i32) {
14355     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
14356     const SDValue Dividend = Op->getOperand(0);
14357     const SDValue Divisor = Op->getOperand(1);
14358     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
14359     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
14360     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
14361 
14362     SDValue Values[2] = {Div, Rem};
14363     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
14364   }
14365 
14366   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
14367                                        VT.getSimpleVT().SimpleTy);
14368   SDValue InChain = DAG.getEntryNode();
14369 
14370   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
14371                                                     DAG.getContext(),
14372                                                     Subtarget);
14373 
14374   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14375                                          getPointerTy(DAG.getDataLayout()));
14376 
14377   Type *RetTy = StructType::get(Ty, Ty);
14378 
14379   if (Subtarget->isTargetWindows())
14380     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
14381 
14382   TargetLowering::CallLoweringInfo CLI(DAG);
14383   CLI.setDebugLoc(dl).setChain(InChain)
14384     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
14385     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14386 
14387   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14388   return CallInfo.first;
14389 }
14390 
14391 // Lowers REM using divmod helpers
14392 // see RTABI section 4.2/4.3
14393 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
14394   // Build return types (div and rem)
14395   std::vector<Type*> RetTyParams;
14396   Type *RetTyElement;
14397 
14398   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
14399   default: llvm_unreachable("Unexpected request for libcall!");
14400   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
14401   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
14402   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
14403   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
14404   }
14405 
14406   RetTyParams.push_back(RetTyElement);
14407   RetTyParams.push_back(RetTyElement);
14408   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
14409   Type *RetTy = StructType::get(*DAG.getContext(), ret);
14410 
14411   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
14412                                                              SimpleTy);
14413   SDValue InChain = DAG.getEntryNode();
14414   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
14415                                                     Subtarget);
14416   bool isSigned = N->getOpcode() == ISD::SREM;
14417   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14418                                          getPointerTy(DAG.getDataLayout()));
14419 
14420   if (Subtarget->isTargetWindows())
14421     InChain = WinDBZCheckDenominator(DAG, N, InChain);
14422 
14423   // Lower call
14424   CallLoweringInfo CLI(DAG);
14425   CLI.setChain(InChain)
14426      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
14427      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
14428   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
14429 
14430   // Return second (rem) result operand (first contains div)
14431   SDNode *ResNode = CallResult.first.getNode();
14432   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
14433   return ResNode->getOperand(1);
14434 }
14435 
14436 SDValue
14437 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
14438   assert(Subtarget->isTargetWindows() && "unsupported target platform");
14439   SDLoc DL(Op);
14440 
14441   // Get the inputs.
14442   SDValue Chain = Op.getOperand(0);
14443   SDValue Size  = Op.getOperand(1);
14444 
14445   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
14446           "no-stack-arg-probe")) {
14447     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14448     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14449     Chain = SP.getValue(1);
14450     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
14451     if (Align)
14452       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
14453                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
14454     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
14455     SDValue Ops[2] = { SP, Chain };
14456     return DAG.getMergeValues(Ops, DL);
14457   }
14458 
14459   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
14460                               DAG.getConstant(2, DL, MVT::i32));
14461 
14462   SDValue Flag;
14463   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
14464   Flag = Chain.getValue(1);
14465 
14466   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14467   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
14468 
14469   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14470   Chain = NewSP.getValue(1);
14471 
14472   SDValue Ops[2] = { NewSP, Chain };
14473   return DAG.getMergeValues(Ops, DL);
14474 }
14475 
14476 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
14477   SDValue SrcVal = Op.getOperand(0);
14478   const unsigned DstSz = Op.getValueType().getSizeInBits();
14479   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
14480   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
14481          "Unexpected type for custom-lowering FP_EXTEND");
14482 
14483   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
14484          "With both FP DP and 16, any FP conversion is legal!");
14485 
14486   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
14487          "With FP16, 16 to 32 conversion is legal!");
14488 
14489   // Either we are converting from 16 -> 64, without FP16 and/or
14490   // FP.double-precision or without Armv8-fp. So we must do it in two
14491   // steps.
14492   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
14493   // without FP16. So we must do a function call.
14494   SDLoc Loc(Op);
14495   RTLIB::Libcall LC;
14496   if (SrcSz == 16) {
14497     // Instruction from 16 -> 32
14498     if (Subtarget->hasFP16())
14499       SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
14500     // Lib call from 16 -> 32
14501     else {
14502       LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
14503       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
14504              "Unexpected type for custom-lowering FP_EXTEND");
14505       SrcVal =
14506         makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first;
14507     }
14508   }
14509 
14510   if (DstSz != 64)
14511     return SrcVal;
14512   // For sure now SrcVal is 32 bits
14513   if (Subtarget->hasFP64()) // Instruction from 32 -> 64
14514     return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
14515 
14516   LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
14517   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
14518          "Unexpected type for custom-lowering FP_EXTEND");
14519   return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first;
14520 }
14521 
14522 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14523   SDValue SrcVal = Op.getOperand(0);
14524   EVT SrcVT = SrcVal.getValueType();
14525   EVT DstVT = Op.getValueType();
14526   const unsigned DstSz = Op.getValueType().getSizeInBits();
14527   const unsigned SrcSz = SrcVT.getSizeInBits();
14528   (void)DstSz;
14529   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
14530          "Unexpected type for custom-lowering FP_ROUND");
14531 
14532   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
14533          "With both FP DP and 16, any FP conversion is legal!");
14534 
14535   SDLoc Loc(Op);
14536 
14537   // Instruction from 32 -> 16 if hasFP16 is valid
14538   if (SrcSz == 32 && Subtarget->hasFP16())
14539     return Op;
14540 
14541   // Lib call from 32 -> 16 / 64 -> [32, 16]
14542   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
14543   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
14544          "Unexpected type for custom-lowering FP_ROUND");
14545   return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first;
14546 }
14547 
14548 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
14549                                  SelectionDAG &DAG) const {
14550   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
14551   MVT HalfT = MVT::i32;
14552   SDLoc dl(N);
14553   SDValue Hi, Lo, Tmp;
14554 
14555   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
14556       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
14557     return ;
14558 
14559   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
14560   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
14561 
14562   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
14563                    DAG.getConstant(0, dl, HalfT));
14564   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
14565                    DAG.getConstant(1, dl, HalfT));
14566 
14567   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
14568                     DAG.getConstant(OpTypeBits - 1, dl,
14569                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
14570   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
14571   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
14572                    SDValue(Lo.getNode(), 1));
14573   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
14574   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
14575 
14576   Results.push_back(Lo);
14577   Results.push_back(Hi);
14578 }
14579 
14580 bool
14581 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14582   // The ARM target isn't yet aware of offsets.
14583   return false;
14584 }
14585 
14586 bool ARM::isBitFieldInvertedMask(unsigned v) {
14587   if (v == 0xffffffff)
14588     return false;
14589 
14590   // there can be 1's on either or both "outsides", all the "inside"
14591   // bits must be 0's
14592   return isShiftedMask_32(~v);
14593 }
14594 
14595 /// isFPImmLegal - Returns true if the target can instruction select the
14596 /// specified FP immediate natively. If false, the legalizer will
14597 /// materialize the FP immediate as a load from a constant pool.
14598 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14599                                      bool ForCodeSize) const {
14600   if (!Subtarget->hasVFP3Base())
14601     return false;
14602   if (VT == MVT::f16 && Subtarget->hasFullFP16())
14603     return ARM_AM::getFP16Imm(Imm) != -1;
14604   if (VT == MVT::f32)
14605     return ARM_AM::getFP32Imm(Imm) != -1;
14606   if (VT == MVT::f64 && Subtarget->hasFP64())
14607     return ARM_AM::getFP64Imm(Imm) != -1;
14608   return false;
14609 }
14610 
14611 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14612 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
14613 /// specified in the intrinsic calls.
14614 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14615                                            const CallInst &I,
14616                                            MachineFunction &MF,
14617                                            unsigned Intrinsic) const {
14618   switch (Intrinsic) {
14619   case Intrinsic::arm_neon_vld1:
14620   case Intrinsic::arm_neon_vld2:
14621   case Intrinsic::arm_neon_vld3:
14622   case Intrinsic::arm_neon_vld4:
14623   case Intrinsic::arm_neon_vld2lane:
14624   case Intrinsic::arm_neon_vld3lane:
14625   case Intrinsic::arm_neon_vld4lane:
14626   case Intrinsic::arm_neon_vld2dup:
14627   case Intrinsic::arm_neon_vld3dup:
14628   case Intrinsic::arm_neon_vld4dup: {
14629     Info.opc = ISD::INTRINSIC_W_CHAIN;
14630     // Conservatively set memVT to the entire set of vectors loaded.
14631     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14632     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14633     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14634     Info.ptrVal = I.getArgOperand(0);
14635     Info.offset = 0;
14636     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14637     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14638     // volatile loads with NEON intrinsics not supported
14639     Info.flags = MachineMemOperand::MOLoad;
14640     return true;
14641   }
14642   case Intrinsic::arm_neon_vld1x2:
14643   case Intrinsic::arm_neon_vld1x3:
14644   case Intrinsic::arm_neon_vld1x4: {
14645     Info.opc = ISD::INTRINSIC_W_CHAIN;
14646     // Conservatively set memVT to the entire set of vectors loaded.
14647     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14648     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14649     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14650     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
14651     Info.offset = 0;
14652     Info.align = 0;
14653     // volatile loads with NEON intrinsics not supported
14654     Info.flags = MachineMemOperand::MOLoad;
14655     return true;
14656   }
14657   case Intrinsic::arm_neon_vst1:
14658   case Intrinsic::arm_neon_vst2:
14659   case Intrinsic::arm_neon_vst3:
14660   case Intrinsic::arm_neon_vst4:
14661   case Intrinsic::arm_neon_vst2lane:
14662   case Intrinsic::arm_neon_vst3lane:
14663   case Intrinsic::arm_neon_vst4lane: {
14664     Info.opc = ISD::INTRINSIC_VOID;
14665     // Conservatively set memVT to the entire set of vectors stored.
14666     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14667     unsigned NumElts = 0;
14668     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14669       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14670       if (!ArgTy->isVectorTy())
14671         break;
14672       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14673     }
14674     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14675     Info.ptrVal = I.getArgOperand(0);
14676     Info.offset = 0;
14677     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14678     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14679     // volatile stores with NEON intrinsics not supported
14680     Info.flags = MachineMemOperand::MOStore;
14681     return true;
14682   }
14683   case Intrinsic::arm_neon_vst1x2:
14684   case Intrinsic::arm_neon_vst1x3:
14685   case Intrinsic::arm_neon_vst1x4: {
14686     Info.opc = ISD::INTRINSIC_VOID;
14687     // Conservatively set memVT to the entire set of vectors stored.
14688     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14689     unsigned NumElts = 0;
14690     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14691       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14692       if (!ArgTy->isVectorTy())
14693         break;
14694       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14695     }
14696     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14697     Info.ptrVal = I.getArgOperand(0);
14698     Info.offset = 0;
14699     Info.align = 0;
14700     // volatile stores with NEON intrinsics not supported
14701     Info.flags = MachineMemOperand::MOStore;
14702     return true;
14703   }
14704   case Intrinsic::arm_ldaex:
14705   case Intrinsic::arm_ldrex: {
14706     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14707     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
14708     Info.opc = ISD::INTRINSIC_W_CHAIN;
14709     Info.memVT = MVT::getVT(PtrTy->getElementType());
14710     Info.ptrVal = I.getArgOperand(0);
14711     Info.offset = 0;
14712     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14713     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14714     return true;
14715   }
14716   case Intrinsic::arm_stlex:
14717   case Intrinsic::arm_strex: {
14718     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14719     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
14720     Info.opc = ISD::INTRINSIC_W_CHAIN;
14721     Info.memVT = MVT::getVT(PtrTy->getElementType());
14722     Info.ptrVal = I.getArgOperand(1);
14723     Info.offset = 0;
14724     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14725     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14726     return true;
14727   }
14728   case Intrinsic::arm_stlexd:
14729   case Intrinsic::arm_strexd:
14730     Info.opc = ISD::INTRINSIC_W_CHAIN;
14731     Info.memVT = MVT::i64;
14732     Info.ptrVal = I.getArgOperand(2);
14733     Info.offset = 0;
14734     Info.align = 8;
14735     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14736     return true;
14737 
14738   case Intrinsic::arm_ldaexd:
14739   case Intrinsic::arm_ldrexd:
14740     Info.opc = ISD::INTRINSIC_W_CHAIN;
14741     Info.memVT = MVT::i64;
14742     Info.ptrVal = I.getArgOperand(0);
14743     Info.offset = 0;
14744     Info.align = 8;
14745     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14746     return true;
14747 
14748   default:
14749     break;
14750   }
14751 
14752   return false;
14753 }
14754 
14755 /// Returns true if it is beneficial to convert a load of a constant
14756 /// to just the constant itself.
14757 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14758                                                           Type *Ty) const {
14759   assert(Ty->isIntegerTy());
14760 
14761   unsigned Bits = Ty->getPrimitiveSizeInBits();
14762   if (Bits == 0 || Bits > 32)
14763     return false;
14764   return true;
14765 }
14766 
14767 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
14768                                                 unsigned Index) const {
14769   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
14770     return false;
14771 
14772   return (Index == 0 || Index == ResVT.getVectorNumElements());
14773 }
14774 
14775 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
14776                                         ARM_MB::MemBOpt Domain) const {
14777   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14778 
14779   // First, if the target has no DMB, see what fallback we can use.
14780   if (!Subtarget->hasDataBarrier()) {
14781     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14782     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14783     // here.
14784     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14785       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14786       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14787                         Builder.getInt32(0), Builder.getInt32(7),
14788                         Builder.getInt32(10), Builder.getInt32(5)};
14789       return Builder.CreateCall(MCR, args);
14790     } else {
14791       // Instead of using barriers, atomic accesses on these subtargets use
14792       // libcalls.
14793       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14794     }
14795   } else {
14796     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14797     // Only a full system barrier exists in the M-class architectures.
14798     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14799     Constant *CDomain = Builder.getInt32(Domain);
14800     return Builder.CreateCall(DMB, CDomain);
14801   }
14802 }
14803 
14804 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14805 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14806                                                  Instruction *Inst,
14807                                                  AtomicOrdering Ord) const {
14808   switch (Ord) {
14809   case AtomicOrdering::NotAtomic:
14810   case AtomicOrdering::Unordered:
14811     llvm_unreachable("Invalid fence: unordered/non-atomic");
14812   case AtomicOrdering::Monotonic:
14813   case AtomicOrdering::Acquire:
14814     return nullptr; // Nothing to do
14815   case AtomicOrdering::SequentiallyConsistent:
14816     if (!Inst->hasAtomicStore())
14817       return nullptr; // Nothing to do
14818     LLVM_FALLTHROUGH;
14819   case AtomicOrdering::Release:
14820   case AtomicOrdering::AcquireRelease:
14821     if (Subtarget->preferISHSTBarriers())
14822       return makeDMB(Builder, ARM_MB::ISHST);
14823     // FIXME: add a comment with a link to documentation justifying this.
14824     else
14825       return makeDMB(Builder, ARM_MB::ISH);
14826   }
14827   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14828 }
14829 
14830 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14831                                                   Instruction *Inst,
14832                                                   AtomicOrdering Ord) const {
14833   switch (Ord) {
14834   case AtomicOrdering::NotAtomic:
14835   case AtomicOrdering::Unordered:
14836     llvm_unreachable("Invalid fence: unordered/not-atomic");
14837   case AtomicOrdering::Monotonic:
14838   case AtomicOrdering::Release:
14839     return nullptr; // Nothing to do
14840   case AtomicOrdering::Acquire:
14841   case AtomicOrdering::AcquireRelease:
14842   case AtomicOrdering::SequentiallyConsistent:
14843     return makeDMB(Builder, ARM_MB::ISH);
14844   }
14845   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14846 }
14847 
14848 // Loads and stores less than 64-bits are already atomic; ones above that
14849 // are doomed anyway, so defer to the default libcall and blame the OS when
14850 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14851 // anything for those.
14852 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14853   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14854   return (Size == 64) && !Subtarget->isMClass();
14855 }
14856 
14857 // Loads and stores less than 64-bits are already atomic; ones above that
14858 // are doomed anyway, so defer to the default libcall and blame the OS when
14859 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14860 // anything for those.
14861 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14862 // guarantee, see DDI0406C ARM architecture reference manual,
14863 // sections A8.8.72-74 LDRD)
14864 TargetLowering::AtomicExpansionKind
14865 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14866   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14867   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14868                                                   : AtomicExpansionKind::None;
14869 }
14870 
14871 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14872 // and up to 64 bits on the non-M profiles
14873 TargetLowering::AtomicExpansionKind
14874 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14875   if (AI->isFloatingPointOperation())
14876     return AtomicExpansionKind::CmpXChg;
14877 
14878   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14879   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14880   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14881              ? AtomicExpansionKind::LLSC
14882              : AtomicExpansionKind::None;
14883 }
14884 
14885 TargetLowering::AtomicExpansionKind
14886 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
14887   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14888   // implement cmpxchg without spilling. If the address being exchanged is also
14889   // on the stack and close enough to the spill slot, this can lead to a
14890   // situation where the monitor always gets cleared and the atomic operation
14891   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14892   bool HasAtomicCmpXchg =
14893       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14894   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
14895     return AtomicExpansionKind::LLSC;
14896   return AtomicExpansionKind::None;
14897 }
14898 
14899 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14900     const Instruction *I) const {
14901   return InsertFencesForAtomic;
14902 }
14903 
14904 // This has so far only been implemented for MachO.
14905 bool ARMTargetLowering::useLoadStackGuardNode() const {
14906   return Subtarget->isTargetMachO();
14907 }
14908 
14909 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14910                                                   unsigned &Cost) const {
14911   // If we do not have NEON, vector types are not natively supported.
14912   if (!Subtarget->hasNEON())
14913     return false;
14914 
14915   // Floating point values and vector values map to the same register file.
14916   // Therefore, although we could do a store extract of a vector type, this is
14917   // better to leave at float as we have more freedom in the addressing mode for
14918   // those.
14919   if (VectorTy->isFPOrFPVectorTy())
14920     return false;
14921 
14922   // If the index is unknown at compile time, this is very expensive to lower
14923   // and it is not possible to combine the store with the extract.
14924   if (!isa<ConstantInt>(Idx))
14925     return false;
14926 
14927   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14928   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14929   // We can do a store + vector extract on any vector that fits perfectly in a D
14930   // or Q register.
14931   if (BitWidth == 64 || BitWidth == 128) {
14932     Cost = 0;
14933     return true;
14934   }
14935   return false;
14936 }
14937 
14938 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14939   return Subtarget->hasV6T2Ops();
14940 }
14941 
14942 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14943   return Subtarget->hasV6T2Ops();
14944 }
14945 
14946 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
14947   return !Subtarget->hasMinSize();
14948 }
14949 
14950 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14951                                          AtomicOrdering Ord) const {
14952   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14953   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14954   bool IsAcquire = isAcquireOrStronger(Ord);
14955 
14956   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14957   // intrinsic must return {i32, i32} and we have to recombine them into a
14958   // single i64 here.
14959   if (ValTy->getPrimitiveSizeInBits() == 64) {
14960     Intrinsic::ID Int =
14961         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14962     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14963 
14964     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14965     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14966 
14967     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14968     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14969     if (!Subtarget->isLittle())
14970       std::swap (Lo, Hi);
14971     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14972     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14973     return Builder.CreateOr(
14974         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14975   }
14976 
14977   Type *Tys[] = { Addr->getType() };
14978   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14979   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14980 
14981   return Builder.CreateTruncOrBitCast(
14982       Builder.CreateCall(Ldrex, Addr),
14983       cast<PointerType>(Addr->getType())->getElementType());
14984 }
14985 
14986 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14987     IRBuilder<> &Builder) const {
14988   if (!Subtarget->hasV7Ops())
14989     return;
14990   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14991   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14992 }
14993 
14994 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14995                                                Value *Addr,
14996                                                AtomicOrdering Ord) const {
14997   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14998   bool IsRelease = isReleaseOrStronger(Ord);
14999 
15000   // Since the intrinsics must have legal type, the i64 intrinsics take two
15001   // parameters: "i32, i32". We must marshal Val into the appropriate form
15002   // before the call.
15003   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
15004     Intrinsic::ID Int =
15005         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
15006     Function *Strex = Intrinsic::getDeclaration(M, Int);
15007     Type *Int32Ty = Type::getInt32Ty(M->getContext());
15008 
15009     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
15010     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
15011     if (!Subtarget->isLittle())
15012       std::swap(Lo, Hi);
15013     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15014     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
15015   }
15016 
15017   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
15018   Type *Tys[] = { Addr->getType() };
15019   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
15020 
15021   return Builder.CreateCall(
15022       Strex, {Builder.CreateZExtOrBitCast(
15023                   Val, Strex->getFunctionType()->getParamType(0)),
15024               Addr});
15025 }
15026 
15027 
15028 bool ARMTargetLowering::alignLoopsWithOptSize() const {
15029   return Subtarget->isMClass();
15030 }
15031 
15032 /// A helper function for determining the number of interleaved accesses we
15033 /// will generate when lowering accesses of the given type.
15034 unsigned
15035 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
15036                                              const DataLayout &DL) const {
15037   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
15038 }
15039 
15040 bool ARMTargetLowering::isLegalInterleavedAccessType(
15041     VectorType *VecTy, const DataLayout &DL) const {
15042 
15043   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
15044   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
15045 
15046   // Ensure the vector doesn't have f16 elements. Even though we could do an
15047   // i16 vldN, we can't hold the f16 vectors and will end up converting via
15048   // f32.
15049   if (VecTy->getElementType()->isHalfTy())
15050     return false;
15051 
15052   // Ensure the number of vector elements is greater than 1.
15053   if (VecTy->getNumElements() < 2)
15054     return false;
15055 
15056   // Ensure the element type is legal.
15057   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
15058     return false;
15059 
15060   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
15061   // 128 will be split into multiple interleaved accesses.
15062   return VecSize == 64 || VecSize % 128 == 0;
15063 }
15064 
15065 /// Lower an interleaved load into a vldN intrinsic.
15066 ///
15067 /// E.g. Lower an interleaved load (Factor = 2):
15068 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
15069 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
15070 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
15071 ///
15072 ///      Into:
15073 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
15074 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
15075 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
15076 bool ARMTargetLowering::lowerInterleavedLoad(
15077     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
15078     ArrayRef<unsigned> Indices, unsigned Factor) const {
15079   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
15080          "Invalid interleave factor");
15081   assert(!Shuffles.empty() && "Empty shufflevector input");
15082   assert(Shuffles.size() == Indices.size() &&
15083          "Unmatched number of shufflevectors and indices");
15084 
15085   VectorType *VecTy = Shuffles[0]->getType();
15086   Type *EltTy = VecTy->getVectorElementType();
15087 
15088   const DataLayout &DL = LI->getModule()->getDataLayout();
15089 
15090   // Skip if we do not have NEON and skip illegal vector types. We can
15091   // "legalize" wide vector types into multiple interleaved accesses as long as
15092   // the vector types are divisible by 128.
15093   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
15094     return false;
15095 
15096   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
15097 
15098   // A pointer vector can not be the return type of the ldN intrinsics. Need to
15099   // load integer vectors first and then convert to pointer vectors.
15100   if (EltTy->isPointerTy())
15101     VecTy =
15102         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
15103 
15104   IRBuilder<> Builder(LI);
15105 
15106   // The base address of the load.
15107   Value *BaseAddr = LI->getPointerOperand();
15108 
15109   if (NumLoads > 1) {
15110     // If we're going to generate more than one load, reset the sub-vector type
15111     // to something legal.
15112     VecTy = VectorType::get(VecTy->getVectorElementType(),
15113                             VecTy->getVectorNumElements() / NumLoads);
15114 
15115     // We will compute the pointer operand of each load from the original base
15116     // address using GEPs. Cast the base address to a pointer to the scalar
15117     // element type.
15118     BaseAddr = Builder.CreateBitCast(
15119         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
15120                       LI->getPointerAddressSpace()));
15121   }
15122 
15123   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
15124 
15125   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
15126   Type *Tys[] = {VecTy, Int8Ptr};
15127   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
15128                                             Intrinsic::arm_neon_vld3,
15129                                             Intrinsic::arm_neon_vld4};
15130   Function *VldnFunc =
15131       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
15132 
15133   // Holds sub-vectors extracted from the load intrinsic return values. The
15134   // sub-vectors are associated with the shufflevector instructions they will
15135   // replace.
15136   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
15137 
15138   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
15139     // If we're generating more than one load, compute the base address of
15140     // subsequent loads as an offset from the previous.
15141     if (LoadCount > 0)
15142       BaseAddr =
15143           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
15144                                      VecTy->getVectorNumElements() * Factor);
15145 
15146     SmallVector<Value *, 2> Ops;
15147     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
15148     Ops.push_back(Builder.getInt32(LI->getAlignment()));
15149 
15150     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
15151 
15152     // Replace uses of each shufflevector with the corresponding vector loaded
15153     // by ldN.
15154     for (unsigned i = 0; i < Shuffles.size(); i++) {
15155       ShuffleVectorInst *SV = Shuffles[i];
15156       unsigned Index = Indices[i];
15157 
15158       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
15159 
15160       // Convert the integer vector to pointer vector if the element is pointer.
15161       if (EltTy->isPointerTy())
15162         SubVec = Builder.CreateIntToPtr(
15163             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
15164                                     VecTy->getVectorNumElements()));
15165 
15166       SubVecs[SV].push_back(SubVec);
15167     }
15168   }
15169 
15170   // Replace uses of the shufflevector instructions with the sub-vectors
15171   // returned by the load intrinsic. If a shufflevector instruction is
15172   // associated with more than one sub-vector, those sub-vectors will be
15173   // concatenated into a single wide vector.
15174   for (ShuffleVectorInst *SVI : Shuffles) {
15175     auto &SubVec = SubVecs[SVI];
15176     auto *WideVec =
15177         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
15178     SVI->replaceAllUsesWith(WideVec);
15179   }
15180 
15181   return true;
15182 }
15183 
15184 /// Lower an interleaved store into a vstN intrinsic.
15185 ///
15186 /// E.g. Lower an interleaved store (Factor = 3):
15187 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
15188 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
15189 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
15190 ///
15191 ///      Into:
15192 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
15193 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
15194 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
15195 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
15196 ///
15197 /// Note that the new shufflevectors will be removed and we'll only generate one
15198 /// vst3 instruction in CodeGen.
15199 ///
15200 /// Example for a more general valid mask (Factor 3). Lower:
15201 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
15202 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
15203 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
15204 ///
15205 ///      Into:
15206 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
15207 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
15208 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
15209 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
15210 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
15211                                               ShuffleVectorInst *SVI,
15212                                               unsigned Factor) const {
15213   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
15214          "Invalid interleave factor");
15215 
15216   VectorType *VecTy = SVI->getType();
15217   assert(VecTy->getVectorNumElements() % Factor == 0 &&
15218          "Invalid interleaved store");
15219 
15220   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
15221   Type *EltTy = VecTy->getVectorElementType();
15222   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
15223 
15224   const DataLayout &DL = SI->getModule()->getDataLayout();
15225 
15226   // Skip if we do not have NEON and skip illegal vector types. We can
15227   // "legalize" wide vector types into multiple interleaved accesses as long as
15228   // the vector types are divisible by 128.
15229   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
15230     return false;
15231 
15232   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
15233 
15234   Value *Op0 = SVI->getOperand(0);
15235   Value *Op1 = SVI->getOperand(1);
15236   IRBuilder<> Builder(SI);
15237 
15238   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
15239   // vectors to integer vectors.
15240   if (EltTy->isPointerTy()) {
15241     Type *IntTy = DL.getIntPtrType(EltTy);
15242 
15243     // Convert to the corresponding integer vector.
15244     Type *IntVecTy =
15245         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
15246     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
15247     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
15248 
15249     SubVecTy = VectorType::get(IntTy, LaneLen);
15250   }
15251 
15252   // The base address of the store.
15253   Value *BaseAddr = SI->getPointerOperand();
15254 
15255   if (NumStores > 1) {
15256     // If we're going to generate more than one store, reset the lane length
15257     // and sub-vector type to something legal.
15258     LaneLen /= NumStores;
15259     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
15260 
15261     // We will compute the pointer operand of each store from the original base
15262     // address using GEPs. Cast the base address to a pointer to the scalar
15263     // element type.
15264     BaseAddr = Builder.CreateBitCast(
15265         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
15266                       SI->getPointerAddressSpace()));
15267   }
15268 
15269   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
15270 
15271   auto Mask = SVI->getShuffleMask();
15272 
15273   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
15274   Type *Tys[] = {Int8Ptr, SubVecTy};
15275   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
15276                                              Intrinsic::arm_neon_vst3,
15277                                              Intrinsic::arm_neon_vst4};
15278 
15279   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
15280     // If we generating more than one store, we compute the base address of
15281     // subsequent stores as an offset from the previous.
15282     if (StoreCount > 0)
15283       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
15284                                             BaseAddr, LaneLen * Factor);
15285 
15286     SmallVector<Value *, 6> Ops;
15287     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
15288 
15289     Function *VstNFunc =
15290         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
15291 
15292     // Split the shufflevector operands into sub vectors for the new vstN call.
15293     for (unsigned i = 0; i < Factor; i++) {
15294       unsigned IdxI = StoreCount * LaneLen * Factor + i;
15295       if (Mask[IdxI] >= 0) {
15296         Ops.push_back(Builder.CreateShuffleVector(
15297             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
15298       } else {
15299         unsigned StartMask = 0;
15300         for (unsigned j = 1; j < LaneLen; j++) {
15301           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
15302           if (Mask[IdxJ * Factor + IdxI] >= 0) {
15303             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
15304             break;
15305           }
15306         }
15307         // Note: If all elements in a chunk are undefs, StartMask=0!
15308         // Note: Filling undef gaps with random elements is ok, since
15309         // those elements were being written anyway (with undefs).
15310         // In the case of all undefs we're defaulting to using elems from 0
15311         // Note: StartMask cannot be negative, it's checked in
15312         // isReInterleaveMask
15313         Ops.push_back(Builder.CreateShuffleVector(
15314             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
15315       }
15316     }
15317 
15318     Ops.push_back(Builder.getInt32(SI->getAlignment()));
15319     Builder.CreateCall(VstNFunc, Ops);
15320   }
15321   return true;
15322 }
15323 
15324 enum HABaseType {
15325   HA_UNKNOWN = 0,
15326   HA_FLOAT,
15327   HA_DOUBLE,
15328   HA_VECT64,
15329   HA_VECT128
15330 };
15331 
15332 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
15333                                    uint64_t &Members) {
15334   if (auto *ST = dyn_cast<StructType>(Ty)) {
15335     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
15336       uint64_t SubMembers = 0;
15337       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
15338         return false;
15339       Members += SubMembers;
15340     }
15341   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
15342     uint64_t SubMembers = 0;
15343     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
15344       return false;
15345     Members += SubMembers * AT->getNumElements();
15346   } else if (Ty->isFloatTy()) {
15347     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
15348       return false;
15349     Members = 1;
15350     Base = HA_FLOAT;
15351   } else if (Ty->isDoubleTy()) {
15352     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
15353       return false;
15354     Members = 1;
15355     Base = HA_DOUBLE;
15356   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
15357     Members = 1;
15358     switch (Base) {
15359     case HA_FLOAT:
15360     case HA_DOUBLE:
15361       return false;
15362     case HA_VECT64:
15363       return VT->getBitWidth() == 64;
15364     case HA_VECT128:
15365       return VT->getBitWidth() == 128;
15366     case HA_UNKNOWN:
15367       switch (VT->getBitWidth()) {
15368       case 64:
15369         Base = HA_VECT64;
15370         return true;
15371       case 128:
15372         Base = HA_VECT128;
15373         return true;
15374       default:
15375         return false;
15376       }
15377     }
15378   }
15379 
15380   return (Members > 0 && Members <= 4);
15381 }
15382 
15383 /// Return the correct alignment for the current calling convention.
15384 unsigned
15385 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
15386                                                  DataLayout DL) const {
15387   if (!ArgTy->isVectorTy())
15388     return DL.getABITypeAlignment(ArgTy);
15389 
15390   // Avoid over-aligning vector parameters. It would require realigning the
15391   // stack and waste space for no real benefit.
15392   return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
15393 }
15394 
15395 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
15396 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
15397 /// passing according to AAPCS rules.
15398 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
15399     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15400   if (getEffectiveCallingConv(CallConv, isVarArg) !=
15401       CallingConv::ARM_AAPCS_VFP)
15402     return false;
15403 
15404   HABaseType Base = HA_UNKNOWN;
15405   uint64_t Members = 0;
15406   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
15407   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
15408 
15409   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
15410   return IsHA || IsIntArray;
15411 }
15412 
15413 unsigned ARMTargetLowering::getExceptionPointerRegister(
15414     const Constant *PersonalityFn) const {
15415   // Platforms which do not use SjLj EH may return values in these registers
15416   // via the personality function.
15417   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
15418 }
15419 
15420 unsigned ARMTargetLowering::getExceptionSelectorRegister(
15421     const Constant *PersonalityFn) const {
15422   // Platforms which do not use SjLj EH may return values in these registers
15423   // via the personality function.
15424   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
15425 }
15426 
15427 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15428   // Update IsSplitCSR in ARMFunctionInfo.
15429   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
15430   AFI->setIsSplitCSR(true);
15431 }
15432 
15433 void ARMTargetLowering::insertCopiesSplitCSR(
15434     MachineBasicBlock *Entry,
15435     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15436   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
15437   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15438   if (!IStart)
15439     return;
15440 
15441   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15442   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15443   MachineBasicBlock::iterator MBBI = Entry->begin();
15444   for (const MCPhysReg *I = IStart; *I; ++I) {
15445     const TargetRegisterClass *RC = nullptr;
15446     if (ARM::GPRRegClass.contains(*I))
15447       RC = &ARM::GPRRegClass;
15448     else if (ARM::DPRRegClass.contains(*I))
15449       RC = &ARM::DPRRegClass;
15450     else
15451       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15452 
15453     unsigned NewVR = MRI->createVirtualRegister(RC);
15454     // Create copy from CSR to a virtual register.
15455     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15456     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15457     // nounwind. If we want to generalize this later, we may need to emit
15458     // CFI pseudo-instructions.
15459     assert(Entry->getParent()->getFunction().hasFnAttribute(
15460                Attribute::NoUnwind) &&
15461            "Function should be nounwind in insertCopiesSplitCSR!");
15462     Entry->addLiveIn(*I);
15463     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15464         .addReg(*I);
15465 
15466     // Insert the copy-back instructions right before the terminator.
15467     for (auto *Exit : Exits)
15468       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15469               TII->get(TargetOpcode::COPY), *I)
15470           .addReg(NewVR);
15471   }
15472 }
15473 
15474 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
15475   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15476   TargetLoweringBase::finalizeLowering(MF);
15477 }
15478