1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMISelLowering.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/ARMBaseInfo.h"
27 #include "Utils/ARMBaseInfo.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/StringSwitch.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/Analysis/VectorUtils.h"
43 #include "llvm/CodeGen/CallingConvLower.h"
44 #include "llvm/CodeGen/ISDOpcodes.h"
45 #include "llvm/CodeGen/IntrinsicLowering.h"
46 #include "llvm/CodeGen/MachineBasicBlock.h"
47 #include "llvm/CodeGen/MachineConstantPool.h"
48 #include "llvm/CodeGen/MachineFrameInfo.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineInstr.h"
51 #include "llvm/CodeGen/MachineInstrBuilder.h"
52 #include "llvm/CodeGen/MachineJumpTableInfo.h"
53 #include "llvm/CodeGen/MachineMemOperand.h"
54 #include "llvm/CodeGen/MachineOperand.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
56 #include "llvm/CodeGen/MachineValueType.h"
57 #include "llvm/CodeGen/RuntimeLibcalls.h"
58 #include "llvm/CodeGen/SelectionDAG.h"
59 #include "llvm/CodeGen/SelectionDAGNodes.h"
60 #include "llvm/CodeGen/ValueTypes.h"
61 #include "llvm/IR/Attributes.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugLoc.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalValue.h"
71 #include "llvm/IR/GlobalVariable.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/Instruction.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/User.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/MC/MCInstrDesc.h"
83 #include "llvm/MC/MCInstrItineraries.h"
84 #include "llvm/MC/MCRegisterInfo.h"
85 #include "llvm/MC/MCSchedule.h"
86 #include "llvm/Support/AtomicOrdering.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CodeGen.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include "llvm/Support/KnownBits.h"
95 #include "llvm/Support/MathExtras.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/Target/TargetInstrInfo.h"
98 #include "llvm/Target/TargetLowering.h"
99 #include "llvm/Target/TargetMachine.h"
100 #include "llvm/Target/TargetOpcodes.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Target/TargetRegisterInfo.h"
103 #include "llvm/Target/TargetSubtargetInfo.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 
117 #define DEBUG_TYPE "arm-isel"
118 
119 STATISTIC(NumTailCalls, "Number of tail calls");
120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
122 STATISTIC(NumConstpoolPromoted,
123   "Number of constants with their storage promoted into constant pools");
124 
125 static cl::opt<bool>
126 ARMInterworking("arm-interworking", cl::Hidden,
127   cl::desc("Enable / disable ARM interworking (for debugging only)"),
128   cl::init(true));
129 
130 static cl::opt<bool> EnableConstpoolPromotion(
131     "arm-promote-constant", cl::Hidden,
132     cl::desc("Enable / disable promotion of unnamed_addr constants into "
133              "constant pools"),
134     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
135 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
136     "arm-promote-constant-max-size", cl::Hidden,
137     cl::desc("Maximum size of constant to promote into a constant pool"),
138     cl::init(64));
139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
140     "arm-promote-constant-max-total", cl::Hidden,
141     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
142     cl::init(128));
143 
144 // The APCS parameter registers.
145 static const MCPhysReg GPRArgRegs[] = {
146   ARM::R0, ARM::R1, ARM::R2, ARM::R3
147 };
148 
149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
150                                        MVT PromotedBitwiseVT) {
151   if (VT != PromotedLdStVT) {
152     setOperationAction(ISD::LOAD, VT, Promote);
153     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
154 
155     setOperationAction(ISD::STORE, VT, Promote);
156     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
157   }
158 
159   MVT ElemTy = VT.getVectorElementType();
160   if (ElemTy != MVT::f64)
161     setOperationAction(ISD::SETCC, VT, Custom);
162   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
163   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
164   if (ElemTy == MVT::i32) {
165     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
166     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
167     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
168     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
169   } else {
170     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
171     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
172     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
173     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
174   }
175   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
176   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
177   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
178   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
179   setOperationAction(ISD::SELECT,            VT, Expand);
180   setOperationAction(ISD::SELECT_CC,         VT, Expand);
181   setOperationAction(ISD::VSELECT,           VT, Expand);
182   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
183   if (VT.isInteger()) {
184     setOperationAction(ISD::SHL, VT, Custom);
185     setOperationAction(ISD::SRA, VT, Custom);
186     setOperationAction(ISD::SRL, VT, Custom);
187   }
188 
189   // Promote all bit-wise operations.
190   if (VT.isInteger() && VT != PromotedBitwiseVT) {
191     setOperationAction(ISD::AND, VT, Promote);
192     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
193     setOperationAction(ISD::OR,  VT, Promote);
194     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
195     setOperationAction(ISD::XOR, VT, Promote);
196     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
197   }
198 
199   // Neon does not support vector divide/remainder operations.
200   setOperationAction(ISD::SDIV, VT, Expand);
201   setOperationAction(ISD::UDIV, VT, Expand);
202   setOperationAction(ISD::FDIV, VT, Expand);
203   setOperationAction(ISD::SREM, VT, Expand);
204   setOperationAction(ISD::UREM, VT, Expand);
205   setOperationAction(ISD::FREM, VT, Expand);
206 
207   if (!VT.isFloatingPoint() &&
208       VT != MVT::v2i64 && VT != MVT::v1i64)
209     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
210       setOperationAction(Opcode, VT, Legal);
211 }
212 
213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
214   addRegisterClass(VT, &ARM::DPRRegClass);
215   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
216 }
217 
218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
219   addRegisterClass(VT, &ARM::DPairRegClass);
220   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
221 }
222 
223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
224                                      const ARMSubtarget &STI)
225     : TargetLowering(TM), Subtarget(&STI) {
226   RegInfo = Subtarget->getRegisterInfo();
227   Itins = Subtarget->getInstrItineraryData();
228 
229   setBooleanContents(ZeroOrOneBooleanContent);
230   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 
232   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
233       !Subtarget->isTargetWatchOS()) {
234     const auto &E = Subtarget->getTargetTriple().getEnvironment();
235 
236     bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
237                       E == Triple::MuslEABIHF;
238     // Windows is a special case.  Technically, we will replace all of the "GNU"
239     // calls with calls to MSVCRT if appropriate and adjust the calling
240     // convention then.
241     IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
242 
243     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
244       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
245                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
246                                        : CallingConv::ARM_AAPCS);
247   }
248 
249   if (Subtarget->isTargetMachO()) {
250     // Uses VFP for Thumb libfuncs if available.
251     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
252         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
253       static const struct {
254         const RTLIB::Libcall Op;
255         const char * const Name;
256         const ISD::CondCode Cond;
257       } LibraryCalls[] = {
258         // Single-precision floating-point arithmetic.
259         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
262         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
263 
264         // Double-precision floating-point arithmetic.
265         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
266         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
267         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
268         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
269 
270         // Single-precision comparisons.
271         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
272         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
273         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
274         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
275         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
276         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
277         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
278         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
279 
280         // Double-precision comparisons.
281         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
282         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
283         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
284         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
285         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
286         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
287         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
288         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
289 
290         // Floating-point to integer conversions.
291         // i64 conversions are done via library routines even when generating VFP
292         // instructions, so use the same ones.
293         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
294         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
295         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
296         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
297 
298         // Conversions between floating types.
299         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
300         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
301 
302         // Integer to floating-point conversions.
303         // i64 conversions are done via library routines even when generating VFP
304         // instructions, so use the same ones.
305         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
306         // e.g., __floatunsidf vs. __floatunssidfvfp.
307         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
308         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
309         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
310         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
311       };
312 
313       for (const auto &LC : LibraryCalls) {
314         setLibcallName(LC.Op, LC.Name);
315         if (LC.Cond != ISD::SETCC_INVALID)
316           setCmpLibcallCC(LC.Op, LC.Cond);
317       }
318     }
319 
320     // Set the correct calling convention for ARMv7k WatchOS. It's just
321     // AAPCS_VFP for functions as simple as libcalls.
322     if (Subtarget->isTargetWatchABI()) {
323       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
324         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
325     }
326   }
327 
328   // These libcalls are not available in 32-bit.
329   setLibcallName(RTLIB::SHL_I128, nullptr);
330   setLibcallName(RTLIB::SRL_I128, nullptr);
331   setLibcallName(RTLIB::SRA_I128, nullptr);
332 
333   // RTLIB
334   if (Subtarget->isAAPCS_ABI() &&
335       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
336        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
337     static const struct {
338       const RTLIB::Libcall Op;
339       const char * const Name;
340       const CallingConv::ID CC;
341       const ISD::CondCode Cond;
342     } LibraryCalls[] = {
343       // Double-precision floating-point arithmetic helper functions
344       // RTABI chapter 4.1.2, Table 2
345       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 
350       // Double-precision floating-point comparison helper functions
351       // RTABI chapter 4.1.2, Table 3
352       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
353       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
354       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
355       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
356       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
357       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
358       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
359       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
360 
361       // Single-precision floating-point arithmetic helper functions
362       // RTABI chapter 4.1.2, Table 4
363       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
364       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
365       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367 
368       // Single-precision floating-point comparison helper functions
369       // RTABI chapter 4.1.2, Table 5
370       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
371       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
372       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
373       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
374       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
375       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
376       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
377       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
378 
379       // Floating-point to integer conversions.
380       // RTABI chapter 4.1.2, Table 6
381       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389 
390       // Conversions between floating types.
391       // RTABI chapter 4.1.2, Table 7
392       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395 
396       // Integer to floating-point conversions.
397       // RTABI chapter 4.1.2, Table 8
398       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
402       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406 
407       // Long long helper functions
408       // RTABI chapter 4.2, Table 9
409       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413 
414       // Integer division functions
415       // RTABI chapter 4.3.1
416       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
419       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
420       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
421       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
422       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
423       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
424     };
425 
426     for (const auto &LC : LibraryCalls) {
427       setLibcallName(LC.Op, LC.Name);
428       setLibcallCallingConv(LC.Op, LC.CC);
429       if (LC.Cond != ISD::SETCC_INVALID)
430         setCmpLibcallCC(LC.Op, LC.Cond);
431     }
432 
433     // EABI dependent RTLIB
434     if (TM.Options.EABIVersion == EABI::EABI4 ||
435         TM.Options.EABIVersion == EABI::EABI5) {
436       static const struct {
437         const RTLIB::Libcall Op;
438         const char *const Name;
439         const CallingConv::ID CC;
440         const ISD::CondCode Cond;
441       } MemOpsLibraryCalls[] = {
442         // Memory operations
443         // RTABI chapter 4.3.4
444         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
445         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
446         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
447       };
448 
449       for (const auto &LC : MemOpsLibraryCalls) {
450         setLibcallName(LC.Op, LC.Name);
451         setLibcallCallingConv(LC.Op, LC.CC);
452         if (LC.Cond != ISD::SETCC_INVALID)
453           setCmpLibcallCC(LC.Op, LC.Cond);
454       }
455     }
456   }
457 
458   if (Subtarget->isTargetWindows()) {
459     static const struct {
460       const RTLIB::Libcall Op;
461       const char * const Name;
462       const CallingConv::ID CC;
463     } LibraryCalls[] = {
464       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
465       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
466       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
467       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
468       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
469       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
470       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
471       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
472     };
473 
474     for (const auto &LC : LibraryCalls) {
475       setLibcallName(LC.Op, LC.Name);
476       setLibcallCallingConv(LC.Op, LC.CC);
477     }
478   }
479 
480   // Use divmod compiler-rt calls for iOS 5.0 and later.
481   if (Subtarget->isTargetMachO() &&
482       !(Subtarget->isTargetIOS() &&
483         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
484     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
485     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
486   }
487 
488   // The half <-> float conversion functions are always soft-float on
489   // non-watchos platforms, but are needed for some targets which use a
490   // hard-float calling convention by default.
491   if (!Subtarget->isTargetWatchABI()) {
492     if (Subtarget->isAAPCS_ABI()) {
493       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
494       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
495       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
496     } else {
497       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
498       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
499       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
500     }
501   }
502 
503   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
504   // a __gnu_ prefix (which is the default).
505   if (Subtarget->isTargetAEABI()) {
506     static const struct {
507       const RTLIB::Libcall Op;
508       const char * const Name;
509       const CallingConv::ID CC;
510     } LibraryCalls[] = {
511       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
512       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
513       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
514     };
515 
516     for (const auto &LC : LibraryCalls) {
517       setLibcallName(LC.Op, LC.Name);
518       setLibcallCallingConv(LC.Op, LC.CC);
519     }
520   }
521 
522   if (Subtarget->isThumb1Only())
523     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
524   else
525     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
526 
527   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
528       !Subtarget->isThumb1Only()) {
529     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
530     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
531   }
532 
533   for (MVT VT : MVT::vector_valuetypes()) {
534     for (MVT InnerVT : MVT::vector_valuetypes()) {
535       setTruncStoreAction(VT, InnerVT, Expand);
536       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
537       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
538       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
539     }
540 
541     setOperationAction(ISD::MULHS, VT, Expand);
542     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
543     setOperationAction(ISD::MULHU, VT, Expand);
544     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
545 
546     setOperationAction(ISD::BSWAP, VT, Expand);
547   }
548 
549   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
550   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
551 
552   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
553   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
554 
555   if (Subtarget->hasNEON()) {
556     addDRTypeForNEON(MVT::v2f32);
557     addDRTypeForNEON(MVT::v8i8);
558     addDRTypeForNEON(MVT::v4i16);
559     addDRTypeForNEON(MVT::v2i32);
560     addDRTypeForNEON(MVT::v1i64);
561 
562     addQRTypeForNEON(MVT::v4f32);
563     addQRTypeForNEON(MVT::v2f64);
564     addQRTypeForNEON(MVT::v16i8);
565     addQRTypeForNEON(MVT::v8i16);
566     addQRTypeForNEON(MVT::v4i32);
567     addQRTypeForNEON(MVT::v2i64);
568 
569     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
570     // neither Neon nor VFP support any arithmetic operations on it.
571     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
572     // supported for v4f32.
573     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
574     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
575     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
576     // FIXME: Code duplication: FDIV and FREM are expanded always, see
577     // ARMTargetLowering::addTypeForNEON method for details.
578     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
579     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
580     // FIXME: Create unittest.
581     // In another words, find a way when "copysign" appears in DAG with vector
582     // operands.
583     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
584     // FIXME: Code duplication: SETCC has custom operation action, see
585     // ARMTargetLowering::addTypeForNEON method for details.
586     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
587     // FIXME: Create unittest for FNEG and for FABS.
588     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
589     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
590     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
591     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
592     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
593     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
594     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
595     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
596     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
597     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
598     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
599     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
600     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
601     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
602     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
603     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
604     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
605     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
606 
607     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
608     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
609     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
610     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
611     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
612     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
613     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
614     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
615     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
616     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
617     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
618     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
619     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
620     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
621 
622     // Mark v2f32 intrinsics.
623     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
624     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
625     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
626     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
627     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
628     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
629     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
630     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
631     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
632     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
633     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
634     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
635     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
636     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
637 
638     // Neon does not support some operations on v1i64 and v2i64 types.
639     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
640     // Custom handling for some quad-vector types to detect VMULL.
641     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
642     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
643     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
644     // Custom handling for some vector types to avoid expensive expansions
645     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
646     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
647     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
648     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
649     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
650     // a destination type that is wider than the source, and nor does
651     // it have a FP_TO_[SU]INT instruction with a narrower destination than
652     // source.
653     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
654     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
655     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
656     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
657 
658     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
659     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
660 
661     // NEON does not have single instruction CTPOP for vectors with element
662     // types wider than 8-bits.  However, custom lowering can leverage the
663     // v8i8/v16i8 vcnt instruction.
664     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
665     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
666     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
667     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
668     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
669     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
670 
671     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
672     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
673 
674     // NEON does not have single instruction CTTZ for vectors.
675     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
676     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
677     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
678     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
679 
680     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
681     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
682     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
683     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
684 
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
686     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
687     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
689 
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
691     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
692     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
693     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
694 
695     // NEON only has FMA instructions as of VFP4.
696     if (!Subtarget->hasVFP4()) {
697       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
698       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
699     }
700 
701     setTargetDAGCombine(ISD::INTRINSIC_VOID);
702     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
703     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
704     setTargetDAGCombine(ISD::SHL);
705     setTargetDAGCombine(ISD::SRL);
706     setTargetDAGCombine(ISD::SRA);
707     setTargetDAGCombine(ISD::SIGN_EXTEND);
708     setTargetDAGCombine(ISD::ZERO_EXTEND);
709     setTargetDAGCombine(ISD::ANY_EXTEND);
710     setTargetDAGCombine(ISD::BUILD_VECTOR);
711     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
712     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
713     setTargetDAGCombine(ISD::STORE);
714     setTargetDAGCombine(ISD::FP_TO_SINT);
715     setTargetDAGCombine(ISD::FP_TO_UINT);
716     setTargetDAGCombine(ISD::FDIV);
717     setTargetDAGCombine(ISD::LOAD);
718 
719     // It is legal to extload from v4i8 to v4i16 or v4i32.
720     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
721                    MVT::v2i32}) {
722       for (MVT VT : MVT::integer_vector_valuetypes()) {
723         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
724         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
725         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
726       }
727     }
728   }
729 
730   if (Subtarget->isFPOnlySP()) {
731     // When targeting a floating-point unit with only single-precision
732     // operations, f64 is legal for the few double-precision instructions which
733     // are present However, no double-precision operations other than moves,
734     // loads and stores are provided by the hardware.
735     setOperationAction(ISD::FADD,       MVT::f64, Expand);
736     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
737     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
738     setOperationAction(ISD::FMA,        MVT::f64, Expand);
739     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
740     setOperationAction(ISD::FREM,       MVT::f64, Expand);
741     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
742     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
743     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
744     setOperationAction(ISD::FABS,       MVT::f64, Expand);
745     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
746     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
747     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
748     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
749     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
750     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
751     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
752     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
753     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
754     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
755     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
756     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
757     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
758     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
759     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
760     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
761     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
762     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
763     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
764     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
765     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
766     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
767   }
768 
769   computeRegisterProperties(Subtarget->getRegisterInfo());
770 
771   // ARM does not have floating-point extending loads.
772   for (MVT VT : MVT::fp_valuetypes()) {
773     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
774     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
775   }
776 
777   // ... or truncating stores
778   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
779   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
780   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
781 
782   // ARM does not have i1 sign extending load.
783   for (MVT VT : MVT::integer_valuetypes())
784     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
785 
786   // ARM supports all 4 flavors of integer indexed load / store.
787   if (!Subtarget->isThumb1Only()) {
788     for (unsigned im = (unsigned)ISD::PRE_INC;
789          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
790       setIndexedLoadAction(im,  MVT::i1,  Legal);
791       setIndexedLoadAction(im,  MVT::i8,  Legal);
792       setIndexedLoadAction(im,  MVT::i16, Legal);
793       setIndexedLoadAction(im,  MVT::i32, Legal);
794       setIndexedStoreAction(im, MVT::i1,  Legal);
795       setIndexedStoreAction(im, MVT::i8,  Legal);
796       setIndexedStoreAction(im, MVT::i16, Legal);
797       setIndexedStoreAction(im, MVT::i32, Legal);
798     }
799   } else {
800     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
801     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
802     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
803   }
804 
805   setOperationAction(ISD::SADDO, MVT::i32, Custom);
806   setOperationAction(ISD::UADDO, MVT::i32, Custom);
807   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
808   setOperationAction(ISD::USUBO, MVT::i32, Custom);
809 
810   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
811   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
812 
813   // i64 operation support.
814   setOperationAction(ISD::MUL,     MVT::i64, Expand);
815   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
816   if (Subtarget->isThumb1Only()) {
817     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
818     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
819   }
820   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
821       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
822     setOperationAction(ISD::MULHS, MVT::i32, Expand);
823 
824   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
825   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
826   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
827   setOperationAction(ISD::SRL,       MVT::i64, Custom);
828   setOperationAction(ISD::SRA,       MVT::i64, Custom);
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
830 
831   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
832   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
833   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
834   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
835 
836   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
837     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
838 
839   // ARM does not have ROTL.
840   setOperationAction(ISD::ROTL, MVT::i32, Expand);
841   for (MVT VT : MVT::vector_valuetypes()) {
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844   }
845   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
846   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
847   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
848     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
849 
850   // @llvm.readcyclecounter requires the Performance Monitors extension.
851   // Default to the 0 expansion on unsupported platforms.
852   // FIXME: Technically there are older ARM CPUs that have
853   // implementation-specific ways of obtaining this information.
854   if (Subtarget->hasPerfMon())
855     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
856 
857   // Only ARMv6 has BSWAP.
858   if (!Subtarget->hasV6Ops())
859     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
860 
861   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
862                                         : Subtarget->hasDivideInARMMode();
863   if (!hasDivide) {
864     // These are expanded into libcalls if the cpu doesn't have HW divider.
865     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
866     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
867   }
868 
869   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
870     setOperationAction(ISD::SDIV, MVT::i32, Custom);
871     setOperationAction(ISD::UDIV, MVT::i32, Custom);
872 
873     setOperationAction(ISD::SDIV, MVT::i64, Custom);
874     setOperationAction(ISD::UDIV, MVT::i64, Custom);
875   }
876 
877   setOperationAction(ISD::SREM,  MVT::i32, Expand);
878   setOperationAction(ISD::UREM,  MVT::i32, Expand);
879 
880   // Register based DivRem for AEABI (RTABI 4.2)
881   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
882       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
883       Subtarget->isTargetWindows()) {
884     setOperationAction(ISD::SREM, MVT::i64, Custom);
885     setOperationAction(ISD::UREM, MVT::i64, Custom);
886     HasStandaloneRem = false;
887 
888     if (Subtarget->isTargetWindows()) {
889       const struct {
890         const RTLIB::Libcall Op;
891         const char * const Name;
892         const CallingConv::ID CC;
893       } LibraryCalls[] = {
894         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
895         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
896         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
897         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
898 
899         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
900         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
901         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
902         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
903       };
904 
905       for (const auto &LC : LibraryCalls) {
906         setLibcallName(LC.Op, LC.Name);
907         setLibcallCallingConv(LC.Op, LC.CC);
908       }
909     } else {
910       const struct {
911         const RTLIB::Libcall Op;
912         const char * const Name;
913         const CallingConv::ID CC;
914       } LibraryCalls[] = {
915         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
916         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
918         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
919 
920         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
921         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
922         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
923         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
924       };
925 
926       for (const auto &LC : LibraryCalls) {
927         setLibcallName(LC.Op, LC.Name);
928         setLibcallCallingConv(LC.Op, LC.CC);
929       }
930     }
931 
932     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
933     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
934     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
935     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
936   } else {
937     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
938     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
939   }
940 
941   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
942     for (auto &VT : {MVT::f32, MVT::f64})
943       setOperationAction(ISD::FPOWI, VT, Custom);
944 
945   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
946   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
947   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
948   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
949 
950   setOperationAction(ISD::TRAP, MVT::Other, Legal);
951 
952   // Use the default implementation.
953   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
954   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
955   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
956   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
957   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
958   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
959 
960   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
961     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
962   else
963     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
964 
965   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
966   // the default expansion.
967   InsertFencesForAtomic = false;
968   if (Subtarget->hasAnyDataBarrier() &&
969       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
970     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
971     // to ldrex/strex loops already.
972     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
973     if (!Subtarget->isThumb() || !Subtarget->isMClass())
974       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
975 
976     // On v8, we have particularly efficient implementations of atomic fences
977     // if they can be combined with nearby atomic loads and stores.
978     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
979       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
980       InsertFencesForAtomic = true;
981     }
982   } else {
983     // If there's anything we can use as a barrier, go through custom lowering
984     // for ATOMIC_FENCE.
985     // If target has DMB in thumb, Fences can be inserted.
986     if (Subtarget->hasDataBarrier())
987       InsertFencesForAtomic = true;
988 
989     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
990                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
991 
992     // Set them all for expansion, which will force libcalls.
993     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1001     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1002     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1003     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1004     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1005     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1006     // Unordered/Monotonic case.
1007     if (!InsertFencesForAtomic) {
1008       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1009       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1010     }
1011   }
1012 
1013   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1014 
1015   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1016   if (!Subtarget->hasV6Ops()) {
1017     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1018     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1019   }
1020   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1021 
1022   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1023       !Subtarget->isThumb1Only()) {
1024     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1025     // iff target supports vfp2.
1026     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1027     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1028   }
1029 
1030   // We want to custom lower some of our intrinsics.
1031   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1032   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1033   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1034   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1035   if (Subtarget->useSjLjEH())
1036     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1037 
1038   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1039   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1040   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1041   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1042   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1043   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1044   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1045   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1046   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1047 
1048   // Thumb-1 cannot currently select ARMISD::SUBE.
1049   if (!Subtarget->isThumb1Only())
1050     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1051 
1052   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1053   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1054   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1055   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1056   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1057 
1058   // We don't support sin/cos/fmod/copysign/pow
1059   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1060   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1061   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1062   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1063   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1064   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1065   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1066   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1067   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1068       !Subtarget->isThumb1Only()) {
1069     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1070     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1071   }
1072   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1073   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1074 
1075   if (!Subtarget->hasVFP4()) {
1076     setOperationAction(ISD::FMA, MVT::f64, Expand);
1077     setOperationAction(ISD::FMA, MVT::f32, Expand);
1078   }
1079 
1080   // Various VFP goodness
1081   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1082     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1083     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1084       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1085       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1086     }
1087 
1088     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1089     if (!Subtarget->hasFP16()) {
1090       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1091       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1092     }
1093   }
1094 
1095   // Combine sin / cos into one node or libcall if possible.
1096   if (Subtarget->hasSinCos()) {
1097     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1098     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1099     if (Subtarget->isTargetWatchABI()) {
1100       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1101       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1102     }
1103     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1104       // For iOS, we don't want to the normal expansion of a libcall to
1105       // sincos. We want to issue a libcall to __sincos_stret.
1106       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1107       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1108     }
1109   }
1110 
1111   // FP-ARMv8 implements a lot of rounding-like FP operations.
1112   if (Subtarget->hasFPARMv8()) {
1113     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1114     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1115     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1116     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1117     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1118     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1119     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1120     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1121     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1122     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1123     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1124     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1125 
1126     if (!Subtarget->isFPOnlySP()) {
1127       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1128       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1129       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1130       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1131       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1132       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1133       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1134       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1135     }
1136   }
1137 
1138   if (Subtarget->hasNEON()) {
1139     // vmin and vmax aren't available in a scalar form, so we use
1140     // a NEON instruction with an undef lane instead.
1141     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1142     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1143     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1144     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1145     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1146     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1147   }
1148 
1149   // We have target-specific dag combine patterns for the following nodes:
1150   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1151   setTargetDAGCombine(ISD::ADD);
1152   setTargetDAGCombine(ISD::SUB);
1153   setTargetDAGCombine(ISD::MUL);
1154   setTargetDAGCombine(ISD::AND);
1155   setTargetDAGCombine(ISD::OR);
1156   setTargetDAGCombine(ISD::XOR);
1157 
1158   if (Subtarget->hasV6Ops())
1159     setTargetDAGCombine(ISD::SRL);
1160 
1161   setStackPointerRegisterToSaveRestore(ARM::SP);
1162 
1163   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1164       !Subtarget->hasVFP2())
1165     setSchedulingPreference(Sched::RegPressure);
1166   else
1167     setSchedulingPreference(Sched::Hybrid);
1168 
1169   //// temporary - rewrite interface to use type
1170   MaxStoresPerMemset = 8;
1171   MaxStoresPerMemsetOptSize = 4;
1172   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1173   MaxStoresPerMemcpyOptSize = 2;
1174   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1175   MaxStoresPerMemmoveOptSize = 2;
1176 
1177   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1178   // are at least 4 bytes aligned.
1179   setMinStackArgumentAlignment(4);
1180 
1181   // Prefer likely predicted branches to selects on out-of-order cores.
1182   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1183 
1184   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1185 }
1186 
1187 bool ARMTargetLowering::useSoftFloat() const {
1188   return Subtarget->useSoftFloat();
1189 }
1190 
1191 // FIXME: It might make sense to define the representative register class as the
1192 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1193 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1194 // SPR's representative would be DPR_VFP2. This should work well if register
1195 // pressure tracking were modified such that a register use would increment the
1196 // pressure of the register class's representative and all of it's super
1197 // classes' representatives transitively. We have not implemented this because
1198 // of the difficulty prior to coalescing of modeling operand register classes
1199 // due to the common occurrence of cross class copies and subregister insertions
1200 // and extractions.
1201 std::pair<const TargetRegisterClass *, uint8_t>
1202 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1203                                            MVT VT) const {
1204   const TargetRegisterClass *RRC = nullptr;
1205   uint8_t Cost = 1;
1206   switch (VT.SimpleTy) {
1207   default:
1208     return TargetLowering::findRepresentativeClass(TRI, VT);
1209   // Use DPR as representative register class for all floating point
1210   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1211   // the cost is 1 for both f32 and f64.
1212   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1213   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1214     RRC = &ARM::DPRRegClass;
1215     // When NEON is used for SP, only half of the register file is available
1216     // because operations that define both SP and DP results will be constrained
1217     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1218     // coalescing by double-counting the SP regs. See the FIXME above.
1219     if (Subtarget->useNEONForSinglePrecisionFP())
1220       Cost = 2;
1221     break;
1222   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1223   case MVT::v4f32: case MVT::v2f64:
1224     RRC = &ARM::DPRRegClass;
1225     Cost = 2;
1226     break;
1227   case MVT::v4i64:
1228     RRC = &ARM::DPRRegClass;
1229     Cost = 4;
1230     break;
1231   case MVT::v8i64:
1232     RRC = &ARM::DPRRegClass;
1233     Cost = 8;
1234     break;
1235   }
1236   return std::make_pair(RRC, Cost);
1237 }
1238 
1239 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1240   switch ((ARMISD::NodeType)Opcode) {
1241   case ARMISD::FIRST_NUMBER:  break;
1242   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1243   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1244   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1245   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1246   case ARMISD::CALL:          return "ARMISD::CALL";
1247   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1248   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1249   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1250   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1251   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1252   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1253   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1254   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1255   case ARMISD::CMP:           return "ARMISD::CMP";
1256   case ARMISD::CMN:           return "ARMISD::CMN";
1257   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1258   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1259   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1260   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1261   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1262 
1263   case ARMISD::CMOV:          return "ARMISD::CMOV";
1264 
1265   case ARMISD::SSAT:          return "ARMISD::SSAT";
1266 
1267   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1268   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1269   case ARMISD::RRX:           return "ARMISD::RRX";
1270 
1271   case ARMISD::ADDC:          return "ARMISD::ADDC";
1272   case ARMISD::ADDE:          return "ARMISD::ADDE";
1273   case ARMISD::SUBC:          return "ARMISD::SUBC";
1274   case ARMISD::SUBE:          return "ARMISD::SUBE";
1275 
1276   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1277   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1278 
1279   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1280   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1281   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1282 
1283   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1284 
1285   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1286 
1287   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1288 
1289   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1290 
1291   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1292 
1293   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1294   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1295 
1296   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1297   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1298   case ARMISD::VCGE:          return "ARMISD::VCGE";
1299   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1300   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1301   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1302   case ARMISD::VCGT:          return "ARMISD::VCGT";
1303   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1304   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1305   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1306   case ARMISD::VTST:          return "ARMISD::VTST";
1307 
1308   case ARMISD::VSHL:          return "ARMISD::VSHL";
1309   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1310   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1311   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1312   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1313   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1314   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1315   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1316   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1317   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1318   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1319   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1320   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1321   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1322   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1323   case ARMISD::VSLI:          return "ARMISD::VSLI";
1324   case ARMISD::VSRI:          return "ARMISD::VSRI";
1325   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1326   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1327   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1328   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1329   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1330   case ARMISD::VDUP:          return "ARMISD::VDUP";
1331   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1332   case ARMISD::VEXT:          return "ARMISD::VEXT";
1333   case ARMISD::VREV64:        return "ARMISD::VREV64";
1334   case ARMISD::VREV32:        return "ARMISD::VREV32";
1335   case ARMISD::VREV16:        return "ARMISD::VREV16";
1336   case ARMISD::VZIP:          return "ARMISD::VZIP";
1337   case ARMISD::VUZP:          return "ARMISD::VUZP";
1338   case ARMISD::VTRN:          return "ARMISD::VTRN";
1339   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1340   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1341   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1342   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1343   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1344   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1345   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1346   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1347   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1348   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1349   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1350   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1351   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1352   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1353   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1354   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1355   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1356   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1357   case ARMISD::BFI:           return "ARMISD::BFI";
1358   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1359   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1360   case ARMISD::VBSL:          return "ARMISD::VBSL";
1361   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1362   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1363   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1364   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1365   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1366   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1367   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1368   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1369   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1370   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1371   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1372   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1373   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1374   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1375   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1376   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1377   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1378   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1379   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1380   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1381   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1382   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1383   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1384   }
1385   return nullptr;
1386 }
1387 
1388 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1389                                           EVT VT) const {
1390   if (!VT.isVector())
1391     return getPointerTy(DL);
1392   return VT.changeVectorElementTypeToInteger();
1393 }
1394 
1395 /// getRegClassFor - Return the register class that should be used for the
1396 /// specified value type.
1397 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1398   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1399   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1400   // load / store 4 to 8 consecutive D registers.
1401   if (Subtarget->hasNEON()) {
1402     if (VT == MVT::v4i64)
1403       return &ARM::QQPRRegClass;
1404     if (VT == MVT::v8i64)
1405       return &ARM::QQQQPRRegClass;
1406   }
1407   return TargetLowering::getRegClassFor(VT);
1408 }
1409 
1410 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1411 // source/dest is aligned and the copy size is large enough. We therefore want
1412 // to align such objects passed to memory intrinsics.
1413 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1414                                                unsigned &PrefAlign) const {
1415   if (!isa<MemIntrinsic>(CI))
1416     return false;
1417   MinSize = 8;
1418   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1419   // cycle faster than 4-byte aligned LDM.
1420   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1421   return true;
1422 }
1423 
1424 // Create a fast isel object.
1425 FastISel *
1426 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1427                                   const TargetLibraryInfo *libInfo) const {
1428   return ARM::createFastISel(funcInfo, libInfo);
1429 }
1430 
1431 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1432   unsigned NumVals = N->getNumValues();
1433   if (!NumVals)
1434     return Sched::RegPressure;
1435 
1436   for (unsigned i = 0; i != NumVals; ++i) {
1437     EVT VT = N->getValueType(i);
1438     if (VT == MVT::Glue || VT == MVT::Other)
1439       continue;
1440     if (VT.isFloatingPoint() || VT.isVector())
1441       return Sched::ILP;
1442   }
1443 
1444   if (!N->isMachineOpcode())
1445     return Sched::RegPressure;
1446 
1447   // Load are scheduled for latency even if there instruction itinerary
1448   // is not available.
1449   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1450   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1451 
1452   if (MCID.getNumDefs() == 0)
1453     return Sched::RegPressure;
1454   if (!Itins->isEmpty() &&
1455       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1456     return Sched::ILP;
1457 
1458   return Sched::RegPressure;
1459 }
1460 
1461 //===----------------------------------------------------------------------===//
1462 // Lowering Code
1463 //===----------------------------------------------------------------------===//
1464 
1465 static bool isSRL16(const SDValue &Op) {
1466   if (Op.getOpcode() != ISD::SRL)
1467     return false;
1468   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1469     return Const->getZExtValue() == 16;
1470   return false;
1471 }
1472 
1473 static bool isSRA16(const SDValue &Op) {
1474   if (Op.getOpcode() != ISD::SRA)
1475     return false;
1476   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1477     return Const->getZExtValue() == 16;
1478   return false;
1479 }
1480 
1481 static bool isSHL16(const SDValue &Op) {
1482   if (Op.getOpcode() != ISD::SHL)
1483     return false;
1484   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1485     return Const->getZExtValue() == 16;
1486   return false;
1487 }
1488 
1489 // Check for a signed 16-bit value. We special case SRA because it makes it
1490 // more simple when also looking for SRAs that aren't sign extending a
1491 // smaller value. Without the check, we'd need to take extra care with
1492 // checking order for some operations.
1493 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1494   if (isSRA16(Op))
1495     return isSHL16(Op.getOperand(0));
1496   return DAG.ComputeNumSignBits(Op) == 17;
1497 }
1498 
1499 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1500 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1501   switch (CC) {
1502   default: llvm_unreachable("Unknown condition code!");
1503   case ISD::SETNE:  return ARMCC::NE;
1504   case ISD::SETEQ:  return ARMCC::EQ;
1505   case ISD::SETGT:  return ARMCC::GT;
1506   case ISD::SETGE:  return ARMCC::GE;
1507   case ISD::SETLT:  return ARMCC::LT;
1508   case ISD::SETLE:  return ARMCC::LE;
1509   case ISD::SETUGT: return ARMCC::HI;
1510   case ISD::SETUGE: return ARMCC::HS;
1511   case ISD::SETULT: return ARMCC::LO;
1512   case ISD::SETULE: return ARMCC::LS;
1513   }
1514 }
1515 
1516 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1517 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1518                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1519   CondCode2 = ARMCC::AL;
1520   InvalidOnQNaN = true;
1521   switch (CC) {
1522   default: llvm_unreachable("Unknown FP condition!");
1523   case ISD::SETEQ:
1524   case ISD::SETOEQ:
1525     CondCode = ARMCC::EQ;
1526     InvalidOnQNaN = false;
1527     break;
1528   case ISD::SETGT:
1529   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1530   case ISD::SETGE:
1531   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1532   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1533   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1534   case ISD::SETONE:
1535     CondCode = ARMCC::MI;
1536     CondCode2 = ARMCC::GT;
1537     InvalidOnQNaN = false;
1538     break;
1539   case ISD::SETO:   CondCode = ARMCC::VC; break;
1540   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1541   case ISD::SETUEQ:
1542     CondCode = ARMCC::EQ;
1543     CondCode2 = ARMCC::VS;
1544     InvalidOnQNaN = false;
1545     break;
1546   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1547   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1548   case ISD::SETLT:
1549   case ISD::SETULT: CondCode = ARMCC::LT; break;
1550   case ISD::SETLE:
1551   case ISD::SETULE: CondCode = ARMCC::LE; break;
1552   case ISD::SETNE:
1553   case ISD::SETUNE:
1554     CondCode = ARMCC::NE;
1555     InvalidOnQNaN = false;
1556     break;
1557   }
1558 }
1559 
1560 //===----------------------------------------------------------------------===//
1561 //                      Calling Convention Implementation
1562 //===----------------------------------------------------------------------===//
1563 
1564 #include "ARMGenCallingConv.inc"
1565 
1566 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1567 /// account presence of floating point hardware and calling convention
1568 /// limitations, such as support for variadic functions.
1569 CallingConv::ID
1570 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1571                                            bool isVarArg) const {
1572   switch (CC) {
1573   default:
1574     report_fatal_error("Unsupported calling convention");
1575   case CallingConv::ARM_AAPCS:
1576   case CallingConv::ARM_APCS:
1577   case CallingConv::GHC:
1578     return CC;
1579   case CallingConv::PreserveMost:
1580     return CallingConv::PreserveMost;
1581   case CallingConv::ARM_AAPCS_VFP:
1582   case CallingConv::Swift:
1583     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1584   case CallingConv::C:
1585     if (!Subtarget->isAAPCS_ABI())
1586       return CallingConv::ARM_APCS;
1587     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1588              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1589              !isVarArg)
1590       return CallingConv::ARM_AAPCS_VFP;
1591     else
1592       return CallingConv::ARM_AAPCS;
1593   case CallingConv::Fast:
1594   case CallingConv::CXX_FAST_TLS:
1595     if (!Subtarget->isAAPCS_ABI()) {
1596       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1597         return CallingConv::Fast;
1598       return CallingConv::ARM_APCS;
1599     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1600       return CallingConv::ARM_AAPCS_VFP;
1601     else
1602       return CallingConv::ARM_AAPCS;
1603   }
1604 }
1605 
1606 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1607                                                  bool isVarArg) const {
1608   return CCAssignFnForNode(CC, false, isVarArg);
1609 }
1610 
1611 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1612                                                    bool isVarArg) const {
1613   return CCAssignFnForNode(CC, true, isVarArg);
1614 }
1615 
1616 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1617 /// CallingConvention.
1618 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1619                                                  bool Return,
1620                                                  bool isVarArg) const {
1621   switch (getEffectiveCallingConv(CC, isVarArg)) {
1622   default:
1623     report_fatal_error("Unsupported calling convention");
1624   case CallingConv::ARM_APCS:
1625     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1626   case CallingConv::ARM_AAPCS:
1627     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1628   case CallingConv::ARM_AAPCS_VFP:
1629     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1630   case CallingConv::Fast:
1631     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1632   case CallingConv::GHC:
1633     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1634   case CallingConv::PreserveMost:
1635     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1636   }
1637 }
1638 
1639 /// LowerCallResult - Lower the result values of a call into the
1640 /// appropriate copies out of appropriate physical registers.
1641 SDValue ARMTargetLowering::LowerCallResult(
1642     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1643     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1644     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1645     SDValue ThisVal) const {
1646   // Assign locations to each value returned by this call.
1647   SmallVector<CCValAssign, 16> RVLocs;
1648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1649                  *DAG.getContext());
1650   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1651 
1652   // Copy all of the result registers out of their specified physreg.
1653   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1654     CCValAssign VA = RVLocs[i];
1655 
1656     // Pass 'this' value directly from the argument to return value, to avoid
1657     // reg unit interference
1658     if (i == 0 && isThisReturn) {
1659       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1660              "unexpected return calling convention register assignment");
1661       InVals.push_back(ThisVal);
1662       continue;
1663     }
1664 
1665     SDValue Val;
1666     if (VA.needsCustom()) {
1667       // Handle f64 or half of a v2f64.
1668       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1669                                       InFlag);
1670       Chain = Lo.getValue(1);
1671       InFlag = Lo.getValue(2);
1672       VA = RVLocs[++i]; // skip ahead to next loc
1673       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1674                                       InFlag);
1675       Chain = Hi.getValue(1);
1676       InFlag = Hi.getValue(2);
1677       if (!Subtarget->isLittle())
1678         std::swap (Lo, Hi);
1679       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1680 
1681       if (VA.getLocVT() == MVT::v2f64) {
1682         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1683         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1684                           DAG.getConstant(0, dl, MVT::i32));
1685 
1686         VA = RVLocs[++i]; // skip ahead to next loc
1687         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1688         Chain = Lo.getValue(1);
1689         InFlag = Lo.getValue(2);
1690         VA = RVLocs[++i]; // skip ahead to next loc
1691         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1692         Chain = Hi.getValue(1);
1693         InFlag = Hi.getValue(2);
1694         if (!Subtarget->isLittle())
1695           std::swap (Lo, Hi);
1696         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1697         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1698                           DAG.getConstant(1, dl, MVT::i32));
1699       }
1700     } else {
1701       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1702                                InFlag);
1703       Chain = Val.getValue(1);
1704       InFlag = Val.getValue(2);
1705     }
1706 
1707     switch (VA.getLocInfo()) {
1708     default: llvm_unreachable("Unknown loc info!");
1709     case CCValAssign::Full: break;
1710     case CCValAssign::BCvt:
1711       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1712       break;
1713     }
1714 
1715     InVals.push_back(Val);
1716   }
1717 
1718   return Chain;
1719 }
1720 
1721 /// LowerMemOpCallTo - Store the argument to the stack.
1722 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1723                                             SDValue Arg, const SDLoc &dl,
1724                                             SelectionDAG &DAG,
1725                                             const CCValAssign &VA,
1726                                             ISD::ArgFlagsTy Flags) const {
1727   unsigned LocMemOffset = VA.getLocMemOffset();
1728   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1729   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1730                        StackPtr, PtrOff);
1731   return DAG.getStore(
1732       Chain, dl, Arg, PtrOff,
1733       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1734 }
1735 
1736 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1737                                          SDValue Chain, SDValue &Arg,
1738                                          RegsToPassVector &RegsToPass,
1739                                          CCValAssign &VA, CCValAssign &NextVA,
1740                                          SDValue &StackPtr,
1741                                          SmallVectorImpl<SDValue> &MemOpChains,
1742                                          ISD::ArgFlagsTy Flags) const {
1743   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1744                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1745   unsigned id = Subtarget->isLittle() ? 0 : 1;
1746   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1747 
1748   if (NextVA.isRegLoc())
1749     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1750   else {
1751     assert(NextVA.isMemLoc());
1752     if (!StackPtr.getNode())
1753       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1754                                     getPointerTy(DAG.getDataLayout()));
1755 
1756     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1757                                            dl, DAG, NextVA,
1758                                            Flags));
1759   }
1760 }
1761 
1762 /// LowerCall - Lowering a call into a callseq_start <-
1763 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1764 /// nodes.
1765 SDValue
1766 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1767                              SmallVectorImpl<SDValue> &InVals) const {
1768   SelectionDAG &DAG                     = CLI.DAG;
1769   SDLoc &dl                             = CLI.DL;
1770   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1771   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1772   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1773   SDValue Chain                         = CLI.Chain;
1774   SDValue Callee                        = CLI.Callee;
1775   bool &isTailCall                      = CLI.IsTailCall;
1776   CallingConv::ID CallConv              = CLI.CallConv;
1777   bool doesNotRet                       = CLI.DoesNotReturn;
1778   bool isVarArg                         = CLI.IsVarArg;
1779 
1780   MachineFunction &MF = DAG.getMachineFunction();
1781   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1782   bool isThisReturn   = false;
1783   bool isSibCall      = false;
1784   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1785 
1786   // Disable tail calls if they're not supported.
1787   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1788     isTailCall = false;
1789 
1790   if (isTailCall) {
1791     // Check if it's really possible to do a tail call.
1792     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1793                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1794                                                    Outs, OutVals, Ins, DAG);
1795     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1796       report_fatal_error("failed to perform tail call elimination on a call "
1797                          "site marked musttail");
1798     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1799     // detected sibcalls.
1800     if (isTailCall) {
1801       ++NumTailCalls;
1802       isSibCall = true;
1803     }
1804   }
1805 
1806   // Analyze operands of the call, assigning locations to each operand.
1807   SmallVector<CCValAssign, 16> ArgLocs;
1808   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1809                  *DAG.getContext());
1810   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1811 
1812   // Get a count of how many bytes are to be pushed on the stack.
1813   unsigned NumBytes = CCInfo.getNextStackOffset();
1814 
1815   // For tail calls, memory operands are available in our caller's stack.
1816   if (isSibCall)
1817     NumBytes = 0;
1818 
1819   // Adjust the stack pointer for the new arguments...
1820   // These operations are automatically eliminated by the prolog/epilog pass
1821   if (!isSibCall)
1822     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1823 
1824   SDValue StackPtr =
1825       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1826 
1827   RegsToPassVector RegsToPass;
1828   SmallVector<SDValue, 8> MemOpChains;
1829 
1830   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1831   // of tail call optimization, arguments are handled later.
1832   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1833        i != e;
1834        ++i, ++realArgIdx) {
1835     CCValAssign &VA = ArgLocs[i];
1836     SDValue Arg = OutVals[realArgIdx];
1837     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1838     bool isByVal = Flags.isByVal();
1839 
1840     // Promote the value if needed.
1841     switch (VA.getLocInfo()) {
1842     default: llvm_unreachable("Unknown loc info!");
1843     case CCValAssign::Full: break;
1844     case CCValAssign::SExt:
1845       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1846       break;
1847     case CCValAssign::ZExt:
1848       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1849       break;
1850     case CCValAssign::AExt:
1851       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1852       break;
1853     case CCValAssign::BCvt:
1854       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1855       break;
1856     }
1857 
1858     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1859     if (VA.needsCustom()) {
1860       if (VA.getLocVT() == MVT::v2f64) {
1861         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1862                                   DAG.getConstant(0, dl, MVT::i32));
1863         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1864                                   DAG.getConstant(1, dl, MVT::i32));
1865 
1866         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1867                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1868 
1869         VA = ArgLocs[++i]; // skip ahead to next loc
1870         if (VA.isRegLoc()) {
1871           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1872                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1873         } else {
1874           assert(VA.isMemLoc());
1875 
1876           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1877                                                  dl, DAG, VA, Flags));
1878         }
1879       } else {
1880         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1881                          StackPtr, MemOpChains, Flags);
1882       }
1883     } else if (VA.isRegLoc()) {
1884       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1885           Outs[0].VT == MVT::i32) {
1886         assert(VA.getLocVT() == MVT::i32 &&
1887                "unexpected calling convention register assignment");
1888         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1889                "unexpected use of 'returned'");
1890         isThisReturn = true;
1891       }
1892       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1893     } else if (isByVal) {
1894       assert(VA.isMemLoc());
1895       unsigned offset = 0;
1896 
1897       // True if this byval aggregate will be split between registers
1898       // and memory.
1899       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1900       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1901 
1902       if (CurByValIdx < ByValArgsCount) {
1903 
1904         unsigned RegBegin, RegEnd;
1905         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1906 
1907         EVT PtrVT =
1908             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1909         unsigned int i, j;
1910         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1911           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1912           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1913           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1914                                      MachinePointerInfo(),
1915                                      DAG.InferPtrAlignment(AddArg));
1916           MemOpChains.push_back(Load.getValue(1));
1917           RegsToPass.push_back(std::make_pair(j, Load));
1918         }
1919 
1920         // If parameter size outsides register area, "offset" value
1921         // helps us to calculate stack slot for remained part properly.
1922         offset = RegEnd - RegBegin;
1923 
1924         CCInfo.nextInRegsParam();
1925       }
1926 
1927       if (Flags.getByValSize() > 4*offset) {
1928         auto PtrVT = getPointerTy(DAG.getDataLayout());
1929         unsigned LocMemOffset = VA.getLocMemOffset();
1930         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1931         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1932         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1933         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1934         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1935                                            MVT::i32);
1936         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1937                                             MVT::i32);
1938 
1939         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1940         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1941         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1942                                           Ops));
1943       }
1944     } else if (!isSibCall) {
1945       assert(VA.isMemLoc());
1946 
1947       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1948                                              dl, DAG, VA, Flags));
1949     }
1950   }
1951 
1952   if (!MemOpChains.empty())
1953     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1954 
1955   // Build a sequence of copy-to-reg nodes chained together with token chain
1956   // and flag operands which copy the outgoing args into the appropriate regs.
1957   SDValue InFlag;
1958   // Tail call byval lowering might overwrite argument registers so in case of
1959   // tail call optimization the copies to registers are lowered later.
1960   if (!isTailCall)
1961     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1962       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1963                                RegsToPass[i].second, InFlag);
1964       InFlag = Chain.getValue(1);
1965     }
1966 
1967   // For tail calls lower the arguments to the 'real' stack slot.
1968   if (isTailCall) {
1969     // Force all the incoming stack arguments to be loaded from the stack
1970     // before any new outgoing arguments are stored to the stack, because the
1971     // outgoing stack slots may alias the incoming argument stack slots, and
1972     // the alias isn't otherwise explicit. This is slightly more conservative
1973     // than necessary, because it means that each store effectively depends
1974     // on every argument instead of just those arguments it would clobber.
1975 
1976     // Do not flag preceding copytoreg stuff together with the following stuff.
1977     InFlag = SDValue();
1978     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1979       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1980                                RegsToPass[i].second, InFlag);
1981       InFlag = Chain.getValue(1);
1982     }
1983     InFlag = SDValue();
1984   }
1985 
1986   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1987   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1988   // node so that legalize doesn't hack it.
1989   bool isDirect = false;
1990 
1991   const TargetMachine &TM = getTargetMachine();
1992   const Module *Mod = MF.getFunction()->getParent();
1993   const GlobalValue *GV = nullptr;
1994   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1995     GV = G->getGlobal();
1996   bool isStub =
1997       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1998 
1999   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2000   bool isLocalARMFunc = false;
2001   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2002   auto PtrVt = getPointerTy(DAG.getDataLayout());
2003 
2004   if (Subtarget->genLongCalls()) {
2005     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2006            "long-calls codegen is not position independent!");
2007     // Handle a global address or an external symbol. If it's not one of
2008     // those, the target's already in a register, so we don't need to do
2009     // anything extra.
2010     if (isa<GlobalAddressSDNode>(Callee)) {
2011       // Create a constant pool entry for the callee address
2012       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2013       ARMConstantPoolValue *CPV =
2014         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2015 
2016       // Get the address of the callee into a register
2017       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2018       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2019       Callee = DAG.getLoad(
2020           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2021           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2022     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2023       const char *Sym = S->getSymbol();
2024 
2025       // Create a constant pool entry for the callee address
2026       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2027       ARMConstantPoolValue *CPV =
2028         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2029                                       ARMPCLabelIndex, 0);
2030       // Get the address of the callee into a register
2031       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2032       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2033       Callee = DAG.getLoad(
2034           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2035           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2036     }
2037   } else if (isa<GlobalAddressSDNode>(Callee)) {
2038     // If we're optimizing for minimum size and the function is called three or
2039     // more times in this block, we can improve codesize by calling indirectly
2040     // as BLXr has a 16-bit encoding.
2041     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2042     auto *BB = CLI.CS.getParent();
2043     bool PreferIndirect =
2044         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2045         count_if(GV->users(), [&BB](const User *U) {
2046           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2047         }) > 2;
2048 
2049     if (!PreferIndirect) {
2050       isDirect = true;
2051       bool isDef = GV->isStrongDefinitionForLinker();
2052 
2053       // ARM call to a local ARM function is predicable.
2054       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2055       // tBX takes a register source operand.
2056       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2057         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2058         Callee = DAG.getNode(
2059             ARMISD::WrapperPIC, dl, PtrVt,
2060             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2061         Callee = DAG.getLoad(
2062             PtrVt, dl, DAG.getEntryNode(), Callee,
2063             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2064             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2065                                      MachineMemOperand::MOInvariant);
2066       } else if (Subtarget->isTargetCOFF()) {
2067         assert(Subtarget->isTargetWindows() &&
2068                "Windows is the only supported COFF target");
2069         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2070                                    ? ARMII::MO_DLLIMPORT
2071                                    : ARMII::MO_NO_FLAG;
2072         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2073                                             TargetFlags);
2074         if (GV->hasDLLImportStorageClass())
2075           Callee =
2076               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2077                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2078                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2079       } else {
2080         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2081       }
2082     }
2083   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2084     isDirect = true;
2085     // tBX takes a register source operand.
2086     const char *Sym = S->getSymbol();
2087     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2088       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2089       ARMConstantPoolValue *CPV =
2090         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2091                                       ARMPCLabelIndex, 4);
2092       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2093       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2094       Callee = DAG.getLoad(
2095           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2096           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2097       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2098       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2099     } else {
2100       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2101     }
2102   }
2103 
2104   // FIXME: handle tail calls differently.
2105   unsigned CallOpc;
2106   if (Subtarget->isThumb()) {
2107     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2108       CallOpc = ARMISD::CALL_NOLINK;
2109     else
2110       CallOpc = ARMISD::CALL;
2111   } else {
2112     if (!isDirect && !Subtarget->hasV5TOps())
2113       CallOpc = ARMISD::CALL_NOLINK;
2114     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2115              // Emit regular call when code size is the priority
2116              !MF.getFunction()->optForMinSize())
2117       // "mov lr, pc; b _foo" to avoid confusing the RSP
2118       CallOpc = ARMISD::CALL_NOLINK;
2119     else
2120       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2121   }
2122 
2123   std::vector<SDValue> Ops;
2124   Ops.push_back(Chain);
2125   Ops.push_back(Callee);
2126 
2127   // Add argument registers to the end of the list so that they are known live
2128   // into the call.
2129   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2130     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2131                                   RegsToPass[i].second.getValueType()));
2132 
2133   // Add a register mask operand representing the call-preserved registers.
2134   if (!isTailCall) {
2135     const uint32_t *Mask;
2136     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2137     if (isThisReturn) {
2138       // For 'this' returns, use the R0-preserving mask if applicable
2139       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2140       if (!Mask) {
2141         // Set isThisReturn to false if the calling convention is not one that
2142         // allows 'returned' to be modeled in this way, so LowerCallResult does
2143         // not try to pass 'this' straight through
2144         isThisReturn = false;
2145         Mask = ARI->getCallPreservedMask(MF, CallConv);
2146       }
2147     } else
2148       Mask = ARI->getCallPreservedMask(MF, CallConv);
2149 
2150     assert(Mask && "Missing call preserved mask for calling convention");
2151     Ops.push_back(DAG.getRegisterMask(Mask));
2152   }
2153 
2154   if (InFlag.getNode())
2155     Ops.push_back(InFlag);
2156 
2157   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2158   if (isTailCall) {
2159     MF.getFrameInfo().setHasTailCall();
2160     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2161   }
2162 
2163   // Returns a chain and a flag for retval copy to use.
2164   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2165   InFlag = Chain.getValue(1);
2166 
2167   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2168                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2169   if (!Ins.empty())
2170     InFlag = Chain.getValue(1);
2171 
2172   // Handle result values, copying them out of physregs into vregs that we
2173   // return.
2174   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2175                          InVals, isThisReturn,
2176                          isThisReturn ? OutVals[0] : SDValue());
2177 }
2178 
2179 /// HandleByVal - Every parameter *after* a byval parameter is passed
2180 /// on the stack.  Remember the next parameter register to allocate,
2181 /// and then confiscate the rest of the parameter registers to insure
2182 /// this.
2183 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2184                                     unsigned Align) const {
2185   // Byval (as with any stack) slots are always at least 4 byte aligned.
2186   Align = std::max(Align, 4U);
2187 
2188   unsigned Reg = State->AllocateReg(GPRArgRegs);
2189   if (!Reg)
2190     return;
2191 
2192   unsigned AlignInRegs = Align / 4;
2193   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2194   for (unsigned i = 0; i < Waste; ++i)
2195     Reg = State->AllocateReg(GPRArgRegs);
2196 
2197   if (!Reg)
2198     return;
2199 
2200   unsigned Excess = 4 * (ARM::R4 - Reg);
2201 
2202   // Special case when NSAA != SP and parameter size greater than size of
2203   // all remained GPR regs. In that case we can't split parameter, we must
2204   // send it to stack. We also must set NCRN to R4, so waste all
2205   // remained registers.
2206   const unsigned NSAAOffset = State->getNextStackOffset();
2207   if (NSAAOffset != 0 && Size > Excess) {
2208     while (State->AllocateReg(GPRArgRegs))
2209       ;
2210     return;
2211   }
2212 
2213   // First register for byval parameter is the first register that wasn't
2214   // allocated before this method call, so it would be "reg".
2215   // If parameter is small enough to be saved in range [reg, r4), then
2216   // the end (first after last) register would be reg + param-size-in-regs,
2217   // else parameter would be splitted between registers and stack,
2218   // end register would be r4 in this case.
2219   unsigned ByValRegBegin = Reg;
2220   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2221   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2222   // Note, first register is allocated in the beginning of function already,
2223   // allocate remained amount of registers we need.
2224   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2225     State->AllocateReg(GPRArgRegs);
2226   // A byval parameter that is split between registers and memory needs its
2227   // size truncated here.
2228   // In the case where the entire structure fits in registers, we set the
2229   // size in memory to zero.
2230   Size = std::max<int>(Size - Excess, 0);
2231 }
2232 
2233 /// MatchingStackOffset - Return true if the given stack call argument is
2234 /// already available in the same position (relatively) of the caller's
2235 /// incoming argument stack.
2236 static
2237 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2238                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2239                          const TargetInstrInfo *TII) {
2240   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2241   int FI = std::numeric_limits<int>::max();
2242   if (Arg.getOpcode() == ISD::CopyFromReg) {
2243     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2244     if (!TargetRegisterInfo::isVirtualRegister(VR))
2245       return false;
2246     MachineInstr *Def = MRI->getVRegDef(VR);
2247     if (!Def)
2248       return false;
2249     if (!Flags.isByVal()) {
2250       if (!TII->isLoadFromStackSlot(*Def, FI))
2251         return false;
2252     } else {
2253       return false;
2254     }
2255   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2256     if (Flags.isByVal())
2257       // ByVal argument is passed in as a pointer but it's now being
2258       // dereferenced. e.g.
2259       // define @foo(%struct.X* %A) {
2260       //   tail call @bar(%struct.X* byval %A)
2261       // }
2262       return false;
2263     SDValue Ptr = Ld->getBasePtr();
2264     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2265     if (!FINode)
2266       return false;
2267     FI = FINode->getIndex();
2268   } else
2269     return false;
2270 
2271   assert(FI != std::numeric_limits<int>::max());
2272   if (!MFI.isFixedObjectIndex(FI))
2273     return false;
2274   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2275 }
2276 
2277 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2278 /// for tail call optimization. Targets which want to do tail call
2279 /// optimization should implement this function.
2280 bool
2281 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2282                                                      CallingConv::ID CalleeCC,
2283                                                      bool isVarArg,
2284                                                      bool isCalleeStructRet,
2285                                                      bool isCallerStructRet,
2286                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2287                                     const SmallVectorImpl<SDValue> &OutVals,
2288                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2289                                                      SelectionDAG& DAG) const {
2290   MachineFunction &MF = DAG.getMachineFunction();
2291   const Function *CallerF = MF.getFunction();
2292   CallingConv::ID CallerCC = CallerF->getCallingConv();
2293 
2294   assert(Subtarget->supportsTailCall());
2295 
2296   // Look for obvious safe cases to perform tail call optimization that do not
2297   // require ABI changes. This is what gcc calls sibcall.
2298 
2299   // Exception-handling functions need a special set of instructions to indicate
2300   // a return to the hardware. Tail-calling another function would probably
2301   // break this.
2302   if (CallerF->hasFnAttribute("interrupt"))
2303     return false;
2304 
2305   // Also avoid sibcall optimization if either caller or callee uses struct
2306   // return semantics.
2307   if (isCalleeStructRet || isCallerStructRet)
2308     return false;
2309 
2310   // Externally-defined functions with weak linkage should not be
2311   // tail-called on ARM when the OS does not support dynamic
2312   // pre-emption of symbols, as the AAELF spec requires normal calls
2313   // to undefined weak functions to be replaced with a NOP or jump to the
2314   // next instruction. The behaviour of branch instructions in this
2315   // situation (as used for tail calls) is implementation-defined, so we
2316   // cannot rely on the linker replacing the tail call with a return.
2317   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2318     const GlobalValue *GV = G->getGlobal();
2319     const Triple &TT = getTargetMachine().getTargetTriple();
2320     if (GV->hasExternalWeakLinkage() &&
2321         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2322       return false;
2323   }
2324 
2325   // Check that the call results are passed in the same way.
2326   LLVMContext &C = *DAG.getContext();
2327   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2328                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2329                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2330     return false;
2331   // The callee has to preserve all registers the caller needs to preserve.
2332   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2333   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2334   if (CalleeCC != CallerCC) {
2335     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2336     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2337       return false;
2338   }
2339 
2340   // If Caller's vararg or byval argument has been split between registers and
2341   // stack, do not perform tail call, since part of the argument is in caller's
2342   // local frame.
2343   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2344   if (AFI_Caller->getArgRegsSaveSize())
2345     return false;
2346 
2347   // If the callee takes no arguments then go on to check the results of the
2348   // call.
2349   if (!Outs.empty()) {
2350     // Check if stack adjustment is needed. For now, do not do this if any
2351     // argument is passed on the stack.
2352     SmallVector<CCValAssign, 16> ArgLocs;
2353     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2354     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2355     if (CCInfo.getNextStackOffset()) {
2356       // Check if the arguments are already laid out in the right way as
2357       // the caller's fixed stack objects.
2358       MachineFrameInfo &MFI = MF.getFrameInfo();
2359       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2360       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2361       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2362            i != e;
2363            ++i, ++realArgIdx) {
2364         CCValAssign &VA = ArgLocs[i];
2365         EVT RegVT = VA.getLocVT();
2366         SDValue Arg = OutVals[realArgIdx];
2367         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2368         if (VA.getLocInfo() == CCValAssign::Indirect)
2369           return false;
2370         if (VA.needsCustom()) {
2371           // f64 and vector types are split into multiple registers or
2372           // register/stack-slot combinations.  The types will not match
2373           // the registers; give up on memory f64 refs until we figure
2374           // out what to do about this.
2375           if (!VA.isRegLoc())
2376             return false;
2377           if (!ArgLocs[++i].isRegLoc())
2378             return false;
2379           if (RegVT == MVT::v2f64) {
2380             if (!ArgLocs[++i].isRegLoc())
2381               return false;
2382             if (!ArgLocs[++i].isRegLoc())
2383               return false;
2384           }
2385         } else if (!VA.isRegLoc()) {
2386           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2387                                    MFI, MRI, TII))
2388             return false;
2389         }
2390       }
2391     }
2392 
2393     const MachineRegisterInfo &MRI = MF.getRegInfo();
2394     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2395       return false;
2396   }
2397 
2398   return true;
2399 }
2400 
2401 bool
2402 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2403                                   MachineFunction &MF, bool isVarArg,
2404                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2405                                   LLVMContext &Context) const {
2406   SmallVector<CCValAssign, 16> RVLocs;
2407   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2408   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2409 }
2410 
2411 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2412                                     const SDLoc &DL, SelectionDAG &DAG) {
2413   const MachineFunction &MF = DAG.getMachineFunction();
2414   const Function *F = MF.getFunction();
2415 
2416   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2417 
2418   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2419   // version of the "preferred return address". These offsets affect the return
2420   // instruction if this is a return from PL1 without hypervisor extensions.
2421   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2422   //    SWI:     0      "subs pc, lr, #0"
2423   //    ABORT:   +4     "subs pc, lr, #4"
2424   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2425   // UNDEF varies depending on where the exception came from ARM or Thumb
2426   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2427 
2428   int64_t LROffset;
2429   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2430       IntKind == "ABORT")
2431     LROffset = 4;
2432   else if (IntKind == "SWI" || IntKind == "UNDEF")
2433     LROffset = 0;
2434   else
2435     report_fatal_error("Unsupported interrupt attribute. If present, value "
2436                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2437 
2438   RetOps.insert(RetOps.begin() + 1,
2439                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2440 
2441   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2442 }
2443 
2444 SDValue
2445 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2446                                bool isVarArg,
2447                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2448                                const SmallVectorImpl<SDValue> &OutVals,
2449                                const SDLoc &dl, SelectionDAG &DAG) const {
2450   // CCValAssign - represent the assignment of the return value to a location.
2451   SmallVector<CCValAssign, 16> RVLocs;
2452 
2453   // CCState - Info about the registers and stack slots.
2454   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2455                  *DAG.getContext());
2456 
2457   // Analyze outgoing return values.
2458   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2459 
2460   SDValue Flag;
2461   SmallVector<SDValue, 4> RetOps;
2462   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2463   bool isLittleEndian = Subtarget->isLittle();
2464 
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   AFI->setReturnRegsCount(RVLocs.size());
2468 
2469   // Copy the result values into the output registers.
2470   for (unsigned i = 0, realRVLocIdx = 0;
2471        i != RVLocs.size();
2472        ++i, ++realRVLocIdx) {
2473     CCValAssign &VA = RVLocs[i];
2474     assert(VA.isRegLoc() && "Can only return in registers!");
2475 
2476     SDValue Arg = OutVals[realRVLocIdx];
2477 
2478     switch (VA.getLocInfo()) {
2479     default: llvm_unreachable("Unknown loc info!");
2480     case CCValAssign::Full: break;
2481     case CCValAssign::BCvt:
2482       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2483       break;
2484     }
2485 
2486     if (VA.needsCustom()) {
2487       if (VA.getLocVT() == MVT::v2f64) {
2488         // Extract the first half and return it in two registers.
2489         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2490                                    DAG.getConstant(0, dl, MVT::i32));
2491         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2492                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2493 
2494         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2496                                  Flag);
2497         Flag = Chain.getValue(1);
2498         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2499         VA = RVLocs[++i]; // skip ahead to next loc
2500         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2501                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2502                                  Flag);
2503         Flag = Chain.getValue(1);
2504         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2505         VA = RVLocs[++i]; // skip ahead to next loc
2506 
2507         // Extract the 2nd half and fall through to handle it as an f64 value.
2508         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2509                           DAG.getConstant(1, dl, MVT::i32));
2510       }
2511       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2512       // available.
2513       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2514                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2515       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2517                                Flag);
2518       Flag = Chain.getValue(1);
2519       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2520       VA = RVLocs[++i]; // skip ahead to next loc
2521       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2522                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2523                                Flag);
2524     } else
2525       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2526 
2527     // Guarantee that all emitted copies are
2528     // stuck together, avoiding something bad.
2529     Flag = Chain.getValue(1);
2530     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2531   }
2532   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2533   const MCPhysReg *I =
2534       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2535   if (I) {
2536     for (; *I; ++I) {
2537       if (ARM::GPRRegClass.contains(*I))
2538         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2539       else if (ARM::DPRRegClass.contains(*I))
2540         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2541       else
2542         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2543     }
2544   }
2545 
2546   // Update chain and glue.
2547   RetOps[0] = Chain;
2548   if (Flag.getNode())
2549     RetOps.push_back(Flag);
2550 
2551   // CPUs which aren't M-class use a special sequence to return from
2552   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2553   // though we use "subs pc, lr, #N").
2554   //
2555   // M-class CPUs actually use a normal return sequence with a special
2556   // (hardware-provided) value in LR, so the normal code path works.
2557   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2558       !Subtarget->isMClass()) {
2559     if (Subtarget->isThumb1Only())
2560       report_fatal_error("interrupt attribute is not supported in Thumb1");
2561     return LowerInterruptReturn(RetOps, dl, DAG);
2562   }
2563 
2564   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2565 }
2566 
2567 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2568   if (N->getNumValues() != 1)
2569     return false;
2570   if (!N->hasNUsesOfValue(1, 0))
2571     return false;
2572 
2573   SDValue TCChain = Chain;
2574   SDNode *Copy = *N->use_begin();
2575   if (Copy->getOpcode() == ISD::CopyToReg) {
2576     // If the copy has a glue operand, we conservatively assume it isn't safe to
2577     // perform a tail call.
2578     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2579       return false;
2580     TCChain = Copy->getOperand(0);
2581   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2582     SDNode *VMov = Copy;
2583     // f64 returned in a pair of GPRs.
2584     SmallPtrSet<SDNode*, 2> Copies;
2585     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2586          UI != UE; ++UI) {
2587       if (UI->getOpcode() != ISD::CopyToReg)
2588         return false;
2589       Copies.insert(*UI);
2590     }
2591     if (Copies.size() > 2)
2592       return false;
2593 
2594     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2595          UI != UE; ++UI) {
2596       SDValue UseChain = UI->getOperand(0);
2597       if (Copies.count(UseChain.getNode()))
2598         // Second CopyToReg
2599         Copy = *UI;
2600       else {
2601         // We are at the top of this chain.
2602         // If the copy has a glue operand, we conservatively assume it
2603         // isn't safe to perform a tail call.
2604         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2605           return false;
2606         // First CopyToReg
2607         TCChain = UseChain;
2608       }
2609     }
2610   } else if (Copy->getOpcode() == ISD::BITCAST) {
2611     // f32 returned in a single GPR.
2612     if (!Copy->hasOneUse())
2613       return false;
2614     Copy = *Copy->use_begin();
2615     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2616       return false;
2617     // If the copy has a glue operand, we conservatively assume it isn't safe to
2618     // perform a tail call.
2619     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2620       return false;
2621     TCChain = Copy->getOperand(0);
2622   } else {
2623     return false;
2624   }
2625 
2626   bool HasRet = false;
2627   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2628        UI != UE; ++UI) {
2629     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2630         UI->getOpcode() != ARMISD::INTRET_FLAG)
2631       return false;
2632     HasRet = true;
2633   }
2634 
2635   if (!HasRet)
2636     return false;
2637 
2638   Chain = TCChain;
2639   return true;
2640 }
2641 
2642 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2643   if (!Subtarget->supportsTailCall())
2644     return false;
2645 
2646   auto Attr =
2647       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2648   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2649     return false;
2650 
2651   return true;
2652 }
2653 
2654 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2655 // and pass the lower and high parts through.
2656 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2657   SDLoc DL(Op);
2658   SDValue WriteValue = Op->getOperand(2);
2659 
2660   // This function is only supposed to be called for i64 type argument.
2661   assert(WriteValue.getValueType() == MVT::i64
2662           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2663 
2664   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2665                            DAG.getConstant(0, DL, MVT::i32));
2666   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2667                            DAG.getConstant(1, DL, MVT::i32));
2668   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2669   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2670 }
2671 
2672 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2673 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2674 // one of the above mentioned nodes. It has to be wrapped because otherwise
2675 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2676 // be used to form addressing mode. These wrapped nodes will be selected
2677 // into MOVi.
2678 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2679                                              SelectionDAG &DAG) const {
2680   EVT PtrVT = Op.getValueType();
2681   // FIXME there is no actual debug info here
2682   SDLoc dl(Op);
2683   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2684   SDValue Res;
2685 
2686   // When generating execute-only code Constant Pools must be promoted to the
2687   // global data section. It's a bit ugly that we can't share them across basic
2688   // blocks, but this way we guarantee that execute-only behaves correct with
2689   // position-independent addressing modes.
2690   if (Subtarget->genExecuteOnly()) {
2691     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2692     auto T = const_cast<Type*>(CP->getType());
2693     auto C = const_cast<Constant*>(CP->getConstVal());
2694     auto M = const_cast<Module*>(DAG.getMachineFunction().
2695                                  getFunction()->getParent());
2696     auto GV = new GlobalVariable(
2697                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2698                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2699                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2700                     Twine(AFI->createPICLabelUId())
2701                   );
2702     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2703                                             dl, PtrVT);
2704     return LowerGlobalAddress(GA, DAG);
2705   }
2706 
2707   if (CP->isMachineConstantPoolEntry())
2708     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2709                                     CP->getAlignment());
2710   else
2711     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2712                                     CP->getAlignment());
2713   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2714 }
2715 
2716 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2717   return MachineJumpTableInfo::EK_Inline;
2718 }
2719 
2720 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2721                                              SelectionDAG &DAG) const {
2722   MachineFunction &MF = DAG.getMachineFunction();
2723   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2724   unsigned ARMPCLabelIndex = 0;
2725   SDLoc DL(Op);
2726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2728   SDValue CPAddr;
2729   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2730   if (!IsPositionIndependent) {
2731     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2732   } else {
2733     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2734     ARMPCLabelIndex = AFI->createPICLabelUId();
2735     ARMConstantPoolValue *CPV =
2736       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2737                                       ARMCP::CPBlockAddress, PCAdj);
2738     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2739   }
2740   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2741   SDValue Result = DAG.getLoad(
2742       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2743       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2744   if (!IsPositionIndependent)
2745     return Result;
2746   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2747   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2748 }
2749 
2750 /// \brief Convert a TLS address reference into the correct sequence of loads
2751 /// and calls to compute the variable's address for Darwin, and return an
2752 /// SDValue containing the final node.
2753 
2754 /// Darwin only has one TLS scheme which must be capable of dealing with the
2755 /// fully general situation, in the worst case. This means:
2756 ///     + "extern __thread" declaration.
2757 ///     + Defined in a possibly unknown dynamic library.
2758 ///
2759 /// The general system is that each __thread variable has a [3 x i32] descriptor
2760 /// which contains information used by the runtime to calculate the address. The
2761 /// only part of this the compiler needs to know about is the first word, which
2762 /// contains a function pointer that must be called with the address of the
2763 /// entire descriptor in "r0".
2764 ///
2765 /// Since this descriptor may be in a different unit, in general access must
2766 /// proceed along the usual ARM rules. A common sequence to produce is:
2767 ///
2768 ///     movw rT1, :lower16:_var$non_lazy_ptr
2769 ///     movt rT1, :upper16:_var$non_lazy_ptr
2770 ///     ldr r0, [rT1]
2771 ///     ldr rT2, [r0]
2772 ///     blx rT2
2773 ///     [...address now in r0...]
2774 SDValue
2775 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2776                                                SelectionDAG &DAG) const {
2777   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2778   SDLoc DL(Op);
2779 
2780   // First step is to get the address of the actua global symbol. This is where
2781   // the TLS descriptor lives.
2782   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2783 
2784   // The first entry in the descriptor is a function pointer that we must call
2785   // to obtain the address of the variable.
2786   SDValue Chain = DAG.getEntryNode();
2787   SDValue FuncTLVGet = DAG.getLoad(
2788       MVT::i32, DL, Chain, DescAddr,
2789       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2790       /* Alignment = */ 4,
2791       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2792           MachineMemOperand::MOInvariant);
2793   Chain = FuncTLVGet.getValue(1);
2794 
2795   MachineFunction &F = DAG.getMachineFunction();
2796   MachineFrameInfo &MFI = F.getFrameInfo();
2797   MFI.setAdjustsStack(true);
2798 
2799   // TLS calls preserve all registers except those that absolutely must be
2800   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2801   // silly).
2802   auto TRI =
2803       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2804   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2805   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2806 
2807   // Finally, we can make the call. This is just a degenerate version of a
2808   // normal AArch64 call node: r0 takes the address of the descriptor, and
2809   // returns the address of the variable in this thread.
2810   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2811   Chain =
2812       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2813                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2814                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2815   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2816 }
2817 
2818 SDValue
2819 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2820                                                 SelectionDAG &DAG) const {
2821   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2822 
2823   SDValue Chain = DAG.getEntryNode();
2824   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2825   SDLoc DL(Op);
2826 
2827   // Load the current TEB (thread environment block)
2828   SDValue Ops[] = {Chain,
2829                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2830                    DAG.getConstant(15, DL, MVT::i32),
2831                    DAG.getConstant(0, DL, MVT::i32),
2832                    DAG.getConstant(13, DL, MVT::i32),
2833                    DAG.getConstant(0, DL, MVT::i32),
2834                    DAG.getConstant(2, DL, MVT::i32)};
2835   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2836                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2837 
2838   SDValue TEB = CurrentTEB.getValue(0);
2839   Chain = CurrentTEB.getValue(1);
2840 
2841   // Load the ThreadLocalStoragePointer from the TEB
2842   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2843   SDValue TLSArray =
2844       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2845   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2846 
2847   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2848   // offset into the TLSArray.
2849 
2850   // Load the TLS index from the C runtime
2851   SDValue TLSIndex =
2852       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2853   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2854   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2855 
2856   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2857                               DAG.getConstant(2, DL, MVT::i32));
2858   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2859                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2860                             MachinePointerInfo());
2861 
2862   // Get the offset of the start of the .tls section (section base)
2863   const auto *GA = cast<GlobalAddressSDNode>(Op);
2864   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2865   SDValue Offset = DAG.getLoad(
2866       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2867                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2868       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2869 
2870   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2871 }
2872 
2873 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2874 SDValue
2875 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2876                                                  SelectionDAG &DAG) const {
2877   SDLoc dl(GA);
2878   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2879   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2880   MachineFunction &MF = DAG.getMachineFunction();
2881   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2882   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2883   ARMConstantPoolValue *CPV =
2884     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2885                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2886   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2887   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2888   Argument = DAG.getLoad(
2889       PtrVT, dl, DAG.getEntryNode(), Argument,
2890       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2891   SDValue Chain = Argument.getValue(1);
2892 
2893   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2894   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2895 
2896   // call __tls_get_addr.
2897   ArgListTy Args;
2898   ArgListEntry Entry;
2899   Entry.Node = Argument;
2900   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2901   Args.push_back(Entry);
2902 
2903   // FIXME: is there useful debug info available here?
2904   TargetLowering::CallLoweringInfo CLI(DAG);
2905   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2906       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2907       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2908 
2909   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2910   return CallResult.first;
2911 }
2912 
2913 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2914 // "local exec" model.
2915 SDValue
2916 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2917                                         SelectionDAG &DAG,
2918                                         TLSModel::Model model) const {
2919   const GlobalValue *GV = GA->getGlobal();
2920   SDLoc dl(GA);
2921   SDValue Offset;
2922   SDValue Chain = DAG.getEntryNode();
2923   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2924   // Get the Thread Pointer
2925   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2926 
2927   if (model == TLSModel::InitialExec) {
2928     MachineFunction &MF = DAG.getMachineFunction();
2929     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2930     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2931     // Initial exec model.
2932     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2933     ARMConstantPoolValue *CPV =
2934       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2935                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2936                                       true);
2937     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2938     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2939     Offset = DAG.getLoad(
2940         PtrVT, dl, Chain, Offset,
2941         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2942     Chain = Offset.getValue(1);
2943 
2944     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2945     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2946 
2947     Offset = DAG.getLoad(
2948         PtrVT, dl, Chain, Offset,
2949         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2950   } else {
2951     // local exec model
2952     assert(model == TLSModel::LocalExec);
2953     ARMConstantPoolValue *CPV =
2954       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2955     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2956     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2957     Offset = DAG.getLoad(
2958         PtrVT, dl, Chain, Offset,
2959         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2960   }
2961 
2962   // The address of the thread local variable is the add of the thread
2963   // pointer with the offset of the variable.
2964   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2965 }
2966 
2967 SDValue
2968 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2969   if (Subtarget->isTargetDarwin())
2970     return LowerGlobalTLSAddressDarwin(Op, DAG);
2971 
2972   if (Subtarget->isTargetWindows())
2973     return LowerGlobalTLSAddressWindows(Op, DAG);
2974 
2975   // TODO: implement the "local dynamic" model
2976   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2977   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2978   if (DAG.getTarget().Options.EmulatedTLS)
2979     return LowerToTLSEmulatedModel(GA, DAG);
2980 
2981   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2982 
2983   switch (model) {
2984     case TLSModel::GeneralDynamic:
2985     case TLSModel::LocalDynamic:
2986       return LowerToTLSGeneralDynamicModel(GA, DAG);
2987     case TLSModel::InitialExec:
2988     case TLSModel::LocalExec:
2989       return LowerToTLSExecModels(GA, DAG, model);
2990   }
2991   llvm_unreachable("bogus TLS model");
2992 }
2993 
2994 /// Return true if all users of V are within function F, looking through
2995 /// ConstantExprs.
2996 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2997   SmallVector<const User*,4> Worklist;
2998   for (auto *U : V->users())
2999     Worklist.push_back(U);
3000   while (!Worklist.empty()) {
3001     auto *U = Worklist.pop_back_val();
3002     if (isa<ConstantExpr>(U)) {
3003       for (auto *UU : U->users())
3004         Worklist.push_back(UU);
3005       continue;
3006     }
3007 
3008     auto *I = dyn_cast<Instruction>(U);
3009     if (!I || I->getParent()->getParent() != F)
3010       return false;
3011   }
3012   return true;
3013 }
3014 
3015 /// Return true if all users of V are within some (any) function, looking through
3016 /// ConstantExprs. In other words, are there any global constant users?
3017 static bool allUsersAreInFunctions(const Value *V) {
3018   SmallVector<const User*,4> Worklist;
3019   for (auto *U : V->users())
3020     Worklist.push_back(U);
3021   while (!Worklist.empty()) {
3022     auto *U = Worklist.pop_back_val();
3023     if (isa<ConstantExpr>(U)) {
3024       for (auto *UU : U->users())
3025         Worklist.push_back(UU);
3026       continue;
3027     }
3028 
3029     if (!isa<Instruction>(U))
3030       return false;
3031   }
3032   return true;
3033 }
3034 
3035 // Return true if T is an integer, float or an array/vector of either.
3036 static bool isSimpleType(Type *T) {
3037   if (T->isIntegerTy() || T->isFloatingPointTy())
3038     return true;
3039   Type *SubT = nullptr;
3040   if (T->isArrayTy())
3041     SubT = T->getArrayElementType();
3042   else if (T->isVectorTy())
3043     SubT = T->getVectorElementType();
3044   else
3045     return false;
3046   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3047 }
3048 
3049 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3050                                      EVT PtrVT, const SDLoc &dl) {
3051   // If we're creating a pool entry for a constant global with unnamed address,
3052   // and the global is small enough, we can emit it inline into the constant pool
3053   // to save ourselves an indirection.
3054   //
3055   // This is a win if the constant is only used in one function (so it doesn't
3056   // need to be duplicated) or duplicating the constant wouldn't increase code
3057   // size (implying the constant is no larger than 4 bytes).
3058   const Function *F = DAG.getMachineFunction().getFunction();
3059 
3060   // We rely on this decision to inline being idemopotent and unrelated to the
3061   // use-site. We know that if we inline a variable at one use site, we'll
3062   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3063   // doesn't know about this optimization, so bail out if it's enabled else
3064   // we could decide to inline here (and thus never emit the GV) but require
3065   // the GV from fast-isel generated code.
3066   if (!EnableConstpoolPromotion ||
3067       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3068       return SDValue();
3069 
3070   auto *GVar = dyn_cast<GlobalVariable>(GV);
3071   if (!GVar || !GVar->hasInitializer() ||
3072       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3073       !GVar->hasLocalLinkage())
3074     return SDValue();
3075 
3076   // Ensure that we don't try and inline any type that contains pointers. If
3077   // we inline a value that contains relocations, we move the relocations from
3078   // .data to .text which is not ideal.
3079   auto *Init = GVar->getInitializer();
3080   if (!isSimpleType(Init->getType()))
3081     return SDValue();
3082 
3083   // The constant islands pass can only really deal with alignment requests
3084   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3085   // any type wanting greater alignment requirements than 4 bytes. We also
3086   // can only promote constants that are multiples of 4 bytes in size or
3087   // are paddable to a multiple of 4. Currently we only try and pad constants
3088   // that are strings for simplicity.
3089   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3090   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3091   unsigned Align = GVar->getAlignment();
3092   unsigned RequiredPadding = 4 - (Size % 4);
3093   bool PaddingPossible =
3094     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3095   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3096       Size == 0)
3097     return SDValue();
3098 
3099   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3100   MachineFunction &MF = DAG.getMachineFunction();
3101   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3102 
3103   // We can't bloat the constant pool too much, else the ConstantIslands pass
3104   // may fail to converge. If we haven't promoted this global yet (it may have
3105   // multiple uses), and promoting it would increase the constant pool size (Sz
3106   // > 4), ensure we have space to do so up to MaxTotal.
3107   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3108     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3109         ConstpoolPromotionMaxTotal)
3110       return SDValue();
3111 
3112   // This is only valid if all users are in a single function OR it has users
3113   // in multiple functions but it no larger than a pointer. We also check if
3114   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3115   // address taken.
3116   if (!allUsersAreInFunction(GVar, F) &&
3117       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3118     return SDValue();
3119 
3120   // We're going to inline this global. Pad it out if needed.
3121   if (RequiredPadding != 4) {
3122     StringRef S = CDAInit->getAsString();
3123 
3124     SmallVector<uint8_t,16> V(S.size());
3125     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3126     while (RequiredPadding--)
3127       V.push_back(0);
3128     Init = ConstantDataArray::get(*DAG.getContext(), V);
3129   }
3130 
3131   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3132   SDValue CPAddr =
3133     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3134   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3135     AFI->markGlobalAsPromotedToConstantPool(GVar);
3136     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3137                                       PaddedSize - 4);
3138   }
3139   ++NumConstpoolPromoted;
3140   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3141 }
3142 
3143 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3144   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3145     GV = GA->getBaseObject();
3146   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3147          isa<Function>(GV);
3148 }
3149 
3150 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3151                                               SelectionDAG &DAG) const {
3152   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3153   default: llvm_unreachable("unknown object format");
3154   case Triple::COFF:
3155     return LowerGlobalAddressWindows(Op, DAG);
3156   case Triple::ELF:
3157     return LowerGlobalAddressELF(Op, DAG);
3158   case Triple::MachO:
3159     return LowerGlobalAddressDarwin(Op, DAG);
3160   }
3161 }
3162 
3163 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3164                                                  SelectionDAG &DAG) const {
3165   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3166   SDLoc dl(Op);
3167   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3168   const TargetMachine &TM = getTargetMachine();
3169   bool IsRO = isReadOnly(GV);
3170 
3171   // promoteToConstantPool only if not generating XO text section
3172   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3173     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3174       return V;
3175 
3176   if (isPositionIndependent()) {
3177     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3178 
3179     MachineFunction &MF = DAG.getMachineFunction();
3180     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3181     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3182     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3183     SDLoc dl(Op);
3184     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3185     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3186         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3187         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3188         /*AddCurrentAddress=*/UseGOT_PREL);
3189     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3190     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3191     SDValue Result = DAG.getLoad(
3192         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3193         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3194     SDValue Chain = Result.getValue(1);
3195     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3196     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3197     if (UseGOT_PREL)
3198       Result =
3199           DAG.getLoad(PtrVT, dl, Chain, Result,
3200                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3201     return Result;
3202   } else if (Subtarget->isROPI() && IsRO) {
3203     // PC-relative.
3204     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3205     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3206     return Result;
3207   } else if (Subtarget->isRWPI() && !IsRO) {
3208     // SB-relative.
3209     SDValue RelAddr;
3210     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3211       ++NumMovwMovt;
3212       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3213       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3214     } else { // use literal pool for address constant
3215       ARMConstantPoolValue *CPV =
3216         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3217       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3218       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3219       RelAddr = DAG.getLoad(
3220           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3221           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3222     }
3223     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3224     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3225     return Result;
3226   }
3227 
3228   // If we have T2 ops, we can materialize the address directly via movt/movw
3229   // pair. This is always cheaper.
3230   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3231     ++NumMovwMovt;
3232     // FIXME: Once remat is capable of dealing with instructions with register
3233     // operands, expand this into two nodes.
3234     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3235                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3236   } else {
3237     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3238     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3239     return DAG.getLoad(
3240         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3241         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3242   }
3243 }
3244 
3245 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3246                                                     SelectionDAG &DAG) const {
3247   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3248          "ROPI/RWPI not currently supported for Darwin");
3249   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3250   SDLoc dl(Op);
3251   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3252 
3253   if (Subtarget->useMovt(DAG.getMachineFunction()))
3254     ++NumMovwMovt;
3255 
3256   // FIXME: Once remat is capable of dealing with instructions with register
3257   // operands, expand this into multiple nodes
3258   unsigned Wrapper =
3259       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3260 
3261   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3262   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3263 
3264   if (Subtarget->isGVIndirectSymbol(GV))
3265     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3266                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3267   return Result;
3268 }
3269 
3270 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3271                                                      SelectionDAG &DAG) const {
3272   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3273   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3274          "Windows on ARM expects to use movw/movt");
3275   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3276          "ROPI/RWPI not currently supported for Windows");
3277 
3278   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3279   const ARMII::TOF TargetFlags =
3280     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3281   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3282   SDValue Result;
3283   SDLoc DL(Op);
3284 
3285   ++NumMovwMovt;
3286 
3287   // FIXME: Once remat is capable of dealing with instructions with register
3288   // operands, expand this into two nodes.
3289   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3290                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3291                                                   TargetFlags));
3292   if (GV->hasDLLImportStorageClass())
3293     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3294                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3295   return Result;
3296 }
3297 
3298 SDValue
3299 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3300   SDLoc dl(Op);
3301   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3302   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3303                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3304                      Op.getOperand(1), Val);
3305 }
3306 
3307 SDValue
3308 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3309   SDLoc dl(Op);
3310   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3311                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3312 }
3313 
3314 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3315                                                       SelectionDAG &DAG) const {
3316   SDLoc dl(Op);
3317   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3318                      Op.getOperand(0));
3319 }
3320 
3321 SDValue
3322 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3323                                           const ARMSubtarget *Subtarget) const {
3324   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3325   SDLoc dl(Op);
3326   switch (IntNo) {
3327   default: return SDValue();    // Don't custom lower most intrinsics.
3328   case Intrinsic::thread_pointer: {
3329     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3330     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3331   }
3332   case Intrinsic::eh_sjlj_lsda: {
3333     MachineFunction &MF = DAG.getMachineFunction();
3334     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3335     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3336     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3337     SDValue CPAddr;
3338     bool IsPositionIndependent = isPositionIndependent();
3339     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3340     ARMConstantPoolValue *CPV =
3341       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3342                                       ARMCP::CPLSDA, PCAdj);
3343     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3344     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3345     SDValue Result = DAG.getLoad(
3346         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3347         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3348 
3349     if (IsPositionIndependent) {
3350       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3351       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3352     }
3353     return Result;
3354   }
3355   case Intrinsic::arm_neon_vabs:
3356     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3357                         Op.getOperand(1));
3358   case Intrinsic::arm_neon_vmulls:
3359   case Intrinsic::arm_neon_vmullu: {
3360     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3361       ? ARMISD::VMULLs : ARMISD::VMULLu;
3362     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3363                        Op.getOperand(1), Op.getOperand(2));
3364   }
3365   case Intrinsic::arm_neon_vminnm:
3366   case Intrinsic::arm_neon_vmaxnm: {
3367     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3368       ? ISD::FMINNUM : ISD::FMAXNUM;
3369     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3370                        Op.getOperand(1), Op.getOperand(2));
3371   }
3372   case Intrinsic::arm_neon_vminu:
3373   case Intrinsic::arm_neon_vmaxu: {
3374     if (Op.getValueType().isFloatingPoint())
3375       return SDValue();
3376     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3377       ? ISD::UMIN : ISD::UMAX;
3378     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3379                          Op.getOperand(1), Op.getOperand(2));
3380   }
3381   case Intrinsic::arm_neon_vmins:
3382   case Intrinsic::arm_neon_vmaxs: {
3383     // v{min,max}s is overloaded between signed integers and floats.
3384     if (!Op.getValueType().isFloatingPoint()) {
3385       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3386         ? ISD::SMIN : ISD::SMAX;
3387       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3388                          Op.getOperand(1), Op.getOperand(2));
3389     }
3390     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3391       ? ISD::FMINNAN : ISD::FMAXNAN;
3392     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3393                        Op.getOperand(1), Op.getOperand(2));
3394   }
3395   case Intrinsic::arm_neon_vtbl1:
3396     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3397                        Op.getOperand(1), Op.getOperand(2));
3398   case Intrinsic::arm_neon_vtbl2:
3399     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3400                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3401   }
3402 }
3403 
3404 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3405                                  const ARMSubtarget *Subtarget) {
3406   SDLoc dl(Op);
3407   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3408   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3409   if (SSID == SyncScope::SingleThread)
3410     return Op;
3411 
3412   if (!Subtarget->hasDataBarrier()) {
3413     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3414     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3415     // here.
3416     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3417            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3418     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3419                        DAG.getConstant(0, dl, MVT::i32));
3420   }
3421 
3422   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3423   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3424   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3425   if (Subtarget->isMClass()) {
3426     // Only a full system barrier exists in the M-class architectures.
3427     Domain = ARM_MB::SY;
3428   } else if (Subtarget->preferISHSTBarriers() &&
3429              Ord == AtomicOrdering::Release) {
3430     // Swift happens to implement ISHST barriers in a way that's compatible with
3431     // Release semantics but weaker than ISH so we'd be fools not to use
3432     // it. Beware: other processors probably don't!
3433     Domain = ARM_MB::ISHST;
3434   }
3435 
3436   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3437                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3438                      DAG.getConstant(Domain, dl, MVT::i32));
3439 }
3440 
3441 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3442                              const ARMSubtarget *Subtarget) {
3443   // ARM pre v5TE and Thumb1 does not have preload instructions.
3444   if (!(Subtarget->isThumb2() ||
3445         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3446     // Just preserve the chain.
3447     return Op.getOperand(0);
3448 
3449   SDLoc dl(Op);
3450   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3451   if (!isRead &&
3452       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3453     // ARMv7 with MP extension has PLDW.
3454     return Op.getOperand(0);
3455 
3456   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3457   if (Subtarget->isThumb()) {
3458     // Invert the bits.
3459     isRead = ~isRead & 1;
3460     isData = ~isData & 1;
3461   }
3462 
3463   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3464                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3465                      DAG.getConstant(isData, dl, MVT::i32));
3466 }
3467 
3468 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3469   MachineFunction &MF = DAG.getMachineFunction();
3470   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3471 
3472   // vastart just stores the address of the VarArgsFrameIndex slot into the
3473   // memory location argument.
3474   SDLoc dl(Op);
3475   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3476   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3477   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3478   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3479                       MachinePointerInfo(SV));
3480 }
3481 
3482 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3483                                                 CCValAssign &NextVA,
3484                                                 SDValue &Root,
3485                                                 SelectionDAG &DAG,
3486                                                 const SDLoc &dl) const {
3487   MachineFunction &MF = DAG.getMachineFunction();
3488   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3489 
3490   const TargetRegisterClass *RC;
3491   if (AFI->isThumb1OnlyFunction())
3492     RC = &ARM::tGPRRegClass;
3493   else
3494     RC = &ARM::GPRRegClass;
3495 
3496   // Transform the arguments stored in physical registers into virtual ones.
3497   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3498   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3499 
3500   SDValue ArgValue2;
3501   if (NextVA.isMemLoc()) {
3502     MachineFrameInfo &MFI = MF.getFrameInfo();
3503     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3504 
3505     // Create load node to retrieve arguments from the stack.
3506     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3507     ArgValue2 = DAG.getLoad(
3508         MVT::i32, dl, Root, FIN,
3509         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3510   } else {
3511     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3512     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3513   }
3514   if (!Subtarget->isLittle())
3515     std::swap (ArgValue, ArgValue2);
3516   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3517 }
3518 
3519 // The remaining GPRs hold either the beginning of variable-argument
3520 // data, or the beginning of an aggregate passed by value (usually
3521 // byval).  Either way, we allocate stack slots adjacent to the data
3522 // provided by our caller, and store the unallocated registers there.
3523 // If this is a variadic function, the va_list pointer will begin with
3524 // these values; otherwise, this reassembles a (byval) structure that
3525 // was split between registers and memory.
3526 // Return: The frame index registers were stored into.
3527 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3528                                       const SDLoc &dl, SDValue &Chain,
3529                                       const Value *OrigArg,
3530                                       unsigned InRegsParamRecordIdx,
3531                                       int ArgOffset, unsigned ArgSize) const {
3532   // Currently, two use-cases possible:
3533   // Case #1. Non-var-args function, and we meet first byval parameter.
3534   //          Setup first unallocated register as first byval register;
3535   //          eat all remained registers
3536   //          (these two actions are performed by HandleByVal method).
3537   //          Then, here, we initialize stack frame with
3538   //          "store-reg" instructions.
3539   // Case #2. Var-args function, that doesn't contain byval parameters.
3540   //          The same: eat all remained unallocated registers,
3541   //          initialize stack frame.
3542 
3543   MachineFunction &MF = DAG.getMachineFunction();
3544   MachineFrameInfo &MFI = MF.getFrameInfo();
3545   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3546   unsigned RBegin, REnd;
3547   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3548     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3549   } else {
3550     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3551     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3552     REnd = ARM::R4;
3553   }
3554 
3555   if (REnd != RBegin)
3556     ArgOffset = -4 * (ARM::R4 - RBegin);
3557 
3558   auto PtrVT = getPointerTy(DAG.getDataLayout());
3559   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3560   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3561 
3562   SmallVector<SDValue, 4> MemOps;
3563   const TargetRegisterClass *RC =
3564       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3565 
3566   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3567     unsigned VReg = MF.addLiveIn(Reg, RC);
3568     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3569     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3570                                  MachinePointerInfo(OrigArg, 4 * i));
3571     MemOps.push_back(Store);
3572     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3573   }
3574 
3575   if (!MemOps.empty())
3576     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3577   return FrameIndex;
3578 }
3579 
3580 // Setup stack frame, the va_list pointer will start from.
3581 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3582                                              const SDLoc &dl, SDValue &Chain,
3583                                              unsigned ArgOffset,
3584                                              unsigned TotalArgRegsSaveSize,
3585                                              bool ForceMutable) const {
3586   MachineFunction &MF = DAG.getMachineFunction();
3587   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3588 
3589   // Try to store any remaining integer argument regs
3590   // to their spots on the stack so that they may be loaded by dereferencing
3591   // the result of va_next.
3592   // If there is no regs to be stored, just point address after last
3593   // argument passed via stack.
3594   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3595                                   CCInfo.getInRegsParamsCount(),
3596                                   CCInfo.getNextStackOffset(), 4);
3597   AFI->setVarArgsFrameIndex(FrameIndex);
3598 }
3599 
3600 SDValue ARMTargetLowering::LowerFormalArguments(
3601     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3602     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3603     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3604   MachineFunction &MF = DAG.getMachineFunction();
3605   MachineFrameInfo &MFI = MF.getFrameInfo();
3606 
3607   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3608 
3609   // Assign locations to all of the incoming arguments.
3610   SmallVector<CCValAssign, 16> ArgLocs;
3611   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3612                  *DAG.getContext());
3613   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3614 
3615   SmallVector<SDValue, 16> ArgValues;
3616   SDValue ArgValue;
3617   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3618   unsigned CurArgIdx = 0;
3619 
3620   // Initially ArgRegsSaveSize is zero.
3621   // Then we increase this value each time we meet byval parameter.
3622   // We also increase this value in case of varargs function.
3623   AFI->setArgRegsSaveSize(0);
3624 
3625   // Calculate the amount of stack space that we need to allocate to store
3626   // byval and variadic arguments that are passed in registers.
3627   // We need to know this before we allocate the first byval or variadic
3628   // argument, as they will be allocated a stack slot below the CFA (Canonical
3629   // Frame Address, the stack pointer at entry to the function).
3630   unsigned ArgRegBegin = ARM::R4;
3631   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3632     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3633       break;
3634 
3635     CCValAssign &VA = ArgLocs[i];
3636     unsigned Index = VA.getValNo();
3637     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3638     if (!Flags.isByVal())
3639       continue;
3640 
3641     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3642     unsigned RBegin, REnd;
3643     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3644     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3645 
3646     CCInfo.nextInRegsParam();
3647   }
3648   CCInfo.rewindByValRegsInfo();
3649 
3650   int lastInsIndex = -1;
3651   if (isVarArg && MFI.hasVAStart()) {
3652     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3653     if (RegIdx != array_lengthof(GPRArgRegs))
3654       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3655   }
3656 
3657   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3658   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3659   auto PtrVT = getPointerTy(DAG.getDataLayout());
3660 
3661   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3662     CCValAssign &VA = ArgLocs[i];
3663     if (Ins[VA.getValNo()].isOrigArg()) {
3664       std::advance(CurOrigArg,
3665                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3666       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3667     }
3668     // Arguments stored in registers.
3669     if (VA.isRegLoc()) {
3670       EVT RegVT = VA.getLocVT();
3671 
3672       if (VA.needsCustom()) {
3673         // f64 and vector types are split up into multiple registers or
3674         // combinations of registers and stack slots.
3675         if (VA.getLocVT() == MVT::v2f64) {
3676           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3677                                                    Chain, DAG, dl);
3678           VA = ArgLocs[++i]; // skip ahead to next loc
3679           SDValue ArgValue2;
3680           if (VA.isMemLoc()) {
3681             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3682             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3683             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3684                                     MachinePointerInfo::getFixedStack(
3685                                         DAG.getMachineFunction(), FI));
3686           } else {
3687             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3688                                              Chain, DAG, dl);
3689           }
3690           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3691           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3692                                  ArgValue, ArgValue1,
3693                                  DAG.getIntPtrConstant(0, dl));
3694           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3695                                  ArgValue, ArgValue2,
3696                                  DAG.getIntPtrConstant(1, dl));
3697         } else
3698           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3699       } else {
3700         const TargetRegisterClass *RC;
3701 
3702         if (RegVT == MVT::f32)
3703           RC = &ARM::SPRRegClass;
3704         else if (RegVT == MVT::f64)
3705           RC = &ARM::DPRRegClass;
3706         else if (RegVT == MVT::v2f64)
3707           RC = &ARM::QPRRegClass;
3708         else if (RegVT == MVT::i32)
3709           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3710                                            : &ARM::GPRRegClass;
3711         else
3712           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3713 
3714         // Transform the arguments in physical registers into virtual ones.
3715         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3716         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3717       }
3718 
3719       // If this is an 8 or 16-bit value, it is really passed promoted
3720       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3721       // truncate to the right size.
3722       switch (VA.getLocInfo()) {
3723       default: llvm_unreachable("Unknown loc info!");
3724       case CCValAssign::Full: break;
3725       case CCValAssign::BCvt:
3726         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3727         break;
3728       case CCValAssign::SExt:
3729         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3730                                DAG.getValueType(VA.getValVT()));
3731         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3732         break;
3733       case CCValAssign::ZExt:
3734         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3735                                DAG.getValueType(VA.getValVT()));
3736         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3737         break;
3738       }
3739 
3740       InVals.push_back(ArgValue);
3741     } else { // VA.isRegLoc()
3742       // sanity check
3743       assert(VA.isMemLoc());
3744       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3745 
3746       int index = VA.getValNo();
3747 
3748       // Some Ins[] entries become multiple ArgLoc[] entries.
3749       // Process them only once.
3750       if (index != lastInsIndex)
3751         {
3752           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3753           // FIXME: For now, all byval parameter objects are marked mutable.
3754           // This can be changed with more analysis.
3755           // In case of tail call optimization mark all arguments mutable.
3756           // Since they could be overwritten by lowering of arguments in case of
3757           // a tail call.
3758           if (Flags.isByVal()) {
3759             assert(Ins[index].isOrigArg() &&
3760                    "Byval arguments cannot be implicit");
3761             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3762 
3763             int FrameIndex = StoreByValRegs(
3764                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3765                 VA.getLocMemOffset(), Flags.getByValSize());
3766             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3767             CCInfo.nextInRegsParam();
3768           } else {
3769             unsigned FIOffset = VA.getLocMemOffset();
3770             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3771                                            FIOffset, true);
3772 
3773             // Create load nodes to retrieve arguments from the stack.
3774             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3775             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3776                                          MachinePointerInfo::getFixedStack(
3777                                              DAG.getMachineFunction(), FI)));
3778           }
3779           lastInsIndex = index;
3780         }
3781     }
3782   }
3783 
3784   // varargs
3785   if (isVarArg && MFI.hasVAStart())
3786     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3787                          CCInfo.getNextStackOffset(),
3788                          TotalArgRegsSaveSize);
3789 
3790   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3791 
3792   return Chain;
3793 }
3794 
3795 /// isFloatingPointZero - Return true if this is +0.0.
3796 static bool isFloatingPointZero(SDValue Op) {
3797   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3798     return CFP->getValueAPF().isPosZero();
3799   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3800     // Maybe this has already been legalized into the constant pool?
3801     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3802       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3803       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3804         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3805           return CFP->getValueAPF().isPosZero();
3806     }
3807   } else if (Op->getOpcode() == ISD::BITCAST &&
3808              Op->getValueType(0) == MVT::f64) {
3809     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3810     // created by LowerConstantFP().
3811     SDValue BitcastOp = Op->getOperand(0);
3812     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3813         isNullConstant(BitcastOp->getOperand(0)))
3814       return true;
3815   }
3816   return false;
3817 }
3818 
3819 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3820 /// the given operands.
3821 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3822                                      SDValue &ARMcc, SelectionDAG &DAG,
3823                                      const SDLoc &dl) const {
3824   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3825     unsigned C = RHSC->getZExtValue();
3826     if (!isLegalICmpImmediate(C)) {
3827       // Constant does not fit, try adjusting it by one?
3828       switch (CC) {
3829       default: break;
3830       case ISD::SETLT:
3831       case ISD::SETGE:
3832         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3833           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3834           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3835         }
3836         break;
3837       case ISD::SETULT:
3838       case ISD::SETUGE:
3839         if (C != 0 && isLegalICmpImmediate(C-1)) {
3840           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3841           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3842         }
3843         break;
3844       case ISD::SETLE:
3845       case ISD::SETGT:
3846         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3847           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3848           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3849         }
3850         break;
3851       case ISD::SETULE:
3852       case ISD::SETUGT:
3853         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3854           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3855           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3856         }
3857         break;
3858       }
3859     }
3860   }
3861 
3862   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3863   ARMISD::NodeType CompareType;
3864   switch (CondCode) {
3865   default:
3866     CompareType = ARMISD::CMP;
3867     break;
3868   case ARMCC::EQ:
3869   case ARMCC::NE:
3870     // Uses only Z Flag
3871     CompareType = ARMISD::CMPZ;
3872     break;
3873   }
3874   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3875   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3876 }
3877 
3878 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3879 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3880                                      SelectionDAG &DAG, const SDLoc &dl,
3881                                      bool InvalidOnQNaN) const {
3882   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3883   SDValue Cmp;
3884   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3885   if (!isFloatingPointZero(RHS))
3886     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3887   else
3888     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3889   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3890 }
3891 
3892 /// duplicateCmp - Glue values can have only one use, so this function
3893 /// duplicates a comparison node.
3894 SDValue
3895 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3896   unsigned Opc = Cmp.getOpcode();
3897   SDLoc DL(Cmp);
3898   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3899     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3900 
3901   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3902   Cmp = Cmp.getOperand(0);
3903   Opc = Cmp.getOpcode();
3904   if (Opc == ARMISD::CMPFP)
3905     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3906                       Cmp.getOperand(1), Cmp.getOperand(2));
3907   else {
3908     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3909     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3910                       Cmp.getOperand(1));
3911   }
3912   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3913 }
3914 
3915 std::pair<SDValue, SDValue>
3916 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3917                                  SDValue &ARMcc) const {
3918   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3919 
3920   SDValue Value, OverflowCmp;
3921   SDValue LHS = Op.getOperand(0);
3922   SDValue RHS = Op.getOperand(1);
3923   SDLoc dl(Op);
3924 
3925   // FIXME: We are currently always generating CMPs because we don't support
3926   // generating CMN through the backend. This is not as good as the natural
3927   // CMP case because it causes a register dependency and cannot be folded
3928   // later.
3929 
3930   switch (Op.getOpcode()) {
3931   default:
3932     llvm_unreachable("Unknown overflow instruction!");
3933   case ISD::SADDO:
3934     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3935     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3936     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3937     break;
3938   case ISD::UADDO:
3939     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3940     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3941     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3942     break;
3943   case ISD::SSUBO:
3944     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3945     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3946     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3947     break;
3948   case ISD::USUBO:
3949     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3950     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3951     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3952     break;
3953   } // switch (...)
3954 
3955   return std::make_pair(Value, OverflowCmp);
3956 }
3957 
3958 SDValue
3959 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
3960   // Let legalize expand this if it isn't a legal type yet.
3961   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3962     return SDValue();
3963 
3964   SDValue Value, OverflowCmp;
3965   SDValue ARMcc;
3966   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3967   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3968   SDLoc dl(Op);
3969   // We use 0 and 1 as false and true values.
3970   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3971   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3972   EVT VT = Op.getValueType();
3973 
3974   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3975                                  ARMcc, CCR, OverflowCmp);
3976 
3977   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3978   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3979 }
3980 
3981 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
3982                                               SelectionDAG &DAG) {
3983   SDLoc DL(BoolCarry);
3984   EVT CarryVT = BoolCarry.getValueType();
3985 
3986   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
3987   // This converts the boolean value carry into the carry flag by doing
3988   // ARMISD::ADDC Carry, ~0
3989   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
3990                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
3991 }
3992 
3993 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
3994                                               SelectionDAG &DAG) {
3995   SDLoc DL(Flags);
3996 
3997   // Now convert the carry flag into a boolean carry. We do this
3998   // using ARMISD:ADDE 0, 0, Carry
3999   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4000                      DAG.getConstant(0, DL, MVT::i32),
4001                      DAG.getConstant(0, DL, MVT::i32), Flags);
4002 }
4003 
4004 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4005                                              SelectionDAG &DAG) const {
4006   // Let legalize expand this if it isn't a legal type yet.
4007   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4008     return SDValue();
4009 
4010   SDValue LHS = Op.getOperand(0);
4011   SDValue RHS = Op.getOperand(1);
4012   SDLoc dl(Op);
4013 
4014   EVT VT = Op.getValueType();
4015   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4016   SDValue Value;
4017   SDValue Overflow;
4018   switch (Op.getOpcode()) {
4019   default:
4020     llvm_unreachable("Unknown overflow instruction!");
4021   case ISD::UADDO:
4022     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4023     // Convert the carry flag into a boolean value.
4024     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4025     break;
4026   case ISD::USUBO:
4027     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4028     // Convert the carry flag into a boolean value.
4029     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4030     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4031     // value. So compute 1 - C.
4032     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4033                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4034     break;
4035   }
4036 
4037   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4038 }
4039 
4040 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4041   SDValue Cond = Op.getOperand(0);
4042   SDValue SelectTrue = Op.getOperand(1);
4043   SDValue SelectFalse = Op.getOperand(2);
4044   SDLoc dl(Op);
4045   unsigned Opc = Cond.getOpcode();
4046 
4047   if (Cond.getResNo() == 1 &&
4048       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4049        Opc == ISD::USUBO)) {
4050     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4051       return SDValue();
4052 
4053     SDValue Value, OverflowCmp;
4054     SDValue ARMcc;
4055     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4056     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4057     EVT VT = Op.getValueType();
4058 
4059     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4060                    OverflowCmp, DAG);
4061   }
4062 
4063   // Convert:
4064   //
4065   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4066   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4067   //
4068   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4069     const ConstantSDNode *CMOVTrue =
4070       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4071     const ConstantSDNode *CMOVFalse =
4072       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4073 
4074     if (CMOVTrue && CMOVFalse) {
4075       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4076       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4077 
4078       SDValue True;
4079       SDValue False;
4080       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4081         True = SelectTrue;
4082         False = SelectFalse;
4083       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4084         True = SelectFalse;
4085         False = SelectTrue;
4086       }
4087 
4088       if (True.getNode() && False.getNode()) {
4089         EVT VT = Op.getValueType();
4090         SDValue ARMcc = Cond.getOperand(2);
4091         SDValue CCR = Cond.getOperand(3);
4092         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4093         assert(True.getValueType() == VT);
4094         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4095       }
4096     }
4097   }
4098 
4099   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4100   // undefined bits before doing a full-word comparison with zero.
4101   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4102                      DAG.getConstant(1, dl, Cond.getValueType()));
4103 
4104   return DAG.getSelectCC(dl, Cond,
4105                          DAG.getConstant(0, dl, Cond.getValueType()),
4106                          SelectTrue, SelectFalse, ISD::SETNE);
4107 }
4108 
4109 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4110                                  bool &swpCmpOps, bool &swpVselOps) {
4111   // Start by selecting the GE condition code for opcodes that return true for
4112   // 'equality'
4113   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4114       CC == ISD::SETULE)
4115     CondCode = ARMCC::GE;
4116 
4117   // and GT for opcodes that return false for 'equality'.
4118   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4119            CC == ISD::SETULT)
4120     CondCode = ARMCC::GT;
4121 
4122   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4123   // to swap the compare operands.
4124   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4125       CC == ISD::SETULT)
4126     swpCmpOps = true;
4127 
4128   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4129   // If we have an unordered opcode, we need to swap the operands to the VSEL
4130   // instruction (effectively negating the condition).
4131   //
4132   // This also has the effect of swapping which one of 'less' or 'greater'
4133   // returns true, so we also swap the compare operands. It also switches
4134   // whether we return true for 'equality', so we compensate by picking the
4135   // opposite condition code to our original choice.
4136   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4137       CC == ISD::SETUGT) {
4138     swpCmpOps = !swpCmpOps;
4139     swpVselOps = !swpVselOps;
4140     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4141   }
4142 
4143   // 'ordered' is 'anything but unordered', so use the VS condition code and
4144   // swap the VSEL operands.
4145   if (CC == ISD::SETO) {
4146     CondCode = ARMCC::VS;
4147     swpVselOps = true;
4148   }
4149 
4150   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4151   // code and swap the VSEL operands.
4152   if (CC == ISD::SETUNE) {
4153     CondCode = ARMCC::EQ;
4154     swpVselOps = true;
4155   }
4156 }
4157 
4158 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4159                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4160                                    SDValue Cmp, SelectionDAG &DAG) const {
4161   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4162     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4163                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4164     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4165                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4166 
4167     SDValue TrueLow = TrueVal.getValue(0);
4168     SDValue TrueHigh = TrueVal.getValue(1);
4169     SDValue FalseLow = FalseVal.getValue(0);
4170     SDValue FalseHigh = FalseVal.getValue(1);
4171 
4172     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4173                               ARMcc, CCR, Cmp);
4174     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4175                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4176 
4177     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4178   } else {
4179     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4180                        Cmp);
4181   }
4182 }
4183 
4184 static bool isGTorGE(ISD::CondCode CC) {
4185   return CC == ISD::SETGT || CC == ISD::SETGE;
4186 }
4187 
4188 static bool isLTorLE(ISD::CondCode CC) {
4189   return CC == ISD::SETLT || CC == ISD::SETLE;
4190 }
4191 
4192 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4193 // All of these conditions (and their <= and >= counterparts) will do:
4194 //          x < k ? k : x
4195 //          x > k ? x : k
4196 //          k < x ? x : k
4197 //          k > x ? k : x
4198 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4199                             const SDValue TrueVal, const SDValue FalseVal,
4200                             const ISD::CondCode CC, const SDValue K) {
4201   return (isGTorGE(CC) &&
4202           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4203          (isLTorLE(CC) &&
4204           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4205 }
4206 
4207 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4208 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4209                             const SDValue TrueVal, const SDValue FalseVal,
4210                             const ISD::CondCode CC, const SDValue K) {
4211   return (isGTorGE(CC) &&
4212           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4213          (isLTorLE(CC) &&
4214           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4215 }
4216 
4217 // Check if two chained conditionals could be converted into SSAT.
4218 //
4219 // SSAT can replace a set of two conditional selectors that bound a number to an
4220 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4221 //
4222 //     x < -k ? -k : (x > k ? k : x)
4223 //     x < -k ? -k : (x < k ? x : k)
4224 //     x > -k ? (x > k ? k : x) : -k
4225 //     x < k ? (x < -k ? -k : x) : k
4226 //     etc.
4227 //
4228 // It returns true if the conversion can be done, false otherwise.
4229 // Additionally, the variable is returned in parameter V and the constant in K.
4230 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4231                                     uint64_t &K) {
4232   SDValue LHS1 = Op.getOperand(0);
4233   SDValue RHS1 = Op.getOperand(1);
4234   SDValue TrueVal1 = Op.getOperand(2);
4235   SDValue FalseVal1 = Op.getOperand(3);
4236   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4237 
4238   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4239   if (Op2.getOpcode() != ISD::SELECT_CC)
4240     return false;
4241 
4242   SDValue LHS2 = Op2.getOperand(0);
4243   SDValue RHS2 = Op2.getOperand(1);
4244   SDValue TrueVal2 = Op2.getOperand(2);
4245   SDValue FalseVal2 = Op2.getOperand(3);
4246   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4247 
4248   // Find out which are the constants and which are the variables
4249   // in each conditional
4250   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4251                                                         ? &RHS1
4252                                                         : nullptr;
4253   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4254                                                         ? &RHS2
4255                                                         : nullptr;
4256   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4257   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4258   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4259   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4260 
4261   // We must detect cases where the original operations worked with 16- or
4262   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4263   // must work with sign-extended values but the select operations return
4264   // the original non-extended value.
4265   SDValue V2TmpReg = V2Tmp;
4266   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4267     V2TmpReg = V2Tmp->getOperand(0);
4268 
4269   // Check that the registers and the constants have the correct values
4270   // in both conditionals
4271   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4272       V2TmpReg != V2)
4273     return false;
4274 
4275   // Figure out which conditional is saturating the lower/upper bound.
4276   const SDValue *LowerCheckOp =
4277       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4278           ? &Op
4279           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4280                 ? &Op2
4281                 : nullptr;
4282   const SDValue *UpperCheckOp =
4283       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4284           ? &Op
4285           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4286                 ? &Op2
4287                 : nullptr;
4288 
4289   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4290     return false;
4291 
4292   // Check that the constant in the lower-bound check is
4293   // the opposite of the constant in the upper-bound check
4294   // in 1's complement.
4295   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4296   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4297   int64_t PosVal = std::max(Val1, Val2);
4298 
4299   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4300        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4301       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4302 
4303     V = V2;
4304     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4305     return true;
4306   }
4307 
4308   return false;
4309 }
4310 
4311 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4312   EVT VT = Op.getValueType();
4313   SDLoc dl(Op);
4314 
4315   // Try to convert two saturating conditional selects into a single SSAT
4316   SDValue SatValue;
4317   uint64_t SatConstant;
4318   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4319       isSaturatingConditional(Op, SatValue, SatConstant))
4320     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4321                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4322 
4323   SDValue LHS = Op.getOperand(0);
4324   SDValue RHS = Op.getOperand(1);
4325   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4326   SDValue TrueVal = Op.getOperand(2);
4327   SDValue FalseVal = Op.getOperand(3);
4328 
4329   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4330     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4331                                                     dl);
4332 
4333     // If softenSetCCOperands only returned one value, we should compare it to
4334     // zero.
4335     if (!RHS.getNode()) {
4336       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4337       CC = ISD::SETNE;
4338     }
4339   }
4340 
4341   if (LHS.getValueType() == MVT::i32) {
4342     // Try to generate VSEL on ARMv8.
4343     // The VSEL instruction can't use all the usual ARM condition
4344     // codes: it only has two bits to select the condition code, so it's
4345     // constrained to use only GE, GT, VS and EQ.
4346     //
4347     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4348     // swap the operands of the previous compare instruction (effectively
4349     // inverting the compare condition, swapping 'less' and 'greater') and
4350     // sometimes need to swap the operands to the VSEL (which inverts the
4351     // condition in the sense of firing whenever the previous condition didn't)
4352     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4353                                     TrueVal.getValueType() == MVT::f64)) {
4354       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4355       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4356           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4357         CC = ISD::getSetCCInverse(CC, true);
4358         std::swap(TrueVal, FalseVal);
4359       }
4360     }
4361 
4362     SDValue ARMcc;
4363     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4364     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4365     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4366   }
4367 
4368   ARMCC::CondCodes CondCode, CondCode2;
4369   bool InvalidOnQNaN;
4370   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4371 
4372   // Try to generate VMAXNM/VMINNM on ARMv8.
4373   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4374                                   TrueVal.getValueType() == MVT::f64)) {
4375     bool swpCmpOps = false;
4376     bool swpVselOps = false;
4377     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4378 
4379     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4380         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4381       if (swpCmpOps)
4382         std::swap(LHS, RHS);
4383       if (swpVselOps)
4384         std::swap(TrueVal, FalseVal);
4385     }
4386   }
4387 
4388   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4389   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4390   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4391   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4392   if (CondCode2 != ARMCC::AL) {
4393     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4394     // FIXME: Needs another CMP because flag can have but one use.
4395     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4396     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4397   }
4398   return Result;
4399 }
4400 
4401 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4402 /// to morph to an integer compare sequence.
4403 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4404                            const ARMSubtarget *Subtarget) {
4405   SDNode *N = Op.getNode();
4406   if (!N->hasOneUse())
4407     // Otherwise it requires moving the value from fp to integer registers.
4408     return false;
4409   if (!N->getNumValues())
4410     return false;
4411   EVT VT = Op.getValueType();
4412   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4413     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4414     // vmrs are very slow, e.g. cortex-a8.
4415     return false;
4416 
4417   if (isFloatingPointZero(Op)) {
4418     SeenZero = true;
4419     return true;
4420   }
4421   return ISD::isNormalLoad(N);
4422 }
4423 
4424 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4425   if (isFloatingPointZero(Op))
4426     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4427 
4428   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4429     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4430                        Ld->getPointerInfo(), Ld->getAlignment(),
4431                        Ld->getMemOperand()->getFlags());
4432 
4433   llvm_unreachable("Unknown VFP cmp argument!");
4434 }
4435 
4436 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4437                            SDValue &RetVal1, SDValue &RetVal2) {
4438   SDLoc dl(Op);
4439 
4440   if (isFloatingPointZero(Op)) {
4441     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4442     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4443     return;
4444   }
4445 
4446   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4447     SDValue Ptr = Ld->getBasePtr();
4448     RetVal1 =
4449         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4450                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4451 
4452     EVT PtrType = Ptr.getValueType();
4453     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4454     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4455                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4456     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4457                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4458                           Ld->getMemOperand()->getFlags());
4459     return;
4460   }
4461 
4462   llvm_unreachable("Unknown VFP cmp argument!");
4463 }
4464 
4465 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4466 /// f32 and even f64 comparisons to integer ones.
4467 SDValue
4468 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4469   SDValue Chain = Op.getOperand(0);
4470   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4471   SDValue LHS = Op.getOperand(2);
4472   SDValue RHS = Op.getOperand(3);
4473   SDValue Dest = Op.getOperand(4);
4474   SDLoc dl(Op);
4475 
4476   bool LHSSeenZero = false;
4477   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4478   bool RHSSeenZero = false;
4479   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4480   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4481     // If unsafe fp math optimization is enabled and there are no other uses of
4482     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4483     // to an integer comparison.
4484     if (CC == ISD::SETOEQ)
4485       CC = ISD::SETEQ;
4486     else if (CC == ISD::SETUNE)
4487       CC = ISD::SETNE;
4488 
4489     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4490     SDValue ARMcc;
4491     if (LHS.getValueType() == MVT::f32) {
4492       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4493                         bitcastf32Toi32(LHS, DAG), Mask);
4494       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4495                         bitcastf32Toi32(RHS, DAG), Mask);
4496       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4497       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4498       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4499                          Chain, Dest, ARMcc, CCR, Cmp);
4500     }
4501 
4502     SDValue LHS1, LHS2;
4503     SDValue RHS1, RHS2;
4504     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4505     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4506     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4507     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4508     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4509     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4510     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4511     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4512     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4513   }
4514 
4515   return SDValue();
4516 }
4517 
4518 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4519   SDValue Chain = Op.getOperand(0);
4520   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4521   SDValue LHS = Op.getOperand(2);
4522   SDValue RHS = Op.getOperand(3);
4523   SDValue Dest = Op.getOperand(4);
4524   SDLoc dl(Op);
4525 
4526   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4527     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4528                                                     dl);
4529 
4530     // If softenSetCCOperands only returned one value, we should compare it to
4531     // zero.
4532     if (!RHS.getNode()) {
4533       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4534       CC = ISD::SETNE;
4535     }
4536   }
4537 
4538   if (LHS.getValueType() == MVT::i32) {
4539     SDValue ARMcc;
4540     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4541     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4542     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4543                        Chain, Dest, ARMcc, CCR, Cmp);
4544   }
4545 
4546   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4547 
4548   if (getTargetMachine().Options.UnsafeFPMath &&
4549       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4550        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4551     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4552       return Result;
4553   }
4554 
4555   ARMCC::CondCodes CondCode, CondCode2;
4556   bool InvalidOnQNaN;
4557   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4558 
4559   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4560   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4561   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4562   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4563   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4564   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4565   if (CondCode2 != ARMCC::AL) {
4566     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4567     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4568     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4569   }
4570   return Res;
4571 }
4572 
4573 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4574   SDValue Chain = Op.getOperand(0);
4575   SDValue Table = Op.getOperand(1);
4576   SDValue Index = Op.getOperand(2);
4577   SDLoc dl(Op);
4578 
4579   EVT PTy = getPointerTy(DAG.getDataLayout());
4580   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4581   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4582   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4583   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4584   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4585   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4586     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4587     // which does another jump to the destination. This also makes it easier
4588     // to translate it to TBB / TBH later (Thumb2 only).
4589     // FIXME: This might not work if the function is extremely large.
4590     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4591                        Addr, Op.getOperand(2), JTI);
4592   }
4593   if (isPositionIndependent() || Subtarget->isROPI()) {
4594     Addr =
4595         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4596                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4597     Chain = Addr.getValue(1);
4598     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4599     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4600   } else {
4601     Addr =
4602         DAG.getLoad(PTy, dl, Chain, Addr,
4603                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4604     Chain = Addr.getValue(1);
4605     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4606   }
4607 }
4608 
4609 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4610   EVT VT = Op.getValueType();
4611   SDLoc dl(Op);
4612 
4613   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4614     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4615       return Op;
4616     return DAG.UnrollVectorOp(Op.getNode());
4617   }
4618 
4619   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4620          "Invalid type for custom lowering!");
4621   if (VT != MVT::v4i16)
4622     return DAG.UnrollVectorOp(Op.getNode());
4623 
4624   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4625   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4626 }
4627 
4628 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4629   EVT VT = Op.getValueType();
4630   if (VT.isVector())
4631     return LowerVectorFP_TO_INT(Op, DAG);
4632   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4633     RTLIB::Libcall LC;
4634     if (Op.getOpcode() == ISD::FP_TO_SINT)
4635       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4636                               Op.getValueType());
4637     else
4638       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4639                               Op.getValueType());
4640     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4641                        /*isSigned*/ false, SDLoc(Op)).first;
4642   }
4643 
4644   return Op;
4645 }
4646 
4647 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4648   EVT VT = Op.getValueType();
4649   SDLoc dl(Op);
4650 
4651   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4652     if (VT.getVectorElementType() == MVT::f32)
4653       return Op;
4654     return DAG.UnrollVectorOp(Op.getNode());
4655   }
4656 
4657   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4658          "Invalid type for custom lowering!");
4659   if (VT != MVT::v4f32)
4660     return DAG.UnrollVectorOp(Op.getNode());
4661 
4662   unsigned CastOpc;
4663   unsigned Opc;
4664   switch (Op.getOpcode()) {
4665   default: llvm_unreachable("Invalid opcode!");
4666   case ISD::SINT_TO_FP:
4667     CastOpc = ISD::SIGN_EXTEND;
4668     Opc = ISD::SINT_TO_FP;
4669     break;
4670   case ISD::UINT_TO_FP:
4671     CastOpc = ISD::ZERO_EXTEND;
4672     Opc = ISD::UINT_TO_FP;
4673     break;
4674   }
4675 
4676   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4677   return DAG.getNode(Opc, dl, VT, Op);
4678 }
4679 
4680 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4681   EVT VT = Op.getValueType();
4682   if (VT.isVector())
4683     return LowerVectorINT_TO_FP(Op, DAG);
4684   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4685     RTLIB::Libcall LC;
4686     if (Op.getOpcode() == ISD::SINT_TO_FP)
4687       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4688                               Op.getValueType());
4689     else
4690       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4691                               Op.getValueType());
4692     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4693                        /*isSigned*/ false, SDLoc(Op)).first;
4694   }
4695 
4696   return Op;
4697 }
4698 
4699 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4700   // Implement fcopysign with a fabs and a conditional fneg.
4701   SDValue Tmp0 = Op.getOperand(0);
4702   SDValue Tmp1 = Op.getOperand(1);
4703   SDLoc dl(Op);
4704   EVT VT = Op.getValueType();
4705   EVT SrcVT = Tmp1.getValueType();
4706   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4707     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4708   bool UseNEON = !InGPR && Subtarget->hasNEON();
4709 
4710   if (UseNEON) {
4711     // Use VBSL to copy the sign bit.
4712     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4713     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4714                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4715     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4716     if (VT == MVT::f64)
4717       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4718                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4719                          DAG.getConstant(32, dl, MVT::i32));
4720     else /*if (VT == MVT::f32)*/
4721       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4722     if (SrcVT == MVT::f32) {
4723       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4724       if (VT == MVT::f64)
4725         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4726                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4727                            DAG.getConstant(32, dl, MVT::i32));
4728     } else if (VT == MVT::f32)
4729       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4730                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4731                          DAG.getConstant(32, dl, MVT::i32));
4732     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4733     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4734 
4735     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4736                                             dl, MVT::i32);
4737     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4738     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4739                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4740 
4741     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4742                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4743                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4744     if (VT == MVT::f32) {
4745       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4746       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4747                         DAG.getConstant(0, dl, MVT::i32));
4748     } else {
4749       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4750     }
4751 
4752     return Res;
4753   }
4754 
4755   // Bitcast operand 1 to i32.
4756   if (SrcVT == MVT::f64)
4757     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4758                        Tmp1).getValue(1);
4759   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4760 
4761   // Or in the signbit with integer operations.
4762   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4763   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4764   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4765   if (VT == MVT::f32) {
4766     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4767                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4768     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4769                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4770   }
4771 
4772   // f64: Or the high part with signbit and then combine two parts.
4773   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4774                      Tmp0);
4775   SDValue Lo = Tmp0.getValue(0);
4776   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4777   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4778   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4779 }
4780 
4781 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4782   MachineFunction &MF = DAG.getMachineFunction();
4783   MachineFrameInfo &MFI = MF.getFrameInfo();
4784   MFI.setReturnAddressIsTaken(true);
4785 
4786   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4787     return SDValue();
4788 
4789   EVT VT = Op.getValueType();
4790   SDLoc dl(Op);
4791   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4792   if (Depth) {
4793     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4794     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4795     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4796                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4797                        MachinePointerInfo());
4798   }
4799 
4800   // Return LR, which contains the return address. Mark it an implicit live-in.
4801   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4802   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4803 }
4804 
4805 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4806   const ARMBaseRegisterInfo &ARI =
4807     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4808   MachineFunction &MF = DAG.getMachineFunction();
4809   MachineFrameInfo &MFI = MF.getFrameInfo();
4810   MFI.setFrameAddressIsTaken(true);
4811 
4812   EVT VT = Op.getValueType();
4813   SDLoc dl(Op);  // FIXME probably not meaningful
4814   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4815   unsigned FrameReg = ARI.getFrameRegister(MF);
4816   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4817   while (Depth--)
4818     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4819                             MachinePointerInfo());
4820   return FrameAddr;
4821 }
4822 
4823 // FIXME? Maybe this could be a TableGen attribute on some registers and
4824 // this table could be generated automatically from RegInfo.
4825 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4826                                               SelectionDAG &DAG) const {
4827   unsigned Reg = StringSwitch<unsigned>(RegName)
4828                        .Case("sp", ARM::SP)
4829                        .Default(0);
4830   if (Reg)
4831     return Reg;
4832   report_fatal_error(Twine("Invalid register name \""
4833                               + StringRef(RegName)  + "\"."));
4834 }
4835 
4836 // Result is 64 bit value so split into two 32 bit values and return as a
4837 // pair of values.
4838 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4839                                 SelectionDAG &DAG) {
4840   SDLoc DL(N);
4841 
4842   // This function is only supposed to be called for i64 type destination.
4843   assert(N->getValueType(0) == MVT::i64
4844           && "ExpandREAD_REGISTER called for non-i64 type result.");
4845 
4846   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4847                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4848                              N->getOperand(0),
4849                              N->getOperand(1));
4850 
4851   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4852                     Read.getValue(1)));
4853   Results.push_back(Read.getOperand(0));
4854 }
4855 
4856 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4857 /// When \p DstVT, the destination type of \p BC, is on the vector
4858 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4859 /// it might be possible to combine them, such that everything stays on the
4860 /// vector register bank.
4861 /// \p return The node that would replace \p BT, if the combine
4862 /// is possible.
4863 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4864                                                 SelectionDAG &DAG) {
4865   SDValue Op = BC->getOperand(0);
4866   EVT DstVT = BC->getValueType(0);
4867 
4868   // The only vector instruction that can produce a scalar (remember,
4869   // since the bitcast was about to be turned into VMOVDRR, the source
4870   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4871   // Moreover, we can do this combine only if there is one use.
4872   // Finally, if the destination type is not a vector, there is not
4873   // much point on forcing everything on the vector bank.
4874   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4875       !Op.hasOneUse())
4876     return SDValue();
4877 
4878   // If the index is not constant, we will introduce an additional
4879   // multiply that will stick.
4880   // Give up in that case.
4881   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4882   if (!Index)
4883     return SDValue();
4884   unsigned DstNumElt = DstVT.getVectorNumElements();
4885 
4886   // Compute the new index.
4887   const APInt &APIntIndex = Index->getAPIntValue();
4888   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4889   NewIndex *= APIntIndex;
4890   // Check if the new constant index fits into i32.
4891   if (NewIndex.getBitWidth() > 32)
4892     return SDValue();
4893 
4894   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4895   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4896   SDLoc dl(Op);
4897   SDValue ExtractSrc = Op.getOperand(0);
4898   EVT VecVT = EVT::getVectorVT(
4899       *DAG.getContext(), DstVT.getScalarType(),
4900       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4901   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4902   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4903                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4904 }
4905 
4906 /// ExpandBITCAST - If the target supports VFP, this function is called to
4907 /// expand a bit convert where either the source or destination type is i64 to
4908 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4909 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4910 /// vectors), since the legalizer won't know what to do with that.
4911 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4913   SDLoc dl(N);
4914   SDValue Op = N->getOperand(0);
4915 
4916   // This function is only supposed to be called for i64 types, either as the
4917   // source or destination of the bit convert.
4918   EVT SrcVT = Op.getValueType();
4919   EVT DstVT = N->getValueType(0);
4920   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4921          "ExpandBITCAST called for non-i64 type");
4922 
4923   // Turn i64->f64 into VMOVDRR.
4924   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4925     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4926     // if we can combine the bitcast with its source.
4927     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4928       return Val;
4929 
4930     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4931                              DAG.getConstant(0, dl, MVT::i32));
4932     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4933                              DAG.getConstant(1, dl, MVT::i32));
4934     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4935                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4936   }
4937 
4938   // Turn f64->i64 into VMOVRRD.
4939   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4940     SDValue Cvt;
4941     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4942         SrcVT.getVectorNumElements() > 1)
4943       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4944                         DAG.getVTList(MVT::i32, MVT::i32),
4945                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4946     else
4947       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4948                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4949     // Merge the pieces into a single i64 value.
4950     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4951   }
4952 
4953   return SDValue();
4954 }
4955 
4956 /// getZeroVector - Returns a vector of specified type with all zero elements.
4957 /// Zero vectors are used to represent vector negation and in those cases
4958 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4959 /// not support i64 elements, so sometimes the zero vectors will need to be
4960 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4961 /// zero vector.
4962 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4963   assert(VT.isVector() && "Expected a vector type");
4964   // The canonical modified immediate encoding of a zero vector is....0!
4965   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4966   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4967   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4968   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4969 }
4970 
4971 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4972 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4973 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4974                                                 SelectionDAG &DAG) const {
4975   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4976   EVT VT = Op.getValueType();
4977   unsigned VTBits = VT.getSizeInBits();
4978   SDLoc dl(Op);
4979   SDValue ShOpLo = Op.getOperand(0);
4980   SDValue ShOpHi = Op.getOperand(1);
4981   SDValue ShAmt  = Op.getOperand(2);
4982   SDValue ARMcc;
4983   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4984   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4985 
4986   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4987 
4988   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4989                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4990   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4991   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4992                                    DAG.getConstant(VTBits, dl, MVT::i32));
4993   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4994   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4995   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4996   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4997                             ISD::SETGE, ARMcc, DAG, dl);
4998   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4999                            ARMcc, CCR, CmpLo);
5000 
5001   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5002   SDValue HiBigShift = Opc == ISD::SRA
5003                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5004                                          DAG.getConstant(VTBits - 1, dl, VT))
5005                            : DAG.getConstant(0, dl, VT);
5006   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5007                             ISD::SETGE, ARMcc, DAG, dl);
5008   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5009                            ARMcc, CCR, CmpHi);
5010 
5011   SDValue Ops[2] = { Lo, Hi };
5012   return DAG.getMergeValues(Ops, dl);
5013 }
5014 
5015 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5016 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5017 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5018                                                SelectionDAG &DAG) const {
5019   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5020   EVT VT = Op.getValueType();
5021   unsigned VTBits = VT.getSizeInBits();
5022   SDLoc dl(Op);
5023   SDValue ShOpLo = Op.getOperand(0);
5024   SDValue ShOpHi = Op.getOperand(1);
5025   SDValue ShAmt  = Op.getOperand(2);
5026   SDValue ARMcc;
5027   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5028 
5029   assert(Op.getOpcode() == ISD::SHL_PARTS);
5030   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5031                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5032   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5033   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5034   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5035 
5036   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5037                                    DAG.getConstant(VTBits, dl, MVT::i32));
5038   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5039   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5040                             ISD::SETGE, ARMcc, DAG, dl);
5041   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5042                            ARMcc, CCR, CmpHi);
5043 
5044   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5045                           ISD::SETGE, ARMcc, DAG, dl);
5046   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5047   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5048                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5049 
5050   SDValue Ops[2] = { Lo, Hi };
5051   return DAG.getMergeValues(Ops, dl);
5052 }
5053 
5054 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5055                                             SelectionDAG &DAG) const {
5056   // The rounding mode is in bits 23:22 of the FPSCR.
5057   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5058   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5059   // so that the shift + and get folded into a bitfield extract.
5060   SDLoc dl(Op);
5061   SDValue Ops[] = { DAG.getEntryNode(),
5062                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5063 
5064   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5065   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5066                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5067   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5068                               DAG.getConstant(22, dl, MVT::i32));
5069   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5070                      DAG.getConstant(3, dl, MVT::i32));
5071 }
5072 
5073 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5074                          const ARMSubtarget *ST) {
5075   SDLoc dl(N);
5076   EVT VT = N->getValueType(0);
5077   if (VT.isVector()) {
5078     assert(ST->hasNEON());
5079 
5080     // Compute the least significant set bit: LSB = X & -X
5081     SDValue X = N->getOperand(0);
5082     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5083     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5084 
5085     EVT ElemTy = VT.getVectorElementType();
5086 
5087     if (ElemTy == MVT::i8) {
5088       // Compute with: cttz(x) = ctpop(lsb - 1)
5089       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5090                                 DAG.getTargetConstant(1, dl, ElemTy));
5091       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5092       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5093     }
5094 
5095     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5096         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5097       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5098       unsigned NumBits = ElemTy.getSizeInBits();
5099       SDValue WidthMinus1 =
5100           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5101                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5102       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5103       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5104     }
5105 
5106     // Compute with: cttz(x) = ctpop(lsb - 1)
5107 
5108     // Since we can only compute the number of bits in a byte with vcnt.8, we
5109     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5110     // and i64.
5111 
5112     // Compute LSB - 1.
5113     SDValue Bits;
5114     if (ElemTy == MVT::i64) {
5115       // Load constant 0xffff'ffff'ffff'ffff to register.
5116       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5117                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5118       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5119     } else {
5120       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5121                                 DAG.getTargetConstant(1, dl, ElemTy));
5122       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5123     }
5124 
5125     // Count #bits with vcnt.8.
5126     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5127     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5128     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5129 
5130     // Gather the #bits with vpaddl (pairwise add.)
5131     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5132     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5133         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5134         Cnt8);
5135     if (ElemTy == MVT::i16)
5136       return Cnt16;
5137 
5138     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5139     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5140         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5141         Cnt16);
5142     if (ElemTy == MVT::i32)
5143       return Cnt32;
5144 
5145     assert(ElemTy == MVT::i64);
5146     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5147         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5148         Cnt32);
5149     return Cnt64;
5150   }
5151 
5152   if (!ST->hasV6T2Ops())
5153     return SDValue();
5154 
5155   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5156   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5157 }
5158 
5159 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5160 /// for each 16-bit element from operand, repeated.  The basic idea is to
5161 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5162 ///
5163 /// Trace for v4i16:
5164 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5165 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5166 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5167 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5168 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5169 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5170 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5171 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5172 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5173   EVT VT = N->getValueType(0);
5174   SDLoc DL(N);
5175 
5176   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5177   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5178   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5179   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5180   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5181   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5182 }
5183 
5184 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5185 /// bit-count for each 16-bit element from the operand.  We need slightly
5186 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5187 /// 64/128-bit registers.
5188 ///
5189 /// Trace for v4i16:
5190 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5191 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5192 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5193 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5194 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5195   EVT VT = N->getValueType(0);
5196   SDLoc DL(N);
5197 
5198   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5199   if (VT.is64BitVector()) {
5200     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5201     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5202                        DAG.getIntPtrConstant(0, DL));
5203   } else {
5204     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5205                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5206     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5207   }
5208 }
5209 
5210 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5211 /// bit-count for each 32-bit element from the operand.  The idea here is
5212 /// to split the vector into 16-bit elements, leverage the 16-bit count
5213 /// routine, and then combine the results.
5214 ///
5215 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5216 /// input    = [v0    v1    ] (vi: 32-bit elements)
5217 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5218 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5219 /// vrev: N0 = [k1 k0 k3 k2 ]
5220 ///            [k0 k1 k2 k3 ]
5221 ///       N1 =+[k1 k0 k3 k2 ]
5222 ///            [k0 k2 k1 k3 ]
5223 ///       N2 =+[k1 k3 k0 k2 ]
5224 ///            [k0    k2    k1    k3    ]
5225 /// Extended =+[k1    k3    k0    k2    ]
5226 ///            [k0    k2    ]
5227 /// Extracted=+[k1    k3    ]
5228 ///
5229 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5230   EVT VT = N->getValueType(0);
5231   SDLoc DL(N);
5232 
5233   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5234 
5235   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5236   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5237   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5238   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5239   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5240 
5241   if (VT.is64BitVector()) {
5242     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5243     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5244                        DAG.getIntPtrConstant(0, DL));
5245   } else {
5246     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5247                                     DAG.getIntPtrConstant(0, DL));
5248     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5249   }
5250 }
5251 
5252 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5253                           const ARMSubtarget *ST) {
5254   EVT VT = N->getValueType(0);
5255 
5256   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5257   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5258           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5259          "Unexpected type for custom ctpop lowering");
5260 
5261   if (VT.getVectorElementType() == MVT::i32)
5262     return lowerCTPOP32BitElements(N, DAG);
5263   else
5264     return lowerCTPOP16BitElements(N, DAG);
5265 }
5266 
5267 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5268                           const ARMSubtarget *ST) {
5269   EVT VT = N->getValueType(0);
5270   SDLoc dl(N);
5271 
5272   if (!VT.isVector())
5273     return SDValue();
5274 
5275   // Lower vector shifts on NEON to use VSHL.
5276   assert(ST->hasNEON() && "unexpected vector shift");
5277 
5278   // Left shifts translate directly to the vshiftu intrinsic.
5279   if (N->getOpcode() == ISD::SHL)
5280     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5281                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5282                                        MVT::i32),
5283                        N->getOperand(0), N->getOperand(1));
5284 
5285   assert((N->getOpcode() == ISD::SRA ||
5286           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5287 
5288   // NEON uses the same intrinsics for both left and right shifts.  For
5289   // right shifts, the shift amounts are negative, so negate the vector of
5290   // shift amounts.
5291   EVT ShiftVT = N->getOperand(1).getValueType();
5292   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5293                                      getZeroVector(ShiftVT, DAG, dl),
5294                                      N->getOperand(1));
5295   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5296                              Intrinsic::arm_neon_vshifts :
5297                              Intrinsic::arm_neon_vshiftu);
5298   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5299                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5300                      N->getOperand(0), NegatedCount);
5301 }
5302 
5303 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5304                                 const ARMSubtarget *ST) {
5305   EVT VT = N->getValueType(0);
5306   SDLoc dl(N);
5307 
5308   // We can get here for a node like i32 = ISD::SHL i32, i64
5309   if (VT != MVT::i64)
5310     return SDValue();
5311 
5312   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5313          "Unknown shift to lower!");
5314 
5315   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5316   if (!isOneConstant(N->getOperand(1)))
5317     return SDValue();
5318 
5319   // If we are in thumb mode, we don't have RRX.
5320   if (ST->isThumb1Only()) return SDValue();
5321 
5322   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5323   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5324                            DAG.getConstant(0, dl, MVT::i32));
5325   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5326                            DAG.getConstant(1, dl, MVT::i32));
5327 
5328   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5329   // captures the result into a carry flag.
5330   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5331   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5332 
5333   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5334   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5335 
5336   // Merge the pieces into a single i64 value.
5337  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5338 }
5339 
5340 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5341   SDValue TmpOp0, TmpOp1;
5342   bool Invert = false;
5343   bool Swap = false;
5344   unsigned Opc = 0;
5345 
5346   SDValue Op0 = Op.getOperand(0);
5347   SDValue Op1 = Op.getOperand(1);
5348   SDValue CC = Op.getOperand(2);
5349   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5350   EVT VT = Op.getValueType();
5351   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5352   SDLoc dl(Op);
5353 
5354   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5355       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5356     // Special-case integer 64-bit equality comparisons. They aren't legal,
5357     // but they can be lowered with a few vector instructions.
5358     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5359     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5360     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5361     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5362     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5363                               DAG.getCondCode(ISD::SETEQ));
5364     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5365     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5366     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5367     if (SetCCOpcode == ISD::SETNE)
5368       Merged = DAG.getNOT(dl, Merged, CmpVT);
5369     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5370     return Merged;
5371   }
5372 
5373   if (CmpVT.getVectorElementType() == MVT::i64)
5374     // 64-bit comparisons are not legal in general.
5375     return SDValue();
5376 
5377   if (Op1.getValueType().isFloatingPoint()) {
5378     switch (SetCCOpcode) {
5379     default: llvm_unreachable("Illegal FP comparison");
5380     case ISD::SETUNE:
5381     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5382     case ISD::SETOEQ:
5383     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5384     case ISD::SETOLT:
5385     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5386     case ISD::SETOGT:
5387     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5388     case ISD::SETOLE:
5389     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5390     case ISD::SETOGE:
5391     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5392     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5393     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5394     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5395     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5396     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5397     case ISD::SETONE:
5398       // Expand this to (OLT | OGT).
5399       TmpOp0 = Op0;
5400       TmpOp1 = Op1;
5401       Opc = ISD::OR;
5402       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5403       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5404       break;
5405     case ISD::SETUO:
5406       Invert = true;
5407       LLVM_FALLTHROUGH;
5408     case ISD::SETO:
5409       // Expand this to (OLT | OGE).
5410       TmpOp0 = Op0;
5411       TmpOp1 = Op1;
5412       Opc = ISD::OR;
5413       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5414       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5415       break;
5416     }
5417   } else {
5418     // Integer comparisons.
5419     switch (SetCCOpcode) {
5420     default: llvm_unreachable("Illegal integer comparison");
5421     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5422     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5423     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5424     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5425     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5426     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5427     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5428     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5429     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5430     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5431     }
5432 
5433     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5434     if (Opc == ARMISD::VCEQ) {
5435       SDValue AndOp;
5436       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5437         AndOp = Op0;
5438       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5439         AndOp = Op1;
5440 
5441       // Ignore bitconvert.
5442       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5443         AndOp = AndOp.getOperand(0);
5444 
5445       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5446         Opc = ARMISD::VTST;
5447         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5448         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5449         Invert = !Invert;
5450       }
5451     }
5452   }
5453 
5454   if (Swap)
5455     std::swap(Op0, Op1);
5456 
5457   // If one of the operands is a constant vector zero, attempt to fold the
5458   // comparison to a specialized compare-against-zero form.
5459   SDValue SingleOp;
5460   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5461     SingleOp = Op0;
5462   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5463     if (Opc == ARMISD::VCGE)
5464       Opc = ARMISD::VCLEZ;
5465     else if (Opc == ARMISD::VCGT)
5466       Opc = ARMISD::VCLTZ;
5467     SingleOp = Op1;
5468   }
5469 
5470   SDValue Result;
5471   if (SingleOp.getNode()) {
5472     switch (Opc) {
5473     case ARMISD::VCEQ:
5474       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5475     case ARMISD::VCGE:
5476       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5477     case ARMISD::VCLEZ:
5478       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5479     case ARMISD::VCGT:
5480       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5481     case ARMISD::VCLTZ:
5482       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5483     default:
5484       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5485     }
5486   } else {
5487      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5488   }
5489 
5490   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5491 
5492   if (Invert)
5493     Result = DAG.getNOT(dl, Result, VT);
5494 
5495   return Result;
5496 }
5497 
5498 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5499   SDValue LHS = Op.getOperand(0);
5500   SDValue RHS = Op.getOperand(1);
5501   SDValue Carry = Op.getOperand(2);
5502   SDValue Cond = Op.getOperand(3);
5503   SDLoc DL(Op);
5504 
5505   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5506 
5507   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5508   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5509   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5510 
5511   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5512   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5513   SDValue ARMcc = DAG.getConstant(
5514       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5515   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5516   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5517                                    Cmp.getValue(1), SDValue());
5518   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5519                      CCR, Chain.getValue(1));
5520 }
5521 
5522 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5523 /// valid vector constant for a NEON instruction with a "modified immediate"
5524 /// operand (e.g., VMOV).  If so, return the encoded value.
5525 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5526                                  unsigned SplatBitSize, SelectionDAG &DAG,
5527                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5528                                  NEONModImmType type) {
5529   unsigned OpCmode, Imm;
5530 
5531   // SplatBitSize is set to the smallest size that splats the vector, so a
5532   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5533   // immediate instructions others than VMOV do not support the 8-bit encoding
5534   // of a zero vector, and the default encoding of zero is supposed to be the
5535   // 32-bit version.
5536   if (SplatBits == 0)
5537     SplatBitSize = 32;
5538 
5539   switch (SplatBitSize) {
5540   case 8:
5541     if (type != VMOVModImm)
5542       return SDValue();
5543     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5544     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5545     OpCmode = 0xe;
5546     Imm = SplatBits;
5547     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5548     break;
5549 
5550   case 16:
5551     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5552     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5553     if ((SplatBits & ~0xff) == 0) {
5554       // Value = 0x00nn: Op=x, Cmode=100x.
5555       OpCmode = 0x8;
5556       Imm = SplatBits;
5557       break;
5558     }
5559     if ((SplatBits & ~0xff00) == 0) {
5560       // Value = 0xnn00: Op=x, Cmode=101x.
5561       OpCmode = 0xa;
5562       Imm = SplatBits >> 8;
5563       break;
5564     }
5565     return SDValue();
5566 
5567   case 32:
5568     // NEON's 32-bit VMOV supports splat values where:
5569     // * only one byte is nonzero, or
5570     // * the least significant byte is 0xff and the second byte is nonzero, or
5571     // * the least significant 2 bytes are 0xff and the third is nonzero.
5572     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5573     if ((SplatBits & ~0xff) == 0) {
5574       // Value = 0x000000nn: Op=x, Cmode=000x.
5575       OpCmode = 0;
5576       Imm = SplatBits;
5577       break;
5578     }
5579     if ((SplatBits & ~0xff00) == 0) {
5580       // Value = 0x0000nn00: Op=x, Cmode=001x.
5581       OpCmode = 0x2;
5582       Imm = SplatBits >> 8;
5583       break;
5584     }
5585     if ((SplatBits & ~0xff0000) == 0) {
5586       // Value = 0x00nn0000: Op=x, Cmode=010x.
5587       OpCmode = 0x4;
5588       Imm = SplatBits >> 16;
5589       break;
5590     }
5591     if ((SplatBits & ~0xff000000) == 0) {
5592       // Value = 0xnn000000: Op=x, Cmode=011x.
5593       OpCmode = 0x6;
5594       Imm = SplatBits >> 24;
5595       break;
5596     }
5597 
5598     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5599     if (type == OtherModImm) return SDValue();
5600 
5601     if ((SplatBits & ~0xffff) == 0 &&
5602         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5603       // Value = 0x0000nnff: Op=x, Cmode=1100.
5604       OpCmode = 0xc;
5605       Imm = SplatBits >> 8;
5606       break;
5607     }
5608 
5609     if ((SplatBits & ~0xffffff) == 0 &&
5610         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5611       // Value = 0x00nnffff: Op=x, Cmode=1101.
5612       OpCmode = 0xd;
5613       Imm = SplatBits >> 16;
5614       break;
5615     }
5616 
5617     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5618     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5619     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5620     // and fall through here to test for a valid 64-bit splat.  But, then the
5621     // caller would also need to check and handle the change in size.
5622     return SDValue();
5623 
5624   case 64: {
5625     if (type != VMOVModImm)
5626       return SDValue();
5627     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5628     uint64_t BitMask = 0xff;
5629     uint64_t Val = 0;
5630     unsigned ImmMask = 1;
5631     Imm = 0;
5632     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5633       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5634         Val |= BitMask;
5635         Imm |= ImmMask;
5636       } else if ((SplatBits & BitMask) != 0) {
5637         return SDValue();
5638       }
5639       BitMask <<= 8;
5640       ImmMask <<= 1;
5641     }
5642 
5643     if (DAG.getDataLayout().isBigEndian())
5644       // swap higher and lower 32 bit word
5645       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5646 
5647     // Op=1, Cmode=1110.
5648     OpCmode = 0x1e;
5649     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5650     break;
5651   }
5652 
5653   default:
5654     llvm_unreachable("unexpected size for isNEONModifiedImm");
5655   }
5656 
5657   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5658   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5659 }
5660 
5661 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5662                                            const ARMSubtarget *ST) const {
5663   bool IsDouble = Op.getValueType() == MVT::f64;
5664   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5665   const APFloat &FPVal = CFP->getValueAPF();
5666 
5667   // Prevent floating-point constants from using literal loads
5668   // when execute-only is enabled.
5669   if (ST->genExecuteOnly()) {
5670     APInt INTVal = FPVal.bitcastToAPInt();
5671     SDLoc DL(CFP);
5672     if (IsDouble) {
5673       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5674       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5675       if (!ST->isLittle())
5676         std::swap(Lo, Hi);
5677       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5678     } else {
5679       return DAG.getConstant(INTVal, DL, MVT::i32);
5680     }
5681   }
5682 
5683   if (!ST->hasVFP3())
5684     return SDValue();
5685 
5686   // Use the default (constant pool) lowering for double constants when we have
5687   // an SP-only FPU
5688   if (IsDouble && Subtarget->isFPOnlySP())
5689     return SDValue();
5690 
5691   // Try splatting with a VMOV.f32...
5692   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5693 
5694   if (ImmVal != -1) {
5695     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5696       // We have code in place to select a valid ConstantFP already, no need to
5697       // do any mangling.
5698       return Op;
5699     }
5700 
5701     // It's a float and we are trying to use NEON operations where
5702     // possible. Lower it to a splat followed by an extract.
5703     SDLoc DL(Op);
5704     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5705     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5706                                       NewVal);
5707     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5708                        DAG.getConstant(0, DL, MVT::i32));
5709   }
5710 
5711   // The rest of our options are NEON only, make sure that's allowed before
5712   // proceeding..
5713   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5714     return SDValue();
5715 
5716   EVT VMovVT;
5717   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5718 
5719   // It wouldn't really be worth bothering for doubles except for one very
5720   // important value, which does happen to match: 0.0. So make sure we don't do
5721   // anything stupid.
5722   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5723     return SDValue();
5724 
5725   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5726   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5727                                      VMovVT, false, VMOVModImm);
5728   if (NewVal != SDValue()) {
5729     SDLoc DL(Op);
5730     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5731                                       NewVal);
5732     if (IsDouble)
5733       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5734 
5735     // It's a float: cast and extract a vector element.
5736     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5737                                        VecConstant);
5738     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5739                        DAG.getConstant(0, DL, MVT::i32));
5740   }
5741 
5742   // Finally, try a VMVN.i32
5743   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5744                              false, VMVNModImm);
5745   if (NewVal != SDValue()) {
5746     SDLoc DL(Op);
5747     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5748 
5749     if (IsDouble)
5750       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5751 
5752     // It's a float: cast and extract a vector element.
5753     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5754                                        VecConstant);
5755     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5756                        DAG.getConstant(0, DL, MVT::i32));
5757   }
5758 
5759   return SDValue();
5760 }
5761 
5762 // check if an VEXT instruction can handle the shuffle mask when the
5763 // vector sources of the shuffle are the same.
5764 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5765   unsigned NumElts = VT.getVectorNumElements();
5766 
5767   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5768   if (M[0] < 0)
5769     return false;
5770 
5771   Imm = M[0];
5772 
5773   // If this is a VEXT shuffle, the immediate value is the index of the first
5774   // element.  The other shuffle indices must be the successive elements after
5775   // the first one.
5776   unsigned ExpectedElt = Imm;
5777   for (unsigned i = 1; i < NumElts; ++i) {
5778     // Increment the expected index.  If it wraps around, just follow it
5779     // back to index zero and keep going.
5780     ++ExpectedElt;
5781     if (ExpectedElt == NumElts)
5782       ExpectedElt = 0;
5783 
5784     if (M[i] < 0) continue; // ignore UNDEF indices
5785     if (ExpectedElt != static_cast<unsigned>(M[i]))
5786       return false;
5787   }
5788 
5789   return true;
5790 }
5791 
5792 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5793                        bool &ReverseVEXT, unsigned &Imm) {
5794   unsigned NumElts = VT.getVectorNumElements();
5795   ReverseVEXT = false;
5796 
5797   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5798   if (M[0] < 0)
5799     return false;
5800 
5801   Imm = M[0];
5802 
5803   // If this is a VEXT shuffle, the immediate value is the index of the first
5804   // element.  The other shuffle indices must be the successive elements after
5805   // the first one.
5806   unsigned ExpectedElt = Imm;
5807   for (unsigned i = 1; i < NumElts; ++i) {
5808     // Increment the expected index.  If it wraps around, it may still be
5809     // a VEXT but the source vectors must be swapped.
5810     ExpectedElt += 1;
5811     if (ExpectedElt == NumElts * 2) {
5812       ExpectedElt = 0;
5813       ReverseVEXT = true;
5814     }
5815 
5816     if (M[i] < 0) continue; // ignore UNDEF indices
5817     if (ExpectedElt != static_cast<unsigned>(M[i]))
5818       return false;
5819   }
5820 
5821   // Adjust the index value if the source operands will be swapped.
5822   if (ReverseVEXT)
5823     Imm -= NumElts;
5824 
5825   return true;
5826 }
5827 
5828 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5829 /// instruction with the specified blocksize.  (The order of the elements
5830 /// within each block of the vector is reversed.)
5831 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5832   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5833          "Only possible block sizes for VREV are: 16, 32, 64");
5834 
5835   unsigned EltSz = VT.getScalarSizeInBits();
5836   if (EltSz == 64)
5837     return false;
5838 
5839   unsigned NumElts = VT.getVectorNumElements();
5840   unsigned BlockElts = M[0] + 1;
5841   // If the first shuffle index is UNDEF, be optimistic.
5842   if (M[0] < 0)
5843     BlockElts = BlockSize / EltSz;
5844 
5845   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5846     return false;
5847 
5848   for (unsigned i = 0; i < NumElts; ++i) {
5849     if (M[i] < 0) continue; // ignore UNDEF indices
5850     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5851       return false;
5852   }
5853 
5854   return true;
5855 }
5856 
5857 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5858   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5859   // range, then 0 is placed into the resulting vector. So pretty much any mask
5860   // of 8 elements can work here.
5861   return VT == MVT::v8i8 && M.size() == 8;
5862 }
5863 
5864 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
5865                                unsigned Index) {
5866   if (Mask.size() == Elements * 2)
5867     return Index / Elements;
5868   return Mask[Index] == 0 ? 0 : 1;
5869 }
5870 
5871 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5872 // checking that pairs of elements in the shuffle mask represent the same index
5873 // in each vector, incrementing the expected index by 2 at each step.
5874 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5875 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5876 //  v2={e,f,g,h}
5877 // WhichResult gives the offset for each element in the mask based on which
5878 // of the two results it belongs to.
5879 //
5880 // The transpose can be represented either as:
5881 // result1 = shufflevector v1, v2, result1_shuffle_mask
5882 // result2 = shufflevector v1, v2, result2_shuffle_mask
5883 // where v1/v2 and the shuffle masks have the same number of elements
5884 // (here WhichResult (see below) indicates which result is being checked)
5885 //
5886 // or as:
5887 // results = shufflevector v1, v2, shuffle_mask
5888 // where both results are returned in one vector and the shuffle mask has twice
5889 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5890 // want to check the low half and high half of the shuffle mask as if it were
5891 // the other case
5892 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5893   unsigned EltSz = VT.getScalarSizeInBits();
5894   if (EltSz == 64)
5895     return false;
5896 
5897   unsigned NumElts = VT.getVectorNumElements();
5898   if (M.size() != NumElts && M.size() != NumElts*2)
5899     return false;
5900 
5901   // If the mask is twice as long as the input vector then we need to check the
5902   // upper and lower parts of the mask with a matching value for WhichResult
5903   // FIXME: A mask with only even values will be rejected in case the first
5904   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5905   // M[0] is used to determine WhichResult
5906   for (unsigned i = 0; i < M.size(); i += NumElts) {
5907     WhichResult = SelectPairHalf(NumElts, M, i);
5908     for (unsigned j = 0; j < NumElts; j += 2) {
5909       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5910           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5911         return false;
5912     }
5913   }
5914 
5915   if (M.size() == NumElts*2)
5916     WhichResult = 0;
5917 
5918   return true;
5919 }
5920 
5921 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5922 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5923 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5924 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5925   unsigned EltSz = VT.getScalarSizeInBits();
5926   if (EltSz == 64)
5927     return false;
5928 
5929   unsigned NumElts = VT.getVectorNumElements();
5930   if (M.size() != NumElts && M.size() != NumElts*2)
5931     return false;
5932 
5933   for (unsigned i = 0; i < M.size(); i += NumElts) {
5934     WhichResult = SelectPairHalf(NumElts, M, i);
5935     for (unsigned j = 0; j < NumElts; j += 2) {
5936       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5937           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5938         return false;
5939     }
5940   }
5941 
5942   if (M.size() == NumElts*2)
5943     WhichResult = 0;
5944 
5945   return true;
5946 }
5947 
5948 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5949 // that the mask elements are either all even and in steps of size 2 or all odd
5950 // and in steps of size 2.
5951 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5952 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5953 //  v2={e,f,g,h}
5954 // Requires similar checks to that of isVTRNMask with
5955 // respect the how results are returned.
5956 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5957   unsigned EltSz = VT.getScalarSizeInBits();
5958   if (EltSz == 64)
5959     return false;
5960 
5961   unsigned NumElts = VT.getVectorNumElements();
5962   if (M.size() != NumElts && M.size() != NumElts*2)
5963     return false;
5964 
5965   for (unsigned i = 0; i < M.size(); i += NumElts) {
5966     WhichResult = SelectPairHalf(NumElts, M, i);
5967     for (unsigned j = 0; j < NumElts; ++j) {
5968       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5969         return false;
5970     }
5971   }
5972 
5973   if (M.size() == NumElts*2)
5974     WhichResult = 0;
5975 
5976   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5977   if (VT.is64BitVector() && EltSz == 32)
5978     return false;
5979 
5980   return true;
5981 }
5982 
5983 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5984 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5985 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5986 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5987   unsigned EltSz = VT.getScalarSizeInBits();
5988   if (EltSz == 64)
5989     return false;
5990 
5991   unsigned NumElts = VT.getVectorNumElements();
5992   if (M.size() != NumElts && M.size() != NumElts*2)
5993     return false;
5994 
5995   unsigned Half = NumElts / 2;
5996   for (unsigned i = 0; i < M.size(); i += NumElts) {
5997     WhichResult = SelectPairHalf(NumElts, M, i);
5998     for (unsigned j = 0; j < NumElts; j += Half) {
5999       unsigned Idx = WhichResult;
6000       for (unsigned k = 0; k < Half; ++k) {
6001         int MIdx = M[i + j + k];
6002         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6003           return false;
6004         Idx += 2;
6005       }
6006     }
6007   }
6008 
6009   if (M.size() == NumElts*2)
6010     WhichResult = 0;
6011 
6012   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6013   if (VT.is64BitVector() && EltSz == 32)
6014     return false;
6015 
6016   return true;
6017 }
6018 
6019 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6020 // that pairs of elements of the shufflemask represent the same index in each
6021 // vector incrementing sequentially through the vectors.
6022 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6023 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6024 //  v2={e,f,g,h}
6025 // Requires similar checks to that of isVTRNMask with respect the how results
6026 // are returned.
6027 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6028   unsigned EltSz = VT.getScalarSizeInBits();
6029   if (EltSz == 64)
6030     return false;
6031 
6032   unsigned NumElts = VT.getVectorNumElements();
6033   if (M.size() != NumElts && M.size() != NumElts*2)
6034     return false;
6035 
6036   for (unsigned i = 0; i < M.size(); i += NumElts) {
6037     WhichResult = SelectPairHalf(NumElts, M, i);
6038     unsigned Idx = WhichResult * NumElts / 2;
6039     for (unsigned j = 0; j < NumElts; j += 2) {
6040       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6041           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6042         return false;
6043       Idx += 1;
6044     }
6045   }
6046 
6047   if (M.size() == NumElts*2)
6048     WhichResult = 0;
6049 
6050   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6051   if (VT.is64BitVector() && EltSz == 32)
6052     return false;
6053 
6054   return true;
6055 }
6056 
6057 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6058 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6059 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6060 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6061   unsigned EltSz = VT.getScalarSizeInBits();
6062   if (EltSz == 64)
6063     return false;
6064 
6065   unsigned NumElts = VT.getVectorNumElements();
6066   if (M.size() != NumElts && M.size() != NumElts*2)
6067     return false;
6068 
6069   for (unsigned i = 0; i < M.size(); i += NumElts) {
6070     WhichResult = SelectPairHalf(NumElts, M, i);
6071     unsigned Idx = WhichResult * NumElts / 2;
6072     for (unsigned j = 0; j < NumElts; j += 2) {
6073       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6074           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6075         return false;
6076       Idx += 1;
6077     }
6078   }
6079 
6080   if (M.size() == NumElts*2)
6081     WhichResult = 0;
6082 
6083   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6084   if (VT.is64BitVector() && EltSz == 32)
6085     return false;
6086 
6087   return true;
6088 }
6089 
6090 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6091 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6092 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6093                                            unsigned &WhichResult,
6094                                            bool &isV_UNDEF) {
6095   isV_UNDEF = false;
6096   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6097     return ARMISD::VTRN;
6098   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6099     return ARMISD::VUZP;
6100   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6101     return ARMISD::VZIP;
6102 
6103   isV_UNDEF = true;
6104   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6105     return ARMISD::VTRN;
6106   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6107     return ARMISD::VUZP;
6108   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6109     return ARMISD::VZIP;
6110 
6111   return 0;
6112 }
6113 
6114 /// \return true if this is a reverse operation on an vector.
6115 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6116   unsigned NumElts = VT.getVectorNumElements();
6117   // Make sure the mask has the right size.
6118   if (NumElts != M.size())
6119       return false;
6120 
6121   // Look for <15, ..., 3, -1, 1, 0>.
6122   for (unsigned i = 0; i != NumElts; ++i)
6123     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6124       return false;
6125 
6126   return true;
6127 }
6128 
6129 // If N is an integer constant that can be moved into a register in one
6130 // instruction, return an SDValue of such a constant (will become a MOV
6131 // instruction).  Otherwise return null.
6132 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6133                                      const ARMSubtarget *ST, const SDLoc &dl) {
6134   uint64_t Val;
6135   if (!isa<ConstantSDNode>(N))
6136     return SDValue();
6137   Val = cast<ConstantSDNode>(N)->getZExtValue();
6138 
6139   if (ST->isThumb1Only()) {
6140     if (Val <= 255 || ~Val <= 255)
6141       return DAG.getConstant(Val, dl, MVT::i32);
6142   } else {
6143     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6144       return DAG.getConstant(Val, dl, MVT::i32);
6145   }
6146   return SDValue();
6147 }
6148 
6149 // If this is a case we can't handle, return null and let the default
6150 // expansion code take care of it.
6151 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6152                                              const ARMSubtarget *ST) const {
6153   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6154   SDLoc dl(Op);
6155   EVT VT = Op.getValueType();
6156 
6157   APInt SplatBits, SplatUndef;
6158   unsigned SplatBitSize;
6159   bool HasAnyUndefs;
6160   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6161     if (SplatUndef.isAllOnesValue())
6162       return DAG.getUNDEF(VT);
6163 
6164     if (SplatBitSize <= 64) {
6165       // Check if an immediate VMOV works.
6166       EVT VmovVT;
6167       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6168                                       SplatUndef.getZExtValue(), SplatBitSize,
6169                                       DAG, dl, VmovVT, VT.is128BitVector(),
6170                                       VMOVModImm);
6171       if (Val.getNode()) {
6172         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6173         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6174       }
6175 
6176       // Try an immediate VMVN.
6177       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6178       Val = isNEONModifiedImm(NegatedImm,
6179                                       SplatUndef.getZExtValue(), SplatBitSize,
6180                                       DAG, dl, VmovVT, VT.is128BitVector(),
6181                                       VMVNModImm);
6182       if (Val.getNode()) {
6183         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6184         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6185       }
6186 
6187       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6188       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6189         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6190         if (ImmVal != -1) {
6191           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6192           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6193         }
6194       }
6195     }
6196   }
6197 
6198   // Scan through the operands to see if only one value is used.
6199   //
6200   // As an optimisation, even if more than one value is used it may be more
6201   // profitable to splat with one value then change some lanes.
6202   //
6203   // Heuristically we decide to do this if the vector has a "dominant" value,
6204   // defined as splatted to more than half of the lanes.
6205   unsigned NumElts = VT.getVectorNumElements();
6206   bool isOnlyLowElement = true;
6207   bool usesOnlyOneValue = true;
6208   bool hasDominantValue = false;
6209   bool isConstant = true;
6210 
6211   // Map of the number of times a particular SDValue appears in the
6212   // element list.
6213   DenseMap<SDValue, unsigned> ValueCounts;
6214   SDValue Value;
6215   for (unsigned i = 0; i < NumElts; ++i) {
6216     SDValue V = Op.getOperand(i);
6217     if (V.isUndef())
6218       continue;
6219     if (i > 0)
6220       isOnlyLowElement = false;
6221     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6222       isConstant = false;
6223 
6224     ValueCounts.insert(std::make_pair(V, 0));
6225     unsigned &Count = ValueCounts[V];
6226 
6227     // Is this value dominant? (takes up more than half of the lanes)
6228     if (++Count > (NumElts / 2)) {
6229       hasDominantValue = true;
6230       Value = V;
6231     }
6232   }
6233   if (ValueCounts.size() != 1)
6234     usesOnlyOneValue = false;
6235   if (!Value.getNode() && !ValueCounts.empty())
6236     Value = ValueCounts.begin()->first;
6237 
6238   if (ValueCounts.empty())
6239     return DAG.getUNDEF(VT);
6240 
6241   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6242   // Keep going if we are hitting this case.
6243   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6244     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6245 
6246   unsigned EltSize = VT.getScalarSizeInBits();
6247 
6248   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6249   // i32 and try again.
6250   if (hasDominantValue && EltSize <= 32) {
6251     if (!isConstant) {
6252       SDValue N;
6253 
6254       // If we are VDUPing a value that comes directly from a vector, that will
6255       // cause an unnecessary move to and from a GPR, where instead we could
6256       // just use VDUPLANE. We can only do this if the lane being extracted
6257       // is at a constant index, as the VDUP from lane instructions only have
6258       // constant-index forms.
6259       ConstantSDNode *constIndex;
6260       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6261           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6262         // We need to create a new undef vector to use for the VDUPLANE if the
6263         // size of the vector from which we get the value is different than the
6264         // size of the vector that we need to create. We will insert the element
6265         // such that the register coalescer will remove unnecessary copies.
6266         if (VT != Value->getOperand(0).getValueType()) {
6267           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6268                              VT.getVectorNumElements();
6269           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6270                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6271                         Value, DAG.getConstant(index, dl, MVT::i32)),
6272                            DAG.getConstant(index, dl, MVT::i32));
6273         } else
6274           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6275                         Value->getOperand(0), Value->getOperand(1));
6276       } else
6277         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6278 
6279       if (!usesOnlyOneValue) {
6280         // The dominant value was splatted as 'N', but we now have to insert
6281         // all differing elements.
6282         for (unsigned I = 0; I < NumElts; ++I) {
6283           if (Op.getOperand(I) == Value)
6284             continue;
6285           SmallVector<SDValue, 3> Ops;
6286           Ops.push_back(N);
6287           Ops.push_back(Op.getOperand(I));
6288           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6289           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6290         }
6291       }
6292       return N;
6293     }
6294     if (VT.getVectorElementType().isFloatingPoint()) {
6295       SmallVector<SDValue, 8> Ops;
6296       for (unsigned i = 0; i < NumElts; ++i)
6297         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6298                                   Op.getOperand(i)));
6299       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6300       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6301       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6302       if (Val.getNode())
6303         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6304     }
6305     if (usesOnlyOneValue) {
6306       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6307       if (isConstant && Val.getNode())
6308         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6309     }
6310   }
6311 
6312   // If all elements are constants and the case above didn't get hit, fall back
6313   // to the default expansion, which will generate a load from the constant
6314   // pool.
6315   if (isConstant)
6316     return SDValue();
6317 
6318   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6319   if (NumElts >= 4) {
6320     SDValue shuffle = ReconstructShuffle(Op, DAG);
6321     if (shuffle != SDValue())
6322       return shuffle;
6323   }
6324 
6325   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6326     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6327     // into two 64-bit vectors; we might discover a better way to lower it.
6328     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6329     EVT ExtVT = VT.getVectorElementType();
6330     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6331     SDValue Lower =
6332         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6333     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6334       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6335     SDValue Upper = DAG.getBuildVector(
6336         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6337     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6338       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6339     if (Lower && Upper)
6340       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6341   }
6342 
6343   // Vectors with 32- or 64-bit elements can be built by directly assigning
6344   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6345   // will be legalized.
6346   if (EltSize >= 32) {
6347     // Do the expansion with floating-point types, since that is what the VFP
6348     // registers are defined to use, and since i64 is not legal.
6349     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6350     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6351     SmallVector<SDValue, 8> Ops;
6352     for (unsigned i = 0; i < NumElts; ++i)
6353       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6354     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6355     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6356   }
6357 
6358   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6359   // know the default expansion would otherwise fall back on something even
6360   // worse. For a vector with one or two non-undef values, that's
6361   // scalar_to_vector for the elements followed by a shuffle (provided the
6362   // shuffle is valid for the target) and materialization element by element
6363   // on the stack followed by a load for everything else.
6364   if (!isConstant && !usesOnlyOneValue) {
6365     SDValue Vec = DAG.getUNDEF(VT);
6366     for (unsigned i = 0 ; i < NumElts; ++i) {
6367       SDValue V = Op.getOperand(i);
6368       if (V.isUndef())
6369         continue;
6370       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6371       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6372     }
6373     return Vec;
6374   }
6375 
6376   return SDValue();
6377 }
6378 
6379 // Gather data to see if the operation can be modelled as a
6380 // shuffle in combination with VEXTs.
6381 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6382                                               SelectionDAG &DAG) const {
6383   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6384   SDLoc dl(Op);
6385   EVT VT = Op.getValueType();
6386   unsigned NumElts = VT.getVectorNumElements();
6387 
6388   struct ShuffleSourceInfo {
6389     SDValue Vec;
6390     unsigned MinElt = std::numeric_limits<unsigned>::max();
6391     unsigned MaxElt = 0;
6392 
6393     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6394     // be compatible with the shuffle we intend to construct. As a result
6395     // ShuffleVec will be some sliding window into the original Vec.
6396     SDValue ShuffleVec;
6397 
6398     // Code should guarantee that element i in Vec starts at element "WindowBase
6399     // + i * WindowScale in ShuffleVec".
6400     int WindowBase = 0;
6401     int WindowScale = 1;
6402 
6403     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6404 
6405     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6406   };
6407 
6408   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6409   // node.
6410   SmallVector<ShuffleSourceInfo, 2> Sources;
6411   for (unsigned i = 0; i < NumElts; ++i) {
6412     SDValue V = Op.getOperand(i);
6413     if (V.isUndef())
6414       continue;
6415     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6416       // A shuffle can only come from building a vector from various
6417       // elements of other vectors.
6418       return SDValue();
6419     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6420       // Furthermore, shuffles require a constant mask, whereas extractelts
6421       // accept variable indices.
6422       return SDValue();
6423     }
6424 
6425     // Add this element source to the list if it's not already there.
6426     SDValue SourceVec = V.getOperand(0);
6427     auto Source = llvm::find(Sources, SourceVec);
6428     if (Source == Sources.end())
6429       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6430 
6431     // Update the minimum and maximum lane number seen.
6432     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6433     Source->MinElt = std::min(Source->MinElt, EltNo);
6434     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6435   }
6436 
6437   // Currently only do something sane when at most two source vectors
6438   // are involved.
6439   if (Sources.size() > 2)
6440     return SDValue();
6441 
6442   // Find out the smallest element size among result and two sources, and use
6443   // it as element size to build the shuffle_vector.
6444   EVT SmallestEltTy = VT.getVectorElementType();
6445   for (auto &Source : Sources) {
6446     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6447     if (SrcEltTy.bitsLT(SmallestEltTy))
6448       SmallestEltTy = SrcEltTy;
6449   }
6450   unsigned ResMultiplier =
6451       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6452   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6453   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6454 
6455   // If the source vector is too wide or too narrow, we may nevertheless be able
6456   // to construct a compatible shuffle either by concatenating it with UNDEF or
6457   // extracting a suitable range of elements.
6458   for (auto &Src : Sources) {
6459     EVT SrcVT = Src.ShuffleVec.getValueType();
6460 
6461     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6462       continue;
6463 
6464     // This stage of the search produces a source with the same element type as
6465     // the original, but with a total width matching the BUILD_VECTOR output.
6466     EVT EltVT = SrcVT.getVectorElementType();
6467     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6468     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6469 
6470     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6471       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6472         return SDValue();
6473       // We can pad out the smaller vector for free, so if it's part of a
6474       // shuffle...
6475       Src.ShuffleVec =
6476           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6477                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6478       continue;
6479     }
6480 
6481     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6482       return SDValue();
6483 
6484     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6485       // Span too large for a VEXT to cope
6486       return SDValue();
6487     }
6488 
6489     if (Src.MinElt >= NumSrcElts) {
6490       // The extraction can just take the second half
6491       Src.ShuffleVec =
6492           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6493                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6494       Src.WindowBase = -NumSrcElts;
6495     } else if (Src.MaxElt < NumSrcElts) {
6496       // The extraction can just take the first half
6497       Src.ShuffleVec =
6498           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6499                       DAG.getConstant(0, dl, MVT::i32));
6500     } else {
6501       // An actual VEXT is needed
6502       SDValue VEXTSrc1 =
6503           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6504                       DAG.getConstant(0, dl, MVT::i32));
6505       SDValue VEXTSrc2 =
6506           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6507                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6508 
6509       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6510                                    VEXTSrc2,
6511                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6512       Src.WindowBase = -Src.MinElt;
6513     }
6514   }
6515 
6516   // Another possible incompatibility occurs from the vector element types. We
6517   // can fix this by bitcasting the source vectors to the same type we intend
6518   // for the shuffle.
6519   for (auto &Src : Sources) {
6520     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6521     if (SrcEltTy == SmallestEltTy)
6522       continue;
6523     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6524     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6525     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6526     Src.WindowBase *= Src.WindowScale;
6527   }
6528 
6529   // Final sanity check before we try to actually produce a shuffle.
6530   DEBUG(
6531     for (auto Src : Sources)
6532       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6533   );
6534 
6535   // The stars all align, our next step is to produce the mask for the shuffle.
6536   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6537   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6538   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6539     SDValue Entry = Op.getOperand(i);
6540     if (Entry.isUndef())
6541       continue;
6542 
6543     auto Src = llvm::find(Sources, Entry.getOperand(0));
6544     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6545 
6546     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6547     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6548     // segment.
6549     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6550     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6551                                VT.getScalarSizeInBits());
6552     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6553 
6554     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6555     // starting at the appropriate offset.
6556     int *LaneMask = &Mask[i * ResMultiplier];
6557 
6558     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6559     ExtractBase += NumElts * (Src - Sources.begin());
6560     for (int j = 0; j < LanesDefined; ++j)
6561       LaneMask[j] = ExtractBase + j;
6562   }
6563 
6564   // Final check before we try to produce nonsense...
6565   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6566     return SDValue();
6567 
6568   // We can't handle more than two sources. This should have already
6569   // been checked before this point.
6570   assert(Sources.size() <= 2 && "Too many sources!");
6571 
6572   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6573   for (unsigned i = 0; i < Sources.size(); ++i)
6574     ShuffleOps[i] = Sources[i].ShuffleVec;
6575 
6576   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6577                                          ShuffleOps[1], Mask);
6578   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6579 }
6580 
6581 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6582 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6583 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6584 /// are assumed to be legal.
6585 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6586   if (VT.getVectorNumElements() == 4 &&
6587       (VT.is128BitVector() || VT.is64BitVector())) {
6588     unsigned PFIndexes[4];
6589     for (unsigned i = 0; i != 4; ++i) {
6590       if (M[i] < 0)
6591         PFIndexes[i] = 8;
6592       else
6593         PFIndexes[i] = M[i];
6594     }
6595 
6596     // Compute the index in the perfect shuffle table.
6597     unsigned PFTableIndex =
6598       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6599     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6600     unsigned Cost = (PFEntry >> 30);
6601 
6602     if (Cost <= 4)
6603       return true;
6604   }
6605 
6606   bool ReverseVEXT, isV_UNDEF;
6607   unsigned Imm, WhichResult;
6608 
6609   unsigned EltSize = VT.getScalarSizeInBits();
6610   return (EltSize >= 32 ||
6611           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6612           isVREVMask(M, VT, 64) ||
6613           isVREVMask(M, VT, 32) ||
6614           isVREVMask(M, VT, 16) ||
6615           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6616           isVTBLMask(M, VT) ||
6617           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6618           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6619 }
6620 
6621 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6622 /// the specified operations to build the shuffle.
6623 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6624                                       SDValue RHS, SelectionDAG &DAG,
6625                                       const SDLoc &dl) {
6626   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6627   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6628   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6629 
6630   enum {
6631     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6632     OP_VREV,
6633     OP_VDUP0,
6634     OP_VDUP1,
6635     OP_VDUP2,
6636     OP_VDUP3,
6637     OP_VEXT1,
6638     OP_VEXT2,
6639     OP_VEXT3,
6640     OP_VUZPL, // VUZP, left result
6641     OP_VUZPR, // VUZP, right result
6642     OP_VZIPL, // VZIP, left result
6643     OP_VZIPR, // VZIP, right result
6644     OP_VTRNL, // VTRN, left result
6645     OP_VTRNR  // VTRN, right result
6646   };
6647 
6648   if (OpNum == OP_COPY) {
6649     if (LHSID == (1*9+2)*9+3) return LHS;
6650     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6651     return RHS;
6652   }
6653 
6654   SDValue OpLHS, OpRHS;
6655   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6656   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6657   EVT VT = OpLHS.getValueType();
6658 
6659   switch (OpNum) {
6660   default: llvm_unreachable("Unknown shuffle opcode!");
6661   case OP_VREV:
6662     // VREV divides the vector in half and swaps within the half.
6663     if (VT.getVectorElementType() == MVT::i32 ||
6664         VT.getVectorElementType() == MVT::f32)
6665       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6666     // vrev <4 x i16> -> VREV32
6667     if (VT.getVectorElementType() == MVT::i16)
6668       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6669     // vrev <4 x i8> -> VREV16
6670     assert(VT.getVectorElementType() == MVT::i8);
6671     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6672   case OP_VDUP0:
6673   case OP_VDUP1:
6674   case OP_VDUP2:
6675   case OP_VDUP3:
6676     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6677                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6678   case OP_VEXT1:
6679   case OP_VEXT2:
6680   case OP_VEXT3:
6681     return DAG.getNode(ARMISD::VEXT, dl, VT,
6682                        OpLHS, OpRHS,
6683                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6684   case OP_VUZPL:
6685   case OP_VUZPR:
6686     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6687                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6688   case OP_VZIPL:
6689   case OP_VZIPR:
6690     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6691                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6692   case OP_VTRNL:
6693   case OP_VTRNR:
6694     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6695                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6696   }
6697 }
6698 
6699 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6700                                        ArrayRef<int> ShuffleMask,
6701                                        SelectionDAG &DAG) {
6702   // Check to see if we can use the VTBL instruction.
6703   SDValue V1 = Op.getOperand(0);
6704   SDValue V2 = Op.getOperand(1);
6705   SDLoc DL(Op);
6706 
6707   SmallVector<SDValue, 8> VTBLMask;
6708   for (ArrayRef<int>::iterator
6709          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6710     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6711 
6712   if (V2.getNode()->isUndef())
6713     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6714                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6715 
6716   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6717                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6718 }
6719 
6720 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6721                                                       SelectionDAG &DAG) {
6722   SDLoc DL(Op);
6723   SDValue OpLHS = Op.getOperand(0);
6724   EVT VT = OpLHS.getValueType();
6725 
6726   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6727          "Expect an v8i16/v16i8 type");
6728   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6729   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6730   // extract the first 8 bytes into the top double word and the last 8 bytes
6731   // into the bottom double word. The v8i16 case is similar.
6732   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6733   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6734                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6735 }
6736 
6737 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6738   SDValue V1 = Op.getOperand(0);
6739   SDValue V2 = Op.getOperand(1);
6740   SDLoc dl(Op);
6741   EVT VT = Op.getValueType();
6742   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6743 
6744   // Convert shuffles that are directly supported on NEON to target-specific
6745   // DAG nodes, instead of keeping them as shuffles and matching them again
6746   // during code selection.  This is more efficient and avoids the possibility
6747   // of inconsistencies between legalization and selection.
6748   // FIXME: floating-point vectors should be canonicalized to integer vectors
6749   // of the same time so that they get CSEd properly.
6750   ArrayRef<int> ShuffleMask = SVN->getMask();
6751 
6752   unsigned EltSize = VT.getScalarSizeInBits();
6753   if (EltSize <= 32) {
6754     if (SVN->isSplat()) {
6755       int Lane = SVN->getSplatIndex();
6756       // If this is undef splat, generate it via "just" vdup, if possible.
6757       if (Lane == -1) Lane = 0;
6758 
6759       // Test if V1 is a SCALAR_TO_VECTOR.
6760       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6761         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6762       }
6763       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6764       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6765       // reaches it).
6766       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6767           !isa<ConstantSDNode>(V1.getOperand(0))) {
6768         bool IsScalarToVector = true;
6769         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6770           if (!V1.getOperand(i).isUndef()) {
6771             IsScalarToVector = false;
6772             break;
6773           }
6774         if (IsScalarToVector)
6775           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6776       }
6777       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6778                          DAG.getConstant(Lane, dl, MVT::i32));
6779     }
6780 
6781     bool ReverseVEXT;
6782     unsigned Imm;
6783     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6784       if (ReverseVEXT)
6785         std::swap(V1, V2);
6786       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6787                          DAG.getConstant(Imm, dl, MVT::i32));
6788     }
6789 
6790     if (isVREVMask(ShuffleMask, VT, 64))
6791       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6792     if (isVREVMask(ShuffleMask, VT, 32))
6793       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6794     if (isVREVMask(ShuffleMask, VT, 16))
6795       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6796 
6797     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6798       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6799                          DAG.getConstant(Imm, dl, MVT::i32));
6800     }
6801 
6802     // Check for Neon shuffles that modify both input vectors in place.
6803     // If both results are used, i.e., if there are two shuffles with the same
6804     // source operands and with masks corresponding to both results of one of
6805     // these operations, DAG memoization will ensure that a single node is
6806     // used for both shuffles.
6807     unsigned WhichResult;
6808     bool isV_UNDEF;
6809     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6810             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6811       if (isV_UNDEF)
6812         V2 = V1;
6813       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6814           .getValue(WhichResult);
6815     }
6816 
6817     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6818     // shuffles that produce a result larger than their operands with:
6819     //   shuffle(concat(v1, undef), concat(v2, undef))
6820     // ->
6821     //   shuffle(concat(v1, v2), undef)
6822     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6823     //
6824     // This is useful in the general case, but there are special cases where
6825     // native shuffles produce larger results: the two-result ops.
6826     //
6827     // Look through the concat when lowering them:
6828     //   shuffle(concat(v1, v2), undef)
6829     // ->
6830     //   concat(VZIP(v1, v2):0, :1)
6831     //
6832     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6833       SDValue SubV1 = V1->getOperand(0);
6834       SDValue SubV2 = V1->getOperand(1);
6835       EVT SubVT = SubV1.getValueType();
6836 
6837       // We expect these to have been canonicalized to -1.
6838       assert(llvm::all_of(ShuffleMask, [&](int i) {
6839         return i < (int)VT.getVectorNumElements();
6840       }) && "Unexpected shuffle index into UNDEF operand!");
6841 
6842       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6843               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6844         if (isV_UNDEF)
6845           SubV2 = SubV1;
6846         assert((WhichResult == 0) &&
6847                "In-place shuffle of concat can only have one result!");
6848         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6849                                   SubV1, SubV2);
6850         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6851                            Res.getValue(1));
6852       }
6853     }
6854   }
6855 
6856   // If the shuffle is not directly supported and it has 4 elements, use
6857   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6858   unsigned NumElts = VT.getVectorNumElements();
6859   if (NumElts == 4) {
6860     unsigned PFIndexes[4];
6861     for (unsigned i = 0; i != 4; ++i) {
6862       if (ShuffleMask[i] < 0)
6863         PFIndexes[i] = 8;
6864       else
6865         PFIndexes[i] = ShuffleMask[i];
6866     }
6867 
6868     // Compute the index in the perfect shuffle table.
6869     unsigned PFTableIndex =
6870       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6871     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6872     unsigned Cost = (PFEntry >> 30);
6873 
6874     if (Cost <= 4)
6875       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6876   }
6877 
6878   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6879   if (EltSize >= 32) {
6880     // Do the expansion with floating-point types, since that is what the VFP
6881     // registers are defined to use, and since i64 is not legal.
6882     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6883     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6884     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6885     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6886     SmallVector<SDValue, 8> Ops;
6887     for (unsigned i = 0; i < NumElts; ++i) {
6888       if (ShuffleMask[i] < 0)
6889         Ops.push_back(DAG.getUNDEF(EltVT));
6890       else
6891         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6892                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6893                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6894                                                   dl, MVT::i32)));
6895     }
6896     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6897     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6898   }
6899 
6900   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6901     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6902 
6903   if (VT == MVT::v8i8)
6904     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6905       return NewOp;
6906 
6907   return SDValue();
6908 }
6909 
6910 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6911   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6912   SDValue Lane = Op.getOperand(2);
6913   if (!isa<ConstantSDNode>(Lane))
6914     return SDValue();
6915 
6916   return Op;
6917 }
6918 
6919 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6920   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6921   SDValue Lane = Op.getOperand(1);
6922   if (!isa<ConstantSDNode>(Lane))
6923     return SDValue();
6924 
6925   SDValue Vec = Op.getOperand(0);
6926   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6927     SDLoc dl(Op);
6928     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6929   }
6930 
6931   return Op;
6932 }
6933 
6934 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6935   // The only time a CONCAT_VECTORS operation can have legal types is when
6936   // two 64-bit vectors are concatenated to a 128-bit vector.
6937   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6938          "unexpected CONCAT_VECTORS");
6939   SDLoc dl(Op);
6940   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6941   SDValue Op0 = Op.getOperand(0);
6942   SDValue Op1 = Op.getOperand(1);
6943   if (!Op0.isUndef())
6944     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6945                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6946                       DAG.getIntPtrConstant(0, dl));
6947   if (!Op1.isUndef())
6948     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6949                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6950                       DAG.getIntPtrConstant(1, dl));
6951   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6952 }
6953 
6954 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6955 /// element has been zero/sign-extended, depending on the isSigned parameter,
6956 /// from an integer type half its size.
6957 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6958                                    bool isSigned) {
6959   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6960   EVT VT = N->getValueType(0);
6961   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6962     SDNode *BVN = N->getOperand(0).getNode();
6963     if (BVN->getValueType(0) != MVT::v4i32 ||
6964         BVN->getOpcode() != ISD::BUILD_VECTOR)
6965       return false;
6966     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6967     unsigned HiElt = 1 - LoElt;
6968     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6969     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6970     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6971     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6972     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6973       return false;
6974     if (isSigned) {
6975       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6976           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6977         return true;
6978     } else {
6979       if (Hi0->isNullValue() && Hi1->isNullValue())
6980         return true;
6981     }
6982     return false;
6983   }
6984 
6985   if (N->getOpcode() != ISD::BUILD_VECTOR)
6986     return false;
6987 
6988   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6989     SDNode *Elt = N->getOperand(i).getNode();
6990     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6991       unsigned EltSize = VT.getScalarSizeInBits();
6992       unsigned HalfSize = EltSize / 2;
6993       if (isSigned) {
6994         if (!isIntN(HalfSize, C->getSExtValue()))
6995           return false;
6996       } else {
6997         if (!isUIntN(HalfSize, C->getZExtValue()))
6998           return false;
6999       }
7000       continue;
7001     }
7002     return false;
7003   }
7004 
7005   return true;
7006 }
7007 
7008 /// isSignExtended - Check if a node is a vector value that is sign-extended
7009 /// or a constant BUILD_VECTOR with sign-extended elements.
7010 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7011   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7012     return true;
7013   if (isExtendedBUILD_VECTOR(N, DAG, true))
7014     return true;
7015   return false;
7016 }
7017 
7018 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7019 /// or a constant BUILD_VECTOR with zero-extended elements.
7020 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7021   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7022     return true;
7023   if (isExtendedBUILD_VECTOR(N, DAG, false))
7024     return true;
7025   return false;
7026 }
7027 
7028 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7029   if (OrigVT.getSizeInBits() >= 64)
7030     return OrigVT;
7031 
7032   assert(OrigVT.isSimple() && "Expecting a simple value type");
7033 
7034   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7035   switch (OrigSimpleTy) {
7036   default: llvm_unreachable("Unexpected Vector Type");
7037   case MVT::v2i8:
7038   case MVT::v2i16:
7039      return MVT::v2i32;
7040   case MVT::v4i8:
7041     return  MVT::v4i16;
7042   }
7043 }
7044 
7045 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7046 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7047 /// We insert the required extension here to get the vector to fill a D register.
7048 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7049                                             const EVT &OrigTy,
7050                                             const EVT &ExtTy,
7051                                             unsigned ExtOpcode) {
7052   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7053   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7054   // 64-bits we need to insert a new extension so that it will be 64-bits.
7055   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7056   if (OrigTy.getSizeInBits() >= 64)
7057     return N;
7058 
7059   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7060   EVT NewVT = getExtensionTo64Bits(OrigTy);
7061 
7062   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7063 }
7064 
7065 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7066 /// does not do any sign/zero extension. If the original vector is less
7067 /// than 64 bits, an appropriate extension will be added after the load to
7068 /// reach a total size of 64 bits. We have to add the extension separately
7069 /// because ARM does not have a sign/zero extending load for vectors.
7070 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7071   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7072 
7073   // The load already has the right type.
7074   if (ExtendedTy == LD->getMemoryVT())
7075     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7076                        LD->getBasePtr(), LD->getPointerInfo(),
7077                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7078 
7079   // We need to create a zextload/sextload. We cannot just create a load
7080   // followed by a zext/zext node because LowerMUL is also run during normal
7081   // operation legalization where we can't create illegal types.
7082   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7083                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7084                         LD->getMemoryVT(), LD->getAlignment(),
7085                         LD->getMemOperand()->getFlags());
7086 }
7087 
7088 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7089 /// extending load, or BUILD_VECTOR with extended elements, return the
7090 /// unextended value. The unextended vector should be 64 bits so that it can
7091 /// be used as an operand to a VMULL instruction. If the original vector size
7092 /// before extension is less than 64 bits we add a an extension to resize
7093 /// the vector to 64 bits.
7094 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7095   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7096     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7097                                         N->getOperand(0)->getValueType(0),
7098                                         N->getValueType(0),
7099                                         N->getOpcode());
7100 
7101   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7102     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7103            "Expected extending load");
7104 
7105     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7106     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7107     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7108     SDValue extLoad =
7109         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7110     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7111 
7112     return newLoad;
7113   }
7114 
7115   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7116   // have been legalized as a BITCAST from v4i32.
7117   if (N->getOpcode() == ISD::BITCAST) {
7118     SDNode *BVN = N->getOperand(0).getNode();
7119     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7120            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7121     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7122     return DAG.getBuildVector(
7123         MVT::v2i32, SDLoc(N),
7124         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7125   }
7126   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7127   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7128   EVT VT = N->getValueType(0);
7129   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7130   unsigned NumElts = VT.getVectorNumElements();
7131   MVT TruncVT = MVT::getIntegerVT(EltSize);
7132   SmallVector<SDValue, 8> Ops;
7133   SDLoc dl(N);
7134   for (unsigned i = 0; i != NumElts; ++i) {
7135     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7136     const APInt &CInt = C->getAPIntValue();
7137     // Element types smaller than 32 bits are not legal, so use i32 elements.
7138     // The values are implicitly truncated so sext vs. zext doesn't matter.
7139     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7140   }
7141   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7142 }
7143 
7144 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7145   unsigned Opcode = N->getOpcode();
7146   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7147     SDNode *N0 = N->getOperand(0).getNode();
7148     SDNode *N1 = N->getOperand(1).getNode();
7149     return N0->hasOneUse() && N1->hasOneUse() &&
7150       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7151   }
7152   return false;
7153 }
7154 
7155 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7156   unsigned Opcode = N->getOpcode();
7157   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7158     SDNode *N0 = N->getOperand(0).getNode();
7159     SDNode *N1 = N->getOperand(1).getNode();
7160     return N0->hasOneUse() && N1->hasOneUse() &&
7161       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7162   }
7163   return false;
7164 }
7165 
7166 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7167   // Multiplications are only custom-lowered for 128-bit vectors so that
7168   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7169   EVT VT = Op.getValueType();
7170   assert(VT.is128BitVector() && VT.isInteger() &&
7171          "unexpected type for custom-lowering ISD::MUL");
7172   SDNode *N0 = Op.getOperand(0).getNode();
7173   SDNode *N1 = Op.getOperand(1).getNode();
7174   unsigned NewOpc = 0;
7175   bool isMLA = false;
7176   bool isN0SExt = isSignExtended(N0, DAG);
7177   bool isN1SExt = isSignExtended(N1, DAG);
7178   if (isN0SExt && isN1SExt)
7179     NewOpc = ARMISD::VMULLs;
7180   else {
7181     bool isN0ZExt = isZeroExtended(N0, DAG);
7182     bool isN1ZExt = isZeroExtended(N1, DAG);
7183     if (isN0ZExt && isN1ZExt)
7184       NewOpc = ARMISD::VMULLu;
7185     else if (isN1SExt || isN1ZExt) {
7186       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7187       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7188       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7189         NewOpc = ARMISD::VMULLs;
7190         isMLA = true;
7191       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7192         NewOpc = ARMISD::VMULLu;
7193         isMLA = true;
7194       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7195         std::swap(N0, N1);
7196         NewOpc = ARMISD::VMULLu;
7197         isMLA = true;
7198       }
7199     }
7200 
7201     if (!NewOpc) {
7202       if (VT == MVT::v2i64)
7203         // Fall through to expand this.  It is not legal.
7204         return SDValue();
7205       else
7206         // Other vector multiplications are legal.
7207         return Op;
7208     }
7209   }
7210 
7211   // Legalize to a VMULL instruction.
7212   SDLoc DL(Op);
7213   SDValue Op0;
7214   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7215   if (!isMLA) {
7216     Op0 = SkipExtensionForVMULL(N0, DAG);
7217     assert(Op0.getValueType().is64BitVector() &&
7218            Op1.getValueType().is64BitVector() &&
7219            "unexpected types for extended operands to VMULL");
7220     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7221   }
7222 
7223   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7224   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7225   //   vmull q0, d4, d6
7226   //   vmlal q0, d5, d6
7227   // is faster than
7228   //   vaddl q0, d4, d5
7229   //   vmovl q1, d6
7230   //   vmul  q0, q0, q1
7231   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7232   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7233   EVT Op1VT = Op1.getValueType();
7234   return DAG.getNode(N0->getOpcode(), DL, VT,
7235                      DAG.getNode(NewOpc, DL, VT,
7236                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7237                      DAG.getNode(NewOpc, DL, VT,
7238                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7239 }
7240 
7241 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7242                               SelectionDAG &DAG) {
7243   // TODO: Should this propagate fast-math-flags?
7244 
7245   // Convert to float
7246   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7247   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7248   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7249   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7250   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7251   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7252   // Get reciprocal estimate.
7253   // float4 recip = vrecpeq_f32(yf);
7254   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7255                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7256                    Y);
7257   // Because char has a smaller range than uchar, we can actually get away
7258   // without any newton steps.  This requires that we use a weird bias
7259   // of 0xb000, however (again, this has been exhaustively tested).
7260   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7261   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7262   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7263   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7264   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7265   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7266   // Convert back to short.
7267   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7268   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7269   return X;
7270 }
7271 
7272 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7273                                SelectionDAG &DAG) {
7274   // TODO: Should this propagate fast-math-flags?
7275 
7276   SDValue N2;
7277   // Convert to float.
7278   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7279   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7280   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7281   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7282   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7283   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7284 
7285   // Use reciprocal estimate and one refinement step.
7286   // float4 recip = vrecpeq_f32(yf);
7287   // recip *= vrecpsq_f32(yf, recip);
7288   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7289                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7290                    N1);
7291   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7292                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7293                    N1, N2);
7294   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7295   // Because short has a smaller range than ushort, we can actually get away
7296   // with only a single newton step.  This requires that we use a weird bias
7297   // of 89, however (again, this has been exhaustively tested).
7298   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7299   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7300   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7301   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7302   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7303   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7304   // Convert back to integer and return.
7305   // return vmovn_s32(vcvt_s32_f32(result));
7306   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7307   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7308   return N0;
7309 }
7310 
7311 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7312   EVT VT = Op.getValueType();
7313   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7314          "unexpected type for custom-lowering ISD::SDIV");
7315 
7316   SDLoc dl(Op);
7317   SDValue N0 = Op.getOperand(0);
7318   SDValue N1 = Op.getOperand(1);
7319   SDValue N2, N3;
7320 
7321   if (VT == MVT::v8i8) {
7322     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7323     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7324 
7325     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7326                      DAG.getIntPtrConstant(4, dl));
7327     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7328                      DAG.getIntPtrConstant(4, dl));
7329     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7330                      DAG.getIntPtrConstant(0, dl));
7331     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7332                      DAG.getIntPtrConstant(0, dl));
7333 
7334     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7335     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7336 
7337     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7338     N0 = LowerCONCAT_VECTORS(N0, DAG);
7339 
7340     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7341     return N0;
7342   }
7343   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7344 }
7345 
7346 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7347   // TODO: Should this propagate fast-math-flags?
7348   EVT VT = Op.getValueType();
7349   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7350          "unexpected type for custom-lowering ISD::UDIV");
7351 
7352   SDLoc dl(Op);
7353   SDValue N0 = Op.getOperand(0);
7354   SDValue N1 = Op.getOperand(1);
7355   SDValue N2, N3;
7356 
7357   if (VT == MVT::v8i8) {
7358     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7359     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7360 
7361     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7362                      DAG.getIntPtrConstant(4, dl));
7363     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7364                      DAG.getIntPtrConstant(4, dl));
7365     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7366                      DAG.getIntPtrConstant(0, dl));
7367     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7368                      DAG.getIntPtrConstant(0, dl));
7369 
7370     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7371     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7372 
7373     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7374     N0 = LowerCONCAT_VECTORS(N0, DAG);
7375 
7376     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7377                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7378                                      MVT::i32),
7379                      N0);
7380     return N0;
7381   }
7382 
7383   // v4i16 sdiv ... Convert to float.
7384   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7385   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7386   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7387   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7388   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7389   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7390 
7391   // Use reciprocal estimate and two refinement steps.
7392   // float4 recip = vrecpeq_f32(yf);
7393   // recip *= vrecpsq_f32(yf, recip);
7394   // recip *= vrecpsq_f32(yf, recip);
7395   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7396                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7397                    BN1);
7398   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7399                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7400                    BN1, N2);
7401   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7402   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7403                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7404                    BN1, N2);
7405   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7406   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7407   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7408   // and that it will never cause us to return an answer too large).
7409   // float4 result = as_float4(as_int4(xf*recip) + 2);
7410   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7411   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7412   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7413   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7414   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7415   // Convert back to integer and return.
7416   // return vmovn_u32(vcvt_s32_f32(result));
7417   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7418   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7419   return N0;
7420 }
7421 
7422 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7423   EVT VT = Op.getNode()->getValueType(0);
7424   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7425 
7426   unsigned Opc;
7427   bool ExtraOp = false;
7428   switch (Op.getOpcode()) {
7429   default: llvm_unreachable("Invalid code");
7430   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7431   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7432   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7433   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7434   }
7435 
7436   if (!ExtraOp)
7437     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7438                        Op.getOperand(1));
7439   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7440                      Op.getOperand(1), Op.getOperand(2));
7441 }
7442 
7443 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7444   SDNode *N = Op.getNode();
7445   EVT VT = N->getValueType(0);
7446   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7447 
7448   SDValue Carry = Op.getOperand(2);
7449   EVT CarryVT = Carry.getValueType();
7450 
7451   SDLoc DL(Op);
7452 
7453   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7454 
7455   SDValue Result;
7456   if (Op.getOpcode() == ISD::ADDCARRY) {
7457     // This converts the boolean value carry into the carry flag.
7458     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7459 
7460     // Do the addition proper using the carry flag we wanted.
7461     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7462                          Op.getOperand(1), Carry.getValue(1));
7463 
7464     // Now convert the carry flag into a boolean value.
7465     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7466   } else {
7467     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7468     // have to invert the carry first.
7469     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7470                         DAG.getConstant(1, DL, MVT::i32), Carry);
7471     // This converts the boolean value carry into the carry flag.
7472     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7473 
7474     // Do the subtraction proper using the carry flag we wanted.
7475     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7476                          Op.getOperand(1), Carry.getValue(1));
7477 
7478     // Now convert the carry flag into a boolean value.
7479     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7480     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7481     // by ISD::SUBCARRY, so compute 1 - C.
7482     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7483                         DAG.getConstant(1, DL, MVT::i32), Carry);
7484   }
7485 
7486   // Return both values.
7487   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7488 }
7489 
7490 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7491   assert(Subtarget->isTargetDarwin());
7492 
7493   // For iOS, we want to call an alternative entry point: __sincos_stret,
7494   // return values are passed via sret.
7495   SDLoc dl(Op);
7496   SDValue Arg = Op.getOperand(0);
7497   EVT ArgVT = Arg.getValueType();
7498   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7499   auto PtrVT = getPointerTy(DAG.getDataLayout());
7500 
7501   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7503 
7504   // Pair of floats / doubles used to pass the result.
7505   Type *RetTy = StructType::get(ArgTy, ArgTy);
7506   auto &DL = DAG.getDataLayout();
7507 
7508   ArgListTy Args;
7509   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7510   SDValue SRet;
7511   if (ShouldUseSRet) {
7512     // Create stack object for sret.
7513     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7514     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7515     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7516     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7517 
7518     ArgListEntry Entry;
7519     Entry.Node = SRet;
7520     Entry.Ty = RetTy->getPointerTo();
7521     Entry.IsSExt = false;
7522     Entry.IsZExt = false;
7523     Entry.IsSRet = true;
7524     Args.push_back(Entry);
7525     RetTy = Type::getVoidTy(*DAG.getContext());
7526   }
7527 
7528   ArgListEntry Entry;
7529   Entry.Node = Arg;
7530   Entry.Ty = ArgTy;
7531   Entry.IsSExt = false;
7532   Entry.IsZExt = false;
7533   Args.push_back(Entry);
7534 
7535   const char *LibcallName =
7536       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7537   RTLIB::Libcall LC =
7538       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7539   CallingConv::ID CC = getLibcallCallingConv(LC);
7540   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7541 
7542   TargetLowering::CallLoweringInfo CLI(DAG);
7543   CLI.setDebugLoc(dl)
7544       .setChain(DAG.getEntryNode())
7545       .setCallee(CC, RetTy, Callee, std::move(Args))
7546       .setDiscardResult(ShouldUseSRet);
7547   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7548 
7549   if (!ShouldUseSRet)
7550     return CallResult.first;
7551 
7552   SDValue LoadSin =
7553       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7554 
7555   // Address of cos field.
7556   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7557                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7558   SDValue LoadCos =
7559       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7560 
7561   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7562   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7563                      LoadSin.getValue(0), LoadCos.getValue(0));
7564 }
7565 
7566 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7567                                                   bool Signed,
7568                                                   SDValue &Chain) const {
7569   EVT VT = Op.getValueType();
7570   assert((VT == MVT::i32 || VT == MVT::i64) &&
7571          "unexpected type for custom lowering DIV");
7572   SDLoc dl(Op);
7573 
7574   const auto &DL = DAG.getDataLayout();
7575   const auto &TLI = DAG.getTargetLoweringInfo();
7576 
7577   const char *Name = nullptr;
7578   if (Signed)
7579     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7580   else
7581     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7582 
7583   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7584 
7585   ARMTargetLowering::ArgListTy Args;
7586 
7587   for (auto AI : {1, 0}) {
7588     ArgListEntry Arg;
7589     Arg.Node = Op.getOperand(AI);
7590     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7591     Args.push_back(Arg);
7592   }
7593 
7594   CallLoweringInfo CLI(DAG);
7595   CLI.setDebugLoc(dl)
7596     .setChain(Chain)
7597     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7598                ES, std::move(Args));
7599 
7600   return LowerCallTo(CLI).first;
7601 }
7602 
7603 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7604                                             bool Signed) const {
7605   assert(Op.getValueType() == MVT::i32 &&
7606          "unexpected type for custom lowering DIV");
7607   SDLoc dl(Op);
7608 
7609   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7610                                DAG.getEntryNode(), Op.getOperand(1));
7611 
7612   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7613 }
7614 
7615 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7616   SDLoc DL(N);
7617   SDValue Op = N->getOperand(1);
7618   if (N->getValueType(0) == MVT::i32)
7619     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7620   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7621                            DAG.getConstant(0, DL, MVT::i32));
7622   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7623                            DAG.getConstant(1, DL, MVT::i32));
7624   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7625                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7626 }
7627 
7628 void ARMTargetLowering::ExpandDIV_Windows(
7629     SDValue Op, SelectionDAG &DAG, bool Signed,
7630     SmallVectorImpl<SDValue> &Results) const {
7631   const auto &DL = DAG.getDataLayout();
7632   const auto &TLI = DAG.getTargetLoweringInfo();
7633 
7634   assert(Op.getValueType() == MVT::i64 &&
7635          "unexpected type for custom lowering DIV");
7636   SDLoc dl(Op);
7637 
7638   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7639 
7640   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7641 
7642   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7643   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7644                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7645   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7646 
7647   Results.push_back(Lower);
7648   Results.push_back(Upper);
7649 }
7650 
7651 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7652   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7653     // Acquire/Release load/store is not legal for targets without a dmb or
7654     // equivalent available.
7655     return SDValue();
7656 
7657   // Monotonic load/store is legal for all targets.
7658   return Op;
7659 }
7660 
7661 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7662                                     SmallVectorImpl<SDValue> &Results,
7663                                     SelectionDAG &DAG,
7664                                     const ARMSubtarget *Subtarget) {
7665   SDLoc DL(N);
7666   // Under Power Management extensions, the cycle-count is:
7667   //    mrc p15, #0, <Rt>, c9, c13, #0
7668   SDValue Ops[] = { N->getOperand(0), // Chain
7669                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7670                     DAG.getConstant(15, DL, MVT::i32),
7671                     DAG.getConstant(0, DL, MVT::i32),
7672                     DAG.getConstant(9, DL, MVT::i32),
7673                     DAG.getConstant(13, DL, MVT::i32),
7674                     DAG.getConstant(0, DL, MVT::i32)
7675   };
7676 
7677   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7678                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7679   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7680                                 DAG.getConstant(0, DL, MVT::i32)));
7681   Results.push_back(Cycles32.getValue(1));
7682 }
7683 
7684 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7685   SDLoc dl(V.getNode());
7686   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7687   SDValue VHi = DAG.getAnyExtOrTrunc(
7688       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7689       dl, MVT::i32);
7690   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7691   if (isBigEndian)
7692     std::swap (VLo, VHi);
7693   SDValue RegClass =
7694       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7695   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7696   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7697   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7698   return SDValue(
7699       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7700 }
7701 
7702 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7703                                        SmallVectorImpl<SDValue> & Results,
7704                                        SelectionDAG &DAG) {
7705   assert(N->getValueType(0) == MVT::i64 &&
7706          "AtomicCmpSwap on types less than 64 should be legal");
7707   SDValue Ops[] = {N->getOperand(1),
7708                    createGPRPairNode(DAG, N->getOperand(2)),
7709                    createGPRPairNode(DAG, N->getOperand(3)),
7710                    N->getOperand(0)};
7711   SDNode *CmpSwap = DAG.getMachineNode(
7712       ARM::CMP_SWAP_64, SDLoc(N),
7713       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7714 
7715   MachineFunction &MF = DAG.getMachineFunction();
7716   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7717   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7718   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7719 
7720   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7721 
7722   Results.push_back(
7723       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7724                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7725   Results.push_back(
7726       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7727                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7728   Results.push_back(SDValue(CmpSwap, 2));
7729 }
7730 
7731 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7732                           SelectionDAG &DAG) {
7733   const auto &TLI = DAG.getTargetLoweringInfo();
7734 
7735   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7736          "Custom lowering is MSVCRT specific!");
7737 
7738   SDLoc dl(Op);
7739   SDValue Val = Op.getOperand(0);
7740   MVT Ty = Val->getSimpleValueType(0);
7741   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7742   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7743                                          TLI.getPointerTy(DAG.getDataLayout()));
7744 
7745   TargetLowering::ArgListTy Args;
7746   TargetLowering::ArgListEntry Entry;
7747 
7748   Entry.Node = Val;
7749   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7750   Entry.IsZExt = true;
7751   Args.push_back(Entry);
7752 
7753   Entry.Node = Exponent;
7754   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7755   Entry.IsZExt = true;
7756   Args.push_back(Entry);
7757 
7758   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7759 
7760   // In the in-chain to the call is the entry node  If we are emitting a
7761   // tailcall, the chain will be mutated if the node has a non-entry input
7762   // chain.
7763   SDValue InChain = DAG.getEntryNode();
7764   SDValue TCChain = InChain;
7765 
7766   const auto *F = DAG.getMachineFunction().getFunction();
7767   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7768               F->getReturnType() == LCRTy;
7769   if (IsTC)
7770     InChain = TCChain;
7771 
7772   TargetLowering::CallLoweringInfo CLI(DAG);
7773   CLI.setDebugLoc(dl)
7774       .setChain(InChain)
7775       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7776       .setTailCall(IsTC);
7777   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7778 
7779   // Return the chain (the DAG root) if it is a tail call
7780   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7781 }
7782 
7783 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7784   DEBUG(dbgs() << "Lowering node: "; Op.dump());
7785   switch (Op.getOpcode()) {
7786   default: llvm_unreachable("Don't know how to custom lower this!");
7787   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7788   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7789   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7790   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7791   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7792   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7793   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7794   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7795   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7796   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7797   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7798   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7799   case ISD::SINT_TO_FP:
7800   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7801   case ISD::FP_TO_SINT:
7802   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7803   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7804   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7805   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7806   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7807   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7808   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7809   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7810                                                                Subtarget);
7811   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7812   case ISD::SHL:
7813   case ISD::SRL:
7814   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7815   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7816   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7817   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7818   case ISD::SRL_PARTS:
7819   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7820   case ISD::CTTZ:
7821   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7822   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7823   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7824   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7825   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7826   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7827   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7828   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7829   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7830   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7831   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7832   case ISD::MUL:           return LowerMUL(Op, DAG);
7833   case ISD::SDIV:
7834     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7835       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7836     return LowerSDIV(Op, DAG);
7837   case ISD::UDIV:
7838     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7839       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7840     return LowerUDIV(Op, DAG);
7841   case ISD::ADDC:
7842   case ISD::ADDE:
7843   case ISD::SUBC:
7844   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7845   case ISD::ADDCARRY:
7846   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
7847   case ISD::SADDO:
7848   case ISD::SSUBO:
7849     return LowerSignedALUO(Op, DAG);
7850   case ISD::UADDO:
7851   case ISD::USUBO:
7852     return LowerUnsignedALUO(Op, DAG);
7853   case ISD::ATOMIC_LOAD:
7854   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7855   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7856   case ISD::SDIVREM:
7857   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7858   case ISD::DYNAMIC_STACKALLOC:
7859     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7860       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7861     llvm_unreachable("Don't know how to custom lower this!");
7862   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7863   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7864   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7865   case ARMISD::WIN__DBZCHK: return SDValue();
7866   }
7867 }
7868 
7869 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7870                                  SelectionDAG &DAG) {
7871   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7872   unsigned Opc = 0;
7873   if (IntNo == Intrinsic::arm_smlald)
7874     Opc = ARMISD::SMLALD;
7875   else if (IntNo == Intrinsic::arm_smlaldx)
7876     Opc = ARMISD::SMLALDX;
7877   else if (IntNo == Intrinsic::arm_smlsld)
7878     Opc = ARMISD::SMLSLD;
7879   else if (IntNo == Intrinsic::arm_smlsldx)
7880     Opc = ARMISD::SMLSLDX;
7881   else
7882     return;
7883 
7884   SDLoc dl(N);
7885   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7886                            N->getOperand(3),
7887                            DAG.getConstant(0, dl, MVT::i32));
7888   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7889                            N->getOperand(3),
7890                            DAG.getConstant(1, dl, MVT::i32));
7891 
7892   SDValue LongMul = DAG.getNode(Opc, dl,
7893                                 DAG.getVTList(MVT::i32, MVT::i32),
7894                                 N->getOperand(1), N->getOperand(2),
7895                                 Lo, Hi);
7896   Results.push_back(LongMul.getValue(0));
7897   Results.push_back(LongMul.getValue(1));
7898 }
7899 
7900 /// ReplaceNodeResults - Replace the results of node with an illegal result
7901 /// type with new values built out of custom code.
7902 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7903                                            SmallVectorImpl<SDValue> &Results,
7904                                            SelectionDAG &DAG) const {
7905   SDValue Res;
7906   switch (N->getOpcode()) {
7907   default:
7908     llvm_unreachable("Don't know how to custom expand this!");
7909   case ISD::READ_REGISTER:
7910     ExpandREAD_REGISTER(N, Results, DAG);
7911     break;
7912   case ISD::BITCAST:
7913     Res = ExpandBITCAST(N, DAG);
7914     break;
7915   case ISD::SRL:
7916   case ISD::SRA:
7917     Res = Expand64BitShift(N, DAG, Subtarget);
7918     break;
7919   case ISD::SREM:
7920   case ISD::UREM:
7921     Res = LowerREM(N, DAG);
7922     break;
7923   case ISD::SDIVREM:
7924   case ISD::UDIVREM:
7925     Res = LowerDivRem(SDValue(N, 0), DAG);
7926     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7927     Results.push_back(Res.getValue(0));
7928     Results.push_back(Res.getValue(1));
7929     return;
7930   case ISD::READCYCLECOUNTER:
7931     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7932     return;
7933   case ISD::UDIV:
7934   case ISD::SDIV:
7935     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7936     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7937                              Results);
7938   case ISD::ATOMIC_CMP_SWAP:
7939     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7940     return;
7941   case ISD::INTRINSIC_WO_CHAIN:
7942     return ReplaceLongIntrinsic(N, Results, DAG);
7943   }
7944   if (Res.getNode())
7945     Results.push_back(Res);
7946 }
7947 
7948 //===----------------------------------------------------------------------===//
7949 //                           ARM Scheduler Hooks
7950 //===----------------------------------------------------------------------===//
7951 
7952 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7953 /// registers the function context.
7954 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7955                                                MachineBasicBlock *MBB,
7956                                                MachineBasicBlock *DispatchBB,
7957                                                int FI) const {
7958   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7959          "ROPI/RWPI not currently supported with SjLj");
7960   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7961   DebugLoc dl = MI.getDebugLoc();
7962   MachineFunction *MF = MBB->getParent();
7963   MachineRegisterInfo *MRI = &MF->getRegInfo();
7964   MachineConstantPool *MCP = MF->getConstantPool();
7965   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7966   const Function *F = MF->getFunction();
7967 
7968   bool isThumb = Subtarget->isThumb();
7969   bool isThumb2 = Subtarget->isThumb2();
7970 
7971   unsigned PCLabelId = AFI->createPICLabelUId();
7972   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7973   ARMConstantPoolValue *CPV =
7974     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7975   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7976 
7977   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7978                                            : &ARM::GPRRegClass;
7979 
7980   // Grab constant pool and fixed stack memory operands.
7981   MachineMemOperand *CPMMO =
7982       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7983                                MachineMemOperand::MOLoad, 4, 4);
7984 
7985   MachineMemOperand *FIMMOSt =
7986       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7987                                MachineMemOperand::MOStore, 4, 4);
7988 
7989   // Load the address of the dispatch MBB into the jump buffer.
7990   if (isThumb2) {
7991     // Incoming value: jbuf
7992     //   ldr.n  r5, LCPI1_1
7993     //   orr    r5, r5, #1
7994     //   add    r5, pc
7995     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7996     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7997     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7998         .addConstantPoolIndex(CPI)
7999         .addMemOperand(CPMMO)
8000         .add(predOps(ARMCC::AL));
8001     // Set the low bit because of thumb mode.
8002     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8003     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8004         .addReg(NewVReg1, RegState::Kill)
8005         .addImm(0x01)
8006         .add(predOps(ARMCC::AL))
8007         .add(condCodeOp());
8008     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8009     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8010       .addReg(NewVReg2, RegState::Kill)
8011       .addImm(PCLabelId);
8012     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8013         .addReg(NewVReg3, RegState::Kill)
8014         .addFrameIndex(FI)
8015         .addImm(36) // &jbuf[1] :: pc
8016         .addMemOperand(FIMMOSt)
8017         .add(predOps(ARMCC::AL));
8018   } else if (isThumb) {
8019     // Incoming value: jbuf
8020     //   ldr.n  r1, LCPI1_4
8021     //   add    r1, pc
8022     //   mov    r2, #1
8023     //   orrs   r1, r2
8024     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8025     //   str    r1, [r2]
8026     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8027     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8028         .addConstantPoolIndex(CPI)
8029         .addMemOperand(CPMMO)
8030         .add(predOps(ARMCC::AL));
8031     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8032     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8033       .addReg(NewVReg1, RegState::Kill)
8034       .addImm(PCLabelId);
8035     // Set the low bit because of thumb mode.
8036     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8037     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8038         .addReg(ARM::CPSR, RegState::Define)
8039         .addImm(1)
8040         .add(predOps(ARMCC::AL));
8041     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8042     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8043         .addReg(ARM::CPSR, RegState::Define)
8044         .addReg(NewVReg2, RegState::Kill)
8045         .addReg(NewVReg3, RegState::Kill)
8046         .add(predOps(ARMCC::AL));
8047     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8048     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8049             .addFrameIndex(FI)
8050             .addImm(36); // &jbuf[1] :: pc
8051     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8052         .addReg(NewVReg4, RegState::Kill)
8053         .addReg(NewVReg5, RegState::Kill)
8054         .addImm(0)
8055         .addMemOperand(FIMMOSt)
8056         .add(predOps(ARMCC::AL));
8057   } else {
8058     // Incoming value: jbuf
8059     //   ldr  r1, LCPI1_1
8060     //   add  r1, pc, r1
8061     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8062     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8063     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8064         .addConstantPoolIndex(CPI)
8065         .addImm(0)
8066         .addMemOperand(CPMMO)
8067         .add(predOps(ARMCC::AL));
8068     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8069     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8070         .addReg(NewVReg1, RegState::Kill)
8071         .addImm(PCLabelId)
8072         .add(predOps(ARMCC::AL));
8073     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8074         .addReg(NewVReg2, RegState::Kill)
8075         .addFrameIndex(FI)
8076         .addImm(36) // &jbuf[1] :: pc
8077         .addMemOperand(FIMMOSt)
8078         .add(predOps(ARMCC::AL));
8079   }
8080 }
8081 
8082 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8083                                               MachineBasicBlock *MBB) const {
8084   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8085   DebugLoc dl = MI.getDebugLoc();
8086   MachineFunction *MF = MBB->getParent();
8087   MachineRegisterInfo *MRI = &MF->getRegInfo();
8088   MachineFrameInfo &MFI = MF->getFrameInfo();
8089   int FI = MFI.getFunctionContextIndex();
8090 
8091   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8092                                                         : &ARM::GPRnopcRegClass;
8093 
8094   // Get a mapping of the call site numbers to all of the landing pads they're
8095   // associated with.
8096   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8097   unsigned MaxCSNum = 0;
8098   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8099        ++BB) {
8100     if (!BB->isEHPad()) continue;
8101 
8102     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8103     // pad.
8104     for (MachineBasicBlock::iterator
8105            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8106       if (!II->isEHLabel()) continue;
8107 
8108       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8109       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8110 
8111       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8112       for (SmallVectorImpl<unsigned>::iterator
8113              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8114            CSI != CSE; ++CSI) {
8115         CallSiteNumToLPad[*CSI].push_back(&*BB);
8116         MaxCSNum = std::max(MaxCSNum, *CSI);
8117       }
8118       break;
8119     }
8120   }
8121 
8122   // Get an ordered list of the machine basic blocks for the jump table.
8123   std::vector<MachineBasicBlock*> LPadList;
8124   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8125   LPadList.reserve(CallSiteNumToLPad.size());
8126   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8127     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8128     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8129            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8130       LPadList.push_back(*II);
8131       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8132     }
8133   }
8134 
8135   assert(!LPadList.empty() &&
8136          "No landing pad destinations for the dispatch jump table!");
8137 
8138   // Create the jump table and associated information.
8139   MachineJumpTableInfo *JTI =
8140     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8141   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8142 
8143   // Create the MBBs for the dispatch code.
8144 
8145   // Shove the dispatch's address into the return slot in the function context.
8146   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8147   DispatchBB->setIsEHPad();
8148 
8149   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8150   unsigned trap_opcode;
8151   if (Subtarget->isThumb())
8152     trap_opcode = ARM::tTRAP;
8153   else
8154     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8155 
8156   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8157   DispatchBB->addSuccessor(TrapBB);
8158 
8159   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8160   DispatchBB->addSuccessor(DispContBB);
8161 
8162   // Insert and MBBs.
8163   MF->insert(MF->end(), DispatchBB);
8164   MF->insert(MF->end(), DispContBB);
8165   MF->insert(MF->end(), TrapBB);
8166 
8167   // Insert code into the entry block that creates and registers the function
8168   // context.
8169   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8170 
8171   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8172       MachinePointerInfo::getFixedStack(*MF, FI),
8173       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8174 
8175   MachineInstrBuilder MIB;
8176   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8177 
8178   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8179   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8180 
8181   // Add a register mask with no preserved registers.  This results in all
8182   // registers being marked as clobbered. This can't work if the dispatch block
8183   // is in a Thumb1 function and is linked with ARM code which uses the FP
8184   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8185   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8186 
8187   bool IsPositionIndependent = isPositionIndependent();
8188   unsigned NumLPads = LPadList.size();
8189   if (Subtarget->isThumb2()) {
8190     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8191     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8192         .addFrameIndex(FI)
8193         .addImm(4)
8194         .addMemOperand(FIMMOLd)
8195         .add(predOps(ARMCC::AL));
8196 
8197     if (NumLPads < 256) {
8198       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8199           .addReg(NewVReg1)
8200           .addImm(LPadList.size())
8201           .add(predOps(ARMCC::AL));
8202     } else {
8203       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8204       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8205           .addImm(NumLPads & 0xFFFF)
8206           .add(predOps(ARMCC::AL));
8207 
8208       unsigned VReg2 = VReg1;
8209       if ((NumLPads & 0xFFFF0000) != 0) {
8210         VReg2 = MRI->createVirtualRegister(TRC);
8211         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8212             .addReg(VReg1)
8213             .addImm(NumLPads >> 16)
8214             .add(predOps(ARMCC::AL));
8215       }
8216 
8217       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8218           .addReg(NewVReg1)
8219           .addReg(VReg2)
8220           .add(predOps(ARMCC::AL));
8221     }
8222 
8223     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8224       .addMBB(TrapBB)
8225       .addImm(ARMCC::HI)
8226       .addReg(ARM::CPSR);
8227 
8228     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8229     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8230         .addJumpTableIndex(MJTI)
8231         .add(predOps(ARMCC::AL));
8232 
8233     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8234     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8235         .addReg(NewVReg3, RegState::Kill)
8236         .addReg(NewVReg1)
8237         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8238         .add(predOps(ARMCC::AL))
8239         .add(condCodeOp());
8240 
8241     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8242       .addReg(NewVReg4, RegState::Kill)
8243       .addReg(NewVReg1)
8244       .addJumpTableIndex(MJTI);
8245   } else if (Subtarget->isThumb()) {
8246     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8247     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8248         .addFrameIndex(FI)
8249         .addImm(1)
8250         .addMemOperand(FIMMOLd)
8251         .add(predOps(ARMCC::AL));
8252 
8253     if (NumLPads < 256) {
8254       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8255           .addReg(NewVReg1)
8256           .addImm(NumLPads)
8257           .add(predOps(ARMCC::AL));
8258     } else {
8259       MachineConstantPool *ConstantPool = MF->getConstantPool();
8260       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8261       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8262 
8263       // MachineConstantPool wants an explicit alignment.
8264       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8265       if (Align == 0)
8266         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8267       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8268 
8269       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8270       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8271           .addReg(VReg1, RegState::Define)
8272           .addConstantPoolIndex(Idx)
8273           .add(predOps(ARMCC::AL));
8274       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8275           .addReg(NewVReg1)
8276           .addReg(VReg1)
8277           .add(predOps(ARMCC::AL));
8278     }
8279 
8280     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8281       .addMBB(TrapBB)
8282       .addImm(ARMCC::HI)
8283       .addReg(ARM::CPSR);
8284 
8285     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8286     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8287         .addReg(ARM::CPSR, RegState::Define)
8288         .addReg(NewVReg1)
8289         .addImm(2)
8290         .add(predOps(ARMCC::AL));
8291 
8292     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8293     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8294         .addJumpTableIndex(MJTI)
8295         .add(predOps(ARMCC::AL));
8296 
8297     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8298     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8299         .addReg(ARM::CPSR, RegState::Define)
8300         .addReg(NewVReg2, RegState::Kill)
8301         .addReg(NewVReg3)
8302         .add(predOps(ARMCC::AL));
8303 
8304     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8305         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8306 
8307     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8308     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8309         .addReg(NewVReg4, RegState::Kill)
8310         .addImm(0)
8311         .addMemOperand(JTMMOLd)
8312         .add(predOps(ARMCC::AL));
8313 
8314     unsigned NewVReg6 = NewVReg5;
8315     if (IsPositionIndependent) {
8316       NewVReg6 = MRI->createVirtualRegister(TRC);
8317       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8318           .addReg(ARM::CPSR, RegState::Define)
8319           .addReg(NewVReg5, RegState::Kill)
8320           .addReg(NewVReg3)
8321           .add(predOps(ARMCC::AL));
8322     }
8323 
8324     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8325       .addReg(NewVReg6, RegState::Kill)
8326       .addJumpTableIndex(MJTI);
8327   } else {
8328     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8329     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8330         .addFrameIndex(FI)
8331         .addImm(4)
8332         .addMemOperand(FIMMOLd)
8333         .add(predOps(ARMCC::AL));
8334 
8335     if (NumLPads < 256) {
8336       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8337           .addReg(NewVReg1)
8338           .addImm(NumLPads)
8339           .add(predOps(ARMCC::AL));
8340     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8341       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8342       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8343           .addImm(NumLPads & 0xFFFF)
8344           .add(predOps(ARMCC::AL));
8345 
8346       unsigned VReg2 = VReg1;
8347       if ((NumLPads & 0xFFFF0000) != 0) {
8348         VReg2 = MRI->createVirtualRegister(TRC);
8349         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8350             .addReg(VReg1)
8351             .addImm(NumLPads >> 16)
8352             .add(predOps(ARMCC::AL));
8353       }
8354 
8355       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8356           .addReg(NewVReg1)
8357           .addReg(VReg2)
8358           .add(predOps(ARMCC::AL));
8359     } else {
8360       MachineConstantPool *ConstantPool = MF->getConstantPool();
8361       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8362       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8363 
8364       // MachineConstantPool wants an explicit alignment.
8365       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8366       if (Align == 0)
8367         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8368       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8369 
8370       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8371       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8372           .addReg(VReg1, RegState::Define)
8373           .addConstantPoolIndex(Idx)
8374           .addImm(0)
8375           .add(predOps(ARMCC::AL));
8376       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8377           .addReg(NewVReg1)
8378           .addReg(VReg1, RegState::Kill)
8379           .add(predOps(ARMCC::AL));
8380     }
8381 
8382     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8383       .addMBB(TrapBB)
8384       .addImm(ARMCC::HI)
8385       .addReg(ARM::CPSR);
8386 
8387     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8388     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8389         .addReg(NewVReg1)
8390         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8391         .add(predOps(ARMCC::AL))
8392         .add(condCodeOp());
8393     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8394     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8395         .addJumpTableIndex(MJTI)
8396         .add(predOps(ARMCC::AL));
8397 
8398     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8399         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8400     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8401     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8402         .addReg(NewVReg3, RegState::Kill)
8403         .addReg(NewVReg4)
8404         .addImm(0)
8405         .addMemOperand(JTMMOLd)
8406         .add(predOps(ARMCC::AL));
8407 
8408     if (IsPositionIndependent) {
8409       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8410         .addReg(NewVReg5, RegState::Kill)
8411         .addReg(NewVReg4)
8412         .addJumpTableIndex(MJTI);
8413     } else {
8414       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8415         .addReg(NewVReg5, RegState::Kill)
8416         .addJumpTableIndex(MJTI);
8417     }
8418   }
8419 
8420   // Add the jump table entries as successors to the MBB.
8421   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8422   for (std::vector<MachineBasicBlock*>::iterator
8423          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8424     MachineBasicBlock *CurMBB = *I;
8425     if (SeenMBBs.insert(CurMBB).second)
8426       DispContBB->addSuccessor(CurMBB);
8427   }
8428 
8429   // N.B. the order the invoke BBs are processed in doesn't matter here.
8430   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8431   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8432   for (MachineBasicBlock *BB : InvokeBBs) {
8433 
8434     // Remove the landing pad successor from the invoke block and replace it
8435     // with the new dispatch block.
8436     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8437                                                   BB->succ_end());
8438     while (!Successors.empty()) {
8439       MachineBasicBlock *SMBB = Successors.pop_back_val();
8440       if (SMBB->isEHPad()) {
8441         BB->removeSuccessor(SMBB);
8442         MBBLPads.push_back(SMBB);
8443       }
8444     }
8445 
8446     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8447     BB->normalizeSuccProbs();
8448 
8449     // Find the invoke call and mark all of the callee-saved registers as
8450     // 'implicit defined' so that they're spilled. This prevents code from
8451     // moving instructions to before the EH block, where they will never be
8452     // executed.
8453     for (MachineBasicBlock::reverse_iterator
8454            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8455       if (!II->isCall()) continue;
8456 
8457       DenseMap<unsigned, bool> DefRegs;
8458       for (MachineInstr::mop_iterator
8459              OI = II->operands_begin(), OE = II->operands_end();
8460            OI != OE; ++OI) {
8461         if (!OI->isReg()) continue;
8462         DefRegs[OI->getReg()] = true;
8463       }
8464 
8465       MachineInstrBuilder MIB(*MF, &*II);
8466 
8467       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8468         unsigned Reg = SavedRegs[i];
8469         if (Subtarget->isThumb2() &&
8470             !ARM::tGPRRegClass.contains(Reg) &&
8471             !ARM::hGPRRegClass.contains(Reg))
8472           continue;
8473         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8474           continue;
8475         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8476           continue;
8477         if (!DefRegs[Reg])
8478           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8479       }
8480 
8481       break;
8482     }
8483   }
8484 
8485   // Mark all former landing pads as non-landing pads. The dispatch is the only
8486   // landing pad now.
8487   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8488          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8489     (*I)->setIsEHPad(false);
8490 
8491   // The instruction is gone now.
8492   MI.eraseFromParent();
8493 }
8494 
8495 static
8496 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8497   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8498        E = MBB->succ_end(); I != E; ++I)
8499     if (*I != Succ)
8500       return *I;
8501   llvm_unreachable("Expecting a BB with two successors!");
8502 }
8503 
8504 /// Return the load opcode for a given load size. If load size >= 8,
8505 /// neon opcode will be returned.
8506 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8507   if (LdSize >= 8)
8508     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8509                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8510   if (IsThumb1)
8511     return LdSize == 4 ? ARM::tLDRi
8512                        : LdSize == 2 ? ARM::tLDRHi
8513                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8514   if (IsThumb2)
8515     return LdSize == 4 ? ARM::t2LDR_POST
8516                        : LdSize == 2 ? ARM::t2LDRH_POST
8517                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8518   return LdSize == 4 ? ARM::LDR_POST_IMM
8519                      : LdSize == 2 ? ARM::LDRH_POST
8520                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8521 }
8522 
8523 /// Return the store opcode for a given store size. If store size >= 8,
8524 /// neon opcode will be returned.
8525 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8526   if (StSize >= 8)
8527     return StSize == 16 ? ARM::VST1q32wb_fixed
8528                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8529   if (IsThumb1)
8530     return StSize == 4 ? ARM::tSTRi
8531                        : StSize == 2 ? ARM::tSTRHi
8532                                      : StSize == 1 ? ARM::tSTRBi : 0;
8533   if (IsThumb2)
8534     return StSize == 4 ? ARM::t2STR_POST
8535                        : StSize == 2 ? ARM::t2STRH_POST
8536                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8537   return StSize == 4 ? ARM::STR_POST_IMM
8538                      : StSize == 2 ? ARM::STRH_POST
8539                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8540 }
8541 
8542 /// Emit a post-increment load operation with given size. The instructions
8543 /// will be added to BB at Pos.
8544 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8545                        const TargetInstrInfo *TII, const DebugLoc &dl,
8546                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8547                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8548   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8549   assert(LdOpc != 0 && "Should have a load opcode");
8550   if (LdSize >= 8) {
8551     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8552         .addReg(AddrOut, RegState::Define)
8553         .addReg(AddrIn)
8554         .addImm(0)
8555         .add(predOps(ARMCC::AL));
8556   } else if (IsThumb1) {
8557     // load + update AddrIn
8558     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8559         .addReg(AddrIn)
8560         .addImm(0)
8561         .add(predOps(ARMCC::AL));
8562     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8563         .add(t1CondCodeOp())
8564         .addReg(AddrIn)
8565         .addImm(LdSize)
8566         .add(predOps(ARMCC::AL));
8567   } else if (IsThumb2) {
8568     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8569         .addReg(AddrOut, RegState::Define)
8570         .addReg(AddrIn)
8571         .addImm(LdSize)
8572         .add(predOps(ARMCC::AL));
8573   } else { // arm
8574     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8575         .addReg(AddrOut, RegState::Define)
8576         .addReg(AddrIn)
8577         .addReg(0)
8578         .addImm(LdSize)
8579         .add(predOps(ARMCC::AL));
8580   }
8581 }
8582 
8583 /// Emit a post-increment store operation with given size. The instructions
8584 /// will be added to BB at Pos.
8585 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8586                        const TargetInstrInfo *TII, const DebugLoc &dl,
8587                        unsigned StSize, unsigned Data, unsigned AddrIn,
8588                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8589   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8590   assert(StOpc != 0 && "Should have a store opcode");
8591   if (StSize >= 8) {
8592     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8593         .addReg(AddrIn)
8594         .addImm(0)
8595         .addReg(Data)
8596         .add(predOps(ARMCC::AL));
8597   } else if (IsThumb1) {
8598     // store + update AddrIn
8599     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8600         .addReg(Data)
8601         .addReg(AddrIn)
8602         .addImm(0)
8603         .add(predOps(ARMCC::AL));
8604     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8605         .add(t1CondCodeOp())
8606         .addReg(AddrIn)
8607         .addImm(StSize)
8608         .add(predOps(ARMCC::AL));
8609   } else if (IsThumb2) {
8610     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8611         .addReg(Data)
8612         .addReg(AddrIn)
8613         .addImm(StSize)
8614         .add(predOps(ARMCC::AL));
8615   } else { // arm
8616     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8617         .addReg(Data)
8618         .addReg(AddrIn)
8619         .addReg(0)
8620         .addImm(StSize)
8621         .add(predOps(ARMCC::AL));
8622   }
8623 }
8624 
8625 MachineBasicBlock *
8626 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8627                                    MachineBasicBlock *BB) const {
8628   // This pseudo instruction has 3 operands: dst, src, size
8629   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8630   // Otherwise, we will generate unrolled scalar copies.
8631   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8632   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8633   MachineFunction::iterator It = ++BB->getIterator();
8634 
8635   unsigned dest = MI.getOperand(0).getReg();
8636   unsigned src = MI.getOperand(1).getReg();
8637   unsigned SizeVal = MI.getOperand(2).getImm();
8638   unsigned Align = MI.getOperand(3).getImm();
8639   DebugLoc dl = MI.getDebugLoc();
8640 
8641   MachineFunction *MF = BB->getParent();
8642   MachineRegisterInfo &MRI = MF->getRegInfo();
8643   unsigned UnitSize = 0;
8644   const TargetRegisterClass *TRC = nullptr;
8645   const TargetRegisterClass *VecTRC = nullptr;
8646 
8647   bool IsThumb1 = Subtarget->isThumb1Only();
8648   bool IsThumb2 = Subtarget->isThumb2();
8649   bool IsThumb = Subtarget->isThumb();
8650 
8651   if (Align & 1) {
8652     UnitSize = 1;
8653   } else if (Align & 2) {
8654     UnitSize = 2;
8655   } else {
8656     // Check whether we can use NEON instructions.
8657     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8658         Subtarget->hasNEON()) {
8659       if ((Align % 16 == 0) && SizeVal >= 16)
8660         UnitSize = 16;
8661       else if ((Align % 8 == 0) && SizeVal >= 8)
8662         UnitSize = 8;
8663     }
8664     // Can't use NEON instructions.
8665     if (UnitSize == 0)
8666       UnitSize = 4;
8667   }
8668 
8669   // Select the correct opcode and register class for unit size load/store
8670   bool IsNeon = UnitSize >= 8;
8671   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8672   if (IsNeon)
8673     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8674                             : UnitSize == 8 ? &ARM::DPRRegClass
8675                                             : nullptr;
8676 
8677   unsigned BytesLeft = SizeVal % UnitSize;
8678   unsigned LoopSize = SizeVal - BytesLeft;
8679 
8680   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8681     // Use LDR and STR to copy.
8682     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8683     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8684     unsigned srcIn = src;
8685     unsigned destIn = dest;
8686     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8687       unsigned srcOut = MRI.createVirtualRegister(TRC);
8688       unsigned destOut = MRI.createVirtualRegister(TRC);
8689       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8690       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8691                  IsThumb1, IsThumb2);
8692       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8693                  IsThumb1, IsThumb2);
8694       srcIn = srcOut;
8695       destIn = destOut;
8696     }
8697 
8698     // Handle the leftover bytes with LDRB and STRB.
8699     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8700     // [destOut] = STRB_POST(scratch, destIn, 1)
8701     for (unsigned i = 0; i < BytesLeft; i++) {
8702       unsigned srcOut = MRI.createVirtualRegister(TRC);
8703       unsigned destOut = MRI.createVirtualRegister(TRC);
8704       unsigned scratch = MRI.createVirtualRegister(TRC);
8705       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8706                  IsThumb1, IsThumb2);
8707       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8708                  IsThumb1, IsThumb2);
8709       srcIn = srcOut;
8710       destIn = destOut;
8711     }
8712     MI.eraseFromParent(); // The instruction is gone now.
8713     return BB;
8714   }
8715 
8716   // Expand the pseudo op to a loop.
8717   // thisMBB:
8718   //   ...
8719   //   movw varEnd, # --> with thumb2
8720   //   movt varEnd, #
8721   //   ldrcp varEnd, idx --> without thumb2
8722   //   fallthrough --> loopMBB
8723   // loopMBB:
8724   //   PHI varPhi, varEnd, varLoop
8725   //   PHI srcPhi, src, srcLoop
8726   //   PHI destPhi, dst, destLoop
8727   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8728   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8729   //   subs varLoop, varPhi, #UnitSize
8730   //   bne loopMBB
8731   //   fallthrough --> exitMBB
8732   // exitMBB:
8733   //   epilogue to handle left-over bytes
8734   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8735   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8736   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8737   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8738   MF->insert(It, loopMBB);
8739   MF->insert(It, exitMBB);
8740 
8741   // Transfer the remainder of BB and its successor edges to exitMBB.
8742   exitMBB->splice(exitMBB->begin(), BB,
8743                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8744   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8745 
8746   // Load an immediate to varEnd.
8747   unsigned varEnd = MRI.createVirtualRegister(TRC);
8748   if (Subtarget->useMovt(*MF)) {
8749     unsigned Vtmp = varEnd;
8750     if ((LoopSize & 0xFFFF0000) != 0)
8751       Vtmp = MRI.createVirtualRegister(TRC);
8752     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8753         .addImm(LoopSize & 0xFFFF)
8754         .add(predOps(ARMCC::AL));
8755 
8756     if ((LoopSize & 0xFFFF0000) != 0)
8757       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8758           .addReg(Vtmp)
8759           .addImm(LoopSize >> 16)
8760           .add(predOps(ARMCC::AL));
8761   } else {
8762     MachineConstantPool *ConstantPool = MF->getConstantPool();
8763     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8764     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8765 
8766     // MachineConstantPool wants an explicit alignment.
8767     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8768     if (Align == 0)
8769       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8770     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8771 
8772     if (IsThumb)
8773       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8774           .addReg(varEnd, RegState::Define)
8775           .addConstantPoolIndex(Idx)
8776           .add(predOps(ARMCC::AL));
8777     else
8778       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8779           .addReg(varEnd, RegState::Define)
8780           .addConstantPoolIndex(Idx)
8781           .addImm(0)
8782           .add(predOps(ARMCC::AL));
8783   }
8784   BB->addSuccessor(loopMBB);
8785 
8786   // Generate the loop body:
8787   //   varPhi = PHI(varLoop, varEnd)
8788   //   srcPhi = PHI(srcLoop, src)
8789   //   destPhi = PHI(destLoop, dst)
8790   MachineBasicBlock *entryBB = BB;
8791   BB = loopMBB;
8792   unsigned varLoop = MRI.createVirtualRegister(TRC);
8793   unsigned varPhi = MRI.createVirtualRegister(TRC);
8794   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8795   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8796   unsigned destLoop = MRI.createVirtualRegister(TRC);
8797   unsigned destPhi = MRI.createVirtualRegister(TRC);
8798 
8799   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8800     .addReg(varLoop).addMBB(loopMBB)
8801     .addReg(varEnd).addMBB(entryBB);
8802   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8803     .addReg(srcLoop).addMBB(loopMBB)
8804     .addReg(src).addMBB(entryBB);
8805   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8806     .addReg(destLoop).addMBB(loopMBB)
8807     .addReg(dest).addMBB(entryBB);
8808 
8809   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8810   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8811   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8812   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8813              IsThumb1, IsThumb2);
8814   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8815              IsThumb1, IsThumb2);
8816 
8817   // Decrement loop variable by UnitSize.
8818   if (IsThumb1) {
8819     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8820         .add(t1CondCodeOp())
8821         .addReg(varPhi)
8822         .addImm(UnitSize)
8823         .add(predOps(ARMCC::AL));
8824   } else {
8825     MachineInstrBuilder MIB =
8826         BuildMI(*BB, BB->end(), dl,
8827                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8828     MIB.addReg(varPhi)
8829         .addImm(UnitSize)
8830         .add(predOps(ARMCC::AL))
8831         .add(condCodeOp());
8832     MIB->getOperand(5).setReg(ARM::CPSR);
8833     MIB->getOperand(5).setIsDef(true);
8834   }
8835   BuildMI(*BB, BB->end(), dl,
8836           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8837       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8838 
8839   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8840   BB->addSuccessor(loopMBB);
8841   BB->addSuccessor(exitMBB);
8842 
8843   // Add epilogue to handle BytesLeft.
8844   BB = exitMBB;
8845   auto StartOfExit = exitMBB->begin();
8846 
8847   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8848   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8849   unsigned srcIn = srcLoop;
8850   unsigned destIn = destLoop;
8851   for (unsigned i = 0; i < BytesLeft; i++) {
8852     unsigned srcOut = MRI.createVirtualRegister(TRC);
8853     unsigned destOut = MRI.createVirtualRegister(TRC);
8854     unsigned scratch = MRI.createVirtualRegister(TRC);
8855     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8856                IsThumb1, IsThumb2);
8857     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8858                IsThumb1, IsThumb2);
8859     srcIn = srcOut;
8860     destIn = destOut;
8861   }
8862 
8863   MI.eraseFromParent(); // The instruction is gone now.
8864   return BB;
8865 }
8866 
8867 MachineBasicBlock *
8868 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8869                                        MachineBasicBlock *MBB) const {
8870   const TargetMachine &TM = getTargetMachine();
8871   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8872   DebugLoc DL = MI.getDebugLoc();
8873 
8874   assert(Subtarget->isTargetWindows() &&
8875          "__chkstk is only supported on Windows");
8876   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8877 
8878   // __chkstk takes the number of words to allocate on the stack in R4, and
8879   // returns the stack adjustment in number of bytes in R4.  This will not
8880   // clober any other registers (other than the obvious lr).
8881   //
8882   // Although, technically, IP should be considered a register which may be
8883   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8884   // thumb-2 environment, so there is no interworking required.  As a result, we
8885   // do not expect a veneer to be emitted by the linker, clobbering IP.
8886   //
8887   // Each module receives its own copy of __chkstk, so no import thunk is
8888   // required, again, ensuring that IP is not clobbered.
8889   //
8890   // Finally, although some linkers may theoretically provide a trampoline for
8891   // out of range calls (which is quite common due to a 32M range limitation of
8892   // branches for Thumb), we can generate the long-call version via
8893   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8894   // IP.
8895 
8896   switch (TM.getCodeModel()) {
8897   case CodeModel::Small:
8898   case CodeModel::Medium:
8899   case CodeModel::Kernel:
8900     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8901         .add(predOps(ARMCC::AL))
8902         .addExternalSymbol("__chkstk")
8903         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8904         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8905         .addReg(ARM::R12,
8906                 RegState::Implicit | RegState::Define | RegState::Dead)
8907         .addReg(ARM::CPSR,
8908                 RegState::Implicit | RegState::Define | RegState::Dead);
8909     break;
8910   case CodeModel::Large: {
8911     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8912     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8913 
8914     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8915       .addExternalSymbol("__chkstk");
8916     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8917         .add(predOps(ARMCC::AL))
8918         .addReg(Reg, RegState::Kill)
8919         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8920         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8921         .addReg(ARM::R12,
8922                 RegState::Implicit | RegState::Define | RegState::Dead)
8923         .addReg(ARM::CPSR,
8924                 RegState::Implicit | RegState::Define | RegState::Dead);
8925     break;
8926   }
8927   }
8928 
8929   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8930       .addReg(ARM::SP, RegState::Kill)
8931       .addReg(ARM::R4, RegState::Kill)
8932       .setMIFlags(MachineInstr::FrameSetup)
8933       .add(predOps(ARMCC::AL))
8934       .add(condCodeOp());
8935 
8936   MI.eraseFromParent();
8937   return MBB;
8938 }
8939 
8940 MachineBasicBlock *
8941 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8942                                        MachineBasicBlock *MBB) const {
8943   DebugLoc DL = MI.getDebugLoc();
8944   MachineFunction *MF = MBB->getParent();
8945   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8946 
8947   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8948   MF->insert(++MBB->getIterator(), ContBB);
8949   ContBB->splice(ContBB->begin(), MBB,
8950                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8951   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8952   MBB->addSuccessor(ContBB);
8953 
8954   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8955   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8956   MF->push_back(TrapBB);
8957   MBB->addSuccessor(TrapBB);
8958 
8959   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8960       .addReg(MI.getOperand(0).getReg())
8961       .addImm(0)
8962       .add(predOps(ARMCC::AL));
8963   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8964       .addMBB(TrapBB)
8965       .addImm(ARMCC::EQ)
8966       .addReg(ARM::CPSR);
8967 
8968   MI.eraseFromParent();
8969   return ContBB;
8970 }
8971 
8972 MachineBasicBlock *
8973 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8974                                                MachineBasicBlock *BB) const {
8975   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8976   DebugLoc dl = MI.getDebugLoc();
8977   bool isThumb2 = Subtarget->isThumb2();
8978   switch (MI.getOpcode()) {
8979   default: {
8980     MI.print(errs());
8981     llvm_unreachable("Unexpected instr type to insert");
8982   }
8983 
8984   // Thumb1 post-indexed loads are really just single-register LDMs.
8985   case ARM::tLDR_postidx: {
8986     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8987         .add(MI.getOperand(1))  // Rn_wb
8988         .add(MI.getOperand(2))  // Rn
8989         .add(MI.getOperand(3))  // PredImm
8990         .add(MI.getOperand(4))  // PredReg
8991         .add(MI.getOperand(0)); // Rt
8992     MI.eraseFromParent();
8993     return BB;
8994   }
8995 
8996   // The Thumb2 pre-indexed stores have the same MI operands, they just
8997   // define them differently in the .td files from the isel patterns, so
8998   // they need pseudos.
8999   case ARM::t2STR_preidx:
9000     MI.setDesc(TII->get(ARM::t2STR_PRE));
9001     return BB;
9002   case ARM::t2STRB_preidx:
9003     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9004     return BB;
9005   case ARM::t2STRH_preidx:
9006     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9007     return BB;
9008 
9009   case ARM::STRi_preidx:
9010   case ARM::STRBi_preidx: {
9011     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9012                                                          : ARM::STRB_PRE_IMM;
9013     // Decode the offset.
9014     unsigned Offset = MI.getOperand(4).getImm();
9015     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9016     Offset = ARM_AM::getAM2Offset(Offset);
9017     if (isSub)
9018       Offset = -Offset;
9019 
9020     MachineMemOperand *MMO = *MI.memoperands_begin();
9021     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9022         .add(MI.getOperand(0)) // Rn_wb
9023         .add(MI.getOperand(1)) // Rt
9024         .add(MI.getOperand(2)) // Rn
9025         .addImm(Offset)        // offset (skip GPR==zero_reg)
9026         .add(MI.getOperand(5)) // pred
9027         .add(MI.getOperand(6))
9028         .addMemOperand(MMO);
9029     MI.eraseFromParent();
9030     return BB;
9031   }
9032   case ARM::STRr_preidx:
9033   case ARM::STRBr_preidx:
9034   case ARM::STRH_preidx: {
9035     unsigned NewOpc;
9036     switch (MI.getOpcode()) {
9037     default: llvm_unreachable("unexpected opcode!");
9038     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9039     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9040     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9041     }
9042     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9043     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9044       MIB.add(MI.getOperand(i));
9045     MI.eraseFromParent();
9046     return BB;
9047   }
9048 
9049   case ARM::tMOVCCr_pseudo: {
9050     // To "insert" a SELECT_CC instruction, we actually have to insert the
9051     // diamond control-flow pattern.  The incoming instruction knows the
9052     // destination vreg to set, the condition code register to branch on, the
9053     // true/false values to select between, and a branch opcode to use.
9054     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9055     MachineFunction::iterator It = ++BB->getIterator();
9056 
9057     //  thisMBB:
9058     //  ...
9059     //   TrueVal = ...
9060     //   cmpTY ccX, r1, r2
9061     //   bCC copy1MBB
9062     //   fallthrough --> copy0MBB
9063     MachineBasicBlock *thisMBB  = BB;
9064     MachineFunction *F = BB->getParent();
9065     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9066     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9067     F->insert(It, copy0MBB);
9068     F->insert(It, sinkMBB);
9069 
9070     // Transfer the remainder of BB and its successor edges to sinkMBB.
9071     sinkMBB->splice(sinkMBB->begin(), BB,
9072                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9073     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9074 
9075     BB->addSuccessor(copy0MBB);
9076     BB->addSuccessor(sinkMBB);
9077 
9078     BuildMI(BB, dl, TII->get(ARM::tBcc))
9079         .addMBB(sinkMBB)
9080         .addImm(MI.getOperand(3).getImm())
9081         .addReg(MI.getOperand(4).getReg());
9082 
9083     //  copy0MBB:
9084     //   %FalseValue = ...
9085     //   # fallthrough to sinkMBB
9086     BB = copy0MBB;
9087 
9088     // Update machine-CFG edges
9089     BB->addSuccessor(sinkMBB);
9090 
9091     //  sinkMBB:
9092     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9093     //  ...
9094     BB = sinkMBB;
9095     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9096         .addReg(MI.getOperand(1).getReg())
9097         .addMBB(copy0MBB)
9098         .addReg(MI.getOperand(2).getReg())
9099         .addMBB(thisMBB);
9100 
9101     MI.eraseFromParent(); // The pseudo instruction is gone now.
9102     return BB;
9103   }
9104 
9105   case ARM::BCCi64:
9106   case ARM::BCCZi64: {
9107     // If there is an unconditional branch to the other successor, remove it.
9108     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9109 
9110     // Compare both parts that make up the double comparison separately for
9111     // equality.
9112     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9113 
9114     unsigned LHS1 = MI.getOperand(1).getReg();
9115     unsigned LHS2 = MI.getOperand(2).getReg();
9116     if (RHSisZero) {
9117       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9118           .addReg(LHS1)
9119           .addImm(0)
9120           .add(predOps(ARMCC::AL));
9121       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9122         .addReg(LHS2).addImm(0)
9123         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9124     } else {
9125       unsigned RHS1 = MI.getOperand(3).getReg();
9126       unsigned RHS2 = MI.getOperand(4).getReg();
9127       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9128           .addReg(LHS1)
9129           .addReg(RHS1)
9130           .add(predOps(ARMCC::AL));
9131       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9132         .addReg(LHS2).addReg(RHS2)
9133         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9134     }
9135 
9136     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9137     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9138     if (MI.getOperand(0).getImm() == ARMCC::NE)
9139       std::swap(destMBB, exitMBB);
9140 
9141     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9142       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9143     if (isThumb2)
9144       BuildMI(BB, dl, TII->get(ARM::t2B))
9145           .addMBB(exitMBB)
9146           .add(predOps(ARMCC::AL));
9147     else
9148       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9149 
9150     MI.eraseFromParent(); // The pseudo instruction is gone now.
9151     return BB;
9152   }
9153 
9154   case ARM::Int_eh_sjlj_setjmp:
9155   case ARM::Int_eh_sjlj_setjmp_nofp:
9156   case ARM::tInt_eh_sjlj_setjmp:
9157   case ARM::t2Int_eh_sjlj_setjmp:
9158   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9159     return BB;
9160 
9161   case ARM::Int_eh_sjlj_setup_dispatch:
9162     EmitSjLjDispatchBlock(MI, BB);
9163     return BB;
9164 
9165   case ARM::ABS:
9166   case ARM::t2ABS: {
9167     // To insert an ABS instruction, we have to insert the
9168     // diamond control-flow pattern.  The incoming instruction knows the
9169     // source vreg to test against 0, the destination vreg to set,
9170     // the condition code register to branch on, the
9171     // true/false values to select between, and a branch opcode to use.
9172     // It transforms
9173     //     V1 = ABS V0
9174     // into
9175     //     V2 = MOVS V0
9176     //     BCC                      (branch to SinkBB if V0 >= 0)
9177     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9178     //     SinkBB: V1 = PHI(V2, V3)
9179     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9180     MachineFunction::iterator BBI = ++BB->getIterator();
9181     MachineFunction *Fn = BB->getParent();
9182     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9183     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9184     Fn->insert(BBI, RSBBB);
9185     Fn->insert(BBI, SinkBB);
9186 
9187     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9188     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9189     bool ABSSrcKIll = MI.getOperand(1).isKill();
9190     bool isThumb2 = Subtarget->isThumb2();
9191     MachineRegisterInfo &MRI = Fn->getRegInfo();
9192     // In Thumb mode S must not be specified if source register is the SP or
9193     // PC and if destination register is the SP, so restrict register class
9194     unsigned NewRsbDstReg =
9195       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9196 
9197     // Transfer the remainder of BB and its successor edges to sinkMBB.
9198     SinkBB->splice(SinkBB->begin(), BB,
9199                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9200     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9201 
9202     BB->addSuccessor(RSBBB);
9203     BB->addSuccessor(SinkBB);
9204 
9205     // fall through to SinkMBB
9206     RSBBB->addSuccessor(SinkBB);
9207 
9208     // insert a cmp at the end of BB
9209     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9210         .addReg(ABSSrcReg)
9211         .addImm(0)
9212         .add(predOps(ARMCC::AL));
9213 
9214     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9215     BuildMI(BB, dl,
9216       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9217       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9218 
9219     // insert rsbri in RSBBB
9220     // Note: BCC and rsbri will be converted into predicated rsbmi
9221     // by if-conversion pass
9222     BuildMI(*RSBBB, RSBBB->begin(), dl,
9223             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9224         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9225         .addImm(0)
9226         .add(predOps(ARMCC::AL))
9227         .add(condCodeOp());
9228 
9229     // insert PHI in SinkBB,
9230     // reuse ABSDstReg to not change uses of ABS instruction
9231     BuildMI(*SinkBB, SinkBB->begin(), dl,
9232       TII->get(ARM::PHI), ABSDstReg)
9233       .addReg(NewRsbDstReg).addMBB(RSBBB)
9234       .addReg(ABSSrcReg).addMBB(BB);
9235 
9236     // remove ABS instruction
9237     MI.eraseFromParent();
9238 
9239     // return last added BB
9240     return SinkBB;
9241   }
9242   case ARM::COPY_STRUCT_BYVAL_I32:
9243     ++NumLoopByVals;
9244     return EmitStructByval(MI, BB);
9245   case ARM::WIN__CHKSTK:
9246     return EmitLowered__chkstk(MI, BB);
9247   case ARM::WIN__DBZCHK:
9248     return EmitLowered__dbzchk(MI, BB);
9249   }
9250 }
9251 
9252 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9253 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9254 /// instead of as a custom inserter because we need the use list from the SDNode.
9255 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9256                                     MachineInstr &MI, const SDNode *Node) {
9257   bool isThumb1 = Subtarget->isThumb1Only();
9258 
9259   DebugLoc DL = MI.getDebugLoc();
9260   MachineFunction *MF = MI.getParent()->getParent();
9261   MachineRegisterInfo &MRI = MF->getRegInfo();
9262   MachineInstrBuilder MIB(*MF, MI);
9263 
9264   // If the new dst/src is unused mark it as dead.
9265   if (!Node->hasAnyUseOfValue(0)) {
9266     MI.getOperand(0).setIsDead(true);
9267   }
9268   if (!Node->hasAnyUseOfValue(1)) {
9269     MI.getOperand(1).setIsDead(true);
9270   }
9271 
9272   // The MEMCPY both defines and kills the scratch registers.
9273   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9274     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9275                                                          : &ARM::GPRRegClass);
9276     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9277   }
9278 }
9279 
9280 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9281                                                       SDNode *Node) const {
9282   if (MI.getOpcode() == ARM::MEMCPY) {
9283     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9284     return;
9285   }
9286 
9287   const MCInstrDesc *MCID = &MI.getDesc();
9288   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9289   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9290   // operand is still set to noreg. If needed, set the optional operand's
9291   // register to CPSR, and remove the redundant implicit def.
9292   //
9293   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9294 
9295   // Rename pseudo opcodes.
9296   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9297   unsigned ccOutIdx;
9298   if (NewOpc) {
9299     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9300     MCID = &TII->get(NewOpc);
9301 
9302     assert(MCID->getNumOperands() ==
9303            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9304         && "converted opcode should be the same except for cc_out"
9305            " (and, on Thumb1, pred)");
9306 
9307     MI.setDesc(*MCID);
9308 
9309     // Add the optional cc_out operand
9310     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9311 
9312     // On Thumb1, move all input operands to the end, then add the predicate
9313     if (Subtarget->isThumb1Only()) {
9314       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9315         MI.addOperand(MI.getOperand(1));
9316         MI.RemoveOperand(1);
9317       }
9318 
9319       // Restore the ties
9320       for (unsigned i = MI.getNumOperands(); i--;) {
9321         const MachineOperand& op = MI.getOperand(i);
9322         if (op.isReg() && op.isUse()) {
9323           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9324           if (DefIdx != -1)
9325             MI.tieOperands(DefIdx, i);
9326         }
9327       }
9328 
9329       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9330       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9331       ccOutIdx = 1;
9332     } else
9333       ccOutIdx = MCID->getNumOperands() - 1;
9334   } else
9335     ccOutIdx = MCID->getNumOperands() - 1;
9336 
9337   // Any ARM instruction that sets the 's' bit should specify an optional
9338   // "cc_out" operand in the last operand position.
9339   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9340     assert(!NewOpc && "Optional cc_out operand required");
9341     return;
9342   }
9343   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9344   // since we already have an optional CPSR def.
9345   bool definesCPSR = false;
9346   bool deadCPSR = false;
9347   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9348        ++i) {
9349     const MachineOperand &MO = MI.getOperand(i);
9350     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9351       definesCPSR = true;
9352       if (MO.isDead())
9353         deadCPSR = true;
9354       MI.RemoveOperand(i);
9355       break;
9356     }
9357   }
9358   if (!definesCPSR) {
9359     assert(!NewOpc && "Optional cc_out operand required");
9360     return;
9361   }
9362   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9363   if (deadCPSR) {
9364     assert(!MI.getOperand(ccOutIdx).getReg() &&
9365            "expect uninitialized optional cc_out operand");
9366     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9367     if (!Subtarget->isThumb1Only())
9368       return;
9369   }
9370 
9371   // If this instruction was defined with an optional CPSR def and its dag node
9372   // had a live implicit CPSR def, then activate the optional CPSR def.
9373   MachineOperand &MO = MI.getOperand(ccOutIdx);
9374   MO.setReg(ARM::CPSR);
9375   MO.setIsDef(true);
9376 }
9377 
9378 //===----------------------------------------------------------------------===//
9379 //                           ARM Optimization Hooks
9380 //===----------------------------------------------------------------------===//
9381 
9382 // Helper function that checks if N is a null or all ones constant.
9383 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9384   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9385 }
9386 
9387 // Return true if N is conditionally 0 or all ones.
9388 // Detects these expressions where cc is an i1 value:
9389 //
9390 //   (select cc 0, y)   [AllOnes=0]
9391 //   (select cc y, 0)   [AllOnes=0]
9392 //   (zext cc)          [AllOnes=0]
9393 //   (sext cc)          [AllOnes=0/1]
9394 //   (select cc -1, y)  [AllOnes=1]
9395 //   (select cc y, -1)  [AllOnes=1]
9396 //
9397 // Invert is set when N is the null/all ones constant when CC is false.
9398 // OtherOp is set to the alternative value of N.
9399 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9400                                        SDValue &CC, bool &Invert,
9401                                        SDValue &OtherOp,
9402                                        SelectionDAG &DAG) {
9403   switch (N->getOpcode()) {
9404   default: return false;
9405   case ISD::SELECT: {
9406     CC = N->getOperand(0);
9407     SDValue N1 = N->getOperand(1);
9408     SDValue N2 = N->getOperand(2);
9409     if (isZeroOrAllOnes(N1, AllOnes)) {
9410       Invert = false;
9411       OtherOp = N2;
9412       return true;
9413     }
9414     if (isZeroOrAllOnes(N2, AllOnes)) {
9415       Invert = true;
9416       OtherOp = N1;
9417       return true;
9418     }
9419     return false;
9420   }
9421   case ISD::ZERO_EXTEND:
9422     // (zext cc) can never be the all ones value.
9423     if (AllOnes)
9424       return false;
9425     LLVM_FALLTHROUGH;
9426   case ISD::SIGN_EXTEND: {
9427     SDLoc dl(N);
9428     EVT VT = N->getValueType(0);
9429     CC = N->getOperand(0);
9430     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9431       return false;
9432     Invert = !AllOnes;
9433     if (AllOnes)
9434       // When looking for an AllOnes constant, N is an sext, and the 'other'
9435       // value is 0.
9436       OtherOp = DAG.getConstant(0, dl, VT);
9437     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9438       // When looking for a 0 constant, N can be zext or sext.
9439       OtherOp = DAG.getConstant(1, dl, VT);
9440     else
9441       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9442                                 VT);
9443     return true;
9444   }
9445   }
9446 }
9447 
9448 // Combine a constant select operand into its use:
9449 //
9450 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9451 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9452 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9453 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9454 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9455 //
9456 // The transform is rejected if the select doesn't have a constant operand that
9457 // is null, or all ones when AllOnes is set.
9458 //
9459 // Also recognize sext/zext from i1:
9460 //
9461 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9462 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9463 //
9464 // These transformations eventually create predicated instructions.
9465 //
9466 // @param N       The node to transform.
9467 // @param Slct    The N operand that is a select.
9468 // @param OtherOp The other N operand (x above).
9469 // @param DCI     Context.
9470 // @param AllOnes Require the select constant to be all ones instead of null.
9471 // @returns The new node, or SDValue() on failure.
9472 static
9473 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9474                             TargetLowering::DAGCombinerInfo &DCI,
9475                             bool AllOnes = false) {
9476   SelectionDAG &DAG = DCI.DAG;
9477   EVT VT = N->getValueType(0);
9478   SDValue NonConstantVal;
9479   SDValue CCOp;
9480   bool SwapSelectOps;
9481   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9482                                   NonConstantVal, DAG))
9483     return SDValue();
9484 
9485   // Slct is now know to be the desired identity constant when CC is true.
9486   SDValue TrueVal = OtherOp;
9487   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9488                                  OtherOp, NonConstantVal);
9489   // Unless SwapSelectOps says CC should be false.
9490   if (SwapSelectOps)
9491     std::swap(TrueVal, FalseVal);
9492 
9493   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9494                      CCOp, TrueVal, FalseVal);
9495 }
9496 
9497 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9498 static
9499 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9500                                        TargetLowering::DAGCombinerInfo &DCI) {
9501   SDValue N0 = N->getOperand(0);
9502   SDValue N1 = N->getOperand(1);
9503   if (N0.getNode()->hasOneUse())
9504     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9505       return Result;
9506   if (N1.getNode()->hasOneUse())
9507     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9508       return Result;
9509   return SDValue();
9510 }
9511 
9512 static bool IsVUZPShuffleNode(SDNode *N) {
9513   // VUZP shuffle node.
9514   if (N->getOpcode() == ARMISD::VUZP)
9515     return true;
9516 
9517   // "VUZP" on i32 is an alias for VTRN.
9518   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9519     return true;
9520 
9521   return false;
9522 }
9523 
9524 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9525                                  TargetLowering::DAGCombinerInfo &DCI,
9526                                  const ARMSubtarget *Subtarget) {
9527   // Look for ADD(VUZP.0, VUZP.1).
9528   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9529       N0 == N1)
9530    return SDValue();
9531 
9532   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9533   if (!N->getValueType(0).is64BitVector())
9534     return SDValue();
9535 
9536   // Generate vpadd.
9537   SelectionDAG &DAG = DCI.DAG;
9538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9539   SDLoc dl(N);
9540   SDNode *Unzip = N0.getNode();
9541   EVT VT = N->getValueType(0);
9542 
9543   SmallVector<SDValue, 8> Ops;
9544   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9545                                 TLI.getPointerTy(DAG.getDataLayout())));
9546   Ops.push_back(Unzip->getOperand(0));
9547   Ops.push_back(Unzip->getOperand(1));
9548 
9549   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9550 }
9551 
9552 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9553                                       TargetLowering::DAGCombinerInfo &DCI,
9554                                       const ARMSubtarget *Subtarget) {
9555   // Check for two extended operands.
9556   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9557         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9558       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9559         N1.getOpcode() == ISD::ZERO_EXTEND))
9560     return SDValue();
9561 
9562   SDValue N00 = N0.getOperand(0);
9563   SDValue N10 = N1.getOperand(0);
9564 
9565   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9566   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9567       N00 == N10)
9568     return SDValue();
9569 
9570   // We only recognize Q register paddl here; this can't be reached until
9571   // after type legalization.
9572   if (!N00.getValueType().is64BitVector() ||
9573       !N0.getValueType().is128BitVector())
9574     return SDValue();
9575 
9576   // Generate vpaddl.
9577   SelectionDAG &DAG = DCI.DAG;
9578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9579   SDLoc dl(N);
9580   EVT VT = N->getValueType(0);
9581 
9582   SmallVector<SDValue, 8> Ops;
9583   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9584   unsigned Opcode;
9585   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9586     Opcode = Intrinsic::arm_neon_vpaddls;
9587   else
9588     Opcode = Intrinsic::arm_neon_vpaddlu;
9589   Ops.push_back(DAG.getConstant(Opcode, dl,
9590                                 TLI.getPointerTy(DAG.getDataLayout())));
9591   EVT ElemTy = N00.getValueType().getVectorElementType();
9592   unsigned NumElts = VT.getVectorNumElements();
9593   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9594   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9595                                N00.getOperand(0), N00.getOperand(1));
9596   Ops.push_back(Concat);
9597 
9598   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9599 }
9600 
9601 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9602 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9603 // much easier to match.
9604 static SDValue
9605 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9606                                TargetLowering::DAGCombinerInfo &DCI,
9607                                const ARMSubtarget *Subtarget) {
9608   // Only perform optimization if after legalize, and if NEON is available. We
9609   // also expected both operands to be BUILD_VECTORs.
9610   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9611       || N0.getOpcode() != ISD::BUILD_VECTOR
9612       || N1.getOpcode() != ISD::BUILD_VECTOR)
9613     return SDValue();
9614 
9615   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9616   EVT VT = N->getValueType(0);
9617   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9618     return SDValue();
9619 
9620   // Check that the vector operands are of the right form.
9621   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9622   // operands, where N is the size of the formed vector.
9623   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9624   // index such that we have a pair wise add pattern.
9625 
9626   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9627   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9628     return SDValue();
9629   SDValue Vec = N0->getOperand(0)->getOperand(0);
9630   SDNode *V = Vec.getNode();
9631   unsigned nextIndex = 0;
9632 
9633   // For each operands to the ADD which are BUILD_VECTORs,
9634   // check to see if each of their operands are an EXTRACT_VECTOR with
9635   // the same vector and appropriate index.
9636   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9637     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9638         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9639 
9640       SDValue ExtVec0 = N0->getOperand(i);
9641       SDValue ExtVec1 = N1->getOperand(i);
9642 
9643       // First operand is the vector, verify its the same.
9644       if (V != ExtVec0->getOperand(0).getNode() ||
9645           V != ExtVec1->getOperand(0).getNode())
9646         return SDValue();
9647 
9648       // Second is the constant, verify its correct.
9649       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9650       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9651 
9652       // For the constant, we want to see all the even or all the odd.
9653       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9654           || C1->getZExtValue() != nextIndex+1)
9655         return SDValue();
9656 
9657       // Increment index.
9658       nextIndex+=2;
9659     } else
9660       return SDValue();
9661   }
9662 
9663   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9664   // we're using the entire input vector, otherwise there's a size/legality
9665   // mismatch somewhere.
9666   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9667       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9668     return SDValue();
9669 
9670   // Create VPADDL node.
9671   SelectionDAG &DAG = DCI.DAG;
9672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9673 
9674   SDLoc dl(N);
9675 
9676   // Build operand list.
9677   SmallVector<SDValue, 8> Ops;
9678   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9679                                 TLI.getPointerTy(DAG.getDataLayout())));
9680 
9681   // Input is the vector.
9682   Ops.push_back(Vec);
9683 
9684   // Get widened type and narrowed type.
9685   MVT widenType;
9686   unsigned numElem = VT.getVectorNumElements();
9687 
9688   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9689   switch (inputLaneType.getSimpleVT().SimpleTy) {
9690     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9691     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9692     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9693     default:
9694       llvm_unreachable("Invalid vector element type for padd optimization.");
9695   }
9696 
9697   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9698   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9699   return DAG.getNode(ExtOp, dl, VT, tmp);
9700 }
9701 
9702 static SDValue findMUL_LOHI(SDValue V) {
9703   if (V->getOpcode() == ISD::UMUL_LOHI ||
9704       V->getOpcode() == ISD::SMUL_LOHI)
9705     return V;
9706   return SDValue();
9707 }
9708 
9709 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9710                                         TargetLowering::DAGCombinerInfo &DCI,
9711                                         const ARMSubtarget *Subtarget) {
9712   if (Subtarget->isThumb()) {
9713     if (!Subtarget->hasDSP())
9714       return SDValue();
9715   } else if (!Subtarget->hasV5TEOps())
9716     return SDValue();
9717 
9718   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9719   // accumulates the product into a 64-bit value. The 16-bit values will
9720   // be sign extended somehow or SRA'd into 32-bit values
9721   // (addc (adde (mul 16bit, 16bit), lo), hi)
9722   SDValue Mul = AddcNode->getOperand(0);
9723   SDValue Lo = AddcNode->getOperand(1);
9724   if (Mul.getOpcode() != ISD::MUL) {
9725     Lo = AddcNode->getOperand(0);
9726     Mul = AddcNode->getOperand(1);
9727     if (Mul.getOpcode() != ISD::MUL)
9728       return SDValue();
9729   }
9730 
9731   SDValue SRA = AddeNode->getOperand(0);
9732   SDValue Hi = AddeNode->getOperand(1);
9733   if (SRA.getOpcode() != ISD::SRA) {
9734     SRA = AddeNode->getOperand(1);
9735     Hi = AddeNode->getOperand(0);
9736     if (SRA.getOpcode() != ISD::SRA)
9737       return SDValue();
9738   }
9739   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9740     if (Const->getZExtValue() != 31)
9741       return SDValue();
9742   } else
9743     return SDValue();
9744 
9745   if (SRA.getOperand(0) != Mul)
9746     return SDValue();
9747 
9748   SelectionDAG &DAG = DCI.DAG;
9749   SDLoc dl(AddcNode);
9750   unsigned Opcode = 0;
9751   SDValue Op0;
9752   SDValue Op1;
9753 
9754   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9755     Opcode = ARMISD::SMLALBB;
9756     Op0 = Mul.getOperand(0);
9757     Op1 = Mul.getOperand(1);
9758   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9759     Opcode = ARMISD::SMLALBT;
9760     Op0 = Mul.getOperand(0);
9761     Op1 = Mul.getOperand(1).getOperand(0);
9762   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9763     Opcode = ARMISD::SMLALTB;
9764     Op0 = Mul.getOperand(0).getOperand(0);
9765     Op1 = Mul.getOperand(1);
9766   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9767     Opcode = ARMISD::SMLALTT;
9768     Op0 = Mul->getOperand(0).getOperand(0);
9769     Op1 = Mul->getOperand(1).getOperand(0);
9770   }
9771 
9772   if (!Op0 || !Op1)
9773     return SDValue();
9774 
9775   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9776                               Op0, Op1, Lo, Hi);
9777   // Replace the ADDs' nodes uses by the MLA node's values.
9778   SDValue HiMLALResult(SMLAL.getNode(), 1);
9779   SDValue LoMLALResult(SMLAL.getNode(), 0);
9780 
9781   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9782   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9783 
9784   // Return original node to notify the driver to stop replacing.
9785   SDValue resNode(AddcNode, 0);
9786   return resNode;
9787 }
9788 
9789 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9790                                      TargetLowering::DAGCombinerInfo &DCI,
9791                                      const ARMSubtarget *Subtarget) {
9792   // Look for multiply add opportunities.
9793   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9794   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9795   // a glue link from the first add to the second add.
9796   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9797   // a S/UMLAL instruction.
9798   //                  UMUL_LOHI
9799   //                 / :lo    \ :hi
9800   //                V          \          [no multiline comment]
9801   //    loAdd ->  ADDC         |
9802   //                 \ :carry /
9803   //                  V      V
9804   //                    ADDE   <- hiAdd
9805   //
9806   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9807 
9808   assert(AddeNode->getNumOperands() == 3 &&
9809          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9810          "ADDE node has the wrong inputs");
9811 
9812   // Check that we are chained to the right ADDC node.
9813   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9814   if (AddcNode->getOpcode() != ARMISD::ADDC)
9815     return SDValue();
9816 
9817   SDValue AddcOp0 = AddcNode->getOperand(0);
9818   SDValue AddcOp1 = AddcNode->getOperand(1);
9819 
9820   // Check if the two operands are from the same mul_lohi node.
9821   if (AddcOp0.getNode() == AddcOp1.getNode())
9822     return SDValue();
9823 
9824   assert(AddcNode->getNumValues() == 2 &&
9825          AddcNode->getValueType(0) == MVT::i32 &&
9826          "Expect ADDC with two result values. First: i32");
9827 
9828   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9829   // maybe a SMLAL which multiplies two 16-bit values.
9830   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9831       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9832       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9833       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9834     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9835 
9836   // Check for the triangle shape.
9837   SDValue AddeOp0 = AddeNode->getOperand(0);
9838   SDValue AddeOp1 = AddeNode->getOperand(1);
9839 
9840   // Make sure that the ADDE operands are not coming from the same node.
9841   if (AddeOp0.getNode() == AddeOp1.getNode())
9842     return SDValue();
9843 
9844   // Find the MUL_LOHI node walking up ADDE's operands.
9845   bool IsLeftOperandMUL = false;
9846   SDValue MULOp = findMUL_LOHI(AddeOp0);
9847   if (MULOp == SDValue())
9848    MULOp = findMUL_LOHI(AddeOp1);
9849   else
9850     IsLeftOperandMUL = true;
9851   if (MULOp == SDValue())
9852     return SDValue();
9853 
9854   // Figure out the right opcode.
9855   unsigned Opc = MULOp->getOpcode();
9856   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9857 
9858   // Figure out the high and low input values to the MLAL node.
9859   SDValue* HiAdd = nullptr;
9860   SDValue* LoMul = nullptr;
9861   SDValue* LowAdd = nullptr;
9862 
9863   // Ensure that ADDE is from high result of ISD::xMUL_LOHI.
9864   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9865     return SDValue();
9866 
9867   if (IsLeftOperandMUL)
9868     HiAdd = &AddeOp1;
9869   else
9870     HiAdd = &AddeOp0;
9871 
9872 
9873   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9874   // whose low result is fed to the ADDC we are checking.
9875 
9876   if (AddcOp0 == MULOp.getValue(0)) {
9877     LoMul = &AddcOp0;
9878     LowAdd = &AddcOp1;
9879   }
9880   if (AddcOp1 == MULOp.getValue(0)) {
9881     LoMul = &AddcOp1;
9882     LowAdd = &AddcOp0;
9883   }
9884 
9885   if (!LoMul)
9886     return SDValue();
9887 
9888   // If HiAdd is the same node as ADDC or is a predecessor of ADDC the
9889   // replacement below will create a cycle.
9890   if (AddcNode == HiAdd->getNode() ||
9891       AddcNode->isPredecessorOf(HiAdd->getNode()))
9892     return SDValue();
9893 
9894   // Create the merged node.
9895   SelectionDAG &DAG = DCI.DAG;
9896 
9897   // Build operand list.
9898   SmallVector<SDValue, 8> Ops;
9899   Ops.push_back(LoMul->getOperand(0));
9900   Ops.push_back(LoMul->getOperand(1));
9901   Ops.push_back(*LowAdd);
9902   Ops.push_back(*HiAdd);
9903 
9904   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9905                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9906 
9907   // Replace the ADDs' nodes uses by the MLA node's values.
9908   SDValue HiMLALResult(MLALNode.getNode(), 1);
9909   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9910 
9911   SDValue LoMLALResult(MLALNode.getNode(), 0);
9912   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9913 
9914   // Return original node to notify the driver to stop replacing.
9915   return SDValue(AddeNode, 0);
9916 }
9917 
9918 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9919                                       TargetLowering::DAGCombinerInfo &DCI,
9920                                       const ARMSubtarget *Subtarget) {
9921   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9922   // While trying to combine for the other MLAL nodes, first search for the
9923   // chance to use UMAAL. Check if Addc uses a node which has already
9924   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9925   // as the addend, and it's handled in PerformUMLALCombine.
9926 
9927   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9928     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9929 
9930   // Check that we have a glued ADDC node.
9931   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9932   if (AddcNode->getOpcode() != ARMISD::ADDC)
9933     return SDValue();
9934 
9935   // Find the converted UMAAL or quit if it doesn't exist.
9936   SDNode *UmlalNode = nullptr;
9937   SDValue AddHi;
9938   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9939     UmlalNode = AddcNode->getOperand(0).getNode();
9940     AddHi = AddcNode->getOperand(1);
9941   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9942     UmlalNode = AddcNode->getOperand(1).getNode();
9943     AddHi = AddcNode->getOperand(0);
9944   } else {
9945     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9946   }
9947 
9948   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9949   // the ADDC as well as Zero.
9950   if (!isNullConstant(UmlalNode->getOperand(3)))
9951     return SDValue();
9952 
9953   if ((isNullConstant(AddeNode->getOperand(0)) &&
9954        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9955       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9956        isNullConstant(AddeNode->getOperand(1)))) {
9957     SelectionDAG &DAG = DCI.DAG;
9958     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9959                       UmlalNode->getOperand(2), AddHi };
9960     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9961                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9962 
9963     // Replace the ADDs' nodes uses by the UMAAL node's values.
9964     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9965     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9966 
9967     // Return original node to notify the driver to stop replacing.
9968     return SDValue(AddeNode, 0);
9969   }
9970   return SDValue();
9971 }
9972 
9973 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9974                                    const ARMSubtarget *Subtarget) {
9975   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9976     return SDValue();
9977 
9978   // Check that we have a pair of ADDC and ADDE as operands.
9979   // Both addends of the ADDE must be zero.
9980   SDNode* AddcNode = N->getOperand(2).getNode();
9981   SDNode* AddeNode = N->getOperand(3).getNode();
9982   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9983       (AddeNode->getOpcode() == ARMISD::ADDE) &&
9984       isNullConstant(AddeNode->getOperand(0)) &&
9985       isNullConstant(AddeNode->getOperand(1)) &&
9986       (AddeNode->getOperand(2).getNode() == AddcNode))
9987     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9988                        DAG.getVTList(MVT::i32, MVT::i32),
9989                        {N->getOperand(0), N->getOperand(1),
9990                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
9991   else
9992     return SDValue();
9993 }
9994 
9995 static SDValue PerformAddcSubcCombine(SDNode *N,
9996                                       TargetLowering::DAGCombinerInfo &DCI,
9997                                       const ARMSubtarget *Subtarget) {
9998   SelectionDAG &DAG(DCI.DAG);
9999 
10000   if (N->getOpcode() == ARMISD::ADDC) {
10001     // (ADDC (ADDE 0, 0, C), -1) -> C
10002     SDValue LHS = N->getOperand(0);
10003     SDValue RHS = N->getOperand(1);
10004     if (LHS->getOpcode() == ARMISD::ADDE &&
10005         isNullConstant(LHS->getOperand(0)) &&
10006         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10007       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10008     }
10009   }
10010 
10011   if (Subtarget->isThumb1Only()) {
10012     SDValue RHS = N->getOperand(1);
10013     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10014       int32_t imm = C->getSExtValue();
10015       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10016         SDLoc DL(N);
10017         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10018         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10019                                                            : ARMISD::ADDC;
10020         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10021       }
10022     }
10023   }
10024   return SDValue();
10025 }
10026 
10027 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
10028                                       const ARMSubtarget *Subtarget) {
10029   if (Subtarget->isThumb1Only()) {
10030     SDValue RHS = N->getOperand(1);
10031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10032       int64_t imm = C->getSExtValue();
10033       if (imm < 0) {
10034         SDLoc DL(N);
10035 
10036         // The with-carry-in form matches bitwise not instead of the negation.
10037         // Effectively, the inverse interpretation of the carry flag already
10038         // accounts for part of the negation.
10039         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10040 
10041         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10042                                                            : ARMISD::ADDE;
10043         return DAG.getNode(Opcode, DL, N->getVTList(),
10044                            N->getOperand(0), RHS, N->getOperand(2));
10045       }
10046     }
10047   }
10048   return SDValue();
10049 }
10050 
10051 /// PerformADDECombine - Target-specific dag combine transform from
10052 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10053 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10054 static SDValue PerformADDECombine(SDNode *N,
10055                                   TargetLowering::DAGCombinerInfo &DCI,
10056                                   const ARMSubtarget *Subtarget) {
10057   // Only ARM and Thumb2 support UMLAL/SMLAL.
10058   if (Subtarget->isThumb1Only())
10059     return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
10060 
10061   // Only perform the checks after legalize when the pattern is available.
10062   if (DCI.isBeforeLegalize()) return SDValue();
10063 
10064   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10065 }
10066 
10067 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10068 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10069 /// called with the default operands, and if that fails, with commuted
10070 /// operands.
10071 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10072                                           TargetLowering::DAGCombinerInfo &DCI,
10073                                           const ARMSubtarget *Subtarget){
10074   // Attempt to create vpadd for this add.
10075   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10076     return Result;
10077 
10078   // Attempt to create vpaddl for this add.
10079   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10080     return Result;
10081   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10082                                                       Subtarget))
10083     return Result;
10084 
10085   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10086   if (N0.getNode()->hasOneUse())
10087     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10088       return Result;
10089   return SDValue();
10090 }
10091 
10092 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10093 ///
10094 static SDValue PerformADDCombine(SDNode *N,
10095                                  TargetLowering::DAGCombinerInfo &DCI,
10096                                  const ARMSubtarget *Subtarget) {
10097   SDValue N0 = N->getOperand(0);
10098   SDValue N1 = N->getOperand(1);
10099 
10100   // First try with the default operand order.
10101   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10102     return Result;
10103 
10104   // If that didn't work, try again with the operands commuted.
10105   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10106 }
10107 
10108 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10109 ///
10110 static SDValue PerformSUBCombine(SDNode *N,
10111                                  TargetLowering::DAGCombinerInfo &DCI) {
10112   SDValue N0 = N->getOperand(0);
10113   SDValue N1 = N->getOperand(1);
10114 
10115   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10116   if (N1.getNode()->hasOneUse())
10117     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10118       return Result;
10119 
10120   return SDValue();
10121 }
10122 
10123 /// PerformVMULCombine
10124 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10125 /// special multiplier accumulator forwarding.
10126 ///   vmul d3, d0, d2
10127 ///   vmla d3, d1, d2
10128 /// is faster than
10129 ///   vadd d3, d0, d1
10130 ///   vmul d3, d3, d2
10131 //  However, for (A + B) * (A + B),
10132 //    vadd d2, d0, d1
10133 //    vmul d3, d0, d2
10134 //    vmla d3, d1, d2
10135 //  is slower than
10136 //    vadd d2, d0, d1
10137 //    vmul d3, d2, d2
10138 static SDValue PerformVMULCombine(SDNode *N,
10139                                   TargetLowering::DAGCombinerInfo &DCI,
10140                                   const ARMSubtarget *Subtarget) {
10141   if (!Subtarget->hasVMLxForwarding())
10142     return SDValue();
10143 
10144   SelectionDAG &DAG = DCI.DAG;
10145   SDValue N0 = N->getOperand(0);
10146   SDValue N1 = N->getOperand(1);
10147   unsigned Opcode = N0.getOpcode();
10148   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10149       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10150     Opcode = N1.getOpcode();
10151     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10152         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10153       return SDValue();
10154     std::swap(N0, N1);
10155   }
10156 
10157   if (N0 == N1)
10158     return SDValue();
10159 
10160   EVT VT = N->getValueType(0);
10161   SDLoc DL(N);
10162   SDValue N00 = N0->getOperand(0);
10163   SDValue N01 = N0->getOperand(1);
10164   return DAG.getNode(Opcode, DL, VT,
10165                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10166                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10167 }
10168 
10169 static SDValue PerformMULCombine(SDNode *N,
10170                                  TargetLowering::DAGCombinerInfo &DCI,
10171                                  const ARMSubtarget *Subtarget) {
10172   SelectionDAG &DAG = DCI.DAG;
10173 
10174   if (Subtarget->isThumb1Only())
10175     return SDValue();
10176 
10177   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10178     return SDValue();
10179 
10180   EVT VT = N->getValueType(0);
10181   if (VT.is64BitVector() || VT.is128BitVector())
10182     return PerformVMULCombine(N, DCI, Subtarget);
10183   if (VT != MVT::i32)
10184     return SDValue();
10185 
10186   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10187   if (!C)
10188     return SDValue();
10189 
10190   int64_t MulAmt = C->getSExtValue();
10191   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10192 
10193   ShiftAmt = ShiftAmt & (32 - 1);
10194   SDValue V = N->getOperand(0);
10195   SDLoc DL(N);
10196 
10197   SDValue Res;
10198   MulAmt >>= ShiftAmt;
10199 
10200   if (MulAmt >= 0) {
10201     if (isPowerOf2_32(MulAmt - 1)) {
10202       // (mul x, 2^N + 1) => (add (shl x, N), x)
10203       Res = DAG.getNode(ISD::ADD, DL, VT,
10204                         V,
10205                         DAG.getNode(ISD::SHL, DL, VT,
10206                                     V,
10207                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10208                                                     MVT::i32)));
10209     } else if (isPowerOf2_32(MulAmt + 1)) {
10210       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10211       Res = DAG.getNode(ISD::SUB, DL, VT,
10212                         DAG.getNode(ISD::SHL, DL, VT,
10213                                     V,
10214                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10215                                                     MVT::i32)),
10216                         V);
10217     } else
10218       return SDValue();
10219   } else {
10220     uint64_t MulAmtAbs = -MulAmt;
10221     if (isPowerOf2_32(MulAmtAbs + 1)) {
10222       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10223       Res = DAG.getNode(ISD::SUB, DL, VT,
10224                         V,
10225                         DAG.getNode(ISD::SHL, DL, VT,
10226                                     V,
10227                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10228                                                     MVT::i32)));
10229     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10230       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10231       Res = DAG.getNode(ISD::ADD, DL, VT,
10232                         V,
10233                         DAG.getNode(ISD::SHL, DL, VT,
10234                                     V,
10235                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10236                                                     MVT::i32)));
10237       Res = DAG.getNode(ISD::SUB, DL, VT,
10238                         DAG.getConstant(0, DL, MVT::i32), Res);
10239     } else
10240       return SDValue();
10241   }
10242 
10243   if (ShiftAmt != 0)
10244     Res = DAG.getNode(ISD::SHL, DL, VT,
10245                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10246 
10247   // Do not add new nodes to DAG combiner worklist.
10248   DCI.CombineTo(N, Res, false);
10249   return SDValue();
10250 }
10251 
10252 static SDValue PerformANDCombine(SDNode *N,
10253                                  TargetLowering::DAGCombinerInfo &DCI,
10254                                  const ARMSubtarget *Subtarget) {
10255   // Attempt to use immediate-form VBIC
10256   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10257   SDLoc dl(N);
10258   EVT VT = N->getValueType(0);
10259   SelectionDAG &DAG = DCI.DAG;
10260 
10261   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10262     return SDValue();
10263 
10264   APInt SplatBits, SplatUndef;
10265   unsigned SplatBitSize;
10266   bool HasAnyUndefs;
10267   if (BVN &&
10268       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10269     if (SplatBitSize <= 64) {
10270       EVT VbicVT;
10271       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10272                                       SplatUndef.getZExtValue(), SplatBitSize,
10273                                       DAG, dl, VbicVT, VT.is128BitVector(),
10274                                       OtherModImm);
10275       if (Val.getNode()) {
10276         SDValue Input =
10277           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10278         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10279         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10280       }
10281     }
10282   }
10283 
10284   if (!Subtarget->isThumb1Only()) {
10285     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10286     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10287       return Result;
10288   }
10289 
10290   return SDValue();
10291 }
10292 
10293 // Try combining OR nodes to SMULWB, SMULWT.
10294 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10295                                          TargetLowering::DAGCombinerInfo &DCI,
10296                                          const ARMSubtarget *Subtarget) {
10297   if (!Subtarget->hasV6Ops() ||
10298       (Subtarget->isThumb() &&
10299        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10300     return SDValue();
10301 
10302   SDValue SRL = OR->getOperand(0);
10303   SDValue SHL = OR->getOperand(1);
10304 
10305   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10306     SRL = OR->getOperand(1);
10307     SHL = OR->getOperand(0);
10308   }
10309   if (!isSRL16(SRL) || !isSHL16(SHL))
10310     return SDValue();
10311 
10312   // The first operands to the shifts need to be the two results from the
10313   // same smul_lohi node.
10314   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10315        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10316     return SDValue();
10317 
10318   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10319   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10320       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10321     return SDValue();
10322 
10323   // Now we have:
10324   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10325   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10326   // For SMUWB the 16-bit value will signed extended somehow.
10327   // For SMULWT only the SRA is required.
10328   // Check both sides of SMUL_LOHI
10329   SDValue OpS16 = SMULLOHI->getOperand(0);
10330   SDValue OpS32 = SMULLOHI->getOperand(1);
10331 
10332   SelectionDAG &DAG = DCI.DAG;
10333   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10334     OpS16 = OpS32;
10335     OpS32 = SMULLOHI->getOperand(0);
10336   }
10337 
10338   SDLoc dl(OR);
10339   unsigned Opcode = 0;
10340   if (isS16(OpS16, DAG))
10341     Opcode = ARMISD::SMULWB;
10342   else if (isSRA16(OpS16)) {
10343     Opcode = ARMISD::SMULWT;
10344     OpS16 = OpS16->getOperand(0);
10345   }
10346   else
10347     return SDValue();
10348 
10349   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10350   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10351   return SDValue(OR, 0);
10352 }
10353 
10354 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10355 static SDValue PerformORCombine(SDNode *N,
10356                                 TargetLowering::DAGCombinerInfo &DCI,
10357                                 const ARMSubtarget *Subtarget) {
10358   // Attempt to use immediate-form VORR
10359   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10360   SDLoc dl(N);
10361   EVT VT = N->getValueType(0);
10362   SelectionDAG &DAG = DCI.DAG;
10363 
10364   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10365     return SDValue();
10366 
10367   APInt SplatBits, SplatUndef;
10368   unsigned SplatBitSize;
10369   bool HasAnyUndefs;
10370   if (BVN && Subtarget->hasNEON() &&
10371       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10372     if (SplatBitSize <= 64) {
10373       EVT VorrVT;
10374       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10375                                       SplatUndef.getZExtValue(), SplatBitSize,
10376                                       DAG, dl, VorrVT, VT.is128BitVector(),
10377                                       OtherModImm);
10378       if (Val.getNode()) {
10379         SDValue Input =
10380           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10381         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10382         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10383       }
10384     }
10385   }
10386 
10387   if (!Subtarget->isThumb1Only()) {
10388     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10389     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10390       return Result;
10391     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10392       return Result;
10393   }
10394 
10395   // The code below optimizes (or (and X, Y), Z).
10396   // The AND operand needs to have a single user to make these optimizations
10397   // profitable.
10398   SDValue N0 = N->getOperand(0);
10399   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10400     return SDValue();
10401   SDValue N1 = N->getOperand(1);
10402 
10403   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10404   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10405       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10406     APInt SplatUndef;
10407     unsigned SplatBitSize;
10408     bool HasAnyUndefs;
10409 
10410     APInt SplatBits0, SplatBits1;
10411     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10412     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10413     // Ensure that the second operand of both ands are constants
10414     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10415                                       HasAnyUndefs) && !HasAnyUndefs) {
10416         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10417                                           HasAnyUndefs) && !HasAnyUndefs) {
10418             // Ensure that the bit width of the constants are the same and that
10419             // the splat arguments are logical inverses as per the pattern we
10420             // are trying to simplify.
10421             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10422                 SplatBits0 == ~SplatBits1) {
10423                 // Canonicalize the vector type to make instruction selection
10424                 // simpler.
10425                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10426                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10427                                              N0->getOperand(1),
10428                                              N0->getOperand(0),
10429                                              N1->getOperand(0));
10430                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10431             }
10432         }
10433     }
10434   }
10435 
10436   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10437   // reasonable.
10438 
10439   // BFI is only available on V6T2+
10440   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10441     return SDValue();
10442 
10443   SDLoc DL(N);
10444   // 1) or (and A, mask), val => ARMbfi A, val, mask
10445   //      iff (val & mask) == val
10446   //
10447   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10448   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10449   //          && mask == ~mask2
10450   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10451   //          && ~mask == mask2
10452   //  (i.e., copy a bitfield value into another bitfield of the same width)
10453 
10454   if (VT != MVT::i32)
10455     return SDValue();
10456 
10457   SDValue N00 = N0.getOperand(0);
10458 
10459   // The value and the mask need to be constants so we can verify this is
10460   // actually a bitfield set. If the mask is 0xffff, we can do better
10461   // via a movt instruction, so don't use BFI in that case.
10462   SDValue MaskOp = N0.getOperand(1);
10463   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10464   if (!MaskC)
10465     return SDValue();
10466   unsigned Mask = MaskC->getZExtValue();
10467   if (Mask == 0xffff)
10468     return SDValue();
10469   SDValue Res;
10470   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10471   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10472   if (N1C) {
10473     unsigned Val = N1C->getZExtValue();
10474     if ((Val & ~Mask) != Val)
10475       return SDValue();
10476 
10477     if (ARM::isBitFieldInvertedMask(Mask)) {
10478       Val >>= countTrailingZeros(~Mask);
10479 
10480       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10481                         DAG.getConstant(Val, DL, MVT::i32),
10482                         DAG.getConstant(Mask, DL, MVT::i32));
10483 
10484       // Do not add new nodes to DAG combiner worklist.
10485       DCI.CombineTo(N, Res, false);
10486       return SDValue();
10487     }
10488   } else if (N1.getOpcode() == ISD::AND) {
10489     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10490     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10491     if (!N11C)
10492       return SDValue();
10493     unsigned Mask2 = N11C->getZExtValue();
10494 
10495     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10496     // as is to match.
10497     if (ARM::isBitFieldInvertedMask(Mask) &&
10498         (Mask == ~Mask2)) {
10499       // The pack halfword instruction works better for masks that fit it,
10500       // so use that when it's available.
10501       if (Subtarget->hasDSP() &&
10502           (Mask == 0xffff || Mask == 0xffff0000))
10503         return SDValue();
10504       // 2a
10505       unsigned amt = countTrailingZeros(Mask2);
10506       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10507                         DAG.getConstant(amt, DL, MVT::i32));
10508       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10509                         DAG.getConstant(Mask, DL, MVT::i32));
10510       // Do not add new nodes to DAG combiner worklist.
10511       DCI.CombineTo(N, Res, false);
10512       return SDValue();
10513     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10514                (~Mask == Mask2)) {
10515       // The pack halfword instruction works better for masks that fit it,
10516       // so use that when it's available.
10517       if (Subtarget->hasDSP() &&
10518           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10519         return SDValue();
10520       // 2b
10521       unsigned lsb = countTrailingZeros(Mask);
10522       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10523                         DAG.getConstant(lsb, DL, MVT::i32));
10524       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10525                         DAG.getConstant(Mask2, DL, MVT::i32));
10526       // Do not add new nodes to DAG combiner worklist.
10527       DCI.CombineTo(N, Res, false);
10528       return SDValue();
10529     }
10530   }
10531 
10532   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10533       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10534       ARM::isBitFieldInvertedMask(~Mask)) {
10535     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10536     // where lsb(mask) == #shamt and masked bits of B are known zero.
10537     SDValue ShAmt = N00.getOperand(1);
10538     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10539     unsigned LSB = countTrailingZeros(Mask);
10540     if (ShAmtC != LSB)
10541       return SDValue();
10542 
10543     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10544                       DAG.getConstant(~Mask, DL, MVT::i32));
10545 
10546     // Do not add new nodes to DAG combiner worklist.
10547     DCI.CombineTo(N, Res, false);
10548   }
10549 
10550   return SDValue();
10551 }
10552 
10553 static SDValue PerformXORCombine(SDNode *N,
10554                                  TargetLowering::DAGCombinerInfo &DCI,
10555                                  const ARMSubtarget *Subtarget) {
10556   EVT VT = N->getValueType(0);
10557   SelectionDAG &DAG = DCI.DAG;
10558 
10559   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10560     return SDValue();
10561 
10562   if (!Subtarget->isThumb1Only()) {
10563     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10564     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10565       return Result;
10566   }
10567 
10568   return SDValue();
10569 }
10570 
10571 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10572 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10573 // their position in "to" (Rd).
10574 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10575   assert(N->getOpcode() == ARMISD::BFI);
10576 
10577   SDValue From = N->getOperand(1);
10578   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10579   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10580 
10581   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10582   // #C in the base of the SHR.
10583   if (From->getOpcode() == ISD::SRL &&
10584       isa<ConstantSDNode>(From->getOperand(1))) {
10585     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10586     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10587     FromMask <<= Shift.getLimitedValue(31);
10588     From = From->getOperand(0);
10589   }
10590 
10591   return From;
10592 }
10593 
10594 // If A and B contain one contiguous set of bits, does A | B == A . B?
10595 //
10596 // Neither A nor B must be zero.
10597 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10598   unsigned LastActiveBitInA =  A.countTrailingZeros();
10599   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10600   return LastActiveBitInA - 1 == FirstActiveBitInB;
10601 }
10602 
10603 static SDValue FindBFIToCombineWith(SDNode *N) {
10604   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10605   // if one exists.
10606   APInt ToMask, FromMask;
10607   SDValue From = ParseBFI(N, ToMask, FromMask);
10608   SDValue To = N->getOperand(0);
10609 
10610   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10611   // aren't compatible, but not if they set the same bit in their destination as
10612   // we do (or that of any BFI we're going to combine with).
10613   SDValue V = To;
10614   APInt CombinedToMask = ToMask;
10615   while (V.getOpcode() == ARMISD::BFI) {
10616     APInt NewToMask, NewFromMask;
10617     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10618     if (NewFrom != From) {
10619       // This BFI has a different base. Keep going.
10620       CombinedToMask |= NewToMask;
10621       V = V.getOperand(0);
10622       continue;
10623     }
10624 
10625     // Do the written bits conflict with any we've seen so far?
10626     if ((NewToMask & CombinedToMask).getBoolValue())
10627       // Conflicting bits - bail out because going further is unsafe.
10628       return SDValue();
10629 
10630     // Are the new bits contiguous when combined with the old bits?
10631     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10632         BitsProperlyConcatenate(FromMask, NewFromMask))
10633       return V;
10634     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10635         BitsProperlyConcatenate(NewFromMask, FromMask))
10636       return V;
10637 
10638     // We've seen a write to some bits, so track it.
10639     CombinedToMask |= NewToMask;
10640     // Keep going...
10641     V = V.getOperand(0);
10642   }
10643 
10644   return SDValue();
10645 }
10646 
10647 static SDValue PerformBFICombine(SDNode *N,
10648                                  TargetLowering::DAGCombinerInfo &DCI) {
10649   SDValue N1 = N->getOperand(1);
10650   if (N1.getOpcode() == ISD::AND) {
10651     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10652     // the bits being cleared by the AND are not demanded by the BFI.
10653     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10654     if (!N11C)
10655       return SDValue();
10656     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10657     unsigned LSB = countTrailingZeros(~InvMask);
10658     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10659     assert(Width <
10660                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10661            "undefined behavior");
10662     unsigned Mask = (1u << Width) - 1;
10663     unsigned Mask2 = N11C->getZExtValue();
10664     if ((Mask & (~Mask2)) == 0)
10665       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10666                              N->getOperand(0), N1.getOperand(0),
10667                              N->getOperand(2));
10668   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10669     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10670     // Keep track of any consecutive bits set that all come from the same base
10671     // value. We can combine these together into a single BFI.
10672     SDValue CombineBFI = FindBFIToCombineWith(N);
10673     if (CombineBFI == SDValue())
10674       return SDValue();
10675 
10676     // We've found a BFI.
10677     APInt ToMask1, FromMask1;
10678     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10679 
10680     APInt ToMask2, FromMask2;
10681     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10682     assert(From1 == From2);
10683     (void)From2;
10684 
10685     // First, unlink CombineBFI.
10686     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10687     // Then create a new BFI, combining the two together.
10688     APInt NewFromMask = FromMask1 | FromMask2;
10689     APInt NewToMask = ToMask1 | ToMask2;
10690 
10691     EVT VT = N->getValueType(0);
10692     SDLoc dl(N);
10693 
10694     if (NewFromMask[0] == 0)
10695       From1 = DCI.DAG.getNode(
10696         ISD::SRL, dl, VT, From1,
10697         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10698     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10699                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10700   }
10701   return SDValue();
10702 }
10703 
10704 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10705 /// ARMISD::VMOVRRD.
10706 static SDValue PerformVMOVRRDCombine(SDNode *N,
10707                                      TargetLowering::DAGCombinerInfo &DCI,
10708                                      const ARMSubtarget *Subtarget) {
10709   // vmovrrd(vmovdrr x, y) -> x,y
10710   SDValue InDouble = N->getOperand(0);
10711   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10712     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10713 
10714   // vmovrrd(load f64) -> (load i32), (load i32)
10715   SDNode *InNode = InDouble.getNode();
10716   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10717       InNode->getValueType(0) == MVT::f64 &&
10718       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10719       !cast<LoadSDNode>(InNode)->isVolatile()) {
10720     // TODO: Should this be done for non-FrameIndex operands?
10721     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10722 
10723     SelectionDAG &DAG = DCI.DAG;
10724     SDLoc DL(LD);
10725     SDValue BasePtr = LD->getBasePtr();
10726     SDValue NewLD1 =
10727         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10728                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10729 
10730     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10731                                     DAG.getConstant(4, DL, MVT::i32));
10732     SDValue NewLD2 = DAG.getLoad(
10733         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10734         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10735 
10736     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10737     if (DCI.DAG.getDataLayout().isBigEndian())
10738       std::swap (NewLD1, NewLD2);
10739     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10740     return Result;
10741   }
10742 
10743   return SDValue();
10744 }
10745 
10746 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10747 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10748 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10749   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10750   SDValue Op0 = N->getOperand(0);
10751   SDValue Op1 = N->getOperand(1);
10752   if (Op0.getOpcode() == ISD::BITCAST)
10753     Op0 = Op0.getOperand(0);
10754   if (Op1.getOpcode() == ISD::BITCAST)
10755     Op1 = Op1.getOperand(0);
10756   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10757       Op0.getNode() == Op1.getNode() &&
10758       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10759     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10760                        N->getValueType(0), Op0.getOperand(0));
10761   return SDValue();
10762 }
10763 
10764 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10765 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10766 /// i64 vector to have f64 elements, since the value can then be loaded
10767 /// directly into a VFP register.
10768 static bool hasNormalLoadOperand(SDNode *N) {
10769   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10770   for (unsigned i = 0; i < NumElts; ++i) {
10771     SDNode *Elt = N->getOperand(i).getNode();
10772     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10773       return true;
10774   }
10775   return false;
10776 }
10777 
10778 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10779 /// ISD::BUILD_VECTOR.
10780 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10781                                           TargetLowering::DAGCombinerInfo &DCI,
10782                                           const ARMSubtarget *Subtarget) {
10783   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10784   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10785   // into a pair of GPRs, which is fine when the value is used as a scalar,
10786   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10787   SelectionDAG &DAG = DCI.DAG;
10788   if (N->getNumOperands() == 2)
10789     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10790       return RV;
10791 
10792   // Load i64 elements as f64 values so that type legalization does not split
10793   // them up into i32 values.
10794   EVT VT = N->getValueType(0);
10795   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10796     return SDValue();
10797   SDLoc dl(N);
10798   SmallVector<SDValue, 8> Ops;
10799   unsigned NumElts = VT.getVectorNumElements();
10800   for (unsigned i = 0; i < NumElts; ++i) {
10801     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10802     Ops.push_back(V);
10803     // Make the DAGCombiner fold the bitcast.
10804     DCI.AddToWorklist(V.getNode());
10805   }
10806   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10807   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10808   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10809 }
10810 
10811 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10812 static SDValue
10813 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10814   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10815   // At that time, we may have inserted bitcasts from integer to float.
10816   // If these bitcasts have survived DAGCombine, change the lowering of this
10817   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10818   // force to use floating point types.
10819 
10820   // Make sure we can change the type of the vector.
10821   // This is possible iff:
10822   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10823   //    1.1. Vector is used only once.
10824   //    1.2. Use is a bit convert to an integer type.
10825   // 2. The size of its operands are 32-bits (64-bits are not legal).
10826   EVT VT = N->getValueType(0);
10827   EVT EltVT = VT.getVectorElementType();
10828 
10829   // Check 1.1. and 2.
10830   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10831     return SDValue();
10832 
10833   // By construction, the input type must be float.
10834   assert(EltVT == MVT::f32 && "Unexpected type!");
10835 
10836   // Check 1.2.
10837   SDNode *Use = *N->use_begin();
10838   if (Use->getOpcode() != ISD::BITCAST ||
10839       Use->getValueType(0).isFloatingPoint())
10840     return SDValue();
10841 
10842   // Check profitability.
10843   // Model is, if more than half of the relevant operands are bitcast from
10844   // i32, turn the build_vector into a sequence of insert_vector_elt.
10845   // Relevant operands are everything that is not statically
10846   // (i.e., at compile time) bitcasted.
10847   unsigned NumOfBitCastedElts = 0;
10848   unsigned NumElts = VT.getVectorNumElements();
10849   unsigned NumOfRelevantElts = NumElts;
10850   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10851     SDValue Elt = N->getOperand(Idx);
10852     if (Elt->getOpcode() == ISD::BITCAST) {
10853       // Assume only bit cast to i32 will go away.
10854       if (Elt->getOperand(0).getValueType() == MVT::i32)
10855         ++NumOfBitCastedElts;
10856     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10857       // Constants are statically casted, thus do not count them as
10858       // relevant operands.
10859       --NumOfRelevantElts;
10860   }
10861 
10862   // Check if more than half of the elements require a non-free bitcast.
10863   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10864     return SDValue();
10865 
10866   SelectionDAG &DAG = DCI.DAG;
10867   // Create the new vector type.
10868   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10869   // Check if the type is legal.
10870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10871   if (!TLI.isTypeLegal(VecVT))
10872     return SDValue();
10873 
10874   // Combine:
10875   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10876   // => BITCAST INSERT_VECTOR_ELT
10877   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10878   //                      (BITCAST EN), N.
10879   SDValue Vec = DAG.getUNDEF(VecVT);
10880   SDLoc dl(N);
10881   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10882     SDValue V = N->getOperand(Idx);
10883     if (V.isUndef())
10884       continue;
10885     if (V.getOpcode() == ISD::BITCAST &&
10886         V->getOperand(0).getValueType() == MVT::i32)
10887       // Fold obvious case.
10888       V = V.getOperand(0);
10889     else {
10890       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10891       // Make the DAGCombiner fold the bitcasts.
10892       DCI.AddToWorklist(V.getNode());
10893     }
10894     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10895     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10896   }
10897   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10898   // Make the DAGCombiner fold the bitcasts.
10899   DCI.AddToWorklist(Vec.getNode());
10900   return Vec;
10901 }
10902 
10903 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10904 /// ISD::INSERT_VECTOR_ELT.
10905 static SDValue PerformInsertEltCombine(SDNode *N,
10906                                        TargetLowering::DAGCombinerInfo &DCI) {
10907   // Bitcast an i64 load inserted into a vector to f64.
10908   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10909   EVT VT = N->getValueType(0);
10910   SDNode *Elt = N->getOperand(1).getNode();
10911   if (VT.getVectorElementType() != MVT::i64 ||
10912       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10913     return SDValue();
10914 
10915   SelectionDAG &DAG = DCI.DAG;
10916   SDLoc dl(N);
10917   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10918                                  VT.getVectorNumElements());
10919   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10920   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10921   // Make the DAGCombiner fold the bitcasts.
10922   DCI.AddToWorklist(Vec.getNode());
10923   DCI.AddToWorklist(V.getNode());
10924   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10925                                Vec, V, N->getOperand(2));
10926   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10927 }
10928 
10929 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10930 /// ISD::VECTOR_SHUFFLE.
10931 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10932   // The LLVM shufflevector instruction does not require the shuffle mask
10933   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10934   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10935   // operands do not match the mask length, they are extended by concatenating
10936   // them with undef vectors.  That is probably the right thing for other
10937   // targets, but for NEON it is better to concatenate two double-register
10938   // size vector operands into a single quad-register size vector.  Do that
10939   // transformation here:
10940   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10941   //   shuffle(concat(v1, v2), undef)
10942   SDValue Op0 = N->getOperand(0);
10943   SDValue Op1 = N->getOperand(1);
10944   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10945       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10946       Op0.getNumOperands() != 2 ||
10947       Op1.getNumOperands() != 2)
10948     return SDValue();
10949   SDValue Concat0Op1 = Op0.getOperand(1);
10950   SDValue Concat1Op1 = Op1.getOperand(1);
10951   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10952     return SDValue();
10953   // Skip the transformation if any of the types are illegal.
10954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10955   EVT VT = N->getValueType(0);
10956   if (!TLI.isTypeLegal(VT) ||
10957       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10958       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10959     return SDValue();
10960 
10961   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10962                                   Op0.getOperand(0), Op1.getOperand(0));
10963   // Translate the shuffle mask.
10964   SmallVector<int, 16> NewMask;
10965   unsigned NumElts = VT.getVectorNumElements();
10966   unsigned HalfElts = NumElts/2;
10967   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10968   for (unsigned n = 0; n < NumElts; ++n) {
10969     int MaskElt = SVN->getMaskElt(n);
10970     int NewElt = -1;
10971     if (MaskElt < (int)HalfElts)
10972       NewElt = MaskElt;
10973     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10974       NewElt = HalfElts + MaskElt - NumElts;
10975     NewMask.push_back(NewElt);
10976   }
10977   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10978                               DAG.getUNDEF(VT), NewMask);
10979 }
10980 
10981 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10982 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10983 /// base address updates.
10984 /// For generic load/stores, the memory type is assumed to be a vector.
10985 /// The caller is assumed to have checked legality.
10986 static SDValue CombineBaseUpdate(SDNode *N,
10987                                  TargetLowering::DAGCombinerInfo &DCI) {
10988   SelectionDAG &DAG = DCI.DAG;
10989   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10990                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10991   const bool isStore = N->getOpcode() == ISD::STORE;
10992   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10993   SDValue Addr = N->getOperand(AddrOpIdx);
10994   MemSDNode *MemN = cast<MemSDNode>(N);
10995   SDLoc dl(N);
10996 
10997   // Search for a use of the address operand that is an increment.
10998   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10999          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11000     SDNode *User = *UI;
11001     if (User->getOpcode() != ISD::ADD ||
11002         UI.getUse().getResNo() != Addr.getResNo())
11003       continue;
11004 
11005     // Check that the add is independent of the load/store.  Otherwise, folding
11006     // it would create a cycle.
11007     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11008       continue;
11009 
11010     // Find the new opcode for the updating load/store.
11011     bool isLoadOp = true;
11012     bool isLaneOp = false;
11013     unsigned NewOpc = 0;
11014     unsigned NumVecs = 0;
11015     if (isIntrinsic) {
11016       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11017       switch (IntNo) {
11018       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11019       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11020         NumVecs = 1; break;
11021       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11022         NumVecs = 2; break;
11023       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11024         NumVecs = 3; break;
11025       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11026         NumVecs = 4; break;
11027       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11028         NumVecs = 2; isLaneOp = true; break;
11029       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11030         NumVecs = 3; isLaneOp = true; break;
11031       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11032         NumVecs = 4; isLaneOp = true; break;
11033       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11034         NumVecs = 1; isLoadOp = false; break;
11035       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11036         NumVecs = 2; isLoadOp = false; break;
11037       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11038         NumVecs = 3; isLoadOp = false; break;
11039       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11040         NumVecs = 4; isLoadOp = false; break;
11041       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11042         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11043       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11044         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11045       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11046         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11047       }
11048     } else {
11049       isLaneOp = true;
11050       switch (N->getOpcode()) {
11051       default: llvm_unreachable("unexpected opcode for Neon base update");
11052       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11053       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11054       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11055       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11056       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11057         NumVecs = 1; isLaneOp = false; break;
11058       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11059         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11060       }
11061     }
11062 
11063     // Find the size of memory referenced by the load/store.
11064     EVT VecTy;
11065     if (isLoadOp) {
11066       VecTy = N->getValueType(0);
11067     } else if (isIntrinsic) {
11068       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11069     } else {
11070       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11071       VecTy = N->getOperand(1).getValueType();
11072     }
11073 
11074     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11075     if (isLaneOp)
11076       NumBytes /= VecTy.getVectorNumElements();
11077 
11078     // If the increment is a constant, it must match the memory ref size.
11079     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11080     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11081     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11082       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11083       // separate instructions that make it harder to use a non-constant update.
11084       continue;
11085     }
11086 
11087     // OK, we found an ADD we can fold into the base update.
11088     // Now, create a _UPD node, taking care of not breaking alignment.
11089 
11090     EVT AlignedVecTy = VecTy;
11091     unsigned Alignment = MemN->getAlignment();
11092 
11093     // If this is a less-than-standard-aligned load/store, change the type to
11094     // match the standard alignment.
11095     // The alignment is overlooked when selecting _UPD variants; and it's
11096     // easier to introduce bitcasts here than fix that.
11097     // There are 3 ways to get to this base-update combine:
11098     // - intrinsics: they are assumed to be properly aligned (to the standard
11099     //   alignment of the memory type), so we don't need to do anything.
11100     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11101     //   intrinsics, so, likewise, there's nothing to do.
11102     // - generic load/store instructions: the alignment is specified as an
11103     //   explicit operand, rather than implicitly as the standard alignment
11104     //   of the memory type (like the intrisics).  We need to change the
11105     //   memory type to match the explicit alignment.  That way, we don't
11106     //   generate non-standard-aligned ARMISD::VLDx nodes.
11107     if (isa<LSBaseSDNode>(N)) {
11108       if (Alignment == 0)
11109         Alignment = 1;
11110       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11111         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11112         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11113         assert(!isLaneOp && "Unexpected generic load/store lane.");
11114         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11115         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11116       }
11117       // Don't set an explicit alignment on regular load/stores that we want
11118       // to transform to VLD/VST 1_UPD nodes.
11119       // This matches the behavior of regular load/stores, which only get an
11120       // explicit alignment if the MMO alignment is larger than the standard
11121       // alignment of the memory type.
11122       // Intrinsics, however, always get an explicit alignment, set to the
11123       // alignment of the MMO.
11124       Alignment = 1;
11125     }
11126 
11127     // Create the new updating load/store node.
11128     // First, create an SDVTList for the new updating node's results.
11129     EVT Tys[6];
11130     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11131     unsigned n;
11132     for (n = 0; n < NumResultVecs; ++n)
11133       Tys[n] = AlignedVecTy;
11134     Tys[n++] = MVT::i32;
11135     Tys[n] = MVT::Other;
11136     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11137 
11138     // Then, gather the new node's operands.
11139     SmallVector<SDValue, 8> Ops;
11140     Ops.push_back(N->getOperand(0)); // incoming chain
11141     Ops.push_back(N->getOperand(AddrOpIdx));
11142     Ops.push_back(Inc);
11143 
11144     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11145       // Try to match the intrinsic's signature
11146       Ops.push_back(StN->getValue());
11147     } else {
11148       // Loads (and of course intrinsics) match the intrinsics' signature,
11149       // so just add all but the alignment operand.
11150       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11151         Ops.push_back(N->getOperand(i));
11152     }
11153 
11154     // For all node types, the alignment operand is always the last one.
11155     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11156 
11157     // If this is a non-standard-aligned STORE, the penultimate operand is the
11158     // stored value.  Bitcast it to the aligned type.
11159     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11160       SDValue &StVal = Ops[Ops.size()-2];
11161       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11162     }
11163 
11164     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11165     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11166                                            MemN->getMemOperand());
11167 
11168     // Update the uses.
11169     SmallVector<SDValue, 5> NewResults;
11170     for (unsigned i = 0; i < NumResultVecs; ++i)
11171       NewResults.push_back(SDValue(UpdN.getNode(), i));
11172 
11173     // If this is an non-standard-aligned LOAD, the first result is the loaded
11174     // value.  Bitcast it to the expected result type.
11175     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11176       SDValue &LdVal = NewResults[0];
11177       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11178     }
11179 
11180     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11181     DCI.CombineTo(N, NewResults);
11182     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11183 
11184     break;
11185   }
11186   return SDValue();
11187 }
11188 
11189 static SDValue PerformVLDCombine(SDNode *N,
11190                                  TargetLowering::DAGCombinerInfo &DCI) {
11191   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11192     return SDValue();
11193 
11194   return CombineBaseUpdate(N, DCI);
11195 }
11196 
11197 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11198 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11199 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11200 /// return true.
11201 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11202   SelectionDAG &DAG = DCI.DAG;
11203   EVT VT = N->getValueType(0);
11204   // vldN-dup instructions only support 64-bit vectors for N > 1.
11205   if (!VT.is64BitVector())
11206     return false;
11207 
11208   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11209   SDNode *VLD = N->getOperand(0).getNode();
11210   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11211     return false;
11212   unsigned NumVecs = 0;
11213   unsigned NewOpc = 0;
11214   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11215   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11216     NumVecs = 2;
11217     NewOpc = ARMISD::VLD2DUP;
11218   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11219     NumVecs = 3;
11220     NewOpc = ARMISD::VLD3DUP;
11221   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11222     NumVecs = 4;
11223     NewOpc = ARMISD::VLD4DUP;
11224   } else {
11225     return false;
11226   }
11227 
11228   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11229   // numbers match the load.
11230   unsigned VLDLaneNo =
11231     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11232   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11233        UI != UE; ++UI) {
11234     // Ignore uses of the chain result.
11235     if (UI.getUse().getResNo() == NumVecs)
11236       continue;
11237     SDNode *User = *UI;
11238     if (User->getOpcode() != ARMISD::VDUPLANE ||
11239         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11240       return false;
11241   }
11242 
11243   // Create the vldN-dup node.
11244   EVT Tys[5];
11245   unsigned n;
11246   for (n = 0; n < NumVecs; ++n)
11247     Tys[n] = VT;
11248   Tys[n] = MVT::Other;
11249   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11250   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11251   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11252   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11253                                            Ops, VLDMemInt->getMemoryVT(),
11254                                            VLDMemInt->getMemOperand());
11255 
11256   // Update the uses.
11257   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11258        UI != UE; ++UI) {
11259     unsigned ResNo = UI.getUse().getResNo();
11260     // Ignore uses of the chain result.
11261     if (ResNo == NumVecs)
11262       continue;
11263     SDNode *User = *UI;
11264     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11265   }
11266 
11267   // Now the vldN-lane intrinsic is dead except for its chain result.
11268   // Update uses of the chain.
11269   std::vector<SDValue> VLDDupResults;
11270   for (unsigned n = 0; n < NumVecs; ++n)
11271     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11272   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11273   DCI.CombineTo(VLD, VLDDupResults);
11274 
11275   return true;
11276 }
11277 
11278 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11279 /// ARMISD::VDUPLANE.
11280 static SDValue PerformVDUPLANECombine(SDNode *N,
11281                                       TargetLowering::DAGCombinerInfo &DCI) {
11282   SDValue Op = N->getOperand(0);
11283 
11284   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11285   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11286   if (CombineVLDDUP(N, DCI))
11287     return SDValue(N, 0);
11288 
11289   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11290   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11291   while (Op.getOpcode() == ISD::BITCAST)
11292     Op = Op.getOperand(0);
11293   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11294     return SDValue();
11295 
11296   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11297   unsigned EltSize = Op.getScalarValueSizeInBits();
11298   // The canonical VMOV for a zero vector uses a 32-bit element size.
11299   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11300   unsigned EltBits;
11301   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11302     EltSize = 8;
11303   EVT VT = N->getValueType(0);
11304   if (EltSize > VT.getScalarSizeInBits())
11305     return SDValue();
11306 
11307   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11308 }
11309 
11310 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11311 static SDValue PerformVDUPCombine(SDNode *N,
11312                                   TargetLowering::DAGCombinerInfo &DCI) {
11313   SelectionDAG &DAG = DCI.DAG;
11314   SDValue Op = N->getOperand(0);
11315 
11316   // Match VDUP(LOAD) -> VLD1DUP.
11317   // We match this pattern here rather than waiting for isel because the
11318   // transform is only legal for unindexed loads.
11319   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11320   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11321       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11322     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11323                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11324     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11325     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11326                                              Ops, LD->getMemoryVT(),
11327                                              LD->getMemOperand());
11328     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11329     return VLDDup;
11330   }
11331 
11332   return SDValue();
11333 }
11334 
11335 static SDValue PerformLOADCombine(SDNode *N,
11336                                   TargetLowering::DAGCombinerInfo &DCI) {
11337   EVT VT = N->getValueType(0);
11338 
11339   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11340   if (ISD::isNormalLoad(N) && VT.isVector() &&
11341       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11342     return CombineBaseUpdate(N, DCI);
11343 
11344   return SDValue();
11345 }
11346 
11347 /// PerformSTORECombine - Target-specific dag combine xforms for
11348 /// ISD::STORE.
11349 static SDValue PerformSTORECombine(SDNode *N,
11350                                    TargetLowering::DAGCombinerInfo &DCI) {
11351   StoreSDNode *St = cast<StoreSDNode>(N);
11352   if (St->isVolatile())
11353     return SDValue();
11354 
11355   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11356   // pack all of the elements in one place.  Next, store to memory in fewer
11357   // chunks.
11358   SDValue StVal = St->getValue();
11359   EVT VT = StVal.getValueType();
11360   if (St->isTruncatingStore() && VT.isVector()) {
11361     SelectionDAG &DAG = DCI.DAG;
11362     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11363     EVT StVT = St->getMemoryVT();
11364     unsigned NumElems = VT.getVectorNumElements();
11365     assert(StVT != VT && "Cannot truncate to the same type");
11366     unsigned FromEltSz = VT.getScalarSizeInBits();
11367     unsigned ToEltSz = StVT.getScalarSizeInBits();
11368 
11369     // From, To sizes and ElemCount must be pow of two
11370     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11371 
11372     // We are going to use the original vector elt for storing.
11373     // Accumulated smaller vector elements must be a multiple of the store size.
11374     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11375 
11376     unsigned SizeRatio  = FromEltSz / ToEltSz;
11377     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11378 
11379     // Create a type on which we perform the shuffle.
11380     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11381                                      NumElems*SizeRatio);
11382     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11383 
11384     SDLoc DL(St);
11385     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11386     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11387     for (unsigned i = 0; i < NumElems; ++i)
11388       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11389                           ? (i + 1) * SizeRatio - 1
11390                           : i * SizeRatio;
11391 
11392     // Can't shuffle using an illegal type.
11393     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11394 
11395     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11396                                 DAG.getUNDEF(WideVec.getValueType()),
11397                                 ShuffleVec);
11398     // At this point all of the data is stored at the bottom of the
11399     // register. We now need to save it to mem.
11400 
11401     // Find the largest store unit
11402     MVT StoreType = MVT::i8;
11403     for (MVT Tp : MVT::integer_valuetypes()) {
11404       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11405         StoreType = Tp;
11406     }
11407     // Didn't find a legal store type.
11408     if (!TLI.isTypeLegal(StoreType))
11409       return SDValue();
11410 
11411     // Bitcast the original vector into a vector of store-size units
11412     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11413             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11414     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11415     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11416     SmallVector<SDValue, 8> Chains;
11417     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11418                                         TLI.getPointerTy(DAG.getDataLayout()));
11419     SDValue BasePtr = St->getBasePtr();
11420 
11421     // Perform one or more big stores into memory.
11422     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11423     for (unsigned I = 0; I < E; I++) {
11424       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11425                                    StoreType, ShuffWide,
11426                                    DAG.getIntPtrConstant(I, DL));
11427       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11428                                 St->getPointerInfo(), St->getAlignment(),
11429                                 St->getMemOperand()->getFlags());
11430       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11431                             Increment);
11432       Chains.push_back(Ch);
11433     }
11434     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11435   }
11436 
11437   if (!ISD::isNormalStore(St))
11438     return SDValue();
11439 
11440   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11441   // ARM stores of arguments in the same cache line.
11442   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11443       StVal.getNode()->hasOneUse()) {
11444     SelectionDAG  &DAG = DCI.DAG;
11445     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11446     SDLoc DL(St);
11447     SDValue BasePtr = St->getBasePtr();
11448     SDValue NewST1 = DAG.getStore(
11449         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11450         BasePtr, St->getPointerInfo(), St->getAlignment(),
11451         St->getMemOperand()->getFlags());
11452 
11453     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11454                                     DAG.getConstant(4, DL, MVT::i32));
11455     return DAG.getStore(NewST1.getValue(0), DL,
11456                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11457                         OffsetPtr, St->getPointerInfo(),
11458                         std::min(4U, St->getAlignment() / 2),
11459                         St->getMemOperand()->getFlags());
11460   }
11461 
11462   if (StVal.getValueType() == MVT::i64 &&
11463       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11464 
11465     // Bitcast an i64 store extracted from a vector to f64.
11466     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11467     SelectionDAG &DAG = DCI.DAG;
11468     SDLoc dl(StVal);
11469     SDValue IntVec = StVal.getOperand(0);
11470     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11471                                    IntVec.getValueType().getVectorNumElements());
11472     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11473     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11474                                  Vec, StVal.getOperand(1));
11475     dl = SDLoc(N);
11476     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11477     // Make the DAGCombiner fold the bitcasts.
11478     DCI.AddToWorklist(Vec.getNode());
11479     DCI.AddToWorklist(ExtElt.getNode());
11480     DCI.AddToWorklist(V.getNode());
11481     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11482                         St->getPointerInfo(), St->getAlignment(),
11483                         St->getMemOperand()->getFlags(), St->getAAInfo());
11484   }
11485 
11486   // If this is a legal vector store, try to combine it into a VST1_UPD.
11487   if (ISD::isNormalStore(N) && VT.isVector() &&
11488       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11489     return CombineBaseUpdate(N, DCI);
11490 
11491   return SDValue();
11492 }
11493 
11494 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11495 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11496 /// when the VMUL has a constant operand that is a power of 2.
11497 ///
11498 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11499 ///  vmul.f32        d16, d17, d16
11500 ///  vcvt.s32.f32    d16, d16
11501 /// becomes:
11502 ///  vcvt.s32.f32    d16, d16, #3
11503 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11504                                   const ARMSubtarget *Subtarget) {
11505   if (!Subtarget->hasNEON())
11506     return SDValue();
11507 
11508   SDValue Op = N->getOperand(0);
11509   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11510       Op.getOpcode() != ISD::FMUL)
11511     return SDValue();
11512 
11513   SDValue ConstVec = Op->getOperand(1);
11514   if (!isa<BuildVectorSDNode>(ConstVec))
11515     return SDValue();
11516 
11517   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11518   uint32_t FloatBits = FloatTy.getSizeInBits();
11519   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11520   uint32_t IntBits = IntTy.getSizeInBits();
11521   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11522   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11523     // These instructions only exist converting from f32 to i32. We can handle
11524     // smaller integers by generating an extra truncate, but larger ones would
11525     // be lossy. We also can't handle more then 4 lanes, since these intructions
11526     // only support v2i32/v4i32 types.
11527     return SDValue();
11528   }
11529 
11530   BitVector UndefElements;
11531   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11532   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11533   if (C == -1 || C == 0 || C > 32)
11534     return SDValue();
11535 
11536   SDLoc dl(N);
11537   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11538   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11539     Intrinsic::arm_neon_vcvtfp2fxu;
11540   SDValue FixConv = DAG.getNode(
11541       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11542       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11543       DAG.getConstant(C, dl, MVT::i32));
11544 
11545   if (IntBits < FloatBits)
11546     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11547 
11548   return FixConv;
11549 }
11550 
11551 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11552 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11553 /// when the VDIV has a constant operand that is a power of 2.
11554 ///
11555 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11556 ///  vcvt.f32.s32    d16, d16
11557 ///  vdiv.f32        d16, d17, d16
11558 /// becomes:
11559 ///  vcvt.f32.s32    d16, d16, #3
11560 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11561                                   const ARMSubtarget *Subtarget) {
11562   if (!Subtarget->hasNEON())
11563     return SDValue();
11564 
11565   SDValue Op = N->getOperand(0);
11566   unsigned OpOpcode = Op.getNode()->getOpcode();
11567   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11568       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11569     return SDValue();
11570 
11571   SDValue ConstVec = N->getOperand(1);
11572   if (!isa<BuildVectorSDNode>(ConstVec))
11573     return SDValue();
11574 
11575   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11576   uint32_t FloatBits = FloatTy.getSizeInBits();
11577   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11578   uint32_t IntBits = IntTy.getSizeInBits();
11579   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11580   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11581     // These instructions only exist converting from i32 to f32. We can handle
11582     // smaller integers by generating an extra extend, but larger ones would
11583     // be lossy. We also can't handle more then 4 lanes, since these intructions
11584     // only support v2i32/v4i32 types.
11585     return SDValue();
11586   }
11587 
11588   BitVector UndefElements;
11589   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11590   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11591   if (C == -1 || C == 0 || C > 32)
11592     return SDValue();
11593 
11594   SDLoc dl(N);
11595   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11596   SDValue ConvInput = Op.getOperand(0);
11597   if (IntBits < FloatBits)
11598     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11599                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11600                             ConvInput);
11601 
11602   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11603     Intrinsic::arm_neon_vcvtfxu2fp;
11604   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11605                      Op.getValueType(),
11606                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11607                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11608 }
11609 
11610 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11611 /// operand of a vector shift operation, where all the elements of the
11612 /// build_vector must have the same constant integer value.
11613 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11614   // Ignore bit_converts.
11615   while (Op.getOpcode() == ISD::BITCAST)
11616     Op = Op.getOperand(0);
11617   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11618   APInt SplatBits, SplatUndef;
11619   unsigned SplatBitSize;
11620   bool HasAnyUndefs;
11621   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11622                                       HasAnyUndefs, ElementBits) ||
11623       SplatBitSize > ElementBits)
11624     return false;
11625   Cnt = SplatBits.getSExtValue();
11626   return true;
11627 }
11628 
11629 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11630 /// operand of a vector shift left operation.  That value must be in the range:
11631 ///   0 <= Value < ElementBits for a left shift; or
11632 ///   0 <= Value <= ElementBits for a long left shift.
11633 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11634   assert(VT.isVector() && "vector shift count is not a vector type");
11635   int64_t ElementBits = VT.getScalarSizeInBits();
11636   if (! getVShiftImm(Op, ElementBits, Cnt))
11637     return false;
11638   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11639 }
11640 
11641 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11642 /// operand of a vector shift right operation.  For a shift opcode, the value
11643 /// is positive, but for an intrinsic the value count must be negative. The
11644 /// absolute value must be in the range:
11645 ///   1 <= |Value| <= ElementBits for a right shift; or
11646 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11647 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11648                          int64_t &Cnt) {
11649   assert(VT.isVector() && "vector shift count is not a vector type");
11650   int64_t ElementBits = VT.getScalarSizeInBits();
11651   if (! getVShiftImm(Op, ElementBits, Cnt))
11652     return false;
11653   if (!isIntrinsic)
11654     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11655   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11656     Cnt = -Cnt;
11657     return true;
11658   }
11659   return false;
11660 }
11661 
11662 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11663 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11664   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11665   switch (IntNo) {
11666   default:
11667     // Don't do anything for most intrinsics.
11668     break;
11669 
11670   // Vector shifts: check for immediate versions and lower them.
11671   // Note: This is done during DAG combining instead of DAG legalizing because
11672   // the build_vectors for 64-bit vector element shift counts are generally
11673   // not legal, and it is hard to see their values after they get legalized to
11674   // loads from a constant pool.
11675   case Intrinsic::arm_neon_vshifts:
11676   case Intrinsic::arm_neon_vshiftu:
11677   case Intrinsic::arm_neon_vrshifts:
11678   case Intrinsic::arm_neon_vrshiftu:
11679   case Intrinsic::arm_neon_vrshiftn:
11680   case Intrinsic::arm_neon_vqshifts:
11681   case Intrinsic::arm_neon_vqshiftu:
11682   case Intrinsic::arm_neon_vqshiftsu:
11683   case Intrinsic::arm_neon_vqshiftns:
11684   case Intrinsic::arm_neon_vqshiftnu:
11685   case Intrinsic::arm_neon_vqshiftnsu:
11686   case Intrinsic::arm_neon_vqrshiftns:
11687   case Intrinsic::arm_neon_vqrshiftnu:
11688   case Intrinsic::arm_neon_vqrshiftnsu: {
11689     EVT VT = N->getOperand(1).getValueType();
11690     int64_t Cnt;
11691     unsigned VShiftOpc = 0;
11692 
11693     switch (IntNo) {
11694     case Intrinsic::arm_neon_vshifts:
11695     case Intrinsic::arm_neon_vshiftu:
11696       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11697         VShiftOpc = ARMISD::VSHL;
11698         break;
11699       }
11700       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11701         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11702                      ARMISD::VSHRs : ARMISD::VSHRu);
11703         break;
11704       }
11705       return SDValue();
11706 
11707     case Intrinsic::arm_neon_vrshifts:
11708     case Intrinsic::arm_neon_vrshiftu:
11709       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11710         break;
11711       return SDValue();
11712 
11713     case Intrinsic::arm_neon_vqshifts:
11714     case Intrinsic::arm_neon_vqshiftu:
11715       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11716         break;
11717       return SDValue();
11718 
11719     case Intrinsic::arm_neon_vqshiftsu:
11720       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11721         break;
11722       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11723 
11724     case Intrinsic::arm_neon_vrshiftn:
11725     case Intrinsic::arm_neon_vqshiftns:
11726     case Intrinsic::arm_neon_vqshiftnu:
11727     case Intrinsic::arm_neon_vqshiftnsu:
11728     case Intrinsic::arm_neon_vqrshiftns:
11729     case Intrinsic::arm_neon_vqrshiftnu:
11730     case Intrinsic::arm_neon_vqrshiftnsu:
11731       // Narrowing shifts require an immediate right shift.
11732       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11733         break;
11734       llvm_unreachable("invalid shift count for narrowing vector shift "
11735                        "intrinsic");
11736 
11737     default:
11738       llvm_unreachable("unhandled vector shift");
11739     }
11740 
11741     switch (IntNo) {
11742     case Intrinsic::arm_neon_vshifts:
11743     case Intrinsic::arm_neon_vshiftu:
11744       // Opcode already set above.
11745       break;
11746     case Intrinsic::arm_neon_vrshifts:
11747       VShiftOpc = ARMISD::VRSHRs; break;
11748     case Intrinsic::arm_neon_vrshiftu:
11749       VShiftOpc = ARMISD::VRSHRu; break;
11750     case Intrinsic::arm_neon_vrshiftn:
11751       VShiftOpc = ARMISD::VRSHRN; break;
11752     case Intrinsic::arm_neon_vqshifts:
11753       VShiftOpc = ARMISD::VQSHLs; break;
11754     case Intrinsic::arm_neon_vqshiftu:
11755       VShiftOpc = ARMISD::VQSHLu; break;
11756     case Intrinsic::arm_neon_vqshiftsu:
11757       VShiftOpc = ARMISD::VQSHLsu; break;
11758     case Intrinsic::arm_neon_vqshiftns:
11759       VShiftOpc = ARMISD::VQSHRNs; break;
11760     case Intrinsic::arm_neon_vqshiftnu:
11761       VShiftOpc = ARMISD::VQSHRNu; break;
11762     case Intrinsic::arm_neon_vqshiftnsu:
11763       VShiftOpc = ARMISD::VQSHRNsu; break;
11764     case Intrinsic::arm_neon_vqrshiftns:
11765       VShiftOpc = ARMISD::VQRSHRNs; break;
11766     case Intrinsic::arm_neon_vqrshiftnu:
11767       VShiftOpc = ARMISD::VQRSHRNu; break;
11768     case Intrinsic::arm_neon_vqrshiftnsu:
11769       VShiftOpc = ARMISD::VQRSHRNsu; break;
11770     }
11771 
11772     SDLoc dl(N);
11773     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11774                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11775   }
11776 
11777   case Intrinsic::arm_neon_vshiftins: {
11778     EVT VT = N->getOperand(1).getValueType();
11779     int64_t Cnt;
11780     unsigned VShiftOpc = 0;
11781 
11782     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11783       VShiftOpc = ARMISD::VSLI;
11784     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11785       VShiftOpc = ARMISD::VSRI;
11786     else {
11787       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11788     }
11789 
11790     SDLoc dl(N);
11791     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11792                        N->getOperand(1), N->getOperand(2),
11793                        DAG.getConstant(Cnt, dl, MVT::i32));
11794   }
11795 
11796   case Intrinsic::arm_neon_vqrshifts:
11797   case Intrinsic::arm_neon_vqrshiftu:
11798     // No immediate versions of these to check for.
11799     break;
11800   }
11801 
11802   return SDValue();
11803 }
11804 
11805 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11806 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11807 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11808 /// vector element shift counts are generally not legal, and it is hard to see
11809 /// their values after they get legalized to loads from a constant pool.
11810 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11811                                    const ARMSubtarget *ST) {
11812   EVT VT = N->getValueType(0);
11813   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11814     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11815     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11816     SDValue N1 = N->getOperand(1);
11817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11818       SDValue N0 = N->getOperand(0);
11819       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11820           DAG.MaskedValueIsZero(N0.getOperand(0),
11821                                 APInt::getHighBitsSet(32, 16)))
11822         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11823     }
11824   }
11825 
11826   // Nothing to be done for scalar shifts.
11827   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11828   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11829     return SDValue();
11830 
11831   assert(ST->hasNEON() && "unexpected vector shift");
11832   int64_t Cnt;
11833 
11834   switch (N->getOpcode()) {
11835   default: llvm_unreachable("unexpected shift opcode");
11836 
11837   case ISD::SHL:
11838     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11839       SDLoc dl(N);
11840       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11841                          DAG.getConstant(Cnt, dl, MVT::i32));
11842     }
11843     break;
11844 
11845   case ISD::SRA:
11846   case ISD::SRL:
11847     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11848       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11849                             ARMISD::VSHRs : ARMISD::VSHRu);
11850       SDLoc dl(N);
11851       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11852                          DAG.getConstant(Cnt, dl, MVT::i32));
11853     }
11854   }
11855   return SDValue();
11856 }
11857 
11858 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11859 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11860 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11861                                     const ARMSubtarget *ST) {
11862   SDValue N0 = N->getOperand(0);
11863 
11864   // Check for sign- and zero-extensions of vector extract operations of 8-
11865   // and 16-bit vector elements.  NEON supports these directly.  They are
11866   // handled during DAG combining because type legalization will promote them
11867   // to 32-bit types and it is messy to recognize the operations after that.
11868   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11869     SDValue Vec = N0.getOperand(0);
11870     SDValue Lane = N0.getOperand(1);
11871     EVT VT = N->getValueType(0);
11872     EVT EltVT = N0.getValueType();
11873     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11874 
11875     if (VT == MVT::i32 &&
11876         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11877         TLI.isTypeLegal(Vec.getValueType()) &&
11878         isa<ConstantSDNode>(Lane)) {
11879 
11880       unsigned Opc = 0;
11881       switch (N->getOpcode()) {
11882       default: llvm_unreachable("unexpected opcode");
11883       case ISD::SIGN_EXTEND:
11884         Opc = ARMISD::VGETLANEs;
11885         break;
11886       case ISD::ZERO_EXTEND:
11887       case ISD::ANY_EXTEND:
11888         Opc = ARMISD::VGETLANEu;
11889         break;
11890       }
11891       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11892     }
11893   }
11894 
11895   return SDValue();
11896 }
11897 
11898 static const APInt *isPowerOf2Constant(SDValue V) {
11899   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11900   if (!C)
11901     return nullptr;
11902   const APInt *CV = &C->getAPIntValue();
11903   return CV->isPowerOf2() ? CV : nullptr;
11904 }
11905 
11906 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11907   // If we have a CMOV, OR and AND combination such as:
11908   //   if (x & CN)
11909   //     y |= CM;
11910   //
11911   // And:
11912   //   * CN is a single bit;
11913   //   * All bits covered by CM are known zero in y
11914   //
11915   // Then we can convert this into a sequence of BFI instructions. This will
11916   // always be a win if CM is a single bit, will always be no worse than the
11917   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11918   // three bits (due to the extra IT instruction).
11919 
11920   SDValue Op0 = CMOV->getOperand(0);
11921   SDValue Op1 = CMOV->getOperand(1);
11922   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11923   auto CC = CCNode->getAPIntValue().getLimitedValue();
11924   SDValue CmpZ = CMOV->getOperand(4);
11925 
11926   // The compare must be against zero.
11927   if (!isNullConstant(CmpZ->getOperand(1)))
11928     return SDValue();
11929 
11930   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11931   SDValue And = CmpZ->getOperand(0);
11932   if (And->getOpcode() != ISD::AND)
11933     return SDValue();
11934   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
11935   if (!AndC)
11936     return SDValue();
11937   SDValue X = And->getOperand(0);
11938 
11939   if (CC == ARMCC::EQ) {
11940     // We're performing an "equal to zero" compare. Swap the operands so we
11941     // canonicalize on a "not equal to zero" compare.
11942     std::swap(Op0, Op1);
11943   } else {
11944     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11945   }
11946 
11947   if (Op1->getOpcode() != ISD::OR)
11948     return SDValue();
11949 
11950   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11951   if (!OrC)
11952     return SDValue();
11953   SDValue Y = Op1->getOperand(0);
11954 
11955   if (Op0 != Y)
11956     return SDValue();
11957 
11958   // Now, is it profitable to continue?
11959   APInt OrCI = OrC->getAPIntValue();
11960   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11961   if (OrCI.countPopulation() > Heuristic)
11962     return SDValue();
11963 
11964   // Lastly, can we determine that the bits defined by OrCI
11965   // are zero in Y?
11966   KnownBits Known;
11967   DAG.computeKnownBits(Y, Known);
11968   if ((OrCI & Known.Zero) != OrCI)
11969     return SDValue();
11970 
11971   // OK, we can do the combine.
11972   SDValue V = Y;
11973   SDLoc dl(X);
11974   EVT VT = X.getValueType();
11975   unsigned BitInX = AndC->logBase2();
11976 
11977   if (BitInX != 0) {
11978     // We must shift X first.
11979     X = DAG.getNode(ISD::SRL, dl, VT, X,
11980                     DAG.getConstant(BitInX, dl, VT));
11981   }
11982 
11983   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11984        BitInY < NumActiveBits; ++BitInY) {
11985     if (OrCI[BitInY] == 0)
11986       continue;
11987     APInt Mask(VT.getSizeInBits(), 0);
11988     Mask.setBit(BitInY);
11989     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11990                     // Confusingly, the operand is an *inverted* mask.
11991                     DAG.getConstant(~Mask, dl, VT));
11992   }
11993 
11994   return V;
11995 }
11996 
11997 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11998 SDValue
11999 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12000   SDValue Cmp = N->getOperand(4);
12001   if (Cmp.getOpcode() != ARMISD::CMPZ)
12002     // Only looking at NE cases.
12003     return SDValue();
12004 
12005   EVT VT = N->getValueType(0);
12006   SDLoc dl(N);
12007   SDValue LHS = Cmp.getOperand(0);
12008   SDValue RHS = Cmp.getOperand(1);
12009   SDValue Chain = N->getOperand(0);
12010   SDValue BB = N->getOperand(1);
12011   SDValue ARMcc = N->getOperand(2);
12012   ARMCC::CondCodes CC =
12013     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12014 
12015   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12016   // -> (brcond Chain BB CC CPSR Cmp)
12017   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12018       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12019       LHS->getOperand(0)->hasOneUse()) {
12020     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12021     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12022     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12023     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12024     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12025         (LHS01C && LHS01C->getZExtValue() == 1) &&
12026         (LHS1C && LHS1C->getZExtValue() == 1) &&
12027         (RHSC && RHSC->getZExtValue() == 0)) {
12028       return DAG.getNode(
12029           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12030           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12031     }
12032   }
12033 
12034   return SDValue();
12035 }
12036 
12037 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12038 SDValue
12039 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12040   SDValue Cmp = N->getOperand(4);
12041   if (Cmp.getOpcode() != ARMISD::CMPZ)
12042     // Only looking at EQ and NE cases.
12043     return SDValue();
12044 
12045   EVT VT = N->getValueType(0);
12046   SDLoc dl(N);
12047   SDValue LHS = Cmp.getOperand(0);
12048   SDValue RHS = Cmp.getOperand(1);
12049   SDValue FalseVal = N->getOperand(0);
12050   SDValue TrueVal = N->getOperand(1);
12051   SDValue ARMcc = N->getOperand(2);
12052   ARMCC::CondCodes CC =
12053     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12054 
12055   // BFI is only available on V6T2+.
12056   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12057     SDValue R = PerformCMOVToBFICombine(N, DAG);
12058     if (R)
12059       return R;
12060   }
12061 
12062   // Simplify
12063   //   mov     r1, r0
12064   //   cmp     r1, x
12065   //   mov     r0, y
12066   //   moveq   r0, x
12067   // to
12068   //   cmp     r0, x
12069   //   movne   r0, y
12070   //
12071   //   mov     r1, r0
12072   //   cmp     r1, x
12073   //   mov     r0, x
12074   //   movne   r0, y
12075   // to
12076   //   cmp     r0, x
12077   //   movne   r0, y
12078   /// FIXME: Turn this into a target neutral optimization?
12079   SDValue Res;
12080   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12081     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12082                       N->getOperand(3), Cmp);
12083   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12084     SDValue ARMcc;
12085     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12086     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12087                       N->getOperand(3), NewCmp);
12088   }
12089 
12090   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12091   // -> (cmov F T CC CPSR Cmp)
12092   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12093     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12094     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12095     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12096     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12097         (LHS1C && LHS1C->getZExtValue() == 1) &&
12098         (RHSC && RHSC->getZExtValue() == 0)) {
12099       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12100                          LHS->getOperand(2), LHS->getOperand(3),
12101                          LHS->getOperand(4));
12102     }
12103   }
12104 
12105   if (Res.getNode()) {
12106     KnownBits Known;
12107     DAG.computeKnownBits(SDValue(N,0), Known);
12108     // Capture demanded bits information that would be otherwise lost.
12109     if (Known.Zero == 0xfffffffe)
12110       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12111                         DAG.getValueType(MVT::i1));
12112     else if (Known.Zero == 0xffffff00)
12113       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12114                         DAG.getValueType(MVT::i8));
12115     else if (Known.Zero == 0xffff0000)
12116       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12117                         DAG.getValueType(MVT::i16));
12118   }
12119 
12120   return Res;
12121 }
12122 
12123 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12124                                              DAGCombinerInfo &DCI) const {
12125   switch (N->getOpcode()) {
12126   default: break;
12127   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12128   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12129   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12130   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12131   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12132   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12133   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12134   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12135   case ARMISD::ADDC:
12136   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12137   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
12138   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12139   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12140   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12141   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12142   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12143   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12144   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12145   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12146   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12147   case ISD::FP_TO_SINT:
12148   case ISD::FP_TO_UINT:
12149     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12150   case ISD::FDIV:
12151     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12152   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12153   case ISD::SHL:
12154   case ISD::SRA:
12155   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12156   case ISD::SIGN_EXTEND:
12157   case ISD::ZERO_EXTEND:
12158   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12159   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12160   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12161   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12162   case ARMISD::VLD1DUP:
12163   case ARMISD::VLD2DUP:
12164   case ARMISD::VLD3DUP:
12165   case ARMISD::VLD4DUP:
12166     return PerformVLDCombine(N, DCI);
12167   case ARMISD::BUILD_VECTOR:
12168     return PerformARMBUILD_VECTORCombine(N, DCI);
12169   case ARMISD::SMULWB: {
12170     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12171     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12172     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12173       return SDValue();
12174     break;
12175   }
12176   case ARMISD::SMULWT: {
12177     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12178     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12179     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12180       return SDValue();
12181     break;
12182   }
12183   case ARMISD::SMLALBB: {
12184     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12185     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12186     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12187         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12188       return SDValue();
12189     break;
12190   }
12191   case ARMISD::SMLALBT: {
12192     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12193     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12194     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12195     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12196     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12197         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12198       return SDValue();
12199     break;
12200   }
12201   case ARMISD::SMLALTB: {
12202     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12203     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12204     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12205     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12206     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12207         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12208       return SDValue();
12209     break;
12210   }
12211   case ARMISD::SMLALTT: {
12212     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12213     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12214     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12215         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12216       return SDValue();
12217     break;
12218   }
12219   case ISD::INTRINSIC_VOID:
12220   case ISD::INTRINSIC_W_CHAIN:
12221     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12222     case Intrinsic::arm_neon_vld1:
12223     case Intrinsic::arm_neon_vld2:
12224     case Intrinsic::arm_neon_vld3:
12225     case Intrinsic::arm_neon_vld4:
12226     case Intrinsic::arm_neon_vld2lane:
12227     case Intrinsic::arm_neon_vld3lane:
12228     case Intrinsic::arm_neon_vld4lane:
12229     case Intrinsic::arm_neon_vst1:
12230     case Intrinsic::arm_neon_vst2:
12231     case Intrinsic::arm_neon_vst3:
12232     case Intrinsic::arm_neon_vst4:
12233     case Intrinsic::arm_neon_vst2lane:
12234     case Intrinsic::arm_neon_vst3lane:
12235     case Intrinsic::arm_neon_vst4lane:
12236       return PerformVLDCombine(N, DCI);
12237     default: break;
12238     }
12239     break;
12240   }
12241   return SDValue();
12242 }
12243 
12244 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12245                                                           EVT VT) const {
12246   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12247 }
12248 
12249 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12250                                                        unsigned,
12251                                                        unsigned,
12252                                                        bool *Fast) const {
12253   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12254   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12255 
12256   switch (VT.getSimpleVT().SimpleTy) {
12257   default:
12258     return false;
12259   case MVT::i8:
12260   case MVT::i16:
12261   case MVT::i32: {
12262     // Unaligned access can use (for example) LRDB, LRDH, LDR
12263     if (AllowsUnaligned) {
12264       if (Fast)
12265         *Fast = Subtarget->hasV7Ops();
12266       return true;
12267     }
12268     return false;
12269   }
12270   case MVT::f64:
12271   case MVT::v2f64: {
12272     // For any little-endian targets with neon, we can support unaligned ld/st
12273     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12274     // A big-endian target may also explicitly support unaligned accesses
12275     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12276       if (Fast)
12277         *Fast = true;
12278       return true;
12279     }
12280     return false;
12281   }
12282   }
12283 }
12284 
12285 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12286                        unsigned AlignCheck) {
12287   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12288           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12289 }
12290 
12291 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12292                                            unsigned DstAlign, unsigned SrcAlign,
12293                                            bool IsMemset, bool ZeroMemset,
12294                                            bool MemcpyStrSrc,
12295                                            MachineFunction &MF) const {
12296   const Function *F = MF.getFunction();
12297 
12298   // See if we can use NEON instructions for this...
12299   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12300       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12301     bool Fast;
12302     if (Size >= 16 &&
12303         (memOpAlign(SrcAlign, DstAlign, 16) ||
12304          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12305       return MVT::v2f64;
12306     } else if (Size >= 8 &&
12307                (memOpAlign(SrcAlign, DstAlign, 8) ||
12308                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12309                  Fast))) {
12310       return MVT::f64;
12311     }
12312   }
12313 
12314   // Let the target-independent logic figure it out.
12315   return MVT::Other;
12316 }
12317 
12318 // 64-bit integers are split into their high and low parts and held in two
12319 // different registers, so the trunc is free since the low register can just
12320 // be used.
12321 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12322   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12323     return false;
12324   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12325   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12326   return (SrcBits == 64 && DestBits == 32);
12327 }
12328 
12329 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12330   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12331       !DstVT.isInteger())
12332     return false;
12333   unsigned SrcBits = SrcVT.getSizeInBits();
12334   unsigned DestBits = DstVT.getSizeInBits();
12335   return (SrcBits == 64 && DestBits == 32);
12336 }
12337 
12338 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12339   if (Val.getOpcode() != ISD::LOAD)
12340     return false;
12341 
12342   EVT VT1 = Val.getValueType();
12343   if (!VT1.isSimple() || !VT1.isInteger() ||
12344       !VT2.isSimple() || !VT2.isInteger())
12345     return false;
12346 
12347   switch (VT1.getSimpleVT().SimpleTy) {
12348   default: break;
12349   case MVT::i1:
12350   case MVT::i8:
12351   case MVT::i16:
12352     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12353     return true;
12354   }
12355 
12356   return false;
12357 }
12358 
12359 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12360   EVT VT = ExtVal.getValueType();
12361 
12362   if (!isTypeLegal(VT))
12363     return false;
12364 
12365   // Don't create a loadext if we can fold the extension into a wide/long
12366   // instruction.
12367   // If there's more than one user instruction, the loadext is desirable no
12368   // matter what.  There can be two uses by the same instruction.
12369   if (ExtVal->use_empty() ||
12370       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12371     return true;
12372 
12373   SDNode *U = *ExtVal->use_begin();
12374   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12375        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12376     return false;
12377 
12378   return true;
12379 }
12380 
12381 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12382   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12383     return false;
12384 
12385   if (!isTypeLegal(EVT::getEVT(Ty1)))
12386     return false;
12387 
12388   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12389 
12390   // Assuming the caller doesn't have a zeroext or signext return parameter,
12391   // truncation all the way down to i1 is valid.
12392   return true;
12393 }
12394 
12395 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12396                                                 const AddrMode &AM, Type *Ty,
12397                                                 unsigned AS) const {
12398   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12399     if (Subtarget->hasFPAO())
12400       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12401     return 0;
12402   }
12403   return -1;
12404 }
12405 
12406 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12407   if (V < 0)
12408     return false;
12409 
12410   unsigned Scale = 1;
12411   switch (VT.getSimpleVT().SimpleTy) {
12412   default: return false;
12413   case MVT::i1:
12414   case MVT::i8:
12415     // Scale == 1;
12416     break;
12417   case MVT::i16:
12418     // Scale == 2;
12419     Scale = 2;
12420     break;
12421   case MVT::i32:
12422     // Scale == 4;
12423     Scale = 4;
12424     break;
12425   }
12426 
12427   if ((V & (Scale - 1)) != 0)
12428     return false;
12429   V /= Scale;
12430   return V == (V & ((1LL << 5) - 1));
12431 }
12432 
12433 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12434                                       const ARMSubtarget *Subtarget) {
12435   bool isNeg = false;
12436   if (V < 0) {
12437     isNeg = true;
12438     V = - V;
12439   }
12440 
12441   switch (VT.getSimpleVT().SimpleTy) {
12442   default: return false;
12443   case MVT::i1:
12444   case MVT::i8:
12445   case MVT::i16:
12446   case MVT::i32:
12447     // + imm12 or - imm8
12448     if (isNeg)
12449       return V == (V & ((1LL << 8) - 1));
12450     return V == (V & ((1LL << 12) - 1));
12451   case MVT::f32:
12452   case MVT::f64:
12453     // Same as ARM mode. FIXME: NEON?
12454     if (!Subtarget->hasVFP2())
12455       return false;
12456     if ((V & 3) != 0)
12457       return false;
12458     V >>= 2;
12459     return V == (V & ((1LL << 8) - 1));
12460   }
12461 }
12462 
12463 /// isLegalAddressImmediate - Return true if the integer value can be used
12464 /// as the offset of the target addressing mode for load / store of the
12465 /// given type.
12466 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12467                                     const ARMSubtarget *Subtarget) {
12468   if (V == 0)
12469     return true;
12470 
12471   if (!VT.isSimple())
12472     return false;
12473 
12474   if (Subtarget->isThumb1Only())
12475     return isLegalT1AddressImmediate(V, VT);
12476   else if (Subtarget->isThumb2())
12477     return isLegalT2AddressImmediate(V, VT, Subtarget);
12478 
12479   // ARM mode.
12480   if (V < 0)
12481     V = - V;
12482   switch (VT.getSimpleVT().SimpleTy) {
12483   default: return false;
12484   case MVT::i1:
12485   case MVT::i8:
12486   case MVT::i32:
12487     // +- imm12
12488     return V == (V & ((1LL << 12) - 1));
12489   case MVT::i16:
12490     // +- imm8
12491     return V == (V & ((1LL << 8) - 1));
12492   case MVT::f32:
12493   case MVT::f64:
12494     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12495       return false;
12496     if ((V & 3) != 0)
12497       return false;
12498     V >>= 2;
12499     return V == (V & ((1LL << 8) - 1));
12500   }
12501 }
12502 
12503 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12504                                                       EVT VT) const {
12505   int Scale = AM.Scale;
12506   if (Scale < 0)
12507     return false;
12508 
12509   switch (VT.getSimpleVT().SimpleTy) {
12510   default: return false;
12511   case MVT::i1:
12512   case MVT::i8:
12513   case MVT::i16:
12514   case MVT::i32:
12515     if (Scale == 1)
12516       return true;
12517     // r + r << imm
12518     Scale = Scale & ~1;
12519     return Scale == 2 || Scale == 4 || Scale == 8;
12520   case MVT::i64:
12521     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12522     // version in Thumb mode.
12523     // r + r
12524     if (Scale == 1)
12525       return true;
12526     // r * 2 (this can be lowered to r + r).
12527     if (!AM.HasBaseReg && Scale == 2)
12528       return true;
12529     return false;
12530   case MVT::isVoid:
12531     // Note, we allow "void" uses (basically, uses that aren't loads or
12532     // stores), because arm allows folding a scale into many arithmetic
12533     // operations.  This should be made more precise and revisited later.
12534 
12535     // Allow r << imm, but the imm has to be a multiple of two.
12536     if (Scale & 1) return false;
12537     return isPowerOf2_32(Scale);
12538   }
12539 }
12540 
12541 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12542                                                       EVT VT) const {
12543   const int Scale = AM.Scale;
12544 
12545   // Negative scales are not supported in Thumb1.
12546   if (Scale < 0)
12547     return false;
12548 
12549   // Thumb1 addressing modes do not support register scaling excepting the
12550   // following cases:
12551   // 1. Scale == 1 means no scaling.
12552   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12553   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12554 }
12555 
12556 /// isLegalAddressingMode - Return true if the addressing mode represented
12557 /// by AM is legal for this target, for a load/store of the specified type.
12558 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12559                                               const AddrMode &AM, Type *Ty,
12560                                               unsigned AS, Instruction *I) const {
12561   EVT VT = getValueType(DL, Ty, true);
12562   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12563     return false;
12564 
12565   // Can never fold addr of global into load/store.
12566   if (AM.BaseGV)
12567     return false;
12568 
12569   switch (AM.Scale) {
12570   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12571     break;
12572   default:
12573     // ARM doesn't support any R+R*scale+imm addr modes.
12574     if (AM.BaseOffs)
12575       return false;
12576 
12577     if (!VT.isSimple())
12578       return false;
12579 
12580     if (Subtarget->isThumb1Only())
12581       return isLegalT1ScaledAddressingMode(AM, VT);
12582 
12583     if (Subtarget->isThumb2())
12584       return isLegalT2ScaledAddressingMode(AM, VT);
12585 
12586     int Scale = AM.Scale;
12587     switch (VT.getSimpleVT().SimpleTy) {
12588     default: return false;
12589     case MVT::i1:
12590     case MVT::i8:
12591     case MVT::i32:
12592       if (Scale < 0) Scale = -Scale;
12593       if (Scale == 1)
12594         return true;
12595       // r + r << imm
12596       return isPowerOf2_32(Scale & ~1);
12597     case MVT::i16:
12598     case MVT::i64:
12599       // r +/- r
12600       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
12601         return true;
12602       // r * 2 (this can be lowered to r + r).
12603       if (!AM.HasBaseReg && Scale == 2)
12604         return true;
12605       return false;
12606 
12607     case MVT::isVoid:
12608       // Note, we allow "void" uses (basically, uses that aren't loads or
12609       // stores), because arm allows folding a scale into many arithmetic
12610       // operations.  This should be made more precise and revisited later.
12611 
12612       // Allow r << imm, but the imm has to be a multiple of two.
12613       if (Scale & 1) return false;
12614       return isPowerOf2_32(Scale);
12615     }
12616   }
12617   return true;
12618 }
12619 
12620 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12621 /// icmp immediate, that is the target has icmp instructions which can compare
12622 /// a register against the immediate without having to materialize the
12623 /// immediate into a register.
12624 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12625   // Thumb2 and ARM modes can use cmn for negative immediates.
12626   if (!Subtarget->isThumb())
12627     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12628   if (Subtarget->isThumb2())
12629     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12630   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12631   return Imm >= 0 && Imm <= 255;
12632 }
12633 
12634 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12635 /// *or sub* immediate, that is the target has add or sub instructions which can
12636 /// add a register with the immediate without having to materialize the
12637 /// immediate into a register.
12638 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12639   // Same encoding for add/sub, just flip the sign.
12640   int64_t AbsImm = std::abs(Imm);
12641   if (!Subtarget->isThumb())
12642     return ARM_AM::getSOImmVal(AbsImm) != -1;
12643   if (Subtarget->isThumb2())
12644     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12645   // Thumb1 only has 8-bit unsigned immediate.
12646   return AbsImm >= 0 && AbsImm <= 255;
12647 }
12648 
12649 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12650                                       bool isSEXTLoad, SDValue &Base,
12651                                       SDValue &Offset, bool &isInc,
12652                                       SelectionDAG &DAG) {
12653   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12654     return false;
12655 
12656   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12657     // AddressingMode 3
12658     Base = Ptr->getOperand(0);
12659     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12660       int RHSC = (int)RHS->getZExtValue();
12661       if (RHSC < 0 && RHSC > -256) {
12662         assert(Ptr->getOpcode() == ISD::ADD);
12663         isInc = false;
12664         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12665         return true;
12666       }
12667     }
12668     isInc = (Ptr->getOpcode() == ISD::ADD);
12669     Offset = Ptr->getOperand(1);
12670     return true;
12671   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12672     // AddressingMode 2
12673     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12674       int RHSC = (int)RHS->getZExtValue();
12675       if (RHSC < 0 && RHSC > -0x1000) {
12676         assert(Ptr->getOpcode() == ISD::ADD);
12677         isInc = false;
12678         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12679         Base = Ptr->getOperand(0);
12680         return true;
12681       }
12682     }
12683 
12684     if (Ptr->getOpcode() == ISD::ADD) {
12685       isInc = true;
12686       ARM_AM::ShiftOpc ShOpcVal=
12687         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12688       if (ShOpcVal != ARM_AM::no_shift) {
12689         Base = Ptr->getOperand(1);
12690         Offset = Ptr->getOperand(0);
12691       } else {
12692         Base = Ptr->getOperand(0);
12693         Offset = Ptr->getOperand(1);
12694       }
12695       return true;
12696     }
12697 
12698     isInc = (Ptr->getOpcode() == ISD::ADD);
12699     Base = Ptr->getOperand(0);
12700     Offset = Ptr->getOperand(1);
12701     return true;
12702   }
12703 
12704   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12705   return false;
12706 }
12707 
12708 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12709                                      bool isSEXTLoad, SDValue &Base,
12710                                      SDValue &Offset, bool &isInc,
12711                                      SelectionDAG &DAG) {
12712   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12713     return false;
12714 
12715   Base = Ptr->getOperand(0);
12716   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12717     int RHSC = (int)RHS->getZExtValue();
12718     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12719       assert(Ptr->getOpcode() == ISD::ADD);
12720       isInc = false;
12721       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12722       return true;
12723     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12724       isInc = Ptr->getOpcode() == ISD::ADD;
12725       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12726       return true;
12727     }
12728   }
12729 
12730   return false;
12731 }
12732 
12733 /// getPreIndexedAddressParts - returns true by value, base pointer and
12734 /// offset pointer and addressing mode by reference if the node's address
12735 /// can be legally represented as pre-indexed load / store address.
12736 bool
12737 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12738                                              SDValue &Offset,
12739                                              ISD::MemIndexedMode &AM,
12740                                              SelectionDAG &DAG) const {
12741   if (Subtarget->isThumb1Only())
12742     return false;
12743 
12744   EVT VT;
12745   SDValue Ptr;
12746   bool isSEXTLoad = false;
12747   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12748     Ptr = LD->getBasePtr();
12749     VT  = LD->getMemoryVT();
12750     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12751   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12752     Ptr = ST->getBasePtr();
12753     VT  = ST->getMemoryVT();
12754   } else
12755     return false;
12756 
12757   bool isInc;
12758   bool isLegal = false;
12759   if (Subtarget->isThumb2())
12760     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12761                                        Offset, isInc, DAG);
12762   else
12763     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12764                                         Offset, isInc, DAG);
12765   if (!isLegal)
12766     return false;
12767 
12768   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12769   return true;
12770 }
12771 
12772 /// getPostIndexedAddressParts - returns true by value, base pointer and
12773 /// offset pointer and addressing mode by reference if this node can be
12774 /// combined with a load / store to form a post-indexed load / store.
12775 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12776                                                    SDValue &Base,
12777                                                    SDValue &Offset,
12778                                                    ISD::MemIndexedMode &AM,
12779                                                    SelectionDAG &DAG) const {
12780   EVT VT;
12781   SDValue Ptr;
12782   bool isSEXTLoad = false, isNonExt;
12783   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12784     VT  = LD->getMemoryVT();
12785     Ptr = LD->getBasePtr();
12786     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12787     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12788   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12789     VT  = ST->getMemoryVT();
12790     Ptr = ST->getBasePtr();
12791     isNonExt = !ST->isTruncatingStore();
12792   } else
12793     return false;
12794 
12795   if (Subtarget->isThumb1Only()) {
12796     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12797     // must be non-extending/truncating, i32, with an offset of 4.
12798     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12799     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12800       return false;
12801     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12802     if (!RHS || RHS->getZExtValue() != 4)
12803       return false;
12804 
12805     Offset = Op->getOperand(1);
12806     Base = Op->getOperand(0);
12807     AM = ISD::POST_INC;
12808     return true;
12809   }
12810 
12811   bool isInc;
12812   bool isLegal = false;
12813   if (Subtarget->isThumb2())
12814     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12815                                        isInc, DAG);
12816   else
12817     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12818                                         isInc, DAG);
12819   if (!isLegal)
12820     return false;
12821 
12822   if (Ptr != Base) {
12823     // Swap base ptr and offset to catch more post-index load / store when
12824     // it's legal. In Thumb2 mode, offset must be an immediate.
12825     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12826         !Subtarget->isThumb2())
12827       std::swap(Base, Offset);
12828 
12829     // Post-indexed load / store update the base pointer.
12830     if (Ptr != Base)
12831       return false;
12832   }
12833 
12834   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12835   return true;
12836 }
12837 
12838 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12839                                                       KnownBits &Known,
12840                                                       const APInt &DemandedElts,
12841                                                       const SelectionDAG &DAG,
12842                                                       unsigned Depth) const {
12843   unsigned BitWidth = Known.getBitWidth();
12844   Known.resetAll();
12845   switch (Op.getOpcode()) {
12846   default: break;
12847   case ARMISD::ADDC:
12848   case ARMISD::ADDE:
12849   case ARMISD::SUBC:
12850   case ARMISD::SUBE:
12851     // Special cases when we convert a carry to a boolean.
12852     if (Op.getResNo() == 0) {
12853       SDValue LHS = Op.getOperand(0);
12854       SDValue RHS = Op.getOperand(1);
12855       // (ADDE 0, 0, C) will give us a single bit.
12856       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
12857           isNullConstant(RHS)) {
12858         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12859         return;
12860       }
12861     }
12862     break;
12863   case ARMISD::CMOV: {
12864     // Bits are known zero/one if known on the LHS and RHS.
12865     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
12866     if (Known.isUnknown())
12867       return;
12868 
12869     KnownBits KnownRHS;
12870     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
12871     Known.Zero &= KnownRHS.Zero;
12872     Known.One  &= KnownRHS.One;
12873     return;
12874   }
12875   case ISD::INTRINSIC_W_CHAIN: {
12876     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12877     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12878     switch (IntID) {
12879     default: return;
12880     case Intrinsic::arm_ldaex:
12881     case Intrinsic::arm_ldrex: {
12882       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12883       unsigned MemBits = VT.getScalarSizeInBits();
12884       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12885       return;
12886     }
12887     }
12888   }
12889   case ARMISD::BFI: {
12890     // Conservatively, we can recurse down the first operand
12891     // and just mask out all affected bits.
12892     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
12893 
12894     // The operand to BFI is already a mask suitable for removing the bits it
12895     // sets.
12896     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
12897     const APInt &Mask = CI->getAPIntValue();
12898     Known.Zero &= Mask;
12899     Known.One &= Mask;
12900     return;
12901   }
12902   }
12903 }
12904 
12905 //===----------------------------------------------------------------------===//
12906 //                           ARM Inline Assembly Support
12907 //===----------------------------------------------------------------------===//
12908 
12909 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12910   // Looking for "rev" which is V6+.
12911   if (!Subtarget->hasV6Ops())
12912     return false;
12913 
12914   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12915   std::string AsmStr = IA->getAsmString();
12916   SmallVector<StringRef, 4> AsmPieces;
12917   SplitString(AsmStr, AsmPieces, ";\n");
12918 
12919   switch (AsmPieces.size()) {
12920   default: return false;
12921   case 1:
12922     AsmStr = AsmPieces[0];
12923     AsmPieces.clear();
12924     SplitString(AsmStr, AsmPieces, " \t,");
12925 
12926     // rev $0, $1
12927     if (AsmPieces.size() == 3 &&
12928         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12929         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12930       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12931       if (Ty && Ty->getBitWidth() == 32)
12932         return IntrinsicLowering::LowerToByteSwap(CI);
12933     }
12934     break;
12935   }
12936 
12937   return false;
12938 }
12939 
12940 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12941   // At this point, we have to lower this constraint to something else, so we
12942   // lower it to an "r" or "w". However, by doing this we will force the result
12943   // to be in register, while the X constraint is much more permissive.
12944   //
12945   // Although we are correct (we are free to emit anything, without
12946   // constraints), we might break use cases that would expect us to be more
12947   // efficient and emit something else.
12948   if (!Subtarget->hasVFP2())
12949     return "r";
12950   if (ConstraintVT.isFloatingPoint())
12951     return "w";
12952   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12953      (ConstraintVT.getSizeInBits() == 64 ||
12954       ConstraintVT.getSizeInBits() == 128))
12955     return "w";
12956 
12957   return "r";
12958 }
12959 
12960 /// getConstraintType - Given a constraint letter, return the type of
12961 /// constraint it is for this target.
12962 ARMTargetLowering::ConstraintType
12963 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12964   if (Constraint.size() == 1) {
12965     switch (Constraint[0]) {
12966     default:  break;
12967     case 'l': return C_RegisterClass;
12968     case 'w': return C_RegisterClass;
12969     case 'h': return C_RegisterClass;
12970     case 'x': return C_RegisterClass;
12971     case 't': return C_RegisterClass;
12972     case 'j': return C_Other; // Constant for movw.
12973       // An address with a single base register. Due to the way we
12974       // currently handle addresses it is the same as an 'r' memory constraint.
12975     case 'Q': return C_Memory;
12976     }
12977   } else if (Constraint.size() == 2) {
12978     switch (Constraint[0]) {
12979     default: break;
12980     // All 'U+' constraints are addresses.
12981     case 'U': return C_Memory;
12982     }
12983   }
12984   return TargetLowering::getConstraintType(Constraint);
12985 }
12986 
12987 /// Examine constraint type and operand type and determine a weight value.
12988 /// This object must already have been set up with the operand type
12989 /// and the current alternative constraint selected.
12990 TargetLowering::ConstraintWeight
12991 ARMTargetLowering::getSingleConstraintMatchWeight(
12992     AsmOperandInfo &info, const char *constraint) const {
12993   ConstraintWeight weight = CW_Invalid;
12994   Value *CallOperandVal = info.CallOperandVal;
12995     // If we don't have a value, we can't do a match,
12996     // but allow it at the lowest weight.
12997   if (!CallOperandVal)
12998     return CW_Default;
12999   Type *type = CallOperandVal->getType();
13000   // Look at the constraint type.
13001   switch (*constraint) {
13002   default:
13003     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13004     break;
13005   case 'l':
13006     if (type->isIntegerTy()) {
13007       if (Subtarget->isThumb())
13008         weight = CW_SpecificReg;
13009       else
13010         weight = CW_Register;
13011     }
13012     break;
13013   case 'w':
13014     if (type->isFloatingPointTy())
13015       weight = CW_Register;
13016     break;
13017   }
13018   return weight;
13019 }
13020 
13021 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13022 
13023 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13024     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13025   if (Constraint.size() == 1) {
13026     // GCC ARM Constraint Letters
13027     switch (Constraint[0]) {
13028     case 'l': // Low regs or general regs.
13029       if (Subtarget->isThumb())
13030         return RCPair(0U, &ARM::tGPRRegClass);
13031       return RCPair(0U, &ARM::GPRRegClass);
13032     case 'h': // High regs or no regs.
13033       if (Subtarget->isThumb())
13034         return RCPair(0U, &ARM::hGPRRegClass);
13035       break;
13036     case 'r':
13037       if (Subtarget->isThumb1Only())
13038         return RCPair(0U, &ARM::tGPRRegClass);
13039       return RCPair(0U, &ARM::GPRRegClass);
13040     case 'w':
13041       if (VT == MVT::Other)
13042         break;
13043       if (VT == MVT::f32)
13044         return RCPair(0U, &ARM::SPRRegClass);
13045       if (VT.getSizeInBits() == 64)
13046         return RCPair(0U, &ARM::DPRRegClass);
13047       if (VT.getSizeInBits() == 128)
13048         return RCPair(0U, &ARM::QPRRegClass);
13049       break;
13050     case 'x':
13051       if (VT == MVT::Other)
13052         break;
13053       if (VT == MVT::f32)
13054         return RCPair(0U, &ARM::SPR_8RegClass);
13055       if (VT.getSizeInBits() == 64)
13056         return RCPair(0U, &ARM::DPR_8RegClass);
13057       if (VT.getSizeInBits() == 128)
13058         return RCPair(0U, &ARM::QPR_8RegClass);
13059       break;
13060     case 't':
13061       if (VT == MVT::f32)
13062         return RCPair(0U, &ARM::SPRRegClass);
13063       break;
13064     }
13065   }
13066   if (StringRef("{cc}").equals_lower(Constraint))
13067     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13068 
13069   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13070 }
13071 
13072 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13073 /// vector.  If it is invalid, don't add anything to Ops.
13074 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13075                                                      std::string &Constraint,
13076                                                      std::vector<SDValue>&Ops,
13077                                                      SelectionDAG &DAG) const {
13078   SDValue Result;
13079 
13080   // Currently only support length 1 constraints.
13081   if (Constraint.length() != 1) return;
13082 
13083   char ConstraintLetter = Constraint[0];
13084   switch (ConstraintLetter) {
13085   default: break;
13086   case 'j':
13087   case 'I': case 'J': case 'K': case 'L':
13088   case 'M': case 'N': case 'O':
13089     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13090     if (!C)
13091       return;
13092 
13093     int64_t CVal64 = C->getSExtValue();
13094     int CVal = (int) CVal64;
13095     // None of these constraints allow values larger than 32 bits.  Check
13096     // that the value fits in an int.
13097     if (CVal != CVal64)
13098       return;
13099 
13100     switch (ConstraintLetter) {
13101       case 'j':
13102         // Constant suitable for movw, must be between 0 and
13103         // 65535.
13104         if (Subtarget->hasV6T2Ops())
13105           if (CVal >= 0 && CVal <= 65535)
13106             break;
13107         return;
13108       case 'I':
13109         if (Subtarget->isThumb1Only()) {
13110           // This must be a constant between 0 and 255, for ADD
13111           // immediates.
13112           if (CVal >= 0 && CVal <= 255)
13113             break;
13114         } else if (Subtarget->isThumb2()) {
13115           // A constant that can be used as an immediate value in a
13116           // data-processing instruction.
13117           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13118             break;
13119         } else {
13120           // A constant that can be used as an immediate value in a
13121           // data-processing instruction.
13122           if (ARM_AM::getSOImmVal(CVal) != -1)
13123             break;
13124         }
13125         return;
13126 
13127       case 'J':
13128         if (Subtarget->isThumb1Only()) {
13129           // This must be a constant between -255 and -1, for negated ADD
13130           // immediates. This can be used in GCC with an "n" modifier that
13131           // prints the negated value, for use with SUB instructions. It is
13132           // not useful otherwise but is implemented for compatibility.
13133           if (CVal >= -255 && CVal <= -1)
13134             break;
13135         } else {
13136           // This must be a constant between -4095 and 4095. It is not clear
13137           // what this constraint is intended for. Implemented for
13138           // compatibility with GCC.
13139           if (CVal >= -4095 && CVal <= 4095)
13140             break;
13141         }
13142         return;
13143 
13144       case 'K':
13145         if (Subtarget->isThumb1Only()) {
13146           // A 32-bit value where only one byte has a nonzero value. Exclude
13147           // zero to match GCC. This constraint is used by GCC internally for
13148           // constants that can be loaded with a move/shift combination.
13149           // It is not useful otherwise but is implemented for compatibility.
13150           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13151             break;
13152         } else if (Subtarget->isThumb2()) {
13153           // A constant whose bitwise inverse can be used as an immediate
13154           // value in a data-processing instruction. This can be used in GCC
13155           // with a "B" modifier that prints the inverted value, for use with
13156           // BIC and MVN instructions. It is not useful otherwise but is
13157           // implemented for compatibility.
13158           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13159             break;
13160         } else {
13161           // A constant whose bitwise inverse can be used as an immediate
13162           // value in a data-processing instruction. This can be used in GCC
13163           // with a "B" modifier that prints the inverted value, for use with
13164           // BIC and MVN instructions. It is not useful otherwise but is
13165           // implemented for compatibility.
13166           if (ARM_AM::getSOImmVal(~CVal) != -1)
13167             break;
13168         }
13169         return;
13170 
13171       case 'L':
13172         if (Subtarget->isThumb1Only()) {
13173           // This must be a constant between -7 and 7,
13174           // for 3-operand ADD/SUB immediate instructions.
13175           if (CVal >= -7 && CVal < 7)
13176             break;
13177         } else if (Subtarget->isThumb2()) {
13178           // A constant whose negation can be used as an immediate value in a
13179           // data-processing instruction. This can be used in GCC with an "n"
13180           // modifier that prints the negated value, for use with SUB
13181           // instructions. It is not useful otherwise but is implemented for
13182           // compatibility.
13183           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13184             break;
13185         } else {
13186           // A constant whose negation can be used as an immediate value in a
13187           // data-processing instruction. This can be used in GCC with an "n"
13188           // modifier that prints the negated value, for use with SUB
13189           // instructions. It is not useful otherwise but is implemented for
13190           // compatibility.
13191           if (ARM_AM::getSOImmVal(-CVal) != -1)
13192             break;
13193         }
13194         return;
13195 
13196       case 'M':
13197         if (Subtarget->isThumb1Only()) {
13198           // This must be a multiple of 4 between 0 and 1020, for
13199           // ADD sp + immediate.
13200           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13201             break;
13202         } else {
13203           // A power of two or a constant between 0 and 32.  This is used in
13204           // GCC for the shift amount on shifted register operands, but it is
13205           // useful in general for any shift amounts.
13206           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13207             break;
13208         }
13209         return;
13210 
13211       case 'N':
13212         if (Subtarget->isThumb()) {  // FIXME thumb2
13213           // This must be a constant between 0 and 31, for shift amounts.
13214           if (CVal >= 0 && CVal <= 31)
13215             break;
13216         }
13217         return;
13218 
13219       case 'O':
13220         if (Subtarget->isThumb()) {  // FIXME thumb2
13221           // This must be a multiple of 4 between -508 and 508, for
13222           // ADD/SUB sp = sp + immediate.
13223           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13224             break;
13225         }
13226         return;
13227     }
13228     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13229     break;
13230   }
13231 
13232   if (Result.getNode()) {
13233     Ops.push_back(Result);
13234     return;
13235   }
13236   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13237 }
13238 
13239 static RTLIB::Libcall getDivRemLibcall(
13240     const SDNode *N, MVT::SimpleValueType SVT) {
13241   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13242           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13243          "Unhandled Opcode in getDivRemLibcall");
13244   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13245                   N->getOpcode() == ISD::SREM;
13246   RTLIB::Libcall LC;
13247   switch (SVT) {
13248   default: llvm_unreachable("Unexpected request for libcall!");
13249   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13250   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13251   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13252   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13253   }
13254   return LC;
13255 }
13256 
13257 static TargetLowering::ArgListTy getDivRemArgList(
13258     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13259   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13260           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13261          "Unhandled Opcode in getDivRemArgList");
13262   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13263                   N->getOpcode() == ISD::SREM;
13264   TargetLowering::ArgListTy Args;
13265   TargetLowering::ArgListEntry Entry;
13266   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13267     EVT ArgVT = N->getOperand(i).getValueType();
13268     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13269     Entry.Node = N->getOperand(i);
13270     Entry.Ty = ArgTy;
13271     Entry.IsSExt = isSigned;
13272     Entry.IsZExt = !isSigned;
13273     Args.push_back(Entry);
13274   }
13275   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13276     std::swap(Args[0], Args[1]);
13277   return Args;
13278 }
13279 
13280 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13281   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13282           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13283           Subtarget->isTargetWindows()) &&
13284          "Register-based DivRem lowering only");
13285   unsigned Opcode = Op->getOpcode();
13286   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13287          "Invalid opcode for Div/Rem lowering");
13288   bool isSigned = (Opcode == ISD::SDIVREM);
13289   EVT VT = Op->getValueType(0);
13290   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13291   SDLoc dl(Op);
13292 
13293   // If the target has hardware divide, use divide + multiply + subtract:
13294   //     div = a / b
13295   //     rem = a - b * div
13296   //     return {div, rem}
13297   // This should be lowered into UDIV/SDIV + MLS later on.
13298   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13299                                         : Subtarget->hasDivideInARMMode();
13300   if (hasDivide && Op->getValueType(0).isSimple() &&
13301       Op->getSimpleValueType(0) == MVT::i32) {
13302     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13303     const SDValue Dividend = Op->getOperand(0);
13304     const SDValue Divisor = Op->getOperand(1);
13305     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13306     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13307     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13308 
13309     SDValue Values[2] = {Div, Rem};
13310     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13311   }
13312 
13313   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13314                                        VT.getSimpleVT().SimpleTy);
13315   SDValue InChain = DAG.getEntryNode();
13316 
13317   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13318                                                     DAG.getContext(),
13319                                                     Subtarget);
13320 
13321   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13322                                          getPointerTy(DAG.getDataLayout()));
13323 
13324   Type *RetTy = StructType::get(Ty, Ty);
13325 
13326   if (Subtarget->isTargetWindows())
13327     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13328 
13329   TargetLowering::CallLoweringInfo CLI(DAG);
13330   CLI.setDebugLoc(dl).setChain(InChain)
13331     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13332     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13333 
13334   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13335   return CallInfo.first;
13336 }
13337 
13338 // Lowers REM using divmod helpers
13339 // see RTABI section 4.2/4.3
13340 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13341   // Build return types (div and rem)
13342   std::vector<Type*> RetTyParams;
13343   Type *RetTyElement;
13344 
13345   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13346   default: llvm_unreachable("Unexpected request for libcall!");
13347   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13348   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13349   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13350   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13351   }
13352 
13353   RetTyParams.push_back(RetTyElement);
13354   RetTyParams.push_back(RetTyElement);
13355   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13356   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13357 
13358   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13359                                                              SimpleTy);
13360   SDValue InChain = DAG.getEntryNode();
13361   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13362                                                     Subtarget);
13363   bool isSigned = N->getOpcode() == ISD::SREM;
13364   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13365                                          getPointerTy(DAG.getDataLayout()));
13366 
13367   if (Subtarget->isTargetWindows())
13368     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13369 
13370   // Lower call
13371   CallLoweringInfo CLI(DAG);
13372   CLI.setChain(InChain)
13373      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13374      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13375   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13376 
13377   // Return second (rem) result operand (first contains div)
13378   SDNode *ResNode = CallResult.first.getNode();
13379   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13380   return ResNode->getOperand(1);
13381 }
13382 
13383 SDValue
13384 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13385   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13386   SDLoc DL(Op);
13387 
13388   // Get the inputs.
13389   SDValue Chain = Op.getOperand(0);
13390   SDValue Size  = Op.getOperand(1);
13391 
13392   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13393                               DAG.getConstant(2, DL, MVT::i32));
13394 
13395   SDValue Flag;
13396   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13397   Flag = Chain.getValue(1);
13398 
13399   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13400   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13401 
13402   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13403   Chain = NewSP.getValue(1);
13404 
13405   SDValue Ops[2] = { NewSP, Chain };
13406   return DAG.getMergeValues(Ops, DL);
13407 }
13408 
13409 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13410   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13411          "Unexpected type for custom-lowering FP_EXTEND");
13412 
13413   RTLIB::Libcall LC;
13414   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13415 
13416   SDValue SrcVal = Op.getOperand(0);
13417   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13418                      SDLoc(Op)).first;
13419 }
13420 
13421 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13422   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13423          Subtarget->isFPOnlySP() &&
13424          "Unexpected type for custom-lowering FP_ROUND");
13425 
13426   RTLIB::Libcall LC;
13427   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13428 
13429   SDValue SrcVal = Op.getOperand(0);
13430   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13431                      SDLoc(Op)).first;
13432 }
13433 
13434 bool
13435 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13436   // The ARM target isn't yet aware of offsets.
13437   return false;
13438 }
13439 
13440 bool ARM::isBitFieldInvertedMask(unsigned v) {
13441   if (v == 0xffffffff)
13442     return false;
13443 
13444   // there can be 1's on either or both "outsides", all the "inside"
13445   // bits must be 0's
13446   return isShiftedMask_32(~v);
13447 }
13448 
13449 /// isFPImmLegal - Returns true if the target can instruction select the
13450 /// specified FP immediate natively. If false, the legalizer will
13451 /// materialize the FP immediate as a load from a constant pool.
13452 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13453   if (!Subtarget->hasVFP3())
13454     return false;
13455   if (VT == MVT::f32)
13456     return ARM_AM::getFP32Imm(Imm) != -1;
13457   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13458     return ARM_AM::getFP64Imm(Imm) != -1;
13459   return false;
13460 }
13461 
13462 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13463 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13464 /// specified in the intrinsic calls.
13465 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13466                                            const CallInst &I,
13467                                            unsigned Intrinsic) const {
13468   switch (Intrinsic) {
13469   case Intrinsic::arm_neon_vld1:
13470   case Intrinsic::arm_neon_vld2:
13471   case Intrinsic::arm_neon_vld3:
13472   case Intrinsic::arm_neon_vld4:
13473   case Intrinsic::arm_neon_vld2lane:
13474   case Intrinsic::arm_neon_vld3lane:
13475   case Intrinsic::arm_neon_vld4lane: {
13476     Info.opc = ISD::INTRINSIC_W_CHAIN;
13477     // Conservatively set memVT to the entire set of vectors loaded.
13478     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13479     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13480     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13481     Info.ptrVal = I.getArgOperand(0);
13482     Info.offset = 0;
13483     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13484     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13485     Info.vol = false; // volatile loads with NEON intrinsics not supported
13486     Info.readMem = true;
13487     Info.writeMem = false;
13488     return true;
13489   }
13490   case Intrinsic::arm_neon_vst1:
13491   case Intrinsic::arm_neon_vst2:
13492   case Intrinsic::arm_neon_vst3:
13493   case Intrinsic::arm_neon_vst4:
13494   case Intrinsic::arm_neon_vst2lane:
13495   case Intrinsic::arm_neon_vst3lane:
13496   case Intrinsic::arm_neon_vst4lane: {
13497     Info.opc = ISD::INTRINSIC_VOID;
13498     // Conservatively set memVT to the entire set of vectors stored.
13499     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13500     unsigned NumElts = 0;
13501     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13502       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13503       if (!ArgTy->isVectorTy())
13504         break;
13505       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13506     }
13507     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13508     Info.ptrVal = I.getArgOperand(0);
13509     Info.offset = 0;
13510     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13511     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13512     Info.vol = false; // volatile stores with NEON intrinsics not supported
13513     Info.readMem = false;
13514     Info.writeMem = true;
13515     return true;
13516   }
13517   case Intrinsic::arm_ldaex:
13518   case Intrinsic::arm_ldrex: {
13519     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13520     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13521     Info.opc = ISD::INTRINSIC_W_CHAIN;
13522     Info.memVT = MVT::getVT(PtrTy->getElementType());
13523     Info.ptrVal = I.getArgOperand(0);
13524     Info.offset = 0;
13525     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13526     Info.vol = true;
13527     Info.readMem = true;
13528     Info.writeMem = false;
13529     return true;
13530   }
13531   case Intrinsic::arm_stlex:
13532   case Intrinsic::arm_strex: {
13533     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13534     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13535     Info.opc = ISD::INTRINSIC_W_CHAIN;
13536     Info.memVT = MVT::getVT(PtrTy->getElementType());
13537     Info.ptrVal = I.getArgOperand(1);
13538     Info.offset = 0;
13539     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13540     Info.vol = true;
13541     Info.readMem = false;
13542     Info.writeMem = true;
13543     return true;
13544   }
13545   case Intrinsic::arm_stlexd:
13546   case Intrinsic::arm_strexd:
13547     Info.opc = ISD::INTRINSIC_W_CHAIN;
13548     Info.memVT = MVT::i64;
13549     Info.ptrVal = I.getArgOperand(2);
13550     Info.offset = 0;
13551     Info.align = 8;
13552     Info.vol = true;
13553     Info.readMem = false;
13554     Info.writeMem = true;
13555     return true;
13556 
13557   case Intrinsic::arm_ldaexd:
13558   case Intrinsic::arm_ldrexd:
13559     Info.opc = ISD::INTRINSIC_W_CHAIN;
13560     Info.memVT = MVT::i64;
13561     Info.ptrVal = I.getArgOperand(0);
13562     Info.offset = 0;
13563     Info.align = 8;
13564     Info.vol = true;
13565     Info.readMem = true;
13566     Info.writeMem = false;
13567     return true;
13568 
13569   default:
13570     break;
13571   }
13572 
13573   return false;
13574 }
13575 
13576 /// \brief Returns true if it is beneficial to convert a load of a constant
13577 /// to just the constant itself.
13578 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13579                                                           Type *Ty) const {
13580   assert(Ty->isIntegerTy());
13581 
13582   unsigned Bits = Ty->getPrimitiveSizeInBits();
13583   if (Bits == 0 || Bits > 32)
13584     return false;
13585   return true;
13586 }
13587 
13588 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13589                                                 unsigned Index) const {
13590   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13591     return false;
13592 
13593   return (Index == 0 || Index == ResVT.getVectorNumElements());
13594 }
13595 
13596 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13597                                         ARM_MB::MemBOpt Domain) const {
13598   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13599 
13600   // First, if the target has no DMB, see what fallback we can use.
13601   if (!Subtarget->hasDataBarrier()) {
13602     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13603     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13604     // here.
13605     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13606       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13607       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13608                         Builder.getInt32(0), Builder.getInt32(7),
13609                         Builder.getInt32(10), Builder.getInt32(5)};
13610       return Builder.CreateCall(MCR, args);
13611     } else {
13612       // Instead of using barriers, atomic accesses on these subtargets use
13613       // libcalls.
13614       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13615     }
13616   } else {
13617     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13618     // Only a full system barrier exists in the M-class architectures.
13619     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13620     Constant *CDomain = Builder.getInt32(Domain);
13621     return Builder.CreateCall(DMB, CDomain);
13622   }
13623 }
13624 
13625 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13626 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13627                                                  Instruction *Inst,
13628                                                  AtomicOrdering Ord) const {
13629   switch (Ord) {
13630   case AtomicOrdering::NotAtomic:
13631   case AtomicOrdering::Unordered:
13632     llvm_unreachable("Invalid fence: unordered/non-atomic");
13633   case AtomicOrdering::Monotonic:
13634   case AtomicOrdering::Acquire:
13635     return nullptr; // Nothing to do
13636   case AtomicOrdering::SequentiallyConsistent:
13637     if (!Inst->hasAtomicStore())
13638       return nullptr; // Nothing to do
13639     /*FALLTHROUGH*/
13640   case AtomicOrdering::Release:
13641   case AtomicOrdering::AcquireRelease:
13642     if (Subtarget->preferISHSTBarriers())
13643       return makeDMB(Builder, ARM_MB::ISHST);
13644     // FIXME: add a comment with a link to documentation justifying this.
13645     else
13646       return makeDMB(Builder, ARM_MB::ISH);
13647   }
13648   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13649 }
13650 
13651 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13652                                                   Instruction *Inst,
13653                                                   AtomicOrdering Ord) const {
13654   switch (Ord) {
13655   case AtomicOrdering::NotAtomic:
13656   case AtomicOrdering::Unordered:
13657     llvm_unreachable("Invalid fence: unordered/not-atomic");
13658   case AtomicOrdering::Monotonic:
13659   case AtomicOrdering::Release:
13660     return nullptr; // Nothing to do
13661   case AtomicOrdering::Acquire:
13662   case AtomicOrdering::AcquireRelease:
13663   case AtomicOrdering::SequentiallyConsistent:
13664     return makeDMB(Builder, ARM_MB::ISH);
13665   }
13666   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13667 }
13668 
13669 // Loads and stores less than 64-bits are already atomic; ones above that
13670 // are doomed anyway, so defer to the default libcall and blame the OS when
13671 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13672 // anything for those.
13673 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13674   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13675   return (Size == 64) && !Subtarget->isMClass();
13676 }
13677 
13678 // Loads and stores less than 64-bits are already atomic; ones above that
13679 // are doomed anyway, so defer to the default libcall and blame the OS when
13680 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13681 // anything for those.
13682 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13683 // guarantee, see DDI0406C ARM architecture reference manual,
13684 // sections A8.8.72-74 LDRD)
13685 TargetLowering::AtomicExpansionKind
13686 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13687   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13688   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13689                                                   : AtomicExpansionKind::None;
13690 }
13691 
13692 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13693 // and up to 64 bits on the non-M profiles
13694 TargetLowering::AtomicExpansionKind
13695 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13696   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13697   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13698   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13699              ? AtomicExpansionKind::LLSC
13700              : AtomicExpansionKind::None;
13701 }
13702 
13703 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13704     AtomicCmpXchgInst *AI) const {
13705   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13706   // implement cmpxchg without spilling. If the address being exchanged is also
13707   // on the stack and close enough to the spill slot, this can lead to a
13708   // situation where the monitor always gets cleared and the atomic operation
13709   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13710   bool hasAtomicCmpXchg =
13711       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13712   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13713 }
13714 
13715 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13716     const Instruction *I) const {
13717   return InsertFencesForAtomic;
13718 }
13719 
13720 // This has so far only been implemented for MachO.
13721 bool ARMTargetLowering::useLoadStackGuardNode() const {
13722   return Subtarget->isTargetMachO();
13723 }
13724 
13725 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13726                                                   unsigned &Cost) const {
13727   // If we do not have NEON, vector types are not natively supported.
13728   if (!Subtarget->hasNEON())
13729     return false;
13730 
13731   // Floating point values and vector values map to the same register file.
13732   // Therefore, although we could do a store extract of a vector type, this is
13733   // better to leave at float as we have more freedom in the addressing mode for
13734   // those.
13735   if (VectorTy->isFPOrFPVectorTy())
13736     return false;
13737 
13738   // If the index is unknown at compile time, this is very expensive to lower
13739   // and it is not possible to combine the store with the extract.
13740   if (!isa<ConstantInt>(Idx))
13741     return false;
13742 
13743   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13744   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13745   // We can do a store + vector extract on any vector that fits perfectly in a D
13746   // or Q register.
13747   if (BitWidth == 64 || BitWidth == 128) {
13748     Cost = 0;
13749     return true;
13750   }
13751   return false;
13752 }
13753 
13754 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13755   return Subtarget->hasV6T2Ops();
13756 }
13757 
13758 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13759   return Subtarget->hasV6T2Ops();
13760 }
13761 
13762 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13763                                          AtomicOrdering Ord) const {
13764   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13765   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13766   bool IsAcquire = isAcquireOrStronger(Ord);
13767 
13768   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13769   // intrinsic must return {i32, i32} and we have to recombine them into a
13770   // single i64 here.
13771   if (ValTy->getPrimitiveSizeInBits() == 64) {
13772     Intrinsic::ID Int =
13773         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13774     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13775 
13776     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13777     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13778 
13779     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13780     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13781     if (!Subtarget->isLittle())
13782       std::swap (Lo, Hi);
13783     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13784     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13785     return Builder.CreateOr(
13786         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13787   }
13788 
13789   Type *Tys[] = { Addr->getType() };
13790   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13791   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13792 
13793   return Builder.CreateTruncOrBitCast(
13794       Builder.CreateCall(Ldrex, Addr),
13795       cast<PointerType>(Addr->getType())->getElementType());
13796 }
13797 
13798 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13799     IRBuilder<> &Builder) const {
13800   if (!Subtarget->hasV7Ops())
13801     return;
13802   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13803   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13804 }
13805 
13806 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13807                                                Value *Addr,
13808                                                AtomicOrdering Ord) const {
13809   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13810   bool IsRelease = isReleaseOrStronger(Ord);
13811 
13812   // Since the intrinsics must have legal type, the i64 intrinsics take two
13813   // parameters: "i32, i32". We must marshal Val into the appropriate form
13814   // before the call.
13815   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13816     Intrinsic::ID Int =
13817         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13818     Function *Strex = Intrinsic::getDeclaration(M, Int);
13819     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13820 
13821     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13822     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13823     if (!Subtarget->isLittle())
13824       std::swap(Lo, Hi);
13825     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13826     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13827   }
13828 
13829   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13830   Type *Tys[] = { Addr->getType() };
13831   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13832 
13833   return Builder.CreateCall(
13834       Strex, {Builder.CreateZExtOrBitCast(
13835                   Val, Strex->getFunctionType()->getParamType(0)),
13836               Addr});
13837 }
13838 
13839 /// A helper function for determining the number of interleaved accesses we
13840 /// will generate when lowering accesses of the given type.
13841 unsigned
13842 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13843                                              const DataLayout &DL) const {
13844   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13845 }
13846 
13847 bool ARMTargetLowering::isLegalInterleavedAccessType(
13848     VectorType *VecTy, const DataLayout &DL) const {
13849 
13850   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13851   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13852 
13853   // Ensure the vector doesn't have f16 elements. Even though we could do an
13854   // i16 vldN, we can't hold the f16 vectors and will end up converting via
13855   // f32.
13856   if (VecTy->getElementType()->isHalfTy())
13857     return false;
13858 
13859   // Ensure the number of vector elements is greater than 1.
13860   if (VecTy->getNumElements() < 2)
13861     return false;
13862 
13863   // Ensure the element type is legal.
13864   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13865     return false;
13866 
13867   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13868   // 128 will be split into multiple interleaved accesses.
13869   return VecSize == 64 || VecSize % 128 == 0;
13870 }
13871 
13872 /// \brief Lower an interleaved load into a vldN intrinsic.
13873 ///
13874 /// E.g. Lower an interleaved load (Factor = 2):
13875 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13876 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13877 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13878 ///
13879 ///      Into:
13880 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13881 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13882 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13883 bool ARMTargetLowering::lowerInterleavedLoad(
13884     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13885     ArrayRef<unsigned> Indices, unsigned Factor) const {
13886   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13887          "Invalid interleave factor");
13888   assert(!Shuffles.empty() && "Empty shufflevector input");
13889   assert(Shuffles.size() == Indices.size() &&
13890          "Unmatched number of shufflevectors and indices");
13891 
13892   VectorType *VecTy = Shuffles[0]->getType();
13893   Type *EltTy = VecTy->getVectorElementType();
13894 
13895   const DataLayout &DL = LI->getModule()->getDataLayout();
13896 
13897   // Skip if we do not have NEON and skip illegal vector types. We can
13898   // "legalize" wide vector types into multiple interleaved accesses as long as
13899   // the vector types are divisible by 128.
13900   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13901     return false;
13902 
13903   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13904 
13905   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13906   // load integer vectors first and then convert to pointer vectors.
13907   if (EltTy->isPointerTy())
13908     VecTy =
13909         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13910 
13911   IRBuilder<> Builder(LI);
13912 
13913   // The base address of the load.
13914   Value *BaseAddr = LI->getPointerOperand();
13915 
13916   if (NumLoads > 1) {
13917     // If we're going to generate more than one load, reset the sub-vector type
13918     // to something legal.
13919     VecTy = VectorType::get(VecTy->getVectorElementType(),
13920                             VecTy->getVectorNumElements() / NumLoads);
13921 
13922     // We will compute the pointer operand of each load from the original base
13923     // address using GEPs. Cast the base address to a pointer to the scalar
13924     // element type.
13925     BaseAddr = Builder.CreateBitCast(
13926         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13927                       LI->getPointerAddressSpace()));
13928   }
13929 
13930   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13931 
13932   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13933   Type *Tys[] = {VecTy, Int8Ptr};
13934   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13935                                             Intrinsic::arm_neon_vld3,
13936                                             Intrinsic::arm_neon_vld4};
13937   Function *VldnFunc =
13938       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13939 
13940   // Holds sub-vectors extracted from the load intrinsic return values. The
13941   // sub-vectors are associated with the shufflevector instructions they will
13942   // replace.
13943   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13944 
13945   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13946     // If we're generating more than one load, compute the base address of
13947     // subsequent loads as an offset from the previous.
13948     if (LoadCount > 0)
13949       BaseAddr = Builder.CreateConstGEP1_32(
13950           BaseAddr, VecTy->getVectorNumElements() * Factor);
13951 
13952     SmallVector<Value *, 2> Ops;
13953     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13954     Ops.push_back(Builder.getInt32(LI->getAlignment()));
13955 
13956     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13957 
13958     // Replace uses of each shufflevector with the corresponding vector loaded
13959     // by ldN.
13960     for (unsigned i = 0; i < Shuffles.size(); i++) {
13961       ShuffleVectorInst *SV = Shuffles[i];
13962       unsigned Index = Indices[i];
13963 
13964       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13965 
13966       // Convert the integer vector to pointer vector if the element is pointer.
13967       if (EltTy->isPointerTy())
13968         SubVec = Builder.CreateIntToPtr(
13969             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
13970                                     VecTy->getVectorNumElements()));
13971 
13972       SubVecs[SV].push_back(SubVec);
13973     }
13974   }
13975 
13976   // Replace uses of the shufflevector instructions with the sub-vectors
13977   // returned by the load intrinsic. If a shufflevector instruction is
13978   // associated with more than one sub-vector, those sub-vectors will be
13979   // concatenated into a single wide vector.
13980   for (ShuffleVectorInst *SVI : Shuffles) {
13981     auto &SubVec = SubVecs[SVI];
13982     auto *WideVec =
13983         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13984     SVI->replaceAllUsesWith(WideVec);
13985   }
13986 
13987   return true;
13988 }
13989 
13990 /// \brief Lower an interleaved store into a vstN intrinsic.
13991 ///
13992 /// E.g. Lower an interleaved store (Factor = 3):
13993 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13994 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13995 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13996 ///
13997 ///      Into:
13998 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13999 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14000 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14001 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14002 ///
14003 /// Note that the new shufflevectors will be removed and we'll only generate one
14004 /// vst3 instruction in CodeGen.
14005 ///
14006 /// Example for a more general valid mask (Factor 3). Lower:
14007 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14008 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14009 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14010 ///
14011 ///      Into:
14012 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14013 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14014 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14015 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14016 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14017                                               ShuffleVectorInst *SVI,
14018                                               unsigned Factor) const {
14019   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14020          "Invalid interleave factor");
14021 
14022   VectorType *VecTy = SVI->getType();
14023   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14024          "Invalid interleaved store");
14025 
14026   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14027   Type *EltTy = VecTy->getVectorElementType();
14028   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14029 
14030   const DataLayout &DL = SI->getModule()->getDataLayout();
14031 
14032   // Skip if we do not have NEON and skip illegal vector types. We can
14033   // "legalize" wide vector types into multiple interleaved accesses as long as
14034   // the vector types are divisible by 128.
14035   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14036     return false;
14037 
14038   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14039 
14040   Value *Op0 = SVI->getOperand(0);
14041   Value *Op1 = SVI->getOperand(1);
14042   IRBuilder<> Builder(SI);
14043 
14044   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14045   // vectors to integer vectors.
14046   if (EltTy->isPointerTy()) {
14047     Type *IntTy = DL.getIntPtrType(EltTy);
14048 
14049     // Convert to the corresponding integer vector.
14050     Type *IntVecTy =
14051         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14052     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14053     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14054 
14055     SubVecTy = VectorType::get(IntTy, LaneLen);
14056   }
14057 
14058   // The base address of the store.
14059   Value *BaseAddr = SI->getPointerOperand();
14060 
14061   if (NumStores > 1) {
14062     // If we're going to generate more than one store, reset the lane length
14063     // and sub-vector type to something legal.
14064     LaneLen /= NumStores;
14065     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14066 
14067     // We will compute the pointer operand of each store from the original base
14068     // address using GEPs. Cast the base address to a pointer to the scalar
14069     // element type.
14070     BaseAddr = Builder.CreateBitCast(
14071         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14072                       SI->getPointerAddressSpace()));
14073   }
14074 
14075   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14076 
14077   auto Mask = SVI->getShuffleMask();
14078 
14079   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14080   Type *Tys[] = {Int8Ptr, SubVecTy};
14081   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14082                                              Intrinsic::arm_neon_vst3,
14083                                              Intrinsic::arm_neon_vst4};
14084 
14085   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14086     // If we generating more than one store, we compute the base address of
14087     // subsequent stores as an offset from the previous.
14088     if (StoreCount > 0)
14089       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14090 
14091     SmallVector<Value *, 6> Ops;
14092     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14093 
14094     Function *VstNFunc =
14095         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14096 
14097     // Split the shufflevector operands into sub vectors for the new vstN call.
14098     for (unsigned i = 0; i < Factor; i++) {
14099       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14100       if (Mask[IdxI] >= 0) {
14101         Ops.push_back(Builder.CreateShuffleVector(
14102             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14103       } else {
14104         unsigned StartMask = 0;
14105         for (unsigned j = 1; j < LaneLen; j++) {
14106           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14107           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14108             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14109             break;
14110           }
14111         }
14112         // Note: If all elements in a chunk are undefs, StartMask=0!
14113         // Note: Filling undef gaps with random elements is ok, since
14114         // those elements were being written anyway (with undefs).
14115         // In the case of all undefs we're defaulting to using elems from 0
14116         // Note: StartMask cannot be negative, it's checked in
14117         // isReInterleaveMask
14118         Ops.push_back(Builder.CreateShuffleVector(
14119             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14120       }
14121     }
14122 
14123     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14124     Builder.CreateCall(VstNFunc, Ops);
14125   }
14126   return true;
14127 }
14128 
14129 enum HABaseType {
14130   HA_UNKNOWN = 0,
14131   HA_FLOAT,
14132   HA_DOUBLE,
14133   HA_VECT64,
14134   HA_VECT128
14135 };
14136 
14137 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14138                                    uint64_t &Members) {
14139   if (auto *ST = dyn_cast<StructType>(Ty)) {
14140     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14141       uint64_t SubMembers = 0;
14142       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14143         return false;
14144       Members += SubMembers;
14145     }
14146   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14147     uint64_t SubMembers = 0;
14148     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14149       return false;
14150     Members += SubMembers * AT->getNumElements();
14151   } else if (Ty->isFloatTy()) {
14152     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14153       return false;
14154     Members = 1;
14155     Base = HA_FLOAT;
14156   } else if (Ty->isDoubleTy()) {
14157     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14158       return false;
14159     Members = 1;
14160     Base = HA_DOUBLE;
14161   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14162     Members = 1;
14163     switch (Base) {
14164     case HA_FLOAT:
14165     case HA_DOUBLE:
14166       return false;
14167     case HA_VECT64:
14168       return VT->getBitWidth() == 64;
14169     case HA_VECT128:
14170       return VT->getBitWidth() == 128;
14171     case HA_UNKNOWN:
14172       switch (VT->getBitWidth()) {
14173       case 64:
14174         Base = HA_VECT64;
14175         return true;
14176       case 128:
14177         Base = HA_VECT128;
14178         return true;
14179       default:
14180         return false;
14181       }
14182     }
14183   }
14184 
14185   return (Members > 0 && Members <= 4);
14186 }
14187 
14188 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14189 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14190 /// passing according to AAPCS rules.
14191 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14192     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14193   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14194       CallingConv::ARM_AAPCS_VFP)
14195     return false;
14196 
14197   HABaseType Base = HA_UNKNOWN;
14198   uint64_t Members = 0;
14199   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14200   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14201 
14202   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14203   return IsHA || IsIntArray;
14204 }
14205 
14206 unsigned ARMTargetLowering::getExceptionPointerRegister(
14207     const Constant *PersonalityFn) const {
14208   // Platforms which do not use SjLj EH may return values in these registers
14209   // via the personality function.
14210   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14211 }
14212 
14213 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14214     const Constant *PersonalityFn) const {
14215   // Platforms which do not use SjLj EH may return values in these registers
14216   // via the personality function.
14217   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14218 }
14219 
14220 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14221   // Update IsSplitCSR in ARMFunctionInfo.
14222   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14223   AFI->setIsSplitCSR(true);
14224 }
14225 
14226 void ARMTargetLowering::insertCopiesSplitCSR(
14227     MachineBasicBlock *Entry,
14228     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14229   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14230   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14231   if (!IStart)
14232     return;
14233 
14234   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14235   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14236   MachineBasicBlock::iterator MBBI = Entry->begin();
14237   for (const MCPhysReg *I = IStart; *I; ++I) {
14238     const TargetRegisterClass *RC = nullptr;
14239     if (ARM::GPRRegClass.contains(*I))
14240       RC = &ARM::GPRRegClass;
14241     else if (ARM::DPRRegClass.contains(*I))
14242       RC = &ARM::DPRRegClass;
14243     else
14244       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14245 
14246     unsigned NewVR = MRI->createVirtualRegister(RC);
14247     // Create copy from CSR to a virtual register.
14248     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14249     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14250     // nounwind. If we want to generalize this later, we may need to emit
14251     // CFI pseudo-instructions.
14252     assert(Entry->getParent()->getFunction()->hasFnAttribute(
14253                Attribute::NoUnwind) &&
14254            "Function should be nounwind in insertCopiesSplitCSR!");
14255     Entry->addLiveIn(*I);
14256     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14257         .addReg(*I);
14258 
14259     // Insert the copy-back instructions right before the terminator.
14260     for (auto *Exit : Exits)
14261       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14262               TII->get(TargetOpcode::COPY), *I)
14263           .addReg(NewVR);
14264   }
14265 }
14266 
14267 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14268   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14269   TargetLoweringBase::finalizeLowering(MF);
14270 }
14271