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/TargetInstrInfo.h"
61 #include "llvm/CodeGen/TargetLowering.h"
62 #include "llvm/CodeGen/TargetOpcodes.h"
63 #include "llvm/CodeGen/TargetRegisterInfo.h"
64 #include "llvm/CodeGen/TargetSubtargetInfo.h"
65 #include "llvm/CodeGen/ValueTypes.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/CallingConv.h"
68 #include "llvm/IR/Constant.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugLoc.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GlobalAlias.h"
75 #include "llvm/IR/GlobalValue.h"
76 #include "llvm/IR/GlobalVariable.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/InlineAsm.h"
79 #include "llvm/IR/Instruction.h"
80 #include "llvm/IR/Instructions.h"
81 #include "llvm/IR/IntrinsicInst.h"
82 #include "llvm/IR/Intrinsics.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace llvm;
116 
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     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
235     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
236       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
237                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
238                                        : CallingConv::ARM_AAPCS);
239   }
240 
241   if (Subtarget->isTargetMachO()) {
242     // Uses VFP for Thumb libfuncs if available.
243     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
244         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
245       static const struct {
246         const RTLIB::Libcall Op;
247         const char * const Name;
248         const ISD::CondCode Cond;
249       } LibraryCalls[] = {
250         // Single-precision floating-point arithmetic.
251         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
252         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
253         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
254         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
255 
256         // Double-precision floating-point arithmetic.
257         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
258         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
259         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
261 
262         // Single-precision comparisons.
263         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
264         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
265         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
266         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
267         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
268         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
269         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
270         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
271 
272         // Double-precision comparisons.
273         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
274         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
275         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
276         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
277         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
278         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
279         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
280         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
281 
282         // Floating-point to integer conversions.
283         // i64 conversions are done via library routines even when generating VFP
284         // instructions, so use the same ones.
285         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
286         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
287         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
288         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
289 
290         // Conversions between floating types.
291         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
292         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
293 
294         // Integer to floating-point conversions.
295         // i64 conversions are done via library routines even when generating VFP
296         // instructions, so use the same ones.
297         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
298         // e.g., __floatunsidf vs. __floatunssidfvfp.
299         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
300         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
301         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
302         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
303       };
304 
305       for (const auto &LC : LibraryCalls) {
306         setLibcallName(LC.Op, LC.Name);
307         if (LC.Cond != ISD::SETCC_INVALID)
308           setCmpLibcallCC(LC.Op, LC.Cond);
309       }
310     }
311 
312     // Set the correct calling convention for ARMv7k WatchOS. It's just
313     // AAPCS_VFP for functions as simple as libcalls.
314     if (Subtarget->isTargetWatchABI()) {
315       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
316         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
317     }
318   }
319 
320   // These libcalls are not available in 32-bit.
321   setLibcallName(RTLIB::SHL_I128, nullptr);
322   setLibcallName(RTLIB::SRL_I128, nullptr);
323   setLibcallName(RTLIB::SRA_I128, nullptr);
324 
325   // RTLIB
326   if (Subtarget->isAAPCS_ABI() &&
327       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
328        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
329     static const struct {
330       const RTLIB::Libcall Op;
331       const char * const Name;
332       const CallingConv::ID CC;
333       const ISD::CondCode Cond;
334     } LibraryCalls[] = {
335       // Double-precision floating-point arithmetic helper functions
336       // RTABI chapter 4.1.2, Table 2
337       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 
342       // Double-precision floating-point comparison helper functions
343       // RTABI chapter 4.1.2, Table 3
344       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
345       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
346       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
347       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
348       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
349       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
352 
353       // Single-precision floating-point arithmetic helper functions
354       // RTABI chapter 4.1.2, Table 4
355       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
356       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
357       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359 
360       // Single-precision floating-point comparison helper functions
361       // RTABI chapter 4.1.2, Table 5
362       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
363       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
364       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
365       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
366       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
367       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
370 
371       // Floating-point to integer conversions.
372       // RTABI chapter 4.1.2, Table 6
373       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 
382       // Conversions between floating types.
383       // RTABI chapter 4.1.2, Table 7
384       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387 
388       // Integer to floating-point conversions.
389       // RTABI chapter 4.1.2, Table 8
390       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398 
399       // Long long helper functions
400       // RTABI chapter 4.2, Table 9
401       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
402       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405 
406       // Integer division functions
407       // RTABI chapter 4.3.1
408       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416     };
417 
418     for (const auto &LC : LibraryCalls) {
419       setLibcallName(LC.Op, LC.Name);
420       setLibcallCallingConv(LC.Op, LC.CC);
421       if (LC.Cond != ISD::SETCC_INVALID)
422         setCmpLibcallCC(LC.Op, LC.Cond);
423     }
424 
425     // EABI dependent RTLIB
426     if (TM.Options.EABIVersion == EABI::EABI4 ||
427         TM.Options.EABIVersion == EABI::EABI5) {
428       static const struct {
429         const RTLIB::Libcall Op;
430         const char *const Name;
431         const CallingConv::ID CC;
432         const ISD::CondCode Cond;
433       } MemOpsLibraryCalls[] = {
434         // Memory operations
435         // RTABI chapter 4.3.4
436         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
437         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
438         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439       };
440 
441       for (const auto &LC : MemOpsLibraryCalls) {
442         setLibcallName(LC.Op, LC.Name);
443         setLibcallCallingConv(LC.Op, LC.CC);
444         if (LC.Cond != ISD::SETCC_INVALID)
445           setCmpLibcallCC(LC.Op, LC.Cond);
446       }
447     }
448   }
449 
450   if (Subtarget->isTargetWindows()) {
451     static const struct {
452       const RTLIB::Libcall Op;
453       const char * const Name;
454       const CallingConv::ID CC;
455     } LibraryCalls[] = {
456       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
457       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
458       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
459       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
464     };
465 
466     for (const auto &LC : LibraryCalls) {
467       setLibcallName(LC.Op, LC.Name);
468       setLibcallCallingConv(LC.Op, LC.CC);
469     }
470   }
471 
472   // Use divmod compiler-rt calls for iOS 5.0 and later.
473   if (Subtarget->isTargetMachO() &&
474       !(Subtarget->isTargetIOS() &&
475         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
476     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
477     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
478   }
479 
480   // The half <-> float conversion functions are always soft-float on
481   // non-watchos platforms, but are needed for some targets which use a
482   // hard-float calling convention by default.
483   if (!Subtarget->isTargetWatchABI()) {
484     if (Subtarget->isAAPCS_ABI()) {
485       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
486       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
487       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
488     } else {
489       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
490       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
491       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
492     }
493   }
494 
495   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
496   // a __gnu_ prefix (which is the default).
497   if (Subtarget->isTargetAEABI()) {
498     static const struct {
499       const RTLIB::Libcall Op;
500       const char * const Name;
501       const CallingConv::ID CC;
502     } LibraryCalls[] = {
503       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
504       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
505       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
506     };
507 
508     for (const auto &LC : LibraryCalls) {
509       setLibcallName(LC.Op, LC.Name);
510       setLibcallCallingConv(LC.Op, LC.CC);
511     }
512   }
513 
514   if (Subtarget->isThumb1Only())
515     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
516   else
517     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
518 
519   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
520       !Subtarget->isThumb1Only()) {
521     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
522     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
523   }
524 
525   for (MVT VT : MVT::vector_valuetypes()) {
526     for (MVT InnerVT : MVT::vector_valuetypes()) {
527       setTruncStoreAction(VT, InnerVT, Expand);
528       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
529       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
530       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
531     }
532 
533     setOperationAction(ISD::MULHS, VT, Expand);
534     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
535     setOperationAction(ISD::MULHU, VT, Expand);
536     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
537 
538     setOperationAction(ISD::BSWAP, VT, Expand);
539   }
540 
541   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
542   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
543 
544   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
545   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
546 
547   if (Subtarget->hasNEON()) {
548     addDRTypeForNEON(MVT::v2f32);
549     addDRTypeForNEON(MVT::v8i8);
550     addDRTypeForNEON(MVT::v4i16);
551     addDRTypeForNEON(MVT::v2i32);
552     addDRTypeForNEON(MVT::v1i64);
553 
554     addQRTypeForNEON(MVT::v4f32);
555     addQRTypeForNEON(MVT::v2f64);
556     addQRTypeForNEON(MVT::v16i8);
557     addQRTypeForNEON(MVT::v8i16);
558     addQRTypeForNEON(MVT::v4i32);
559     addQRTypeForNEON(MVT::v2i64);
560 
561     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
562     // neither Neon nor VFP support any arithmetic operations on it.
563     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
564     // supported for v4f32.
565     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
566     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
567     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
568     // FIXME: Code duplication: FDIV and FREM are expanded always, see
569     // ARMTargetLowering::addTypeForNEON method for details.
570     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
571     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
572     // FIXME: Create unittest.
573     // In another words, find a way when "copysign" appears in DAG with vector
574     // operands.
575     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
576     // FIXME: Code duplication: SETCC has custom operation action, see
577     // ARMTargetLowering::addTypeForNEON method for details.
578     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
579     // FIXME: Create unittest for FNEG and for FABS.
580     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
581     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
582     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
583     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
584     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
585     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
586     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
587     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
588     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
589     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
590     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
591     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
592     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
593     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
594     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
595     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
596     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
597     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
598 
599     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
600     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
601     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
602     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
603     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
604     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
605     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
606     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
607     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
608     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
609     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
610     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
611     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
612     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
613 
614     // Mark v2f32 intrinsics.
615     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
616     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
617     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
618     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
619     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
620     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
621     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
622     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
623     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
624     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
625     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
626     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
627     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
628     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
629 
630     // Neon does not support some operations on v1i64 and v2i64 types.
631     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
632     // Custom handling for some quad-vector types to detect VMULL.
633     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
634     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
635     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
636     // Custom handling for some vector types to avoid expensive expansions
637     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
638     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
639     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
640     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
641     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
642     // a destination type that is wider than the source, and nor does
643     // it have a FP_TO_[SU]INT instruction with a narrower destination than
644     // source.
645     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
646     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
647     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
648     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
649 
650     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
651     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
652 
653     // NEON does not have single instruction CTPOP for vectors with element
654     // types wider than 8-bits.  However, custom lowering can leverage the
655     // v8i8/v16i8 vcnt instruction.
656     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
657     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
658     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
659     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
660     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
661     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
662 
663     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
664     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
665 
666     // NEON does not have single instruction CTTZ for vectors.
667     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
668     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
669     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
670     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
671 
672     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
673     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
674     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
675     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
676 
677     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
678     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
679     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
680     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
681 
682     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
683     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
684     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
686 
687     // NEON only has FMA instructions as of VFP4.
688     if (!Subtarget->hasVFP4()) {
689       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
690       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
691     }
692 
693     setTargetDAGCombine(ISD::INTRINSIC_VOID);
694     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
695     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
696     setTargetDAGCombine(ISD::SHL);
697     setTargetDAGCombine(ISD::SRL);
698     setTargetDAGCombine(ISD::SRA);
699     setTargetDAGCombine(ISD::SIGN_EXTEND);
700     setTargetDAGCombine(ISD::ZERO_EXTEND);
701     setTargetDAGCombine(ISD::ANY_EXTEND);
702     setTargetDAGCombine(ISD::BUILD_VECTOR);
703     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
704     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
705     setTargetDAGCombine(ISD::STORE);
706     setTargetDAGCombine(ISD::FP_TO_SINT);
707     setTargetDAGCombine(ISD::FP_TO_UINT);
708     setTargetDAGCombine(ISD::FDIV);
709     setTargetDAGCombine(ISD::LOAD);
710 
711     // It is legal to extload from v4i8 to v4i16 or v4i32.
712     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
713                    MVT::v2i32}) {
714       for (MVT VT : MVT::integer_vector_valuetypes()) {
715         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
716         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
717         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
718       }
719     }
720   }
721 
722   if (Subtarget->isFPOnlySP()) {
723     // When targeting a floating-point unit with only single-precision
724     // operations, f64 is legal for the few double-precision instructions which
725     // are present However, no double-precision operations other than moves,
726     // loads and stores are provided by the hardware.
727     setOperationAction(ISD::FADD,       MVT::f64, Expand);
728     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
729     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
730     setOperationAction(ISD::FMA,        MVT::f64, Expand);
731     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
732     setOperationAction(ISD::FREM,       MVT::f64, Expand);
733     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
734     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
735     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
736     setOperationAction(ISD::FABS,       MVT::f64, Expand);
737     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
738     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
739     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
740     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
741     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
742     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
743     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
744     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
745     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
746     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
747     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
748     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
749     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
750     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
751     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
752     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
753     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
754     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
755     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
756     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
757     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
758     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
759   }
760 
761   computeRegisterProperties(Subtarget->getRegisterInfo());
762 
763   // ARM does not have floating-point extending loads.
764   for (MVT VT : MVT::fp_valuetypes()) {
765     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
766     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
767   }
768 
769   // ... or truncating stores
770   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
771   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
772   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
773 
774   // ARM does not have i1 sign extending load.
775   for (MVT VT : MVT::integer_valuetypes())
776     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
777 
778   // ARM supports all 4 flavors of integer indexed load / store.
779   if (!Subtarget->isThumb1Only()) {
780     for (unsigned im = (unsigned)ISD::PRE_INC;
781          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
782       setIndexedLoadAction(im,  MVT::i1,  Legal);
783       setIndexedLoadAction(im,  MVT::i8,  Legal);
784       setIndexedLoadAction(im,  MVT::i16, Legal);
785       setIndexedLoadAction(im,  MVT::i32, Legal);
786       setIndexedStoreAction(im, MVT::i1,  Legal);
787       setIndexedStoreAction(im, MVT::i8,  Legal);
788       setIndexedStoreAction(im, MVT::i16, Legal);
789       setIndexedStoreAction(im, MVT::i32, Legal);
790     }
791   } else {
792     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
793     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
794     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
795   }
796 
797   setOperationAction(ISD::SADDO, MVT::i32, Custom);
798   setOperationAction(ISD::UADDO, MVT::i32, Custom);
799   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
800   setOperationAction(ISD::USUBO, MVT::i32, Custom);
801 
802   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
803   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
804 
805   // i64 operation support.
806   setOperationAction(ISD::MUL,     MVT::i64, Expand);
807   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
808   if (Subtarget->isThumb1Only()) {
809     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
810     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
811   }
812   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
813       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
814     setOperationAction(ISD::MULHS, MVT::i32, Expand);
815 
816   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
817   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
818   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
819   setOperationAction(ISD::SRL,       MVT::i64, Custom);
820   setOperationAction(ISD::SRA,       MVT::i64, Custom);
821   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
822 
823   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
824   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
825   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
826   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
827 
828   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
829     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
830 
831   // ARM does not have ROTL.
832   setOperationAction(ISD::ROTL, MVT::i32, Expand);
833   for (MVT VT : MVT::vector_valuetypes()) {
834     setOperationAction(ISD::ROTL, VT, Expand);
835     setOperationAction(ISD::ROTR, VT, Expand);
836   }
837   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
838   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
839   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
840     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
841 
842   // @llvm.readcyclecounter requires the Performance Monitors extension.
843   // Default to the 0 expansion on unsupported platforms.
844   // FIXME: Technically there are older ARM CPUs that have
845   // implementation-specific ways of obtaining this information.
846   if (Subtarget->hasPerfMon())
847     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
848 
849   // Only ARMv6 has BSWAP.
850   if (!Subtarget->hasV6Ops())
851     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
852 
853   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
854                                         : Subtarget->hasDivideInARMMode();
855   if (!hasDivide) {
856     // These are expanded into libcalls if the cpu doesn't have HW divider.
857     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
858     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
859   }
860 
861   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
862     setOperationAction(ISD::SDIV, MVT::i32, Custom);
863     setOperationAction(ISD::UDIV, MVT::i32, Custom);
864 
865     setOperationAction(ISD::SDIV, MVT::i64, Custom);
866     setOperationAction(ISD::UDIV, MVT::i64, Custom);
867   }
868 
869   setOperationAction(ISD::SREM,  MVT::i32, Expand);
870   setOperationAction(ISD::UREM,  MVT::i32, Expand);
871 
872   // Register based DivRem for AEABI (RTABI 4.2)
873   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
874       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
875       Subtarget->isTargetWindows()) {
876     setOperationAction(ISD::SREM, MVT::i64, Custom);
877     setOperationAction(ISD::UREM, MVT::i64, Custom);
878     HasStandaloneRem = false;
879 
880     if (Subtarget->isTargetWindows()) {
881       const struct {
882         const RTLIB::Libcall Op;
883         const char * const Name;
884         const CallingConv::ID CC;
885       } LibraryCalls[] = {
886         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
887         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
888         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
889         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
890 
891         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
892         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
893         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
894         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
895       };
896 
897       for (const auto &LC : LibraryCalls) {
898         setLibcallName(LC.Op, LC.Name);
899         setLibcallCallingConv(LC.Op, LC.CC);
900       }
901     } else {
902       const struct {
903         const RTLIB::Libcall Op;
904         const char * const Name;
905         const CallingConv::ID CC;
906       } LibraryCalls[] = {
907         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
908         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
909         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
910         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
911 
912         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
913         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
914         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
915         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
916       };
917 
918       for (const auto &LC : LibraryCalls) {
919         setLibcallName(LC.Op, LC.Name);
920         setLibcallCallingConv(LC.Op, LC.CC);
921       }
922     }
923 
924     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
925     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
926     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
927     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
928   } else {
929     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
930     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
931   }
932 
933   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
934     for (auto &VT : {MVT::f32, MVT::f64})
935       setOperationAction(ISD::FPOWI, VT, Custom);
936 
937   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
938   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
939   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
940   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
941 
942   setOperationAction(ISD::TRAP, MVT::Other, Legal);
943 
944   // Use the default implementation.
945   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
946   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
947   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
948   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
949   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
950   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
951 
952   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
953     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
954   else
955     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
956 
957   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
958   // the default expansion.
959   InsertFencesForAtomic = false;
960   if (Subtarget->hasAnyDataBarrier() &&
961       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
962     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
963     // to ldrex/strex loops already.
964     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
965     if (!Subtarget->isThumb() || !Subtarget->isMClass())
966       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
967 
968     // On v8, we have particularly efficient implementations of atomic fences
969     // if they can be combined with nearby atomic loads and stores.
970     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
971       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
972       InsertFencesForAtomic = true;
973     }
974   } else {
975     // If there's anything we can use as a barrier, go through custom lowering
976     // for ATOMIC_FENCE.
977     // If target has DMB in thumb, Fences can be inserted.
978     if (Subtarget->hasDataBarrier())
979       InsertFencesForAtomic = true;
980 
981     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
982                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
983 
984     // Set them all for expansion, which will force libcalls.
985     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
986     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
987     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
988     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
989     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
990     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
991     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
992     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
997     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
998     // Unordered/Monotonic case.
999     if (!InsertFencesForAtomic) {
1000       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1001       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1002     }
1003   }
1004 
1005   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1006 
1007   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1008   if (!Subtarget->hasV6Ops()) {
1009     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1010     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1011   }
1012   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1013 
1014   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1015       !Subtarget->isThumb1Only()) {
1016     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1017     // iff target supports vfp2.
1018     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1019     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1020   }
1021 
1022   // We want to custom lower some of our intrinsics.
1023   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1024   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1025   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1026   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1027   if (Subtarget->useSjLjEH())
1028     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1029 
1030   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1031   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1032   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1033   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1034   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1035   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1036   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1037   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1038   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1039 
1040   // Thumb-1 cannot currently select ARMISD::SUBE.
1041   if (!Subtarget->isThumb1Only())
1042     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1043 
1044   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1045   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1046   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1047   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1048   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1049 
1050   // We don't support sin/cos/fmod/copysign/pow
1051   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1052   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1053   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1054   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1055   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1056   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1057   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1058   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1059   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1060       !Subtarget->isThumb1Only()) {
1061     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1062     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1063   }
1064   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1065   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1066 
1067   if (!Subtarget->hasVFP4()) {
1068     setOperationAction(ISD::FMA, MVT::f64, Expand);
1069     setOperationAction(ISD::FMA, MVT::f32, Expand);
1070   }
1071 
1072   // Various VFP goodness
1073   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1074     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1075     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1076       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1077       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1078     }
1079 
1080     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1081     if (!Subtarget->hasFP16()) {
1082       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1083       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1084     }
1085   }
1086 
1087   // Use __sincos_stret if available.
1088   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1089       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1090     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1091     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1092   }
1093 
1094   // FP-ARMv8 implements a lot of rounding-like FP operations.
1095   if (Subtarget->hasFPARMv8()) {
1096     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1097     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1098     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1099     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1100     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1101     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1102     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1103     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1104     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1105     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1106     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1107     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1108 
1109     if (!Subtarget->isFPOnlySP()) {
1110       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1111       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1112       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1113       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1114       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1115       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1116       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1117       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1118     }
1119   }
1120 
1121   if (Subtarget->hasNEON()) {
1122     // vmin and vmax aren't available in a scalar form, so we use
1123     // a NEON instruction with an undef lane instead.
1124     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1125     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1126     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1127     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1128     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1129     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1130   }
1131 
1132   // We have target-specific dag combine patterns for the following nodes:
1133   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1134   setTargetDAGCombine(ISD::ADD);
1135   setTargetDAGCombine(ISD::SUB);
1136   setTargetDAGCombine(ISD::MUL);
1137   setTargetDAGCombine(ISD::AND);
1138   setTargetDAGCombine(ISD::OR);
1139   setTargetDAGCombine(ISD::XOR);
1140 
1141   if (Subtarget->hasV6Ops())
1142     setTargetDAGCombine(ISD::SRL);
1143 
1144   setStackPointerRegisterToSaveRestore(ARM::SP);
1145 
1146   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1147       !Subtarget->hasVFP2())
1148     setSchedulingPreference(Sched::RegPressure);
1149   else
1150     setSchedulingPreference(Sched::Hybrid);
1151 
1152   //// temporary - rewrite interface to use type
1153   MaxStoresPerMemset = 8;
1154   MaxStoresPerMemsetOptSize = 4;
1155   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1156   MaxStoresPerMemcpyOptSize = 2;
1157   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1158   MaxStoresPerMemmoveOptSize = 2;
1159 
1160   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1161   // are at least 4 bytes aligned.
1162   setMinStackArgumentAlignment(4);
1163 
1164   // Prefer likely predicted branches to selects on out-of-order cores.
1165   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1166 
1167   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1168 }
1169 
1170 bool ARMTargetLowering::useSoftFloat() const {
1171   return Subtarget->useSoftFloat();
1172 }
1173 
1174 // FIXME: It might make sense to define the representative register class as the
1175 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1176 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1177 // SPR's representative would be DPR_VFP2. This should work well if register
1178 // pressure tracking were modified such that a register use would increment the
1179 // pressure of the register class's representative and all of it's super
1180 // classes' representatives transitively. We have not implemented this because
1181 // of the difficulty prior to coalescing of modeling operand register classes
1182 // due to the common occurrence of cross class copies and subregister insertions
1183 // and extractions.
1184 std::pair<const TargetRegisterClass *, uint8_t>
1185 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1186                                            MVT VT) const {
1187   const TargetRegisterClass *RRC = nullptr;
1188   uint8_t Cost = 1;
1189   switch (VT.SimpleTy) {
1190   default:
1191     return TargetLowering::findRepresentativeClass(TRI, VT);
1192   // Use DPR as representative register class for all floating point
1193   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1194   // the cost is 1 for both f32 and f64.
1195   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1196   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1197     RRC = &ARM::DPRRegClass;
1198     // When NEON is used for SP, only half of the register file is available
1199     // because operations that define both SP and DP results will be constrained
1200     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1201     // coalescing by double-counting the SP regs. See the FIXME above.
1202     if (Subtarget->useNEONForSinglePrecisionFP())
1203       Cost = 2;
1204     break;
1205   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1206   case MVT::v4f32: case MVT::v2f64:
1207     RRC = &ARM::DPRRegClass;
1208     Cost = 2;
1209     break;
1210   case MVT::v4i64:
1211     RRC = &ARM::DPRRegClass;
1212     Cost = 4;
1213     break;
1214   case MVT::v8i64:
1215     RRC = &ARM::DPRRegClass;
1216     Cost = 8;
1217     break;
1218   }
1219   return std::make_pair(RRC, Cost);
1220 }
1221 
1222 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1223   switch ((ARMISD::NodeType)Opcode) {
1224   case ARMISD::FIRST_NUMBER:  break;
1225   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1226   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1227   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1228   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1229   case ARMISD::CALL:          return "ARMISD::CALL";
1230   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1231   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1232   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1233   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1234   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1235   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1236   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1237   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1238   case ARMISD::CMP:           return "ARMISD::CMP";
1239   case ARMISD::CMN:           return "ARMISD::CMN";
1240   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1241   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1242   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1243   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1244   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1245 
1246   case ARMISD::CMOV:          return "ARMISD::CMOV";
1247 
1248   case ARMISD::SSAT:          return "ARMISD::SSAT";
1249   case ARMISD::USAT:          return "ARMISD::USAT";
1250 
1251   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1252   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1253   case ARMISD::RRX:           return "ARMISD::RRX";
1254 
1255   case ARMISD::ADDC:          return "ARMISD::ADDC";
1256   case ARMISD::ADDE:          return "ARMISD::ADDE";
1257   case ARMISD::SUBC:          return "ARMISD::SUBC";
1258   case ARMISD::SUBE:          return "ARMISD::SUBE";
1259 
1260   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1261   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1262 
1263   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1264   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1265   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1266 
1267   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1268 
1269   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1270 
1271   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1272 
1273   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1274 
1275   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1276 
1277   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1278   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1279 
1280   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1281   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1282   case ARMISD::VCGE:          return "ARMISD::VCGE";
1283   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1284   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1285   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1286   case ARMISD::VCGT:          return "ARMISD::VCGT";
1287   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1288   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1289   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1290   case ARMISD::VTST:          return "ARMISD::VTST";
1291 
1292   case ARMISD::VSHL:          return "ARMISD::VSHL";
1293   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1294   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1295   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1296   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1297   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1298   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1299   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1300   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1301   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1302   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1303   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1304   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1305   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1306   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1307   case ARMISD::VSLI:          return "ARMISD::VSLI";
1308   case ARMISD::VSRI:          return "ARMISD::VSRI";
1309   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1310   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1311   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1312   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1313   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1314   case ARMISD::VDUP:          return "ARMISD::VDUP";
1315   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1316   case ARMISD::VEXT:          return "ARMISD::VEXT";
1317   case ARMISD::VREV64:        return "ARMISD::VREV64";
1318   case ARMISD::VREV32:        return "ARMISD::VREV32";
1319   case ARMISD::VREV16:        return "ARMISD::VREV16";
1320   case ARMISD::VZIP:          return "ARMISD::VZIP";
1321   case ARMISD::VUZP:          return "ARMISD::VUZP";
1322   case ARMISD::VTRN:          return "ARMISD::VTRN";
1323   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1324   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1325   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1326   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1327   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1328   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1329   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1330   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1331   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1332   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1333   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1334   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1335   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1336   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1337   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1338   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1339   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1340   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1341   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1342   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1343   case ARMISD::BFI:           return "ARMISD::BFI";
1344   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1345   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1346   case ARMISD::VBSL:          return "ARMISD::VBSL";
1347   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1348   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1349   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1350   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1351   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1352   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1353   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1354   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1355   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1356   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1357   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1358   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1359   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1360   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1361   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1362   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1363   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1364   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1365   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1366   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1367   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1368   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1369   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1370   }
1371   return nullptr;
1372 }
1373 
1374 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1375                                           EVT VT) const {
1376   if (!VT.isVector())
1377     return getPointerTy(DL);
1378   return VT.changeVectorElementTypeToInteger();
1379 }
1380 
1381 /// getRegClassFor - Return the register class that should be used for the
1382 /// specified value type.
1383 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1384   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1385   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1386   // load / store 4 to 8 consecutive D registers.
1387   if (Subtarget->hasNEON()) {
1388     if (VT == MVT::v4i64)
1389       return &ARM::QQPRRegClass;
1390     if (VT == MVT::v8i64)
1391       return &ARM::QQQQPRRegClass;
1392   }
1393   return TargetLowering::getRegClassFor(VT);
1394 }
1395 
1396 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1397 // source/dest is aligned and the copy size is large enough. We therefore want
1398 // to align such objects passed to memory intrinsics.
1399 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1400                                                unsigned &PrefAlign) const {
1401   if (!isa<MemIntrinsic>(CI))
1402     return false;
1403   MinSize = 8;
1404   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1405   // cycle faster than 4-byte aligned LDM.
1406   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1407   return true;
1408 }
1409 
1410 // Create a fast isel object.
1411 FastISel *
1412 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1413                                   const TargetLibraryInfo *libInfo) const {
1414   return ARM::createFastISel(funcInfo, libInfo);
1415 }
1416 
1417 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1418   unsigned NumVals = N->getNumValues();
1419   if (!NumVals)
1420     return Sched::RegPressure;
1421 
1422   for (unsigned i = 0; i != NumVals; ++i) {
1423     EVT VT = N->getValueType(i);
1424     if (VT == MVT::Glue || VT == MVT::Other)
1425       continue;
1426     if (VT.isFloatingPoint() || VT.isVector())
1427       return Sched::ILP;
1428   }
1429 
1430   if (!N->isMachineOpcode())
1431     return Sched::RegPressure;
1432 
1433   // Load are scheduled for latency even if there instruction itinerary
1434   // is not available.
1435   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1436   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1437 
1438   if (MCID.getNumDefs() == 0)
1439     return Sched::RegPressure;
1440   if (!Itins->isEmpty() &&
1441       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1442     return Sched::ILP;
1443 
1444   return Sched::RegPressure;
1445 }
1446 
1447 //===----------------------------------------------------------------------===//
1448 // Lowering Code
1449 //===----------------------------------------------------------------------===//
1450 
1451 static bool isSRL16(const SDValue &Op) {
1452   if (Op.getOpcode() != ISD::SRL)
1453     return false;
1454   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1455     return Const->getZExtValue() == 16;
1456   return false;
1457 }
1458 
1459 static bool isSRA16(const SDValue &Op) {
1460   if (Op.getOpcode() != ISD::SRA)
1461     return false;
1462   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1463     return Const->getZExtValue() == 16;
1464   return false;
1465 }
1466 
1467 static bool isSHL16(const SDValue &Op) {
1468   if (Op.getOpcode() != ISD::SHL)
1469     return false;
1470   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1471     return Const->getZExtValue() == 16;
1472   return false;
1473 }
1474 
1475 // Check for a signed 16-bit value. We special case SRA because it makes it
1476 // more simple when also looking for SRAs that aren't sign extending a
1477 // smaller value. Without the check, we'd need to take extra care with
1478 // checking order for some operations.
1479 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1480   if (isSRA16(Op))
1481     return isSHL16(Op.getOperand(0));
1482   return DAG.ComputeNumSignBits(Op) == 17;
1483 }
1484 
1485 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1486 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1487   switch (CC) {
1488   default: llvm_unreachable("Unknown condition code!");
1489   case ISD::SETNE:  return ARMCC::NE;
1490   case ISD::SETEQ:  return ARMCC::EQ;
1491   case ISD::SETGT:  return ARMCC::GT;
1492   case ISD::SETGE:  return ARMCC::GE;
1493   case ISD::SETLT:  return ARMCC::LT;
1494   case ISD::SETLE:  return ARMCC::LE;
1495   case ISD::SETUGT: return ARMCC::HI;
1496   case ISD::SETUGE: return ARMCC::HS;
1497   case ISD::SETULT: return ARMCC::LO;
1498   case ISD::SETULE: return ARMCC::LS;
1499   }
1500 }
1501 
1502 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1503 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1504                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1505   CondCode2 = ARMCC::AL;
1506   InvalidOnQNaN = true;
1507   switch (CC) {
1508   default: llvm_unreachable("Unknown FP condition!");
1509   case ISD::SETEQ:
1510   case ISD::SETOEQ:
1511     CondCode = ARMCC::EQ;
1512     InvalidOnQNaN = false;
1513     break;
1514   case ISD::SETGT:
1515   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1516   case ISD::SETGE:
1517   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1518   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1519   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1520   case ISD::SETONE:
1521     CondCode = ARMCC::MI;
1522     CondCode2 = ARMCC::GT;
1523     InvalidOnQNaN = false;
1524     break;
1525   case ISD::SETO:   CondCode = ARMCC::VC; break;
1526   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1527   case ISD::SETUEQ:
1528     CondCode = ARMCC::EQ;
1529     CondCode2 = ARMCC::VS;
1530     InvalidOnQNaN = false;
1531     break;
1532   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1533   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1534   case ISD::SETLT:
1535   case ISD::SETULT: CondCode = ARMCC::LT; break;
1536   case ISD::SETLE:
1537   case ISD::SETULE: CondCode = ARMCC::LE; break;
1538   case ISD::SETNE:
1539   case ISD::SETUNE:
1540     CondCode = ARMCC::NE;
1541     InvalidOnQNaN = false;
1542     break;
1543   }
1544 }
1545 
1546 //===----------------------------------------------------------------------===//
1547 //                      Calling Convention Implementation
1548 //===----------------------------------------------------------------------===//
1549 
1550 #include "ARMGenCallingConv.inc"
1551 
1552 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1553 /// account presence of floating point hardware and calling convention
1554 /// limitations, such as support for variadic functions.
1555 CallingConv::ID
1556 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1557                                            bool isVarArg) const {
1558   switch (CC) {
1559   default:
1560     report_fatal_error("Unsupported calling convention");
1561   case CallingConv::ARM_AAPCS:
1562   case CallingConv::ARM_APCS:
1563   case CallingConv::GHC:
1564     return CC;
1565   case CallingConv::PreserveMost:
1566     return CallingConv::PreserveMost;
1567   case CallingConv::ARM_AAPCS_VFP:
1568   case CallingConv::Swift:
1569     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1570   case CallingConv::C:
1571     if (!Subtarget->isAAPCS_ABI())
1572       return CallingConv::ARM_APCS;
1573     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1574              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1575              !isVarArg)
1576       return CallingConv::ARM_AAPCS_VFP;
1577     else
1578       return CallingConv::ARM_AAPCS;
1579   case CallingConv::Fast:
1580   case CallingConv::CXX_FAST_TLS:
1581     if (!Subtarget->isAAPCS_ABI()) {
1582       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1583         return CallingConv::Fast;
1584       return CallingConv::ARM_APCS;
1585     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1586       return CallingConv::ARM_AAPCS_VFP;
1587     else
1588       return CallingConv::ARM_AAPCS;
1589   }
1590 }
1591 
1592 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1593                                                  bool isVarArg) const {
1594   return CCAssignFnForNode(CC, false, isVarArg);
1595 }
1596 
1597 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1598                                                    bool isVarArg) const {
1599   return CCAssignFnForNode(CC, true, isVarArg);
1600 }
1601 
1602 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1603 /// CallingConvention.
1604 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1605                                                  bool Return,
1606                                                  bool isVarArg) const {
1607   switch (getEffectiveCallingConv(CC, isVarArg)) {
1608   default:
1609     report_fatal_error("Unsupported calling convention");
1610   case CallingConv::ARM_APCS:
1611     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1612   case CallingConv::ARM_AAPCS:
1613     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1614   case CallingConv::ARM_AAPCS_VFP:
1615     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1616   case CallingConv::Fast:
1617     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1618   case CallingConv::GHC:
1619     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1620   case CallingConv::PreserveMost:
1621     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1622   }
1623 }
1624 
1625 /// LowerCallResult - Lower the result values of a call into the
1626 /// appropriate copies out of appropriate physical registers.
1627 SDValue ARMTargetLowering::LowerCallResult(
1628     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1629     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1630     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1631     SDValue ThisVal) const {
1632   // Assign locations to each value returned by this call.
1633   SmallVector<CCValAssign, 16> RVLocs;
1634   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1635                  *DAG.getContext());
1636   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1637 
1638   // Copy all of the result registers out of their specified physreg.
1639   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1640     CCValAssign VA = RVLocs[i];
1641 
1642     // Pass 'this' value directly from the argument to return value, to avoid
1643     // reg unit interference
1644     if (i == 0 && isThisReturn) {
1645       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1646              "unexpected return calling convention register assignment");
1647       InVals.push_back(ThisVal);
1648       continue;
1649     }
1650 
1651     SDValue Val;
1652     if (VA.needsCustom()) {
1653       // Handle f64 or half of a v2f64.
1654       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1655                                       InFlag);
1656       Chain = Lo.getValue(1);
1657       InFlag = Lo.getValue(2);
1658       VA = RVLocs[++i]; // skip ahead to next loc
1659       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1660                                       InFlag);
1661       Chain = Hi.getValue(1);
1662       InFlag = Hi.getValue(2);
1663       if (!Subtarget->isLittle())
1664         std::swap (Lo, Hi);
1665       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1666 
1667       if (VA.getLocVT() == MVT::v2f64) {
1668         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1669         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1670                           DAG.getConstant(0, dl, MVT::i32));
1671 
1672         VA = RVLocs[++i]; // skip ahead to next loc
1673         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1674         Chain = Lo.getValue(1);
1675         InFlag = Lo.getValue(2);
1676         VA = RVLocs[++i]; // skip ahead to next loc
1677         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1678         Chain = Hi.getValue(1);
1679         InFlag = Hi.getValue(2);
1680         if (!Subtarget->isLittle())
1681           std::swap (Lo, Hi);
1682         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1683         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1684                           DAG.getConstant(1, dl, MVT::i32));
1685       }
1686     } else {
1687       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1688                                InFlag);
1689       Chain = Val.getValue(1);
1690       InFlag = Val.getValue(2);
1691     }
1692 
1693     switch (VA.getLocInfo()) {
1694     default: llvm_unreachable("Unknown loc info!");
1695     case CCValAssign::Full: break;
1696     case CCValAssign::BCvt:
1697       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1698       break;
1699     }
1700 
1701     InVals.push_back(Val);
1702   }
1703 
1704   return Chain;
1705 }
1706 
1707 /// LowerMemOpCallTo - Store the argument to the stack.
1708 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1709                                             SDValue Arg, const SDLoc &dl,
1710                                             SelectionDAG &DAG,
1711                                             const CCValAssign &VA,
1712                                             ISD::ArgFlagsTy Flags) const {
1713   unsigned LocMemOffset = VA.getLocMemOffset();
1714   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1715   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1716                        StackPtr, PtrOff);
1717   return DAG.getStore(
1718       Chain, dl, Arg, PtrOff,
1719       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1720 }
1721 
1722 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1723                                          SDValue Chain, SDValue &Arg,
1724                                          RegsToPassVector &RegsToPass,
1725                                          CCValAssign &VA, CCValAssign &NextVA,
1726                                          SDValue &StackPtr,
1727                                          SmallVectorImpl<SDValue> &MemOpChains,
1728                                          ISD::ArgFlagsTy Flags) const {
1729   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1730                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1731   unsigned id = Subtarget->isLittle() ? 0 : 1;
1732   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1733 
1734   if (NextVA.isRegLoc())
1735     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1736   else {
1737     assert(NextVA.isMemLoc());
1738     if (!StackPtr.getNode())
1739       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1740                                     getPointerTy(DAG.getDataLayout()));
1741 
1742     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1743                                            dl, DAG, NextVA,
1744                                            Flags));
1745   }
1746 }
1747 
1748 /// LowerCall - Lowering a call into a callseq_start <-
1749 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1750 /// nodes.
1751 SDValue
1752 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1753                              SmallVectorImpl<SDValue> &InVals) const {
1754   SelectionDAG &DAG                     = CLI.DAG;
1755   SDLoc &dl                             = CLI.DL;
1756   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1757   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1758   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1759   SDValue Chain                         = CLI.Chain;
1760   SDValue Callee                        = CLI.Callee;
1761   bool &isTailCall                      = CLI.IsTailCall;
1762   CallingConv::ID CallConv              = CLI.CallConv;
1763   bool doesNotRet                       = CLI.DoesNotReturn;
1764   bool isVarArg                         = CLI.IsVarArg;
1765 
1766   MachineFunction &MF = DAG.getMachineFunction();
1767   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1768   bool isThisReturn   = false;
1769   bool isSibCall      = false;
1770   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1771 
1772   // Disable tail calls if they're not supported.
1773   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1774     isTailCall = false;
1775 
1776   if (isTailCall) {
1777     // Check if it's really possible to do a tail call.
1778     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1779                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1780                                                    Outs, OutVals, Ins, DAG);
1781     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1782       report_fatal_error("failed to perform tail call elimination on a call "
1783                          "site marked musttail");
1784     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1785     // detected sibcalls.
1786     if (isTailCall) {
1787       ++NumTailCalls;
1788       isSibCall = true;
1789     }
1790   }
1791 
1792   // Analyze operands of the call, assigning locations to each operand.
1793   SmallVector<CCValAssign, 16> ArgLocs;
1794   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1795                  *DAG.getContext());
1796   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1797 
1798   // Get a count of how many bytes are to be pushed on the stack.
1799   unsigned NumBytes = CCInfo.getNextStackOffset();
1800 
1801   // For tail calls, memory operands are available in our caller's stack.
1802   if (isSibCall)
1803     NumBytes = 0;
1804 
1805   // Adjust the stack pointer for the new arguments...
1806   // These operations are automatically eliminated by the prolog/epilog pass
1807   if (!isSibCall)
1808     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1809 
1810   SDValue StackPtr =
1811       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1812 
1813   RegsToPassVector RegsToPass;
1814   SmallVector<SDValue, 8> MemOpChains;
1815 
1816   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1817   // of tail call optimization, arguments are handled later.
1818   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1819        i != e;
1820        ++i, ++realArgIdx) {
1821     CCValAssign &VA = ArgLocs[i];
1822     SDValue Arg = OutVals[realArgIdx];
1823     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1824     bool isByVal = Flags.isByVal();
1825 
1826     // Promote the value if needed.
1827     switch (VA.getLocInfo()) {
1828     default: llvm_unreachable("Unknown loc info!");
1829     case CCValAssign::Full: break;
1830     case CCValAssign::SExt:
1831       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1832       break;
1833     case CCValAssign::ZExt:
1834       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1835       break;
1836     case CCValAssign::AExt:
1837       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1838       break;
1839     case CCValAssign::BCvt:
1840       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1841       break;
1842     }
1843 
1844     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1845     if (VA.needsCustom()) {
1846       if (VA.getLocVT() == MVT::v2f64) {
1847         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1848                                   DAG.getConstant(0, dl, MVT::i32));
1849         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1850                                   DAG.getConstant(1, dl, MVT::i32));
1851 
1852         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1853                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1854 
1855         VA = ArgLocs[++i]; // skip ahead to next loc
1856         if (VA.isRegLoc()) {
1857           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1858                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1859         } else {
1860           assert(VA.isMemLoc());
1861 
1862           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1863                                                  dl, DAG, VA, Flags));
1864         }
1865       } else {
1866         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1867                          StackPtr, MemOpChains, Flags);
1868       }
1869     } else if (VA.isRegLoc()) {
1870       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1871           Outs[0].VT == MVT::i32) {
1872         assert(VA.getLocVT() == MVT::i32 &&
1873                "unexpected calling convention register assignment");
1874         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1875                "unexpected use of 'returned'");
1876         isThisReturn = true;
1877       }
1878       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1879     } else if (isByVal) {
1880       assert(VA.isMemLoc());
1881       unsigned offset = 0;
1882 
1883       // True if this byval aggregate will be split between registers
1884       // and memory.
1885       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1886       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1887 
1888       if (CurByValIdx < ByValArgsCount) {
1889 
1890         unsigned RegBegin, RegEnd;
1891         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1892 
1893         EVT PtrVT =
1894             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1895         unsigned int i, j;
1896         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1897           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1898           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1899           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1900                                      MachinePointerInfo(),
1901                                      DAG.InferPtrAlignment(AddArg));
1902           MemOpChains.push_back(Load.getValue(1));
1903           RegsToPass.push_back(std::make_pair(j, Load));
1904         }
1905 
1906         // If parameter size outsides register area, "offset" value
1907         // helps us to calculate stack slot for remained part properly.
1908         offset = RegEnd - RegBegin;
1909 
1910         CCInfo.nextInRegsParam();
1911       }
1912 
1913       if (Flags.getByValSize() > 4*offset) {
1914         auto PtrVT = getPointerTy(DAG.getDataLayout());
1915         unsigned LocMemOffset = VA.getLocMemOffset();
1916         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1917         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1918         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1919         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1920         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1921                                            MVT::i32);
1922         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1923                                             MVT::i32);
1924 
1925         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1926         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1927         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1928                                           Ops));
1929       }
1930     } else if (!isSibCall) {
1931       assert(VA.isMemLoc());
1932 
1933       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1934                                              dl, DAG, VA, Flags));
1935     }
1936   }
1937 
1938   if (!MemOpChains.empty())
1939     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1940 
1941   // Build a sequence of copy-to-reg nodes chained together with token chain
1942   // and flag operands which copy the outgoing args into the appropriate regs.
1943   SDValue InFlag;
1944   // Tail call byval lowering might overwrite argument registers so in case of
1945   // tail call optimization the copies to registers are lowered later.
1946   if (!isTailCall)
1947     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1948       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1949                                RegsToPass[i].second, InFlag);
1950       InFlag = Chain.getValue(1);
1951     }
1952 
1953   // For tail calls lower the arguments to the 'real' stack slot.
1954   if (isTailCall) {
1955     // Force all the incoming stack arguments to be loaded from the stack
1956     // before any new outgoing arguments are stored to the stack, because the
1957     // outgoing stack slots may alias the incoming argument stack slots, and
1958     // the alias isn't otherwise explicit. This is slightly more conservative
1959     // than necessary, because it means that each store effectively depends
1960     // on every argument instead of just those arguments it would clobber.
1961 
1962     // Do not flag preceding copytoreg stuff together with the following stuff.
1963     InFlag = SDValue();
1964     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1965       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1966                                RegsToPass[i].second, InFlag);
1967       InFlag = Chain.getValue(1);
1968     }
1969     InFlag = SDValue();
1970   }
1971 
1972   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1973   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1974   // node so that legalize doesn't hack it.
1975   bool isDirect = false;
1976 
1977   const TargetMachine &TM = getTargetMachine();
1978   const Module *Mod = MF.getFunction().getParent();
1979   const GlobalValue *GV = nullptr;
1980   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1981     GV = G->getGlobal();
1982   bool isStub =
1983       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1984 
1985   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1986   bool isLocalARMFunc = false;
1987   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1988   auto PtrVt = getPointerTy(DAG.getDataLayout());
1989 
1990   if (Subtarget->genLongCalls()) {
1991     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1992            "long-calls codegen is not position independent!");
1993     // Handle a global address or an external symbol. If it's not one of
1994     // those, the target's already in a register, so we don't need to do
1995     // anything extra.
1996     if (isa<GlobalAddressSDNode>(Callee)) {
1997       // Create a constant pool entry for the callee address
1998       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1999       ARMConstantPoolValue *CPV =
2000         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2001 
2002       // Get the address of the callee into a register
2003       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2004       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2005       Callee = DAG.getLoad(
2006           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2007           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2008     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2009       const char *Sym = S->getSymbol();
2010 
2011       // Create a constant pool entry for the callee address
2012       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2013       ARMConstantPoolValue *CPV =
2014         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2015                                       ARMPCLabelIndex, 0);
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     }
2023   } else if (isa<GlobalAddressSDNode>(Callee)) {
2024     // If we're optimizing for minimum size and the function is called three or
2025     // more times in this block, we can improve codesize by calling indirectly
2026     // as BLXr has a 16-bit encoding.
2027     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2028     auto *BB = CLI.CS.getParent();
2029     bool PreferIndirect =
2030         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2031         count_if(GV->users(), [&BB](const User *U) {
2032           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2033         }) > 2;
2034 
2035     if (!PreferIndirect) {
2036       isDirect = true;
2037       bool isDef = GV->isStrongDefinitionForLinker();
2038 
2039       // ARM call to a local ARM function is predicable.
2040       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2041       // tBX takes a register source operand.
2042       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2043         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2044         Callee = DAG.getNode(
2045             ARMISD::WrapperPIC, dl, PtrVt,
2046             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2047         Callee = DAG.getLoad(
2048             PtrVt, dl, DAG.getEntryNode(), Callee,
2049             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2050             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2051                                      MachineMemOperand::MOInvariant);
2052       } else if (Subtarget->isTargetCOFF()) {
2053         assert(Subtarget->isTargetWindows() &&
2054                "Windows is the only supported COFF target");
2055         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2056                                    ? ARMII::MO_DLLIMPORT
2057                                    : ARMII::MO_NO_FLAG;
2058         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2059                                             TargetFlags);
2060         if (GV->hasDLLImportStorageClass())
2061           Callee =
2062               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2063                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2064                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2065       } else {
2066         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2067       }
2068     }
2069   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2070     isDirect = true;
2071     // tBX takes a register source operand.
2072     const char *Sym = S->getSymbol();
2073     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2074       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2075       ARMConstantPoolValue *CPV =
2076         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2077                                       ARMPCLabelIndex, 4);
2078       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2079       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2080       Callee = DAG.getLoad(
2081           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2082           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2083       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2084       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2085     } else {
2086       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2087     }
2088   }
2089 
2090   // FIXME: handle tail calls differently.
2091   unsigned CallOpc;
2092   if (Subtarget->isThumb()) {
2093     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2094       CallOpc = ARMISD::CALL_NOLINK;
2095     else
2096       CallOpc = ARMISD::CALL;
2097   } else {
2098     if (!isDirect && !Subtarget->hasV5TOps())
2099       CallOpc = ARMISD::CALL_NOLINK;
2100     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2101              // Emit regular call when code size is the priority
2102              !MF.getFunction().optForMinSize())
2103       // "mov lr, pc; b _foo" to avoid confusing the RSP
2104       CallOpc = ARMISD::CALL_NOLINK;
2105     else
2106       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2107   }
2108 
2109   std::vector<SDValue> Ops;
2110   Ops.push_back(Chain);
2111   Ops.push_back(Callee);
2112 
2113   // Add argument registers to the end of the list so that they are known live
2114   // into the call.
2115   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2116     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2117                                   RegsToPass[i].second.getValueType()));
2118 
2119   // Add a register mask operand representing the call-preserved registers.
2120   if (!isTailCall) {
2121     const uint32_t *Mask;
2122     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2123     if (isThisReturn) {
2124       // For 'this' returns, use the R0-preserving mask if applicable
2125       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2126       if (!Mask) {
2127         // Set isThisReturn to false if the calling convention is not one that
2128         // allows 'returned' to be modeled in this way, so LowerCallResult does
2129         // not try to pass 'this' straight through
2130         isThisReturn = false;
2131         Mask = ARI->getCallPreservedMask(MF, CallConv);
2132       }
2133     } else
2134       Mask = ARI->getCallPreservedMask(MF, CallConv);
2135 
2136     assert(Mask && "Missing call preserved mask for calling convention");
2137     Ops.push_back(DAG.getRegisterMask(Mask));
2138   }
2139 
2140   if (InFlag.getNode())
2141     Ops.push_back(InFlag);
2142 
2143   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2144   if (isTailCall) {
2145     MF.getFrameInfo().setHasTailCall();
2146     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2147   }
2148 
2149   // Returns a chain and a flag for retval copy to use.
2150   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2151   InFlag = Chain.getValue(1);
2152 
2153   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2154                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2155   if (!Ins.empty())
2156     InFlag = Chain.getValue(1);
2157 
2158   // Handle result values, copying them out of physregs into vregs that we
2159   // return.
2160   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2161                          InVals, isThisReturn,
2162                          isThisReturn ? OutVals[0] : SDValue());
2163 }
2164 
2165 /// HandleByVal - Every parameter *after* a byval parameter is passed
2166 /// on the stack.  Remember the next parameter register to allocate,
2167 /// and then confiscate the rest of the parameter registers to insure
2168 /// this.
2169 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2170                                     unsigned Align) const {
2171   // Byval (as with any stack) slots are always at least 4 byte aligned.
2172   Align = std::max(Align, 4U);
2173 
2174   unsigned Reg = State->AllocateReg(GPRArgRegs);
2175   if (!Reg)
2176     return;
2177 
2178   unsigned AlignInRegs = Align / 4;
2179   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2180   for (unsigned i = 0; i < Waste; ++i)
2181     Reg = State->AllocateReg(GPRArgRegs);
2182 
2183   if (!Reg)
2184     return;
2185 
2186   unsigned Excess = 4 * (ARM::R4 - Reg);
2187 
2188   // Special case when NSAA != SP and parameter size greater than size of
2189   // all remained GPR regs. In that case we can't split parameter, we must
2190   // send it to stack. We also must set NCRN to R4, so waste all
2191   // remained registers.
2192   const unsigned NSAAOffset = State->getNextStackOffset();
2193   if (NSAAOffset != 0 && Size > Excess) {
2194     while (State->AllocateReg(GPRArgRegs))
2195       ;
2196     return;
2197   }
2198 
2199   // First register for byval parameter is the first register that wasn't
2200   // allocated before this method call, so it would be "reg".
2201   // If parameter is small enough to be saved in range [reg, r4), then
2202   // the end (first after last) register would be reg + param-size-in-regs,
2203   // else parameter would be splitted between registers and stack,
2204   // end register would be r4 in this case.
2205   unsigned ByValRegBegin = Reg;
2206   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2207   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2208   // Note, first register is allocated in the beginning of function already,
2209   // allocate remained amount of registers we need.
2210   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2211     State->AllocateReg(GPRArgRegs);
2212   // A byval parameter that is split between registers and memory needs its
2213   // size truncated here.
2214   // In the case where the entire structure fits in registers, we set the
2215   // size in memory to zero.
2216   Size = std::max<int>(Size - Excess, 0);
2217 }
2218 
2219 /// MatchingStackOffset - Return true if the given stack call argument is
2220 /// already available in the same position (relatively) of the caller's
2221 /// incoming argument stack.
2222 static
2223 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2224                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2225                          const TargetInstrInfo *TII) {
2226   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2227   int FI = std::numeric_limits<int>::max();
2228   if (Arg.getOpcode() == ISD::CopyFromReg) {
2229     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2230     if (!TargetRegisterInfo::isVirtualRegister(VR))
2231       return false;
2232     MachineInstr *Def = MRI->getVRegDef(VR);
2233     if (!Def)
2234       return false;
2235     if (!Flags.isByVal()) {
2236       if (!TII->isLoadFromStackSlot(*Def, FI))
2237         return false;
2238     } else {
2239       return false;
2240     }
2241   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2242     if (Flags.isByVal())
2243       // ByVal argument is passed in as a pointer but it's now being
2244       // dereferenced. e.g.
2245       // define @foo(%struct.X* %A) {
2246       //   tail call @bar(%struct.X* byval %A)
2247       // }
2248       return false;
2249     SDValue Ptr = Ld->getBasePtr();
2250     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2251     if (!FINode)
2252       return false;
2253     FI = FINode->getIndex();
2254   } else
2255     return false;
2256 
2257   assert(FI != std::numeric_limits<int>::max());
2258   if (!MFI.isFixedObjectIndex(FI))
2259     return false;
2260   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2261 }
2262 
2263 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2264 /// for tail call optimization. Targets which want to do tail call
2265 /// optimization should implement this function.
2266 bool
2267 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2268                                                      CallingConv::ID CalleeCC,
2269                                                      bool isVarArg,
2270                                                      bool isCalleeStructRet,
2271                                                      bool isCallerStructRet,
2272                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2273                                     const SmallVectorImpl<SDValue> &OutVals,
2274                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2275                                                      SelectionDAG& DAG) const {
2276   MachineFunction &MF = DAG.getMachineFunction();
2277   const Function &CallerF = MF.getFunction();
2278   CallingConv::ID CallerCC = CallerF.getCallingConv();
2279 
2280   assert(Subtarget->supportsTailCall());
2281 
2282   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2283   // to the call take up r0-r3. The reason is that there are no legal registers
2284   // left to hold the pointer to the function to be called.
2285   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2286       !isa<GlobalAddressSDNode>(Callee.getNode()))
2287       return false;
2288 
2289   // Look for obvious safe cases to perform tail call optimization that do not
2290   // require ABI changes. This is what gcc calls sibcall.
2291 
2292   // Exception-handling functions need a special set of instructions to indicate
2293   // a return to the hardware. Tail-calling another function would probably
2294   // break this.
2295   if (CallerF.hasFnAttribute("interrupt"))
2296     return false;
2297 
2298   // Also avoid sibcall optimization if either caller or callee uses struct
2299   // return semantics.
2300   if (isCalleeStructRet || isCallerStructRet)
2301     return false;
2302 
2303   // Externally-defined functions with weak linkage should not be
2304   // tail-called on ARM when the OS does not support dynamic
2305   // pre-emption of symbols, as the AAELF spec requires normal calls
2306   // to undefined weak functions to be replaced with a NOP or jump to the
2307   // next instruction. The behaviour of branch instructions in this
2308   // situation (as used for tail calls) is implementation-defined, so we
2309   // cannot rely on the linker replacing the tail call with a return.
2310   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2311     const GlobalValue *GV = G->getGlobal();
2312     const Triple &TT = getTargetMachine().getTargetTriple();
2313     if (GV->hasExternalWeakLinkage() &&
2314         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2315       return false;
2316   }
2317 
2318   // Check that the call results are passed in the same way.
2319   LLVMContext &C = *DAG.getContext();
2320   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2321                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2322                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2323     return false;
2324   // The callee has to preserve all registers the caller needs to preserve.
2325   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2326   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2327   if (CalleeCC != CallerCC) {
2328     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2329     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2330       return false;
2331   }
2332 
2333   // If Caller's vararg or byval argument has been split between registers and
2334   // stack, do not perform tail call, since part of the argument is in caller's
2335   // local frame.
2336   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2337   if (AFI_Caller->getArgRegsSaveSize())
2338     return false;
2339 
2340   // If the callee takes no arguments then go on to check the results of the
2341   // call.
2342   if (!Outs.empty()) {
2343     // Check if stack adjustment is needed. For now, do not do this if any
2344     // argument is passed on the stack.
2345     SmallVector<CCValAssign, 16> ArgLocs;
2346     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2347     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2348     if (CCInfo.getNextStackOffset()) {
2349       // Check if the arguments are already laid out in the right way as
2350       // the caller's fixed stack objects.
2351       MachineFrameInfo &MFI = MF.getFrameInfo();
2352       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2353       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2354       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2355            i != e;
2356            ++i, ++realArgIdx) {
2357         CCValAssign &VA = ArgLocs[i];
2358         EVT RegVT = VA.getLocVT();
2359         SDValue Arg = OutVals[realArgIdx];
2360         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2361         if (VA.getLocInfo() == CCValAssign::Indirect)
2362           return false;
2363         if (VA.needsCustom()) {
2364           // f64 and vector types are split into multiple registers or
2365           // register/stack-slot combinations.  The types will not match
2366           // the registers; give up on memory f64 refs until we figure
2367           // out what to do about this.
2368           if (!VA.isRegLoc())
2369             return false;
2370           if (!ArgLocs[++i].isRegLoc())
2371             return false;
2372           if (RegVT == MVT::v2f64) {
2373             if (!ArgLocs[++i].isRegLoc())
2374               return false;
2375             if (!ArgLocs[++i].isRegLoc())
2376               return false;
2377           }
2378         } else if (!VA.isRegLoc()) {
2379           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2380                                    MFI, MRI, TII))
2381             return false;
2382         }
2383       }
2384     }
2385 
2386     const MachineRegisterInfo &MRI = MF.getRegInfo();
2387     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2388       return false;
2389   }
2390 
2391   return true;
2392 }
2393 
2394 bool
2395 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2396                                   MachineFunction &MF, bool isVarArg,
2397                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2398                                   LLVMContext &Context) const {
2399   SmallVector<CCValAssign, 16> RVLocs;
2400   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2401   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2402 }
2403 
2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2405                                     const SDLoc &DL, SelectionDAG &DAG) {
2406   const MachineFunction &MF = DAG.getMachineFunction();
2407   const Function &F = MF.getFunction();
2408 
2409   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2410 
2411   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2412   // version of the "preferred return address". These offsets affect the return
2413   // instruction if this is a return from PL1 without hypervisor extensions.
2414   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2415   //    SWI:     0      "subs pc, lr, #0"
2416   //    ABORT:   +4     "subs pc, lr, #4"
2417   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2418   // UNDEF varies depending on where the exception came from ARM or Thumb
2419   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2420 
2421   int64_t LROffset;
2422   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2423       IntKind == "ABORT")
2424     LROffset = 4;
2425   else if (IntKind == "SWI" || IntKind == "UNDEF")
2426     LROffset = 0;
2427   else
2428     report_fatal_error("Unsupported interrupt attribute. If present, value "
2429                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2430 
2431   RetOps.insert(RetOps.begin() + 1,
2432                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2433 
2434   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2435 }
2436 
2437 SDValue
2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2439                                bool isVarArg,
2440                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2441                                const SmallVectorImpl<SDValue> &OutVals,
2442                                const SDLoc &dl, SelectionDAG &DAG) const {
2443   // CCValAssign - represent the assignment of the return value to a location.
2444   SmallVector<CCValAssign, 16> RVLocs;
2445 
2446   // CCState - Info about the registers and stack slots.
2447   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2448                  *DAG.getContext());
2449 
2450   // Analyze outgoing return values.
2451   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2452 
2453   SDValue Flag;
2454   SmallVector<SDValue, 4> RetOps;
2455   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2456   bool isLittleEndian = Subtarget->isLittle();
2457 
2458   MachineFunction &MF = DAG.getMachineFunction();
2459   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2460   AFI->setReturnRegsCount(RVLocs.size());
2461 
2462   // Copy the result values into the output registers.
2463   for (unsigned i = 0, realRVLocIdx = 0;
2464        i != RVLocs.size();
2465        ++i, ++realRVLocIdx) {
2466     CCValAssign &VA = RVLocs[i];
2467     assert(VA.isRegLoc() && "Can only return in registers!");
2468 
2469     SDValue Arg = OutVals[realRVLocIdx];
2470 
2471     switch (VA.getLocInfo()) {
2472     default: llvm_unreachable("Unknown loc info!");
2473     case CCValAssign::Full: break;
2474     case CCValAssign::BCvt:
2475       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2476       break;
2477     }
2478 
2479     if (VA.needsCustom()) {
2480       if (VA.getLocVT() == MVT::v2f64) {
2481         // Extract the first half and return it in two registers.
2482         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2483                                    DAG.getConstant(0, dl, MVT::i32));
2484         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2485                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2486 
2487         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2488                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2489                                  Flag);
2490         Flag = Chain.getValue(1);
2491         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2492         VA = RVLocs[++i]; // skip ahead to next loc
2493         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2494                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2495                                  Flag);
2496         Flag = Chain.getValue(1);
2497         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2498         VA = RVLocs[++i]; // skip ahead to next loc
2499 
2500         // Extract the 2nd half and fall through to handle it as an f64 value.
2501         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2502                           DAG.getConstant(1, dl, MVT::i32));
2503       }
2504       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2505       // available.
2506       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2507                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2508       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2509                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2510                                Flag);
2511       Flag = Chain.getValue(1);
2512       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2513       VA = RVLocs[++i]; // skip ahead to next loc
2514       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2515                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2516                                Flag);
2517     } else
2518       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2519 
2520     // Guarantee that all emitted copies are
2521     // stuck together, avoiding something bad.
2522     Flag = Chain.getValue(1);
2523     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2524   }
2525   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2526   const MCPhysReg *I =
2527       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2528   if (I) {
2529     for (; *I; ++I) {
2530       if (ARM::GPRRegClass.contains(*I))
2531         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2532       else if (ARM::DPRRegClass.contains(*I))
2533         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2534       else
2535         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2536     }
2537   }
2538 
2539   // Update chain and glue.
2540   RetOps[0] = Chain;
2541   if (Flag.getNode())
2542     RetOps.push_back(Flag);
2543 
2544   // CPUs which aren't M-class use a special sequence to return from
2545   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2546   // though we use "subs pc, lr, #N").
2547   //
2548   // M-class CPUs actually use a normal return sequence with a special
2549   // (hardware-provided) value in LR, so the normal code path works.
2550   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2551       !Subtarget->isMClass()) {
2552     if (Subtarget->isThumb1Only())
2553       report_fatal_error("interrupt attribute is not supported in Thumb1");
2554     return LowerInterruptReturn(RetOps, dl, DAG);
2555   }
2556 
2557   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2558 }
2559 
2560 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2561   if (N->getNumValues() != 1)
2562     return false;
2563   if (!N->hasNUsesOfValue(1, 0))
2564     return false;
2565 
2566   SDValue TCChain = Chain;
2567   SDNode *Copy = *N->use_begin();
2568   if (Copy->getOpcode() == ISD::CopyToReg) {
2569     // If the copy has a glue operand, we conservatively assume it isn't safe to
2570     // perform a tail call.
2571     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2572       return false;
2573     TCChain = Copy->getOperand(0);
2574   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2575     SDNode *VMov = Copy;
2576     // f64 returned in a pair of GPRs.
2577     SmallPtrSet<SDNode*, 2> Copies;
2578     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2579          UI != UE; ++UI) {
2580       if (UI->getOpcode() != ISD::CopyToReg)
2581         return false;
2582       Copies.insert(*UI);
2583     }
2584     if (Copies.size() > 2)
2585       return false;
2586 
2587     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2588          UI != UE; ++UI) {
2589       SDValue UseChain = UI->getOperand(0);
2590       if (Copies.count(UseChain.getNode()))
2591         // Second CopyToReg
2592         Copy = *UI;
2593       else {
2594         // We are at the top of this chain.
2595         // If the copy has a glue operand, we conservatively assume it
2596         // isn't safe to perform a tail call.
2597         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2598           return false;
2599         // First CopyToReg
2600         TCChain = UseChain;
2601       }
2602     }
2603   } else if (Copy->getOpcode() == ISD::BITCAST) {
2604     // f32 returned in a single GPR.
2605     if (!Copy->hasOneUse())
2606       return false;
2607     Copy = *Copy->use_begin();
2608     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2609       return false;
2610     // If the copy has a glue operand, we conservatively assume it isn't safe to
2611     // perform a tail call.
2612     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2613       return false;
2614     TCChain = Copy->getOperand(0);
2615   } else {
2616     return false;
2617   }
2618 
2619   bool HasRet = false;
2620   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2621        UI != UE; ++UI) {
2622     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2623         UI->getOpcode() != ARMISD::INTRET_FLAG)
2624       return false;
2625     HasRet = true;
2626   }
2627 
2628   if (!HasRet)
2629     return false;
2630 
2631   Chain = TCChain;
2632   return true;
2633 }
2634 
2635 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2636   if (!Subtarget->supportsTailCall())
2637     return false;
2638 
2639   auto Attr =
2640       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2641   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2642     return false;
2643 
2644   return true;
2645 }
2646 
2647 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2648 // and pass the lower and high parts through.
2649 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2650   SDLoc DL(Op);
2651   SDValue WriteValue = Op->getOperand(2);
2652 
2653   // This function is only supposed to be called for i64 type argument.
2654   assert(WriteValue.getValueType() == MVT::i64
2655           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2656 
2657   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2658                            DAG.getConstant(0, DL, MVT::i32));
2659   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2660                            DAG.getConstant(1, DL, MVT::i32));
2661   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2662   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2663 }
2664 
2665 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2666 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2667 // one of the above mentioned nodes. It has to be wrapped because otherwise
2668 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2669 // be used to form addressing mode. These wrapped nodes will be selected
2670 // into MOVi.
2671 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2672                                              SelectionDAG &DAG) const {
2673   EVT PtrVT = Op.getValueType();
2674   // FIXME there is no actual debug info here
2675   SDLoc dl(Op);
2676   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2677   SDValue Res;
2678 
2679   // When generating execute-only code Constant Pools must be promoted to the
2680   // global data section. It's a bit ugly that we can't share them across basic
2681   // blocks, but this way we guarantee that execute-only behaves correct with
2682   // position-independent addressing modes.
2683   if (Subtarget->genExecuteOnly()) {
2684     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2685     auto T = const_cast<Type*>(CP->getType());
2686     auto C = const_cast<Constant*>(CP->getConstVal());
2687     auto M = const_cast<Module*>(DAG.getMachineFunction().
2688                                  getFunction().getParent());
2689     auto GV = new GlobalVariable(
2690                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2691                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2692                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2693                     Twine(AFI->createPICLabelUId())
2694                   );
2695     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2696                                             dl, PtrVT);
2697     return LowerGlobalAddress(GA, DAG);
2698   }
2699 
2700   if (CP->isMachineConstantPoolEntry())
2701     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2702                                     CP->getAlignment());
2703   else
2704     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2705                                     CP->getAlignment());
2706   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2707 }
2708 
2709 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2710   return MachineJumpTableInfo::EK_Inline;
2711 }
2712 
2713 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2714                                              SelectionDAG &DAG) const {
2715   MachineFunction &MF = DAG.getMachineFunction();
2716   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2717   unsigned ARMPCLabelIndex = 0;
2718   SDLoc DL(Op);
2719   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2720   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2721   SDValue CPAddr;
2722   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2723   if (!IsPositionIndependent) {
2724     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2725   } else {
2726     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2727     ARMPCLabelIndex = AFI->createPICLabelUId();
2728     ARMConstantPoolValue *CPV =
2729       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2730                                       ARMCP::CPBlockAddress, PCAdj);
2731     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2732   }
2733   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2734   SDValue Result = DAG.getLoad(
2735       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2736       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2737   if (!IsPositionIndependent)
2738     return Result;
2739   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2740   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2741 }
2742 
2743 /// \brief Convert a TLS address reference into the correct sequence of loads
2744 /// and calls to compute the variable's address for Darwin, and return an
2745 /// SDValue containing the final node.
2746 
2747 /// Darwin only has one TLS scheme which must be capable of dealing with the
2748 /// fully general situation, in the worst case. This means:
2749 ///     + "extern __thread" declaration.
2750 ///     + Defined in a possibly unknown dynamic library.
2751 ///
2752 /// The general system is that each __thread variable has a [3 x i32] descriptor
2753 /// which contains information used by the runtime to calculate the address. The
2754 /// only part of this the compiler needs to know about is the first word, which
2755 /// contains a function pointer that must be called with the address of the
2756 /// entire descriptor in "r0".
2757 ///
2758 /// Since this descriptor may be in a different unit, in general access must
2759 /// proceed along the usual ARM rules. A common sequence to produce is:
2760 ///
2761 ///     movw rT1, :lower16:_var$non_lazy_ptr
2762 ///     movt rT1, :upper16:_var$non_lazy_ptr
2763 ///     ldr r0, [rT1]
2764 ///     ldr rT2, [r0]
2765 ///     blx rT2
2766 ///     [...address now in r0...]
2767 SDValue
2768 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2769                                                SelectionDAG &DAG) const {
2770   assert(Subtarget->isTargetDarwin() &&
2771          "This function expects a Darwin target");
2772   SDLoc DL(Op);
2773 
2774   // First step is to get the address of the actua global symbol. This is where
2775   // the TLS descriptor lives.
2776   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2777 
2778   // The first entry in the descriptor is a function pointer that we must call
2779   // to obtain the address of the variable.
2780   SDValue Chain = DAG.getEntryNode();
2781   SDValue FuncTLVGet = DAG.getLoad(
2782       MVT::i32, DL, Chain, DescAddr,
2783       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2784       /* Alignment = */ 4,
2785       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2786           MachineMemOperand::MOInvariant);
2787   Chain = FuncTLVGet.getValue(1);
2788 
2789   MachineFunction &F = DAG.getMachineFunction();
2790   MachineFrameInfo &MFI = F.getFrameInfo();
2791   MFI.setAdjustsStack(true);
2792 
2793   // TLS calls preserve all registers except those that absolutely must be
2794   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2795   // silly).
2796   auto TRI =
2797       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2798   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2799   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2800 
2801   // Finally, we can make the call. This is just a degenerate version of a
2802   // normal AArch64 call node: r0 takes the address of the descriptor, and
2803   // returns the address of the variable in this thread.
2804   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2805   Chain =
2806       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2807                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2808                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2809   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2810 }
2811 
2812 SDValue
2813 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2814                                                 SelectionDAG &DAG) const {
2815   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2816 
2817   SDValue Chain = DAG.getEntryNode();
2818   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2819   SDLoc DL(Op);
2820 
2821   // Load the current TEB (thread environment block)
2822   SDValue Ops[] = {Chain,
2823                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2824                    DAG.getConstant(15, DL, MVT::i32),
2825                    DAG.getConstant(0, DL, MVT::i32),
2826                    DAG.getConstant(13, DL, MVT::i32),
2827                    DAG.getConstant(0, DL, MVT::i32),
2828                    DAG.getConstant(2, DL, MVT::i32)};
2829   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2830                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2831 
2832   SDValue TEB = CurrentTEB.getValue(0);
2833   Chain = CurrentTEB.getValue(1);
2834 
2835   // Load the ThreadLocalStoragePointer from the TEB
2836   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2837   SDValue TLSArray =
2838       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2839   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2840 
2841   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2842   // offset into the TLSArray.
2843 
2844   // Load the TLS index from the C runtime
2845   SDValue TLSIndex =
2846       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2847   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2848   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2849 
2850   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2851                               DAG.getConstant(2, DL, MVT::i32));
2852   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2853                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2854                             MachinePointerInfo());
2855 
2856   // Get the offset of the start of the .tls section (section base)
2857   const auto *GA = cast<GlobalAddressSDNode>(Op);
2858   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2859   SDValue Offset = DAG.getLoad(
2860       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2861                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2862       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2863 
2864   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2865 }
2866 
2867 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2868 SDValue
2869 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2870                                                  SelectionDAG &DAG) const {
2871   SDLoc dl(GA);
2872   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2873   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2874   MachineFunction &MF = DAG.getMachineFunction();
2875   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2876   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2877   ARMConstantPoolValue *CPV =
2878     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2879                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2880   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2881   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2882   Argument = DAG.getLoad(
2883       PtrVT, dl, DAG.getEntryNode(), Argument,
2884       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2885   SDValue Chain = Argument.getValue(1);
2886 
2887   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2888   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2889 
2890   // call __tls_get_addr.
2891   ArgListTy Args;
2892   ArgListEntry Entry;
2893   Entry.Node = Argument;
2894   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2895   Args.push_back(Entry);
2896 
2897   // FIXME: is there useful debug info available here?
2898   TargetLowering::CallLoweringInfo CLI(DAG);
2899   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2900       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2901       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2902 
2903   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2904   return CallResult.first;
2905 }
2906 
2907 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2908 // "local exec" model.
2909 SDValue
2910 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2911                                         SelectionDAG &DAG,
2912                                         TLSModel::Model model) const {
2913   const GlobalValue *GV = GA->getGlobal();
2914   SDLoc dl(GA);
2915   SDValue Offset;
2916   SDValue Chain = DAG.getEntryNode();
2917   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2918   // Get the Thread Pointer
2919   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2920 
2921   if (model == TLSModel::InitialExec) {
2922     MachineFunction &MF = DAG.getMachineFunction();
2923     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2924     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2925     // Initial exec model.
2926     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2927     ARMConstantPoolValue *CPV =
2928       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2929                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2930                                       true);
2931     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2932     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2933     Offset = DAG.getLoad(
2934         PtrVT, dl, Chain, Offset,
2935         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2936     Chain = Offset.getValue(1);
2937 
2938     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2939     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2940 
2941     Offset = DAG.getLoad(
2942         PtrVT, dl, Chain, Offset,
2943         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2944   } else {
2945     // local exec model
2946     assert(model == TLSModel::LocalExec);
2947     ARMConstantPoolValue *CPV =
2948       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2949     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2951     Offset = DAG.getLoad(
2952         PtrVT, dl, Chain, Offset,
2953         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2954   }
2955 
2956   // The address of the thread local variable is the add of the thread
2957   // pointer with the offset of the variable.
2958   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2959 }
2960 
2961 SDValue
2962 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2963   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2964   if (DAG.getTarget().Options.EmulatedTLS)
2965     return LowerToTLSEmulatedModel(GA, DAG);
2966 
2967   if (Subtarget->isTargetDarwin())
2968     return LowerGlobalTLSAddressDarwin(Op, DAG);
2969 
2970   if (Subtarget->isTargetWindows())
2971     return LowerGlobalTLSAddressWindows(Op, DAG);
2972 
2973   // TODO: implement the "local dynamic" model
2974   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2975   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2976 
2977   switch (model) {
2978     case TLSModel::GeneralDynamic:
2979     case TLSModel::LocalDynamic:
2980       return LowerToTLSGeneralDynamicModel(GA, DAG);
2981     case TLSModel::InitialExec:
2982     case TLSModel::LocalExec:
2983       return LowerToTLSExecModels(GA, DAG, model);
2984   }
2985   llvm_unreachable("bogus TLS model");
2986 }
2987 
2988 /// Return true if all users of V are within function F, looking through
2989 /// ConstantExprs.
2990 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2991   SmallVector<const User*,4> Worklist;
2992   for (auto *U : V->users())
2993     Worklist.push_back(U);
2994   while (!Worklist.empty()) {
2995     auto *U = Worklist.pop_back_val();
2996     if (isa<ConstantExpr>(U)) {
2997       for (auto *UU : U->users())
2998         Worklist.push_back(UU);
2999       continue;
3000     }
3001 
3002     auto *I = dyn_cast<Instruction>(U);
3003     if (!I || I->getParent()->getParent() != F)
3004       return false;
3005   }
3006   return true;
3007 }
3008 
3009 /// Return true if all users of V are within some (any) function, looking through
3010 /// ConstantExprs. In other words, are there any global constant users?
3011 static bool allUsersAreInFunctions(const Value *V) {
3012   SmallVector<const User*,4> Worklist;
3013   for (auto *U : V->users())
3014     Worklist.push_back(U);
3015   while (!Worklist.empty()) {
3016     auto *U = Worklist.pop_back_val();
3017     if (isa<ConstantExpr>(U)) {
3018       for (auto *UU : U->users())
3019         Worklist.push_back(UU);
3020       continue;
3021     }
3022 
3023     if (!isa<Instruction>(U))
3024       return false;
3025   }
3026   return true;
3027 }
3028 
3029 // Return true if T is an integer, float or an array/vector of either.
3030 static bool isSimpleType(Type *T) {
3031   if (T->isIntegerTy() || T->isFloatingPointTy())
3032     return true;
3033   Type *SubT = nullptr;
3034   if (T->isArrayTy())
3035     SubT = T->getArrayElementType();
3036   else if (T->isVectorTy())
3037     SubT = T->getVectorElementType();
3038   else
3039     return false;
3040   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3041 }
3042 
3043 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3044                                      EVT PtrVT, const SDLoc &dl) {
3045   // If we're creating a pool entry for a constant global with unnamed address,
3046   // and the global is small enough, we can emit it inline into the constant pool
3047   // to save ourselves an indirection.
3048   //
3049   // This is a win if the constant is only used in one function (so it doesn't
3050   // need to be duplicated) or duplicating the constant wouldn't increase code
3051   // size (implying the constant is no larger than 4 bytes).
3052   const Function &F = DAG.getMachineFunction().getFunction();
3053 
3054   // We rely on this decision to inline being idemopotent and unrelated to the
3055   // use-site. We know that if we inline a variable at one use site, we'll
3056   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3057   // doesn't know about this optimization, so bail out if it's enabled else
3058   // we could decide to inline here (and thus never emit the GV) but require
3059   // the GV from fast-isel generated code.
3060   if (!EnableConstpoolPromotion ||
3061       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3062       return SDValue();
3063 
3064   auto *GVar = dyn_cast<GlobalVariable>(GV);
3065   if (!GVar || !GVar->hasInitializer() ||
3066       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3067       !GVar->hasLocalLinkage())
3068     return SDValue();
3069 
3070   // Ensure that we don't try and inline any type that contains pointers. If
3071   // we inline a value that contains relocations, we move the relocations from
3072   // .data to .text which is not ideal.
3073   auto *Init = GVar->getInitializer();
3074   if (!isSimpleType(Init->getType()))
3075     return SDValue();
3076 
3077   // The constant islands pass can only really deal with alignment requests
3078   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3079   // any type wanting greater alignment requirements than 4 bytes. We also
3080   // can only promote constants that are multiples of 4 bytes in size or
3081   // are paddable to a multiple of 4. Currently we only try and pad constants
3082   // that are strings for simplicity.
3083   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3084   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3085   unsigned Align = GVar->getAlignment();
3086   unsigned RequiredPadding = 4 - (Size % 4);
3087   bool PaddingPossible =
3088     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3089   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3090       Size == 0)
3091     return SDValue();
3092 
3093   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3094   MachineFunction &MF = DAG.getMachineFunction();
3095   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3096 
3097   // We can't bloat the constant pool too much, else the ConstantIslands pass
3098   // may fail to converge. If we haven't promoted this global yet (it may have
3099   // multiple uses), and promoting it would increase the constant pool size (Sz
3100   // > 4), ensure we have space to do so up to MaxTotal.
3101   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3102     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3103         ConstpoolPromotionMaxTotal)
3104       return SDValue();
3105 
3106   // This is only valid if all users are in a single function OR it has users
3107   // in multiple functions but it no larger than a pointer. We also check if
3108   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3109   // address taken.
3110   if (!allUsersAreInFunction(GVar, &F) &&
3111       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3112     return SDValue();
3113 
3114   // We're going to inline this global. Pad it out if needed.
3115   if (RequiredPadding != 4) {
3116     StringRef S = CDAInit->getAsString();
3117 
3118     SmallVector<uint8_t,16> V(S.size());
3119     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3120     while (RequiredPadding--)
3121       V.push_back(0);
3122     Init = ConstantDataArray::get(*DAG.getContext(), V);
3123   }
3124 
3125   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3126   SDValue CPAddr =
3127     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3128   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3129     AFI->markGlobalAsPromotedToConstantPool(GVar);
3130     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3131                                       PaddedSize - 4);
3132   }
3133   ++NumConstpoolPromoted;
3134   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3135 }
3136 
3137 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3138   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3139     GV = GA->getBaseObject();
3140   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3141          isa<Function>(GV);
3142 }
3143 
3144 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3145                                               SelectionDAG &DAG) const {
3146   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3147   default: llvm_unreachable("unknown object format");
3148   case Triple::COFF:
3149     return LowerGlobalAddressWindows(Op, DAG);
3150   case Triple::ELF:
3151     return LowerGlobalAddressELF(Op, DAG);
3152   case Triple::MachO:
3153     return LowerGlobalAddressDarwin(Op, DAG);
3154   }
3155 }
3156 
3157 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3158                                                  SelectionDAG &DAG) const {
3159   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3160   SDLoc dl(Op);
3161   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3162   const TargetMachine &TM = getTargetMachine();
3163   bool IsRO = isReadOnly(GV);
3164 
3165   // promoteToConstantPool only if not generating XO text section
3166   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3167     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3168       return V;
3169 
3170   if (isPositionIndependent()) {
3171     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3172     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3173                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3174     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3175     if (UseGOT_PREL)
3176       Result =
3177           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3178                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3179     return Result;
3180   } else if (Subtarget->isROPI() && IsRO) {
3181     // PC-relative.
3182     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3183     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3184     return Result;
3185   } else if (Subtarget->isRWPI() && !IsRO) {
3186     // SB-relative.
3187     SDValue RelAddr;
3188     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3189       ++NumMovwMovt;
3190       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3191       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3192     } else { // use literal pool for address constant
3193       ARMConstantPoolValue *CPV =
3194         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3195       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3196       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3197       RelAddr = DAG.getLoad(
3198           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3199           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3200     }
3201     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3202     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3203     return Result;
3204   }
3205 
3206   // If we have T2 ops, we can materialize the address directly via movt/movw
3207   // pair. This is always cheaper.
3208   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3209     ++NumMovwMovt;
3210     // FIXME: Once remat is capable of dealing with instructions with register
3211     // operands, expand this into two nodes.
3212     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3213                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3214   } else {
3215     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3216     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3217     return DAG.getLoad(
3218         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3219         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3220   }
3221 }
3222 
3223 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3224                                                     SelectionDAG &DAG) const {
3225   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3226          "ROPI/RWPI not currently supported for Darwin");
3227   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3228   SDLoc dl(Op);
3229   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3230 
3231   if (Subtarget->useMovt(DAG.getMachineFunction()))
3232     ++NumMovwMovt;
3233 
3234   // FIXME: Once remat is capable of dealing with instructions with register
3235   // operands, expand this into multiple nodes
3236   unsigned Wrapper =
3237       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3238 
3239   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3240   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3241 
3242   if (Subtarget->isGVIndirectSymbol(GV))
3243     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3244                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3245   return Result;
3246 }
3247 
3248 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3249                                                      SelectionDAG &DAG) const {
3250   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3251   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3252          "Windows on ARM expects to use movw/movt");
3253   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3254          "ROPI/RWPI not currently supported for Windows");
3255 
3256   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3257   const ARMII::TOF TargetFlags =
3258     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3259   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3260   SDValue Result;
3261   SDLoc DL(Op);
3262 
3263   ++NumMovwMovt;
3264 
3265   // FIXME: Once remat is capable of dealing with instructions with register
3266   // operands, expand this into two nodes.
3267   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3268                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3269                                                   TargetFlags));
3270   if (GV->hasDLLImportStorageClass())
3271     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3272                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3273   return Result;
3274 }
3275 
3276 SDValue
3277 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3278   SDLoc dl(Op);
3279   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3280   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3281                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3282                      Op.getOperand(1), Val);
3283 }
3284 
3285 SDValue
3286 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3287   SDLoc dl(Op);
3288   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3289                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3290 }
3291 
3292 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3293                                                       SelectionDAG &DAG) const {
3294   SDLoc dl(Op);
3295   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3296                      Op.getOperand(0));
3297 }
3298 
3299 SDValue
3300 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3301                                           const ARMSubtarget *Subtarget) const {
3302   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3303   SDLoc dl(Op);
3304   switch (IntNo) {
3305   default: return SDValue();    // Don't custom lower most intrinsics.
3306   case Intrinsic::thread_pointer: {
3307     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3308     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3309   }
3310   case Intrinsic::eh_sjlj_lsda: {
3311     MachineFunction &MF = DAG.getMachineFunction();
3312     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3313     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3314     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3315     SDValue CPAddr;
3316     bool IsPositionIndependent = isPositionIndependent();
3317     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3318     ARMConstantPoolValue *CPV =
3319       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3320                                       ARMCP::CPLSDA, PCAdj);
3321     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3322     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3323     SDValue Result = DAG.getLoad(
3324         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3325         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3326 
3327     if (IsPositionIndependent) {
3328       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3329       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3330     }
3331     return Result;
3332   }
3333   case Intrinsic::arm_neon_vabs:
3334     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3335                         Op.getOperand(1));
3336   case Intrinsic::arm_neon_vmulls:
3337   case Intrinsic::arm_neon_vmullu: {
3338     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3339       ? ARMISD::VMULLs : ARMISD::VMULLu;
3340     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3341                        Op.getOperand(1), Op.getOperand(2));
3342   }
3343   case Intrinsic::arm_neon_vminnm:
3344   case Intrinsic::arm_neon_vmaxnm: {
3345     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3346       ? ISD::FMINNUM : ISD::FMAXNUM;
3347     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3348                        Op.getOperand(1), Op.getOperand(2));
3349   }
3350   case Intrinsic::arm_neon_vminu:
3351   case Intrinsic::arm_neon_vmaxu: {
3352     if (Op.getValueType().isFloatingPoint())
3353       return SDValue();
3354     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3355       ? ISD::UMIN : ISD::UMAX;
3356     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3357                          Op.getOperand(1), Op.getOperand(2));
3358   }
3359   case Intrinsic::arm_neon_vmins:
3360   case Intrinsic::arm_neon_vmaxs: {
3361     // v{min,max}s is overloaded between signed integers and floats.
3362     if (!Op.getValueType().isFloatingPoint()) {
3363       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3364         ? ISD::SMIN : ISD::SMAX;
3365       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3366                          Op.getOperand(1), Op.getOperand(2));
3367     }
3368     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3369       ? ISD::FMINNAN : ISD::FMAXNAN;
3370     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3371                        Op.getOperand(1), Op.getOperand(2));
3372   }
3373   case Intrinsic::arm_neon_vtbl1:
3374     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3375                        Op.getOperand(1), Op.getOperand(2));
3376   case Intrinsic::arm_neon_vtbl2:
3377     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3378                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3379   }
3380 }
3381 
3382 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3383                                  const ARMSubtarget *Subtarget) {
3384   SDLoc dl(Op);
3385   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3386   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3387   if (SSID == SyncScope::SingleThread)
3388     return Op;
3389 
3390   if (!Subtarget->hasDataBarrier()) {
3391     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3392     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3393     // here.
3394     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3395            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3396     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3397                        DAG.getConstant(0, dl, MVT::i32));
3398   }
3399 
3400   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3401   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3402   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3403   if (Subtarget->isMClass()) {
3404     // Only a full system barrier exists in the M-class architectures.
3405     Domain = ARM_MB::SY;
3406   } else if (Subtarget->preferISHSTBarriers() &&
3407              Ord == AtomicOrdering::Release) {
3408     // Swift happens to implement ISHST barriers in a way that's compatible with
3409     // Release semantics but weaker than ISH so we'd be fools not to use
3410     // it. Beware: other processors probably don't!
3411     Domain = ARM_MB::ISHST;
3412   }
3413 
3414   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3415                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3416                      DAG.getConstant(Domain, dl, MVT::i32));
3417 }
3418 
3419 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3420                              const ARMSubtarget *Subtarget) {
3421   // ARM pre v5TE and Thumb1 does not have preload instructions.
3422   if (!(Subtarget->isThumb2() ||
3423         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3424     // Just preserve the chain.
3425     return Op.getOperand(0);
3426 
3427   SDLoc dl(Op);
3428   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3429   if (!isRead &&
3430       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3431     // ARMv7 with MP extension has PLDW.
3432     return Op.getOperand(0);
3433 
3434   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3435   if (Subtarget->isThumb()) {
3436     // Invert the bits.
3437     isRead = ~isRead & 1;
3438     isData = ~isData & 1;
3439   }
3440 
3441   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3442                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3443                      DAG.getConstant(isData, dl, MVT::i32));
3444 }
3445 
3446 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3447   MachineFunction &MF = DAG.getMachineFunction();
3448   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3449 
3450   // vastart just stores the address of the VarArgsFrameIndex slot into the
3451   // memory location argument.
3452   SDLoc dl(Op);
3453   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3454   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3455   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3456   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3457                       MachinePointerInfo(SV));
3458 }
3459 
3460 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3461                                                 CCValAssign &NextVA,
3462                                                 SDValue &Root,
3463                                                 SelectionDAG &DAG,
3464                                                 const SDLoc &dl) const {
3465   MachineFunction &MF = DAG.getMachineFunction();
3466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3467 
3468   const TargetRegisterClass *RC;
3469   if (AFI->isThumb1OnlyFunction())
3470     RC = &ARM::tGPRRegClass;
3471   else
3472     RC = &ARM::GPRRegClass;
3473 
3474   // Transform the arguments stored in physical registers into virtual ones.
3475   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3476   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3477 
3478   SDValue ArgValue2;
3479   if (NextVA.isMemLoc()) {
3480     MachineFrameInfo &MFI = MF.getFrameInfo();
3481     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3482 
3483     // Create load node to retrieve arguments from the stack.
3484     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3485     ArgValue2 = DAG.getLoad(
3486         MVT::i32, dl, Root, FIN,
3487         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3488   } else {
3489     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3490     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3491   }
3492   if (!Subtarget->isLittle())
3493     std::swap (ArgValue, ArgValue2);
3494   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3495 }
3496 
3497 // The remaining GPRs hold either the beginning of variable-argument
3498 // data, or the beginning of an aggregate passed by value (usually
3499 // byval).  Either way, we allocate stack slots adjacent to the data
3500 // provided by our caller, and store the unallocated registers there.
3501 // If this is a variadic function, the va_list pointer will begin with
3502 // these values; otherwise, this reassembles a (byval) structure that
3503 // was split between registers and memory.
3504 // Return: The frame index registers were stored into.
3505 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3506                                       const SDLoc &dl, SDValue &Chain,
3507                                       const Value *OrigArg,
3508                                       unsigned InRegsParamRecordIdx,
3509                                       int ArgOffset, unsigned ArgSize) const {
3510   // Currently, two use-cases possible:
3511   // Case #1. Non-var-args function, and we meet first byval parameter.
3512   //          Setup first unallocated register as first byval register;
3513   //          eat all remained registers
3514   //          (these two actions are performed by HandleByVal method).
3515   //          Then, here, we initialize stack frame with
3516   //          "store-reg" instructions.
3517   // Case #2. Var-args function, that doesn't contain byval parameters.
3518   //          The same: eat all remained unallocated registers,
3519   //          initialize stack frame.
3520 
3521   MachineFunction &MF = DAG.getMachineFunction();
3522   MachineFrameInfo &MFI = MF.getFrameInfo();
3523   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3524   unsigned RBegin, REnd;
3525   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3526     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3527   } else {
3528     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3529     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3530     REnd = ARM::R4;
3531   }
3532 
3533   if (REnd != RBegin)
3534     ArgOffset = -4 * (ARM::R4 - RBegin);
3535 
3536   auto PtrVT = getPointerTy(DAG.getDataLayout());
3537   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3538   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3539 
3540   SmallVector<SDValue, 4> MemOps;
3541   const TargetRegisterClass *RC =
3542       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3543 
3544   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3545     unsigned VReg = MF.addLiveIn(Reg, RC);
3546     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3547     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3548                                  MachinePointerInfo(OrigArg, 4 * i));
3549     MemOps.push_back(Store);
3550     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3551   }
3552 
3553   if (!MemOps.empty())
3554     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3555   return FrameIndex;
3556 }
3557 
3558 // Setup stack frame, the va_list pointer will start from.
3559 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3560                                              const SDLoc &dl, SDValue &Chain,
3561                                              unsigned ArgOffset,
3562                                              unsigned TotalArgRegsSaveSize,
3563                                              bool ForceMutable) const {
3564   MachineFunction &MF = DAG.getMachineFunction();
3565   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3566 
3567   // Try to store any remaining integer argument regs
3568   // to their spots on the stack so that they may be loaded by dereferencing
3569   // the result of va_next.
3570   // If there is no regs to be stored, just point address after last
3571   // argument passed via stack.
3572   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3573                                   CCInfo.getInRegsParamsCount(),
3574                                   CCInfo.getNextStackOffset(), 4);
3575   AFI->setVarArgsFrameIndex(FrameIndex);
3576 }
3577 
3578 SDValue ARMTargetLowering::LowerFormalArguments(
3579     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3580     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3581     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3582   MachineFunction &MF = DAG.getMachineFunction();
3583   MachineFrameInfo &MFI = MF.getFrameInfo();
3584 
3585   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3586 
3587   // Assign locations to all of the incoming arguments.
3588   SmallVector<CCValAssign, 16> ArgLocs;
3589   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3590                  *DAG.getContext());
3591   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3592 
3593   SmallVector<SDValue, 16> ArgValues;
3594   SDValue ArgValue;
3595   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3596   unsigned CurArgIdx = 0;
3597 
3598   // Initially ArgRegsSaveSize is zero.
3599   // Then we increase this value each time we meet byval parameter.
3600   // We also increase this value in case of varargs function.
3601   AFI->setArgRegsSaveSize(0);
3602 
3603   // Calculate the amount of stack space that we need to allocate to store
3604   // byval and variadic arguments that are passed in registers.
3605   // We need to know this before we allocate the first byval or variadic
3606   // argument, as they will be allocated a stack slot below the CFA (Canonical
3607   // Frame Address, the stack pointer at entry to the function).
3608   unsigned ArgRegBegin = ARM::R4;
3609   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3610     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3611       break;
3612 
3613     CCValAssign &VA = ArgLocs[i];
3614     unsigned Index = VA.getValNo();
3615     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3616     if (!Flags.isByVal())
3617       continue;
3618 
3619     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3620     unsigned RBegin, REnd;
3621     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3622     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3623 
3624     CCInfo.nextInRegsParam();
3625   }
3626   CCInfo.rewindByValRegsInfo();
3627 
3628   int lastInsIndex = -1;
3629   if (isVarArg && MFI.hasVAStart()) {
3630     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3631     if (RegIdx != array_lengthof(GPRArgRegs))
3632       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3633   }
3634 
3635   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3636   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3637   auto PtrVT = getPointerTy(DAG.getDataLayout());
3638 
3639   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3640     CCValAssign &VA = ArgLocs[i];
3641     if (Ins[VA.getValNo()].isOrigArg()) {
3642       std::advance(CurOrigArg,
3643                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3644       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3645     }
3646     // Arguments stored in registers.
3647     if (VA.isRegLoc()) {
3648       EVT RegVT = VA.getLocVT();
3649 
3650       if (VA.needsCustom()) {
3651         // f64 and vector types are split up into multiple registers or
3652         // combinations of registers and stack slots.
3653         if (VA.getLocVT() == MVT::v2f64) {
3654           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3655                                                    Chain, DAG, dl);
3656           VA = ArgLocs[++i]; // skip ahead to next loc
3657           SDValue ArgValue2;
3658           if (VA.isMemLoc()) {
3659             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3660             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3661             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3662                                     MachinePointerInfo::getFixedStack(
3663                                         DAG.getMachineFunction(), FI));
3664           } else {
3665             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3666                                              Chain, DAG, dl);
3667           }
3668           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3669           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3670                                  ArgValue, ArgValue1,
3671                                  DAG.getIntPtrConstant(0, dl));
3672           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3673                                  ArgValue, ArgValue2,
3674                                  DAG.getIntPtrConstant(1, dl));
3675         } else
3676           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3677       } else {
3678         const TargetRegisterClass *RC;
3679 
3680         if (RegVT == MVT::f32)
3681           RC = &ARM::SPRRegClass;
3682         else if (RegVT == MVT::f64)
3683           RC = &ARM::DPRRegClass;
3684         else if (RegVT == MVT::v2f64)
3685           RC = &ARM::QPRRegClass;
3686         else if (RegVT == MVT::i32)
3687           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3688                                            : &ARM::GPRRegClass;
3689         else
3690           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3691 
3692         // Transform the arguments in physical registers into virtual ones.
3693         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3694         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3695       }
3696 
3697       // If this is an 8 or 16-bit value, it is really passed promoted
3698       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3699       // truncate to the right size.
3700       switch (VA.getLocInfo()) {
3701       default: llvm_unreachable("Unknown loc info!");
3702       case CCValAssign::Full: break;
3703       case CCValAssign::BCvt:
3704         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3705         break;
3706       case CCValAssign::SExt:
3707         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3708                                DAG.getValueType(VA.getValVT()));
3709         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3710         break;
3711       case CCValAssign::ZExt:
3712         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3713                                DAG.getValueType(VA.getValVT()));
3714         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3715         break;
3716       }
3717 
3718       InVals.push_back(ArgValue);
3719     } else { // VA.isRegLoc()
3720       // sanity check
3721       assert(VA.isMemLoc());
3722       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3723 
3724       int index = VA.getValNo();
3725 
3726       // Some Ins[] entries become multiple ArgLoc[] entries.
3727       // Process them only once.
3728       if (index != lastInsIndex)
3729         {
3730           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3731           // FIXME: For now, all byval parameter objects are marked mutable.
3732           // This can be changed with more analysis.
3733           // In case of tail call optimization mark all arguments mutable.
3734           // Since they could be overwritten by lowering of arguments in case of
3735           // a tail call.
3736           if (Flags.isByVal()) {
3737             assert(Ins[index].isOrigArg() &&
3738                    "Byval arguments cannot be implicit");
3739             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3740 
3741             int FrameIndex = StoreByValRegs(
3742                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3743                 VA.getLocMemOffset(), Flags.getByValSize());
3744             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3745             CCInfo.nextInRegsParam();
3746           } else {
3747             unsigned FIOffset = VA.getLocMemOffset();
3748             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3749                                            FIOffset, true);
3750 
3751             // Create load nodes to retrieve arguments from the stack.
3752             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3753             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3754                                          MachinePointerInfo::getFixedStack(
3755                                              DAG.getMachineFunction(), FI)));
3756           }
3757           lastInsIndex = index;
3758         }
3759     }
3760   }
3761 
3762   // varargs
3763   if (isVarArg && MFI.hasVAStart())
3764     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3765                          CCInfo.getNextStackOffset(),
3766                          TotalArgRegsSaveSize);
3767 
3768   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3769 
3770   return Chain;
3771 }
3772 
3773 /// isFloatingPointZero - Return true if this is +0.0.
3774 static bool isFloatingPointZero(SDValue Op) {
3775   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3776     return CFP->getValueAPF().isPosZero();
3777   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3778     // Maybe this has already been legalized into the constant pool?
3779     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3780       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3781       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3782         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3783           return CFP->getValueAPF().isPosZero();
3784     }
3785   } else if (Op->getOpcode() == ISD::BITCAST &&
3786              Op->getValueType(0) == MVT::f64) {
3787     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3788     // created by LowerConstantFP().
3789     SDValue BitcastOp = Op->getOperand(0);
3790     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3791         isNullConstant(BitcastOp->getOperand(0)))
3792       return true;
3793   }
3794   return false;
3795 }
3796 
3797 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3798 /// the given operands.
3799 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3800                                      SDValue &ARMcc, SelectionDAG &DAG,
3801                                      const SDLoc &dl) const {
3802   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3803     unsigned C = RHSC->getZExtValue();
3804     if (!isLegalICmpImmediate(C)) {
3805       // Constant does not fit, try adjusting it by one?
3806       switch (CC) {
3807       default: break;
3808       case ISD::SETLT:
3809       case ISD::SETGE:
3810         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3811           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3812           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3813         }
3814         break;
3815       case ISD::SETULT:
3816       case ISD::SETUGE:
3817         if (C != 0 && isLegalICmpImmediate(C-1)) {
3818           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3819           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3820         }
3821         break;
3822       case ISD::SETLE:
3823       case ISD::SETGT:
3824         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3825           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3826           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3827         }
3828         break;
3829       case ISD::SETULE:
3830       case ISD::SETUGT:
3831         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3832           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3833           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3834         }
3835         break;
3836       }
3837     }
3838   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3839              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3840     // In ARM and Thumb-2, the compare instructions can shift their second
3841     // operand.
3842     CC = ISD::getSetCCSwappedOperands(CC);
3843     std::swap(LHS, RHS);
3844   }
3845 
3846   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3847   ARMISD::NodeType CompareType;
3848   switch (CondCode) {
3849   default:
3850     CompareType = ARMISD::CMP;
3851     break;
3852   case ARMCC::EQ:
3853   case ARMCC::NE:
3854     // Uses only Z Flag
3855     CompareType = ARMISD::CMPZ;
3856     break;
3857   }
3858   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3859   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3860 }
3861 
3862 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3863 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3864                                      SelectionDAG &DAG, const SDLoc &dl,
3865                                      bool InvalidOnQNaN) const {
3866   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3867   SDValue Cmp;
3868   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3869   if (!isFloatingPointZero(RHS))
3870     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3871   else
3872     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3873   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3874 }
3875 
3876 /// duplicateCmp - Glue values can have only one use, so this function
3877 /// duplicates a comparison node.
3878 SDValue
3879 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3880   unsigned Opc = Cmp.getOpcode();
3881   SDLoc DL(Cmp);
3882   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3883     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3884 
3885   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3886   Cmp = Cmp.getOperand(0);
3887   Opc = Cmp.getOpcode();
3888   if (Opc == ARMISD::CMPFP)
3889     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3890                       Cmp.getOperand(1), Cmp.getOperand(2));
3891   else {
3892     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3893     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3894                       Cmp.getOperand(1));
3895   }
3896   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3897 }
3898 
3899 // This function returns three things: the arithmetic computation itself
3900 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3901 // comparison and the condition code define the case in which the arithmetic
3902 // computation *does not* overflow.
3903 std::pair<SDValue, SDValue>
3904 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3905                                  SDValue &ARMcc) const {
3906   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3907 
3908   SDValue Value, OverflowCmp;
3909   SDValue LHS = Op.getOperand(0);
3910   SDValue RHS = Op.getOperand(1);
3911   SDLoc dl(Op);
3912 
3913   // FIXME: We are currently always generating CMPs because we don't support
3914   // generating CMN through the backend. This is not as good as the natural
3915   // CMP case because it causes a register dependency and cannot be folded
3916   // later.
3917 
3918   switch (Op.getOpcode()) {
3919   default:
3920     llvm_unreachable("Unknown overflow instruction!");
3921   case ISD::SADDO:
3922     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3923     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3924     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3925     break;
3926   case ISD::UADDO:
3927     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3928     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3929     // We do not use it in the USUBO case as Value may not be used.
3930     Value = DAG.getNode(ARMISD::ADDC, dl,
3931                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3932                 .getValue(0);
3933     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3934     break;
3935   case ISD::SSUBO:
3936     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3937     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3938     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3939     break;
3940   case ISD::USUBO:
3941     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3942     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3943     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3944     break;
3945   } // switch (...)
3946 
3947   return std::make_pair(Value, OverflowCmp);
3948 }
3949 
3950 SDValue
3951 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
3952   // Let legalize expand this if it isn't a legal type yet.
3953   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3954     return SDValue();
3955 
3956   SDValue Value, OverflowCmp;
3957   SDValue ARMcc;
3958   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3959   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3960   SDLoc dl(Op);
3961   // We use 0 and 1 as false and true values.
3962   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3963   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3964   EVT VT = Op.getValueType();
3965 
3966   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3967                                  ARMcc, CCR, OverflowCmp);
3968 
3969   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3970   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3971 }
3972 
3973 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
3974                                               SelectionDAG &DAG) {
3975   SDLoc DL(BoolCarry);
3976   EVT CarryVT = BoolCarry.getValueType();
3977 
3978   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
3979   // This converts the boolean value carry into the carry flag by doing
3980   // ARMISD::ADDC Carry, ~0
3981   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
3982                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
3983 }
3984 
3985 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
3986                                               SelectionDAG &DAG) {
3987   SDLoc DL(Flags);
3988 
3989   // Now convert the carry flag into a boolean carry. We do this
3990   // using ARMISD:ADDE 0, 0, Carry
3991   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
3992                      DAG.getConstant(0, DL, MVT::i32),
3993                      DAG.getConstant(0, DL, MVT::i32), Flags);
3994 }
3995 
3996 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
3997                                              SelectionDAG &DAG) const {
3998   // Let legalize expand this if it isn't a legal type yet.
3999   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4000     return SDValue();
4001 
4002   SDValue LHS = Op.getOperand(0);
4003   SDValue RHS = Op.getOperand(1);
4004   SDLoc dl(Op);
4005 
4006   EVT VT = Op.getValueType();
4007   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4008   SDValue Value;
4009   SDValue Overflow;
4010   switch (Op.getOpcode()) {
4011   default:
4012     llvm_unreachable("Unknown overflow instruction!");
4013   case ISD::UADDO:
4014     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4015     // Convert the carry flag into a boolean value.
4016     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4017     break;
4018   case ISD::USUBO: {
4019     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4020     // Convert the carry flag into a boolean value.
4021     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4022     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4023     // value. So compute 1 - C.
4024     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4025                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4026     break;
4027   }
4028   }
4029 
4030   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4031 }
4032 
4033 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4034   SDValue Cond = Op.getOperand(0);
4035   SDValue SelectTrue = Op.getOperand(1);
4036   SDValue SelectFalse = Op.getOperand(2);
4037   SDLoc dl(Op);
4038   unsigned Opc = Cond.getOpcode();
4039 
4040   if (Cond.getResNo() == 1 &&
4041       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4042        Opc == ISD::USUBO)) {
4043     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4044       return SDValue();
4045 
4046     SDValue Value, OverflowCmp;
4047     SDValue ARMcc;
4048     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4049     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4050     EVT VT = Op.getValueType();
4051 
4052     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4053                    OverflowCmp, DAG);
4054   }
4055 
4056   // Convert:
4057   //
4058   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4059   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4060   //
4061   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4062     const ConstantSDNode *CMOVTrue =
4063       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4064     const ConstantSDNode *CMOVFalse =
4065       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4066 
4067     if (CMOVTrue && CMOVFalse) {
4068       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4069       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4070 
4071       SDValue True;
4072       SDValue False;
4073       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4074         True = SelectTrue;
4075         False = SelectFalse;
4076       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4077         True = SelectFalse;
4078         False = SelectTrue;
4079       }
4080 
4081       if (True.getNode() && False.getNode()) {
4082         EVT VT = Op.getValueType();
4083         SDValue ARMcc = Cond.getOperand(2);
4084         SDValue CCR = Cond.getOperand(3);
4085         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4086         assert(True.getValueType() == VT);
4087         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4088       }
4089     }
4090   }
4091 
4092   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4093   // undefined bits before doing a full-word comparison with zero.
4094   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4095                      DAG.getConstant(1, dl, Cond.getValueType()));
4096 
4097   return DAG.getSelectCC(dl, Cond,
4098                          DAG.getConstant(0, dl, Cond.getValueType()),
4099                          SelectTrue, SelectFalse, ISD::SETNE);
4100 }
4101 
4102 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4103                                  bool &swpCmpOps, bool &swpVselOps) {
4104   // Start by selecting the GE condition code for opcodes that return true for
4105   // 'equality'
4106   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4107       CC == ISD::SETULE)
4108     CondCode = ARMCC::GE;
4109 
4110   // and GT for opcodes that return false for 'equality'.
4111   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4112            CC == ISD::SETULT)
4113     CondCode = ARMCC::GT;
4114 
4115   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4116   // to swap the compare operands.
4117   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4118       CC == ISD::SETULT)
4119     swpCmpOps = true;
4120 
4121   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4122   // If we have an unordered opcode, we need to swap the operands to the VSEL
4123   // instruction (effectively negating the condition).
4124   //
4125   // This also has the effect of swapping which one of 'less' or 'greater'
4126   // returns true, so we also swap the compare operands. It also switches
4127   // whether we return true for 'equality', so we compensate by picking the
4128   // opposite condition code to our original choice.
4129   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4130       CC == ISD::SETUGT) {
4131     swpCmpOps = !swpCmpOps;
4132     swpVselOps = !swpVselOps;
4133     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4134   }
4135 
4136   // 'ordered' is 'anything but unordered', so use the VS condition code and
4137   // swap the VSEL operands.
4138   if (CC == ISD::SETO) {
4139     CondCode = ARMCC::VS;
4140     swpVselOps = true;
4141   }
4142 
4143   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4144   // code and swap the VSEL operands.
4145   if (CC == ISD::SETUNE) {
4146     CondCode = ARMCC::EQ;
4147     swpVselOps = true;
4148   }
4149 }
4150 
4151 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4152                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4153                                    SDValue Cmp, SelectionDAG &DAG) const {
4154   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4155     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4156                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4157     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4158                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4159 
4160     SDValue TrueLow = TrueVal.getValue(0);
4161     SDValue TrueHigh = TrueVal.getValue(1);
4162     SDValue FalseLow = FalseVal.getValue(0);
4163     SDValue FalseHigh = FalseVal.getValue(1);
4164 
4165     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4166                               ARMcc, CCR, Cmp);
4167     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4168                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4169 
4170     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4171   } else {
4172     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4173                        Cmp);
4174   }
4175 }
4176 
4177 static bool isGTorGE(ISD::CondCode CC) {
4178   return CC == ISD::SETGT || CC == ISD::SETGE;
4179 }
4180 
4181 static bool isLTorLE(ISD::CondCode CC) {
4182   return CC == ISD::SETLT || CC == ISD::SETLE;
4183 }
4184 
4185 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4186 // All of these conditions (and their <= and >= counterparts) will do:
4187 //          x < k ? k : x
4188 //          x > k ? x : k
4189 //          k < x ? x : k
4190 //          k > x ? k : x
4191 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4192                             const SDValue TrueVal, const SDValue FalseVal,
4193                             const ISD::CondCode CC, const SDValue K) {
4194   return (isGTorGE(CC) &&
4195           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4196          (isLTorLE(CC) &&
4197           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4198 }
4199 
4200 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4201 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4202                             const SDValue TrueVal, const SDValue FalseVal,
4203                             const ISD::CondCode CC, const SDValue K) {
4204   return (isGTorGE(CC) &&
4205           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4206          (isLTorLE(CC) &&
4207           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4208 }
4209 
4210 // Check if two chained conditionals could be converted into SSAT or USAT.
4211 //
4212 // SSAT can replace a set of two conditional selectors that bound a number to an
4213 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4214 //
4215 //     x < -k ? -k : (x > k ? k : x)
4216 //     x < -k ? -k : (x < k ? x : k)
4217 //     x > -k ? (x > k ? k : x) : -k
4218 //     x < k ? (x < -k ? -k : x) : k
4219 //     etc.
4220 //
4221 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4222 // a power of 2.
4223 //
4224 // It returns true if the conversion can be done, false otherwise.
4225 // Additionally, the variable is returned in parameter V, the constant in K and
4226 // usat is set to true if the conditional represents an unsigned saturation
4227 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4228                                     uint64_t &K, bool &usat) {
4229   SDValue LHS1 = Op.getOperand(0);
4230   SDValue RHS1 = Op.getOperand(1);
4231   SDValue TrueVal1 = Op.getOperand(2);
4232   SDValue FalseVal1 = Op.getOperand(3);
4233   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4234 
4235   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4236   if (Op2.getOpcode() != ISD::SELECT_CC)
4237     return false;
4238 
4239   SDValue LHS2 = Op2.getOperand(0);
4240   SDValue RHS2 = Op2.getOperand(1);
4241   SDValue TrueVal2 = Op2.getOperand(2);
4242   SDValue FalseVal2 = Op2.getOperand(3);
4243   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4244 
4245   // Find out which are the constants and which are the variables
4246   // in each conditional
4247   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4248                                                         ? &RHS1
4249                                                         : nullptr;
4250   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4251                                                         ? &RHS2
4252                                                         : nullptr;
4253   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4254   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4255   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4256   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4257 
4258   // We must detect cases where the original operations worked with 16- or
4259   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4260   // must work with sign-extended values but the select operations return
4261   // the original non-extended value.
4262   SDValue V2TmpReg = V2Tmp;
4263   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4264     V2TmpReg = V2Tmp->getOperand(0);
4265 
4266   // Check that the registers and the constants have the correct values
4267   // in both conditionals
4268   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4269       V2TmpReg != V2)
4270     return false;
4271 
4272   // Figure out which conditional is saturating the lower/upper bound.
4273   const SDValue *LowerCheckOp =
4274       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4275           ? &Op
4276           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4277                 ? &Op2
4278                 : nullptr;
4279   const SDValue *UpperCheckOp =
4280       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4281           ? &Op
4282           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4283                 ? &Op2
4284                 : nullptr;
4285 
4286   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4287     return false;
4288 
4289   // Check that the constant in the lower-bound check is
4290   // the opposite of the constant in the upper-bound check
4291   // in 1's complement.
4292   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4293   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4294   int64_t PosVal = std::max(Val1, Val2);
4295   int64_t NegVal = std::min(Val1, Val2);
4296 
4297   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4298        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4299       isPowerOf2_64(PosVal + 1)) {
4300 
4301     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4302     if (Val1 == ~Val2)
4303       usat = false;
4304     else if (NegVal == 0)
4305       usat = true;
4306     else
4307       return false;
4308 
4309     V = V2;
4310     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4311 
4312     return true;
4313   }
4314 
4315   return false;
4316 }
4317 
4318 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4319   EVT VT = Op.getValueType();
4320   SDLoc dl(Op);
4321 
4322   // Try to convert two saturating conditional selects into a single SSAT
4323   SDValue SatValue;
4324   uint64_t SatConstant;
4325   bool SatUSat;
4326   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4327       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4328     if (SatUSat)
4329       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4330                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4331     else
4332       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4333                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4334   }
4335 
4336   SDValue LHS = Op.getOperand(0);
4337   SDValue RHS = Op.getOperand(1);
4338   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4339   SDValue TrueVal = Op.getOperand(2);
4340   SDValue FalseVal = Op.getOperand(3);
4341 
4342   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4343     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4344                                                     dl);
4345 
4346     // If softenSetCCOperands only returned one value, we should compare it to
4347     // zero.
4348     if (!RHS.getNode()) {
4349       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4350       CC = ISD::SETNE;
4351     }
4352   }
4353 
4354   if (LHS.getValueType() == MVT::i32) {
4355     // Try to generate VSEL on ARMv8.
4356     // The VSEL instruction can't use all the usual ARM condition
4357     // codes: it only has two bits to select the condition code, so it's
4358     // constrained to use only GE, GT, VS and EQ.
4359     //
4360     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4361     // swap the operands of the previous compare instruction (effectively
4362     // inverting the compare condition, swapping 'less' and 'greater') and
4363     // sometimes need to swap the operands to the VSEL (which inverts the
4364     // condition in the sense of firing whenever the previous condition didn't)
4365     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4366                                     TrueVal.getValueType() == MVT::f64)) {
4367       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4368       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4369           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4370         CC = ISD::getSetCCInverse(CC, true);
4371         std::swap(TrueVal, FalseVal);
4372       }
4373     }
4374 
4375     SDValue ARMcc;
4376     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4377     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4378     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4379   }
4380 
4381   ARMCC::CondCodes CondCode, CondCode2;
4382   bool InvalidOnQNaN;
4383   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4384 
4385   // Try to generate VMAXNM/VMINNM on ARMv8.
4386   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4387                                   TrueVal.getValueType() == MVT::f64)) {
4388     bool swpCmpOps = false;
4389     bool swpVselOps = false;
4390     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4391 
4392     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4393         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4394       if (swpCmpOps)
4395         std::swap(LHS, RHS);
4396       if (swpVselOps)
4397         std::swap(TrueVal, FalseVal);
4398     }
4399   }
4400 
4401   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4402   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4403   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4404   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4405   if (CondCode2 != ARMCC::AL) {
4406     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4407     // FIXME: Needs another CMP because flag can have but one use.
4408     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4409     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4410   }
4411   return Result;
4412 }
4413 
4414 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4415 /// to morph to an integer compare sequence.
4416 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4417                            const ARMSubtarget *Subtarget) {
4418   SDNode *N = Op.getNode();
4419   if (!N->hasOneUse())
4420     // Otherwise it requires moving the value from fp to integer registers.
4421     return false;
4422   if (!N->getNumValues())
4423     return false;
4424   EVT VT = Op.getValueType();
4425   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4426     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4427     // vmrs are very slow, e.g. cortex-a8.
4428     return false;
4429 
4430   if (isFloatingPointZero(Op)) {
4431     SeenZero = true;
4432     return true;
4433   }
4434   return ISD::isNormalLoad(N);
4435 }
4436 
4437 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4438   if (isFloatingPointZero(Op))
4439     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4440 
4441   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4442     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4443                        Ld->getPointerInfo(), Ld->getAlignment(),
4444                        Ld->getMemOperand()->getFlags());
4445 
4446   llvm_unreachable("Unknown VFP cmp argument!");
4447 }
4448 
4449 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4450                            SDValue &RetVal1, SDValue &RetVal2) {
4451   SDLoc dl(Op);
4452 
4453   if (isFloatingPointZero(Op)) {
4454     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4455     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4456     return;
4457   }
4458 
4459   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4460     SDValue Ptr = Ld->getBasePtr();
4461     RetVal1 =
4462         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4463                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4464 
4465     EVT PtrType = Ptr.getValueType();
4466     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4467     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4468                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4469     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4470                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4471                           Ld->getMemOperand()->getFlags());
4472     return;
4473   }
4474 
4475   llvm_unreachable("Unknown VFP cmp argument!");
4476 }
4477 
4478 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4479 /// f32 and even f64 comparisons to integer ones.
4480 SDValue
4481 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4482   SDValue Chain = Op.getOperand(0);
4483   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4484   SDValue LHS = Op.getOperand(2);
4485   SDValue RHS = Op.getOperand(3);
4486   SDValue Dest = Op.getOperand(4);
4487   SDLoc dl(Op);
4488 
4489   bool LHSSeenZero = false;
4490   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4491   bool RHSSeenZero = false;
4492   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4493   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4494     // If unsafe fp math optimization is enabled and there are no other uses of
4495     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4496     // to an integer comparison.
4497     if (CC == ISD::SETOEQ)
4498       CC = ISD::SETEQ;
4499     else if (CC == ISD::SETUNE)
4500       CC = ISD::SETNE;
4501 
4502     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4503     SDValue ARMcc;
4504     if (LHS.getValueType() == MVT::f32) {
4505       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4506                         bitcastf32Toi32(LHS, DAG), Mask);
4507       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4508                         bitcastf32Toi32(RHS, DAG), Mask);
4509       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4510       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4511       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4512                          Chain, Dest, ARMcc, CCR, Cmp);
4513     }
4514 
4515     SDValue LHS1, LHS2;
4516     SDValue RHS1, RHS2;
4517     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4518     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4519     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4520     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4521     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4522     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4523     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4524     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4525     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4526   }
4527 
4528   return SDValue();
4529 }
4530 
4531 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4532   SDValue Chain = Op.getOperand(0);
4533   SDValue Cond = Op.getOperand(1);
4534   SDValue Dest = Op.getOperand(2);
4535   SDLoc dl(Op);
4536 
4537   // Optimize {s|u}{add|sub}.with.overflow feeding into a branch instruction.
4538   unsigned Opc = Cond.getOpcode();
4539   if (Cond.getResNo() == 1 && (Opc == ISD::SADDO || Opc == ISD::UADDO ||
4540                                Opc == ISD::SSUBO || Opc == ISD::USUBO)) {
4541     // Only lower legal XALUO ops.
4542     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4543       return SDValue();
4544 
4545     // The actual operation with overflow check.
4546     SDValue Value, OverflowCmp;
4547     SDValue ARMcc;
4548     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4549 
4550     // Reverse the condition code.
4551     ARMCC::CondCodes CondCode =
4552         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4553     CondCode = ARMCC::getOppositeCondition(CondCode);
4554     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4555     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4556 
4557     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4558                        OverflowCmp);
4559   }
4560 
4561   return SDValue();
4562 }
4563 
4564 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4565   SDValue Chain = Op.getOperand(0);
4566   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4567   SDValue LHS = Op.getOperand(2);
4568   SDValue RHS = Op.getOperand(3);
4569   SDValue Dest = Op.getOperand(4);
4570   SDLoc dl(Op);
4571 
4572   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4573     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4574                                                     dl);
4575 
4576     // If softenSetCCOperands only returned one value, we should compare it to
4577     // zero.
4578     if (!RHS.getNode()) {
4579       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4580       CC = ISD::SETNE;
4581     }
4582   }
4583 
4584   // Optimize {s|u}{add|sub}.with.overflow feeding into a branch instruction.
4585   unsigned Opc = LHS.getOpcode();
4586   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4587       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4588        Opc == ISD::USUBO) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4589     // Only lower legal XALUO ops.
4590     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4591       return SDValue();
4592 
4593     // The actual operation with overflow check.
4594     SDValue Value, OverflowCmp;
4595     SDValue ARMcc;
4596     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4597 
4598     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4599       // Reverse the condition code.
4600       ARMCC::CondCodes CondCode =
4601           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4602       CondCode = ARMCC::getOppositeCondition(CondCode);
4603       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4604     }
4605     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4606 
4607     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4608                        OverflowCmp);
4609   }
4610 
4611   if (LHS.getValueType() == MVT::i32) {
4612     SDValue ARMcc;
4613     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4614     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4615     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4616                        Chain, Dest, ARMcc, CCR, Cmp);
4617   }
4618 
4619   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4620 
4621   if (getTargetMachine().Options.UnsafeFPMath &&
4622       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4623        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4624     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4625       return Result;
4626   }
4627 
4628   ARMCC::CondCodes CondCode, CondCode2;
4629   bool InvalidOnQNaN;
4630   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4631 
4632   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4633   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4634   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4635   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4636   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4637   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4638   if (CondCode2 != ARMCC::AL) {
4639     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4640     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4641     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4642   }
4643   return Res;
4644 }
4645 
4646 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4647   SDValue Chain = Op.getOperand(0);
4648   SDValue Table = Op.getOperand(1);
4649   SDValue Index = Op.getOperand(2);
4650   SDLoc dl(Op);
4651 
4652   EVT PTy = getPointerTy(DAG.getDataLayout());
4653   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4654   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4655   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4656   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4657   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4658   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4659     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4660     // which does another jump to the destination. This also makes it easier
4661     // to translate it to TBB / TBH later (Thumb2 only).
4662     // FIXME: This might not work if the function is extremely large.
4663     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4664                        Addr, Op.getOperand(2), JTI);
4665   }
4666   if (isPositionIndependent() || Subtarget->isROPI()) {
4667     Addr =
4668         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4669                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4670     Chain = Addr.getValue(1);
4671     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4672     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4673   } else {
4674     Addr =
4675         DAG.getLoad(PTy, dl, Chain, Addr,
4676                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4677     Chain = Addr.getValue(1);
4678     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4679   }
4680 }
4681 
4682 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4683   EVT VT = Op.getValueType();
4684   SDLoc dl(Op);
4685 
4686   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4687     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4688       return Op;
4689     return DAG.UnrollVectorOp(Op.getNode());
4690   }
4691 
4692   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4693          "Invalid type for custom lowering!");
4694   if (VT != MVT::v4i16)
4695     return DAG.UnrollVectorOp(Op.getNode());
4696 
4697   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4698   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4699 }
4700 
4701 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4702   EVT VT = Op.getValueType();
4703   if (VT.isVector())
4704     return LowerVectorFP_TO_INT(Op, DAG);
4705   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4706     RTLIB::Libcall LC;
4707     if (Op.getOpcode() == ISD::FP_TO_SINT)
4708       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4709                               Op.getValueType());
4710     else
4711       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4712                               Op.getValueType());
4713     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4714                        /*isSigned*/ false, SDLoc(Op)).first;
4715   }
4716 
4717   return Op;
4718 }
4719 
4720 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4721   EVT VT = Op.getValueType();
4722   SDLoc dl(Op);
4723 
4724   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4725     if (VT.getVectorElementType() == MVT::f32)
4726       return Op;
4727     return DAG.UnrollVectorOp(Op.getNode());
4728   }
4729 
4730   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4731          "Invalid type for custom lowering!");
4732   if (VT != MVT::v4f32)
4733     return DAG.UnrollVectorOp(Op.getNode());
4734 
4735   unsigned CastOpc;
4736   unsigned Opc;
4737   switch (Op.getOpcode()) {
4738   default: llvm_unreachable("Invalid opcode!");
4739   case ISD::SINT_TO_FP:
4740     CastOpc = ISD::SIGN_EXTEND;
4741     Opc = ISD::SINT_TO_FP;
4742     break;
4743   case ISD::UINT_TO_FP:
4744     CastOpc = ISD::ZERO_EXTEND;
4745     Opc = ISD::UINT_TO_FP;
4746     break;
4747   }
4748 
4749   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4750   return DAG.getNode(Opc, dl, VT, Op);
4751 }
4752 
4753 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4754   EVT VT = Op.getValueType();
4755   if (VT.isVector())
4756     return LowerVectorINT_TO_FP(Op, DAG);
4757   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4758     RTLIB::Libcall LC;
4759     if (Op.getOpcode() == ISD::SINT_TO_FP)
4760       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4761                               Op.getValueType());
4762     else
4763       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4764                               Op.getValueType());
4765     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4766                        /*isSigned*/ false, SDLoc(Op)).first;
4767   }
4768 
4769   return Op;
4770 }
4771 
4772 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4773   // Implement fcopysign with a fabs and a conditional fneg.
4774   SDValue Tmp0 = Op.getOperand(0);
4775   SDValue Tmp1 = Op.getOperand(1);
4776   SDLoc dl(Op);
4777   EVT VT = Op.getValueType();
4778   EVT SrcVT = Tmp1.getValueType();
4779   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4780     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4781   bool UseNEON = !InGPR && Subtarget->hasNEON();
4782 
4783   if (UseNEON) {
4784     // Use VBSL to copy the sign bit.
4785     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4786     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4787                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4788     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4789     if (VT == MVT::f64)
4790       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4791                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4792                          DAG.getConstant(32, dl, MVT::i32));
4793     else /*if (VT == MVT::f32)*/
4794       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4795     if (SrcVT == MVT::f32) {
4796       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4797       if (VT == MVT::f64)
4798         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4799                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4800                            DAG.getConstant(32, dl, MVT::i32));
4801     } else if (VT == MVT::f32)
4802       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4803                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4804                          DAG.getConstant(32, dl, MVT::i32));
4805     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4806     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4807 
4808     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4809                                             dl, MVT::i32);
4810     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4811     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4812                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4813 
4814     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4815                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4816                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4817     if (VT == MVT::f32) {
4818       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4819       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4820                         DAG.getConstant(0, dl, MVT::i32));
4821     } else {
4822       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4823     }
4824 
4825     return Res;
4826   }
4827 
4828   // Bitcast operand 1 to i32.
4829   if (SrcVT == MVT::f64)
4830     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4831                        Tmp1).getValue(1);
4832   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4833 
4834   // Or in the signbit with integer operations.
4835   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4836   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4837   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4838   if (VT == MVT::f32) {
4839     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4840                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4841     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4842                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4843   }
4844 
4845   // f64: Or the high part with signbit and then combine two parts.
4846   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4847                      Tmp0);
4848   SDValue Lo = Tmp0.getValue(0);
4849   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4850   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4851   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4852 }
4853 
4854 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4855   MachineFunction &MF = DAG.getMachineFunction();
4856   MachineFrameInfo &MFI = MF.getFrameInfo();
4857   MFI.setReturnAddressIsTaken(true);
4858 
4859   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4860     return SDValue();
4861 
4862   EVT VT = Op.getValueType();
4863   SDLoc dl(Op);
4864   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4865   if (Depth) {
4866     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4867     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4868     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4869                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4870                        MachinePointerInfo());
4871   }
4872 
4873   // Return LR, which contains the return address. Mark it an implicit live-in.
4874   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4875   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4876 }
4877 
4878 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4879   const ARMBaseRegisterInfo &ARI =
4880     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4881   MachineFunction &MF = DAG.getMachineFunction();
4882   MachineFrameInfo &MFI = MF.getFrameInfo();
4883   MFI.setFrameAddressIsTaken(true);
4884 
4885   EVT VT = Op.getValueType();
4886   SDLoc dl(Op);  // FIXME probably not meaningful
4887   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4888   unsigned FrameReg = ARI.getFrameRegister(MF);
4889   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4890   while (Depth--)
4891     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4892                             MachinePointerInfo());
4893   return FrameAddr;
4894 }
4895 
4896 // FIXME? Maybe this could be a TableGen attribute on some registers and
4897 // this table could be generated automatically from RegInfo.
4898 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4899                                               SelectionDAG &DAG) const {
4900   unsigned Reg = StringSwitch<unsigned>(RegName)
4901                        .Case("sp", ARM::SP)
4902                        .Default(0);
4903   if (Reg)
4904     return Reg;
4905   report_fatal_error(Twine("Invalid register name \""
4906                               + StringRef(RegName)  + "\"."));
4907 }
4908 
4909 // Result is 64 bit value so split into two 32 bit values and return as a
4910 // pair of values.
4911 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4912                                 SelectionDAG &DAG) {
4913   SDLoc DL(N);
4914 
4915   // This function is only supposed to be called for i64 type destination.
4916   assert(N->getValueType(0) == MVT::i64
4917           && "ExpandREAD_REGISTER called for non-i64 type result.");
4918 
4919   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4920                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4921                              N->getOperand(0),
4922                              N->getOperand(1));
4923 
4924   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4925                     Read.getValue(1)));
4926   Results.push_back(Read.getOperand(0));
4927 }
4928 
4929 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4930 /// When \p DstVT, the destination type of \p BC, is on the vector
4931 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4932 /// it might be possible to combine them, such that everything stays on the
4933 /// vector register bank.
4934 /// \p return The node that would replace \p BT, if the combine
4935 /// is possible.
4936 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4937                                                 SelectionDAG &DAG) {
4938   SDValue Op = BC->getOperand(0);
4939   EVT DstVT = BC->getValueType(0);
4940 
4941   // The only vector instruction that can produce a scalar (remember,
4942   // since the bitcast was about to be turned into VMOVDRR, the source
4943   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4944   // Moreover, we can do this combine only if there is one use.
4945   // Finally, if the destination type is not a vector, there is not
4946   // much point on forcing everything on the vector bank.
4947   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4948       !Op.hasOneUse())
4949     return SDValue();
4950 
4951   // If the index is not constant, we will introduce an additional
4952   // multiply that will stick.
4953   // Give up in that case.
4954   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4955   if (!Index)
4956     return SDValue();
4957   unsigned DstNumElt = DstVT.getVectorNumElements();
4958 
4959   // Compute the new index.
4960   const APInt &APIntIndex = Index->getAPIntValue();
4961   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4962   NewIndex *= APIntIndex;
4963   // Check if the new constant index fits into i32.
4964   if (NewIndex.getBitWidth() > 32)
4965     return SDValue();
4966 
4967   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4968   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4969   SDLoc dl(Op);
4970   SDValue ExtractSrc = Op.getOperand(0);
4971   EVT VecVT = EVT::getVectorVT(
4972       *DAG.getContext(), DstVT.getScalarType(),
4973       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4974   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4975   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4976                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4977 }
4978 
4979 /// ExpandBITCAST - If the target supports VFP, this function is called to
4980 /// expand a bit convert where either the source or destination type is i64 to
4981 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4982 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4983 /// vectors), since the legalizer won't know what to do with that.
4984 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4986   SDLoc dl(N);
4987   SDValue Op = N->getOperand(0);
4988 
4989   // This function is only supposed to be called for i64 types, either as the
4990   // source or destination of the bit convert.
4991   EVT SrcVT = Op.getValueType();
4992   EVT DstVT = N->getValueType(0);
4993   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4994          "ExpandBITCAST called for non-i64 type");
4995 
4996   // Turn i64->f64 into VMOVDRR.
4997   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4998     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4999     // if we can combine the bitcast with its source.
5000     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5001       return Val;
5002 
5003     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5004                              DAG.getConstant(0, dl, MVT::i32));
5005     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5006                              DAG.getConstant(1, dl, MVT::i32));
5007     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5008                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5009   }
5010 
5011   // Turn f64->i64 into VMOVRRD.
5012   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5013     SDValue Cvt;
5014     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5015         SrcVT.getVectorNumElements() > 1)
5016       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5017                         DAG.getVTList(MVT::i32, MVT::i32),
5018                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5019     else
5020       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5021                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5022     // Merge the pieces into a single i64 value.
5023     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5024   }
5025 
5026   return SDValue();
5027 }
5028 
5029 /// getZeroVector - Returns a vector of specified type with all zero elements.
5030 /// Zero vectors are used to represent vector negation and in those cases
5031 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5032 /// not support i64 elements, so sometimes the zero vectors will need to be
5033 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5034 /// zero vector.
5035 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5036   assert(VT.isVector() && "Expected a vector type");
5037   // The canonical modified immediate encoding of a zero vector is....0!
5038   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5039   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5040   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5041   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5042 }
5043 
5044 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5045 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5046 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5047                                                 SelectionDAG &DAG) const {
5048   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5049   EVT VT = Op.getValueType();
5050   unsigned VTBits = VT.getSizeInBits();
5051   SDLoc dl(Op);
5052   SDValue ShOpLo = Op.getOperand(0);
5053   SDValue ShOpHi = Op.getOperand(1);
5054   SDValue ShAmt  = Op.getOperand(2);
5055   SDValue ARMcc;
5056   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5057   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5058 
5059   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5060 
5061   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5062                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5063   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5064   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5065                                    DAG.getConstant(VTBits, dl, MVT::i32));
5066   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5067   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5068   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5069   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5070                             ISD::SETGE, ARMcc, DAG, dl);
5071   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5072                            ARMcc, CCR, CmpLo);
5073 
5074   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5075   SDValue HiBigShift = Opc == ISD::SRA
5076                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5077                                          DAG.getConstant(VTBits - 1, dl, VT))
5078                            : DAG.getConstant(0, dl, VT);
5079   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5080                             ISD::SETGE, ARMcc, DAG, dl);
5081   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5082                            ARMcc, CCR, CmpHi);
5083 
5084   SDValue Ops[2] = { Lo, Hi };
5085   return DAG.getMergeValues(Ops, dl);
5086 }
5087 
5088 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5089 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5090 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5091                                                SelectionDAG &DAG) const {
5092   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5093   EVT VT = Op.getValueType();
5094   unsigned VTBits = VT.getSizeInBits();
5095   SDLoc dl(Op);
5096   SDValue ShOpLo = Op.getOperand(0);
5097   SDValue ShOpHi = Op.getOperand(1);
5098   SDValue ShAmt  = Op.getOperand(2);
5099   SDValue ARMcc;
5100   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5101 
5102   assert(Op.getOpcode() == ISD::SHL_PARTS);
5103   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5104                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5105   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5106   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5107   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5108 
5109   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5110                                    DAG.getConstant(VTBits, dl, MVT::i32));
5111   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5112   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5113                             ISD::SETGE, ARMcc, DAG, dl);
5114   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5115                            ARMcc, CCR, CmpHi);
5116 
5117   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5118                           ISD::SETGE, ARMcc, DAG, dl);
5119   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5120   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5121                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5122 
5123   SDValue Ops[2] = { Lo, Hi };
5124   return DAG.getMergeValues(Ops, dl);
5125 }
5126 
5127 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5128                                             SelectionDAG &DAG) const {
5129   // The rounding mode is in bits 23:22 of the FPSCR.
5130   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5131   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5132   // so that the shift + and get folded into a bitfield extract.
5133   SDLoc dl(Op);
5134   SDValue Ops[] = { DAG.getEntryNode(),
5135                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5136 
5137   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5138   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5139                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5140   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5141                               DAG.getConstant(22, dl, MVT::i32));
5142   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5143                      DAG.getConstant(3, dl, MVT::i32));
5144 }
5145 
5146 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5147                          const ARMSubtarget *ST) {
5148   SDLoc dl(N);
5149   EVT VT = N->getValueType(0);
5150   if (VT.isVector()) {
5151     assert(ST->hasNEON());
5152 
5153     // Compute the least significant set bit: LSB = X & -X
5154     SDValue X = N->getOperand(0);
5155     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5156     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5157 
5158     EVT ElemTy = VT.getVectorElementType();
5159 
5160     if (ElemTy == MVT::i8) {
5161       // Compute with: cttz(x) = ctpop(lsb - 1)
5162       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5163                                 DAG.getTargetConstant(1, dl, ElemTy));
5164       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5165       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5166     }
5167 
5168     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5169         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5170       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5171       unsigned NumBits = ElemTy.getSizeInBits();
5172       SDValue WidthMinus1 =
5173           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5174                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5175       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5176       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5177     }
5178 
5179     // Compute with: cttz(x) = ctpop(lsb - 1)
5180 
5181     // Since we can only compute the number of bits in a byte with vcnt.8, we
5182     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5183     // and i64.
5184 
5185     // Compute LSB - 1.
5186     SDValue Bits;
5187     if (ElemTy == MVT::i64) {
5188       // Load constant 0xffff'ffff'ffff'ffff to register.
5189       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5190                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5191       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5192     } else {
5193       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5194                                 DAG.getTargetConstant(1, dl, ElemTy));
5195       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5196     }
5197 
5198     // Count #bits with vcnt.8.
5199     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5200     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5201     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5202 
5203     // Gather the #bits with vpaddl (pairwise add.)
5204     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5205     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5206         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5207         Cnt8);
5208     if (ElemTy == MVT::i16)
5209       return Cnt16;
5210 
5211     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5212     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5213         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5214         Cnt16);
5215     if (ElemTy == MVT::i32)
5216       return Cnt32;
5217 
5218     assert(ElemTy == MVT::i64);
5219     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5220         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5221         Cnt32);
5222     return Cnt64;
5223   }
5224 
5225   if (!ST->hasV6T2Ops())
5226     return SDValue();
5227 
5228   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5229   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5230 }
5231 
5232 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5233 /// for each 16-bit element from operand, repeated.  The basic idea is to
5234 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5235 ///
5236 /// Trace for v4i16:
5237 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5238 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5239 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5240 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5241 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5242 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5243 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5244 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5245 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5246   EVT VT = N->getValueType(0);
5247   SDLoc DL(N);
5248 
5249   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5250   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5251   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5252   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5253   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5254   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5255 }
5256 
5257 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5258 /// bit-count for each 16-bit element from the operand.  We need slightly
5259 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5260 /// 64/128-bit registers.
5261 ///
5262 /// Trace for v4i16:
5263 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5264 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5265 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5266 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5267 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5268   EVT VT = N->getValueType(0);
5269   SDLoc DL(N);
5270 
5271   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5272   if (VT.is64BitVector()) {
5273     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5274     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5275                        DAG.getIntPtrConstant(0, DL));
5276   } else {
5277     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5278                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5279     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5280   }
5281 }
5282 
5283 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5284 /// bit-count for each 32-bit element from the operand.  The idea here is
5285 /// to split the vector into 16-bit elements, leverage the 16-bit count
5286 /// routine, and then combine the results.
5287 ///
5288 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5289 /// input    = [v0    v1    ] (vi: 32-bit elements)
5290 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5291 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5292 /// vrev: N0 = [k1 k0 k3 k2 ]
5293 ///            [k0 k1 k2 k3 ]
5294 ///       N1 =+[k1 k0 k3 k2 ]
5295 ///            [k0 k2 k1 k3 ]
5296 ///       N2 =+[k1 k3 k0 k2 ]
5297 ///            [k0    k2    k1    k3    ]
5298 /// Extended =+[k1    k3    k0    k2    ]
5299 ///            [k0    k2    ]
5300 /// Extracted=+[k1    k3    ]
5301 ///
5302 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5303   EVT VT = N->getValueType(0);
5304   SDLoc DL(N);
5305 
5306   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5307 
5308   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5309   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5310   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5311   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5312   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5313 
5314   if (VT.is64BitVector()) {
5315     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5316     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5317                        DAG.getIntPtrConstant(0, DL));
5318   } else {
5319     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5320                                     DAG.getIntPtrConstant(0, DL));
5321     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5322   }
5323 }
5324 
5325 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5326                           const ARMSubtarget *ST) {
5327   EVT VT = N->getValueType(0);
5328 
5329   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5330   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5331           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5332          "Unexpected type for custom ctpop lowering");
5333 
5334   if (VT.getVectorElementType() == MVT::i32)
5335     return lowerCTPOP32BitElements(N, DAG);
5336   else
5337     return lowerCTPOP16BitElements(N, DAG);
5338 }
5339 
5340 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5341                           const ARMSubtarget *ST) {
5342   EVT VT = N->getValueType(0);
5343   SDLoc dl(N);
5344 
5345   if (!VT.isVector())
5346     return SDValue();
5347 
5348   // Lower vector shifts on NEON to use VSHL.
5349   assert(ST->hasNEON() && "unexpected vector shift");
5350 
5351   // Left shifts translate directly to the vshiftu intrinsic.
5352   if (N->getOpcode() == ISD::SHL)
5353     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5354                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5355                                        MVT::i32),
5356                        N->getOperand(0), N->getOperand(1));
5357 
5358   assert((N->getOpcode() == ISD::SRA ||
5359           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5360 
5361   // NEON uses the same intrinsics for both left and right shifts.  For
5362   // right shifts, the shift amounts are negative, so negate the vector of
5363   // shift amounts.
5364   EVT ShiftVT = N->getOperand(1).getValueType();
5365   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5366                                      getZeroVector(ShiftVT, DAG, dl),
5367                                      N->getOperand(1));
5368   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5369                              Intrinsic::arm_neon_vshifts :
5370                              Intrinsic::arm_neon_vshiftu);
5371   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5372                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5373                      N->getOperand(0), NegatedCount);
5374 }
5375 
5376 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5377                                 const ARMSubtarget *ST) {
5378   EVT VT = N->getValueType(0);
5379   SDLoc dl(N);
5380 
5381   // We can get here for a node like i32 = ISD::SHL i32, i64
5382   if (VT != MVT::i64)
5383     return SDValue();
5384 
5385   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5386          "Unknown shift to lower!");
5387 
5388   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5389   if (!isOneConstant(N->getOperand(1)))
5390     return SDValue();
5391 
5392   // If we are in thumb mode, we don't have RRX.
5393   if (ST->isThumb1Only()) return SDValue();
5394 
5395   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5396   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5397                            DAG.getConstant(0, dl, MVT::i32));
5398   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5399                            DAG.getConstant(1, dl, MVT::i32));
5400 
5401   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5402   // captures the result into a carry flag.
5403   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5404   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5405 
5406   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5407   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5408 
5409   // Merge the pieces into a single i64 value.
5410  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5411 }
5412 
5413 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5414   SDValue TmpOp0, TmpOp1;
5415   bool Invert = false;
5416   bool Swap = false;
5417   unsigned Opc = 0;
5418 
5419   SDValue Op0 = Op.getOperand(0);
5420   SDValue Op1 = Op.getOperand(1);
5421   SDValue CC = Op.getOperand(2);
5422   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5423   EVT VT = Op.getValueType();
5424   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5425   SDLoc dl(Op);
5426 
5427   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5428       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5429     // Special-case integer 64-bit equality comparisons. They aren't legal,
5430     // but they can be lowered with a few vector instructions.
5431     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5432     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5433     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5434     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5435     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5436                               DAG.getCondCode(ISD::SETEQ));
5437     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5438     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5439     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5440     if (SetCCOpcode == ISD::SETNE)
5441       Merged = DAG.getNOT(dl, Merged, CmpVT);
5442     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5443     return Merged;
5444   }
5445 
5446   if (CmpVT.getVectorElementType() == MVT::i64)
5447     // 64-bit comparisons are not legal in general.
5448     return SDValue();
5449 
5450   if (Op1.getValueType().isFloatingPoint()) {
5451     switch (SetCCOpcode) {
5452     default: llvm_unreachable("Illegal FP comparison");
5453     case ISD::SETUNE:
5454     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5455     case ISD::SETOEQ:
5456     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5457     case ISD::SETOLT:
5458     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5459     case ISD::SETOGT:
5460     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5461     case ISD::SETOLE:
5462     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5463     case ISD::SETOGE:
5464     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5465     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5466     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5467     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5468     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5469     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5470     case ISD::SETONE:
5471       // Expand this to (OLT | OGT).
5472       TmpOp0 = Op0;
5473       TmpOp1 = Op1;
5474       Opc = ISD::OR;
5475       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5476       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5477       break;
5478     case ISD::SETUO:
5479       Invert = true;
5480       LLVM_FALLTHROUGH;
5481     case ISD::SETO:
5482       // Expand this to (OLT | OGE).
5483       TmpOp0 = Op0;
5484       TmpOp1 = Op1;
5485       Opc = ISD::OR;
5486       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5487       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5488       break;
5489     }
5490   } else {
5491     // Integer comparisons.
5492     switch (SetCCOpcode) {
5493     default: llvm_unreachable("Illegal integer comparison");
5494     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5495     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5496     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5497     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5498     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5499     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5500     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5501     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5502     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5503     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5504     }
5505 
5506     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5507     if (Opc == ARMISD::VCEQ) {
5508       SDValue AndOp;
5509       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5510         AndOp = Op0;
5511       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5512         AndOp = Op1;
5513 
5514       // Ignore bitconvert.
5515       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5516         AndOp = AndOp.getOperand(0);
5517 
5518       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5519         Opc = ARMISD::VTST;
5520         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5521         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5522         Invert = !Invert;
5523       }
5524     }
5525   }
5526 
5527   if (Swap)
5528     std::swap(Op0, Op1);
5529 
5530   // If one of the operands is a constant vector zero, attempt to fold the
5531   // comparison to a specialized compare-against-zero form.
5532   SDValue SingleOp;
5533   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5534     SingleOp = Op0;
5535   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5536     if (Opc == ARMISD::VCGE)
5537       Opc = ARMISD::VCLEZ;
5538     else if (Opc == ARMISD::VCGT)
5539       Opc = ARMISD::VCLTZ;
5540     SingleOp = Op1;
5541   }
5542 
5543   SDValue Result;
5544   if (SingleOp.getNode()) {
5545     switch (Opc) {
5546     case ARMISD::VCEQ:
5547       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5548     case ARMISD::VCGE:
5549       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5550     case ARMISD::VCLEZ:
5551       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5552     case ARMISD::VCGT:
5553       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5554     case ARMISD::VCLTZ:
5555       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5556     default:
5557       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5558     }
5559   } else {
5560      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5561   }
5562 
5563   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5564 
5565   if (Invert)
5566     Result = DAG.getNOT(dl, Result, VT);
5567 
5568   return Result;
5569 }
5570 
5571 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5572   SDValue LHS = Op.getOperand(0);
5573   SDValue RHS = Op.getOperand(1);
5574   SDValue Carry = Op.getOperand(2);
5575   SDValue Cond = Op.getOperand(3);
5576   SDLoc DL(Op);
5577 
5578   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5579 
5580   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5581   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5582   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5583 
5584   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5585   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5586   SDValue ARMcc = DAG.getConstant(
5587       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5588   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5589   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5590                                    Cmp.getValue(1), SDValue());
5591   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5592                      CCR, Chain.getValue(1));
5593 }
5594 
5595 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5596 /// valid vector constant for a NEON instruction with a "modified immediate"
5597 /// operand (e.g., VMOV).  If so, return the encoded value.
5598 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5599                                  unsigned SplatBitSize, SelectionDAG &DAG,
5600                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5601                                  NEONModImmType type) {
5602   unsigned OpCmode, Imm;
5603 
5604   // SplatBitSize is set to the smallest size that splats the vector, so a
5605   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5606   // immediate instructions others than VMOV do not support the 8-bit encoding
5607   // of a zero vector, and the default encoding of zero is supposed to be the
5608   // 32-bit version.
5609   if (SplatBits == 0)
5610     SplatBitSize = 32;
5611 
5612   switch (SplatBitSize) {
5613   case 8:
5614     if (type != VMOVModImm)
5615       return SDValue();
5616     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5617     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5618     OpCmode = 0xe;
5619     Imm = SplatBits;
5620     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5621     break;
5622 
5623   case 16:
5624     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5625     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5626     if ((SplatBits & ~0xff) == 0) {
5627       // Value = 0x00nn: Op=x, Cmode=100x.
5628       OpCmode = 0x8;
5629       Imm = SplatBits;
5630       break;
5631     }
5632     if ((SplatBits & ~0xff00) == 0) {
5633       // Value = 0xnn00: Op=x, Cmode=101x.
5634       OpCmode = 0xa;
5635       Imm = SplatBits >> 8;
5636       break;
5637     }
5638     return SDValue();
5639 
5640   case 32:
5641     // NEON's 32-bit VMOV supports splat values where:
5642     // * only one byte is nonzero, or
5643     // * the least significant byte is 0xff and the second byte is nonzero, or
5644     // * the least significant 2 bytes are 0xff and the third is nonzero.
5645     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5646     if ((SplatBits & ~0xff) == 0) {
5647       // Value = 0x000000nn: Op=x, Cmode=000x.
5648       OpCmode = 0;
5649       Imm = SplatBits;
5650       break;
5651     }
5652     if ((SplatBits & ~0xff00) == 0) {
5653       // Value = 0x0000nn00: Op=x, Cmode=001x.
5654       OpCmode = 0x2;
5655       Imm = SplatBits >> 8;
5656       break;
5657     }
5658     if ((SplatBits & ~0xff0000) == 0) {
5659       // Value = 0x00nn0000: Op=x, Cmode=010x.
5660       OpCmode = 0x4;
5661       Imm = SplatBits >> 16;
5662       break;
5663     }
5664     if ((SplatBits & ~0xff000000) == 0) {
5665       // Value = 0xnn000000: Op=x, Cmode=011x.
5666       OpCmode = 0x6;
5667       Imm = SplatBits >> 24;
5668       break;
5669     }
5670 
5671     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5672     if (type == OtherModImm) return SDValue();
5673 
5674     if ((SplatBits & ~0xffff) == 0 &&
5675         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5676       // Value = 0x0000nnff: Op=x, Cmode=1100.
5677       OpCmode = 0xc;
5678       Imm = SplatBits >> 8;
5679       break;
5680     }
5681 
5682     if ((SplatBits & ~0xffffff) == 0 &&
5683         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5684       // Value = 0x00nnffff: Op=x, Cmode=1101.
5685       OpCmode = 0xd;
5686       Imm = SplatBits >> 16;
5687       break;
5688     }
5689 
5690     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5691     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5692     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5693     // and fall through here to test for a valid 64-bit splat.  But, then the
5694     // caller would also need to check and handle the change in size.
5695     return SDValue();
5696 
5697   case 64: {
5698     if (type != VMOVModImm)
5699       return SDValue();
5700     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5701     uint64_t BitMask = 0xff;
5702     uint64_t Val = 0;
5703     unsigned ImmMask = 1;
5704     Imm = 0;
5705     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5706       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5707         Val |= BitMask;
5708         Imm |= ImmMask;
5709       } else if ((SplatBits & BitMask) != 0) {
5710         return SDValue();
5711       }
5712       BitMask <<= 8;
5713       ImmMask <<= 1;
5714     }
5715 
5716     if (DAG.getDataLayout().isBigEndian())
5717       // swap higher and lower 32 bit word
5718       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5719 
5720     // Op=1, Cmode=1110.
5721     OpCmode = 0x1e;
5722     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5723     break;
5724   }
5725 
5726   default:
5727     llvm_unreachable("unexpected size for isNEONModifiedImm");
5728   }
5729 
5730   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5731   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5732 }
5733 
5734 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5735                                            const ARMSubtarget *ST) const {
5736   bool IsDouble = Op.getValueType() == MVT::f64;
5737   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5738   const APFloat &FPVal = CFP->getValueAPF();
5739 
5740   // Prevent floating-point constants from using literal loads
5741   // when execute-only is enabled.
5742   if (ST->genExecuteOnly()) {
5743     APInt INTVal = FPVal.bitcastToAPInt();
5744     SDLoc DL(CFP);
5745     if (IsDouble) {
5746       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5747       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5748       if (!ST->isLittle())
5749         std::swap(Lo, Hi);
5750       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5751     } else {
5752       return DAG.getConstant(INTVal, DL, MVT::i32);
5753     }
5754   }
5755 
5756   if (!ST->hasVFP3())
5757     return SDValue();
5758 
5759   // Use the default (constant pool) lowering for double constants when we have
5760   // an SP-only FPU
5761   if (IsDouble && Subtarget->isFPOnlySP())
5762     return SDValue();
5763 
5764   // Try splatting with a VMOV.f32...
5765   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5766 
5767   if (ImmVal != -1) {
5768     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5769       // We have code in place to select a valid ConstantFP already, no need to
5770       // do any mangling.
5771       return Op;
5772     }
5773 
5774     // It's a float and we are trying to use NEON operations where
5775     // possible. Lower it to a splat followed by an extract.
5776     SDLoc DL(Op);
5777     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5778     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5779                                       NewVal);
5780     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5781                        DAG.getConstant(0, DL, MVT::i32));
5782   }
5783 
5784   // The rest of our options are NEON only, make sure that's allowed before
5785   // proceeding..
5786   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5787     return SDValue();
5788 
5789   EVT VMovVT;
5790   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5791 
5792   // It wouldn't really be worth bothering for doubles except for one very
5793   // important value, which does happen to match: 0.0. So make sure we don't do
5794   // anything stupid.
5795   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5796     return SDValue();
5797 
5798   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5799   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5800                                      VMovVT, false, VMOVModImm);
5801   if (NewVal != SDValue()) {
5802     SDLoc DL(Op);
5803     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5804                                       NewVal);
5805     if (IsDouble)
5806       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5807 
5808     // It's a float: cast and extract a vector element.
5809     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5810                                        VecConstant);
5811     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5812                        DAG.getConstant(0, DL, MVT::i32));
5813   }
5814 
5815   // Finally, try a VMVN.i32
5816   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5817                              false, VMVNModImm);
5818   if (NewVal != SDValue()) {
5819     SDLoc DL(Op);
5820     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5821 
5822     if (IsDouble)
5823       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5824 
5825     // It's a float: cast and extract a vector element.
5826     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5827                                        VecConstant);
5828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5829                        DAG.getConstant(0, DL, MVT::i32));
5830   }
5831 
5832   return SDValue();
5833 }
5834 
5835 // check if an VEXT instruction can handle the shuffle mask when the
5836 // vector sources of the shuffle are the same.
5837 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5838   unsigned NumElts = VT.getVectorNumElements();
5839 
5840   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5841   if (M[0] < 0)
5842     return false;
5843 
5844   Imm = M[0];
5845 
5846   // If this is a VEXT shuffle, the immediate value is the index of the first
5847   // element.  The other shuffle indices must be the successive elements after
5848   // the first one.
5849   unsigned ExpectedElt = Imm;
5850   for (unsigned i = 1; i < NumElts; ++i) {
5851     // Increment the expected index.  If it wraps around, just follow it
5852     // back to index zero and keep going.
5853     ++ExpectedElt;
5854     if (ExpectedElt == NumElts)
5855       ExpectedElt = 0;
5856 
5857     if (M[i] < 0) continue; // ignore UNDEF indices
5858     if (ExpectedElt != static_cast<unsigned>(M[i]))
5859       return false;
5860   }
5861 
5862   return true;
5863 }
5864 
5865 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5866                        bool &ReverseVEXT, unsigned &Imm) {
5867   unsigned NumElts = VT.getVectorNumElements();
5868   ReverseVEXT = false;
5869 
5870   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5871   if (M[0] < 0)
5872     return false;
5873 
5874   Imm = M[0];
5875 
5876   // If this is a VEXT shuffle, the immediate value is the index of the first
5877   // element.  The other shuffle indices must be the successive elements after
5878   // the first one.
5879   unsigned ExpectedElt = Imm;
5880   for (unsigned i = 1; i < NumElts; ++i) {
5881     // Increment the expected index.  If it wraps around, it may still be
5882     // a VEXT but the source vectors must be swapped.
5883     ExpectedElt += 1;
5884     if (ExpectedElt == NumElts * 2) {
5885       ExpectedElt = 0;
5886       ReverseVEXT = true;
5887     }
5888 
5889     if (M[i] < 0) continue; // ignore UNDEF indices
5890     if (ExpectedElt != static_cast<unsigned>(M[i]))
5891       return false;
5892   }
5893 
5894   // Adjust the index value if the source operands will be swapped.
5895   if (ReverseVEXT)
5896     Imm -= NumElts;
5897 
5898   return true;
5899 }
5900 
5901 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5902 /// instruction with the specified blocksize.  (The order of the elements
5903 /// within each block of the vector is reversed.)
5904 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5905   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5906          "Only possible block sizes for VREV are: 16, 32, 64");
5907 
5908   unsigned EltSz = VT.getScalarSizeInBits();
5909   if (EltSz == 64)
5910     return false;
5911 
5912   unsigned NumElts = VT.getVectorNumElements();
5913   unsigned BlockElts = M[0] + 1;
5914   // If the first shuffle index is UNDEF, be optimistic.
5915   if (M[0] < 0)
5916     BlockElts = BlockSize / EltSz;
5917 
5918   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5919     return false;
5920 
5921   for (unsigned i = 0; i < NumElts; ++i) {
5922     if (M[i] < 0) continue; // ignore UNDEF indices
5923     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5924       return false;
5925   }
5926 
5927   return true;
5928 }
5929 
5930 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5931   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5932   // range, then 0 is placed into the resulting vector. So pretty much any mask
5933   // of 8 elements can work here.
5934   return VT == MVT::v8i8 && M.size() == 8;
5935 }
5936 
5937 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
5938                                unsigned Index) {
5939   if (Mask.size() == Elements * 2)
5940     return Index / Elements;
5941   return Mask[Index] == 0 ? 0 : 1;
5942 }
5943 
5944 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5945 // checking that pairs of elements in the shuffle mask represent the same index
5946 // in each vector, incrementing the expected index by 2 at each step.
5947 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5948 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5949 //  v2={e,f,g,h}
5950 // WhichResult gives the offset for each element in the mask based on which
5951 // of the two results it belongs to.
5952 //
5953 // The transpose can be represented either as:
5954 // result1 = shufflevector v1, v2, result1_shuffle_mask
5955 // result2 = shufflevector v1, v2, result2_shuffle_mask
5956 // where v1/v2 and the shuffle masks have the same number of elements
5957 // (here WhichResult (see below) indicates which result is being checked)
5958 //
5959 // or as:
5960 // results = shufflevector v1, v2, shuffle_mask
5961 // where both results are returned in one vector and the shuffle mask has twice
5962 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5963 // want to check the low half and high half of the shuffle mask as if it were
5964 // the other case
5965 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5966   unsigned EltSz = VT.getScalarSizeInBits();
5967   if (EltSz == 64)
5968     return false;
5969 
5970   unsigned NumElts = VT.getVectorNumElements();
5971   if (M.size() != NumElts && M.size() != NumElts*2)
5972     return false;
5973 
5974   // If the mask is twice as long as the input vector then we need to check the
5975   // upper and lower parts of the mask with a matching value for WhichResult
5976   // FIXME: A mask with only even values will be rejected in case the first
5977   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5978   // M[0] is used to determine WhichResult
5979   for (unsigned i = 0; i < M.size(); i += NumElts) {
5980     WhichResult = SelectPairHalf(NumElts, M, i);
5981     for (unsigned j = 0; j < NumElts; j += 2) {
5982       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5983           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5984         return false;
5985     }
5986   }
5987 
5988   if (M.size() == NumElts*2)
5989     WhichResult = 0;
5990 
5991   return true;
5992 }
5993 
5994 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5995 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5996 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5997 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5998   unsigned EltSz = VT.getScalarSizeInBits();
5999   if (EltSz == 64)
6000     return false;
6001 
6002   unsigned NumElts = VT.getVectorNumElements();
6003   if (M.size() != NumElts && M.size() != NumElts*2)
6004     return false;
6005 
6006   for (unsigned i = 0; i < M.size(); i += NumElts) {
6007     WhichResult = SelectPairHalf(NumElts, M, i);
6008     for (unsigned j = 0; j < NumElts; j += 2) {
6009       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6010           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6011         return false;
6012     }
6013   }
6014 
6015   if (M.size() == NumElts*2)
6016     WhichResult = 0;
6017 
6018   return true;
6019 }
6020 
6021 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6022 // that the mask elements are either all even and in steps of size 2 or all odd
6023 // and in steps of size 2.
6024 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6025 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6026 //  v2={e,f,g,h}
6027 // Requires similar checks to that of isVTRNMask with
6028 // respect the how results are returned.
6029 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6030   unsigned EltSz = VT.getScalarSizeInBits();
6031   if (EltSz == 64)
6032     return false;
6033 
6034   unsigned NumElts = VT.getVectorNumElements();
6035   if (M.size() != NumElts && M.size() != NumElts*2)
6036     return false;
6037 
6038   for (unsigned i = 0; i < M.size(); i += NumElts) {
6039     WhichResult = SelectPairHalf(NumElts, M, i);
6040     for (unsigned j = 0; j < NumElts; ++j) {
6041       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6042         return false;
6043     }
6044   }
6045 
6046   if (M.size() == NumElts*2)
6047     WhichResult = 0;
6048 
6049   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6050   if (VT.is64BitVector() && EltSz == 32)
6051     return false;
6052 
6053   return true;
6054 }
6055 
6056 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6057 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6058 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6059 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6060   unsigned EltSz = VT.getScalarSizeInBits();
6061   if (EltSz == 64)
6062     return false;
6063 
6064   unsigned NumElts = VT.getVectorNumElements();
6065   if (M.size() != NumElts && M.size() != NumElts*2)
6066     return false;
6067 
6068   unsigned Half = NumElts / 2;
6069   for (unsigned i = 0; i < M.size(); i += NumElts) {
6070     WhichResult = SelectPairHalf(NumElts, M, i);
6071     for (unsigned j = 0; j < NumElts; j += Half) {
6072       unsigned Idx = WhichResult;
6073       for (unsigned k = 0; k < Half; ++k) {
6074         int MIdx = M[i + j + k];
6075         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6076           return false;
6077         Idx += 2;
6078       }
6079     }
6080   }
6081 
6082   if (M.size() == NumElts*2)
6083     WhichResult = 0;
6084 
6085   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6086   if (VT.is64BitVector() && EltSz == 32)
6087     return false;
6088 
6089   return true;
6090 }
6091 
6092 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6093 // that pairs of elements of the shufflemask represent the same index in each
6094 // vector incrementing sequentially through the vectors.
6095 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6096 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6097 //  v2={e,f,g,h}
6098 // Requires similar checks to that of isVTRNMask with respect the how results
6099 // are returned.
6100 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6101   unsigned EltSz = VT.getScalarSizeInBits();
6102   if (EltSz == 64)
6103     return false;
6104 
6105   unsigned NumElts = VT.getVectorNumElements();
6106   if (M.size() != NumElts && M.size() != NumElts*2)
6107     return false;
6108 
6109   for (unsigned i = 0; i < M.size(); i += NumElts) {
6110     WhichResult = SelectPairHalf(NumElts, M, i);
6111     unsigned Idx = WhichResult * NumElts / 2;
6112     for (unsigned j = 0; j < NumElts; j += 2) {
6113       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6114           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6115         return false;
6116       Idx += 1;
6117     }
6118   }
6119 
6120   if (M.size() == NumElts*2)
6121     WhichResult = 0;
6122 
6123   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6124   if (VT.is64BitVector() && EltSz == 32)
6125     return false;
6126 
6127   return true;
6128 }
6129 
6130 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6131 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6132 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6133 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6134   unsigned EltSz = VT.getScalarSizeInBits();
6135   if (EltSz == 64)
6136     return false;
6137 
6138   unsigned NumElts = VT.getVectorNumElements();
6139   if (M.size() != NumElts && M.size() != NumElts*2)
6140     return false;
6141 
6142   for (unsigned i = 0; i < M.size(); i += NumElts) {
6143     WhichResult = SelectPairHalf(NumElts, M, i);
6144     unsigned Idx = WhichResult * NumElts / 2;
6145     for (unsigned j = 0; j < NumElts; j += 2) {
6146       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6147           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6148         return false;
6149       Idx += 1;
6150     }
6151   }
6152 
6153   if (M.size() == NumElts*2)
6154     WhichResult = 0;
6155 
6156   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6157   if (VT.is64BitVector() && EltSz == 32)
6158     return false;
6159 
6160   return true;
6161 }
6162 
6163 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6164 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6165 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6166                                            unsigned &WhichResult,
6167                                            bool &isV_UNDEF) {
6168   isV_UNDEF = false;
6169   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6170     return ARMISD::VTRN;
6171   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6172     return ARMISD::VUZP;
6173   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6174     return ARMISD::VZIP;
6175 
6176   isV_UNDEF = true;
6177   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6178     return ARMISD::VTRN;
6179   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6180     return ARMISD::VUZP;
6181   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6182     return ARMISD::VZIP;
6183 
6184   return 0;
6185 }
6186 
6187 /// \return true if this is a reverse operation on an vector.
6188 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6189   unsigned NumElts = VT.getVectorNumElements();
6190   // Make sure the mask has the right size.
6191   if (NumElts != M.size())
6192       return false;
6193 
6194   // Look for <15, ..., 3, -1, 1, 0>.
6195   for (unsigned i = 0; i != NumElts; ++i)
6196     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6197       return false;
6198 
6199   return true;
6200 }
6201 
6202 // If N is an integer constant that can be moved into a register in one
6203 // instruction, return an SDValue of such a constant (will become a MOV
6204 // instruction).  Otherwise return null.
6205 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6206                                      const ARMSubtarget *ST, const SDLoc &dl) {
6207   uint64_t Val;
6208   if (!isa<ConstantSDNode>(N))
6209     return SDValue();
6210   Val = cast<ConstantSDNode>(N)->getZExtValue();
6211 
6212   if (ST->isThumb1Only()) {
6213     if (Val <= 255 || ~Val <= 255)
6214       return DAG.getConstant(Val, dl, MVT::i32);
6215   } else {
6216     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6217       return DAG.getConstant(Val, dl, MVT::i32);
6218   }
6219   return SDValue();
6220 }
6221 
6222 // If this is a case we can't handle, return null and let the default
6223 // expansion code take care of it.
6224 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6225                                              const ARMSubtarget *ST) const {
6226   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6227   SDLoc dl(Op);
6228   EVT VT = Op.getValueType();
6229 
6230   APInt SplatBits, SplatUndef;
6231   unsigned SplatBitSize;
6232   bool HasAnyUndefs;
6233   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6234     if (SplatUndef.isAllOnesValue())
6235       return DAG.getUNDEF(VT);
6236 
6237     if (SplatBitSize <= 64) {
6238       // Check if an immediate VMOV works.
6239       EVT VmovVT;
6240       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6241                                       SplatUndef.getZExtValue(), SplatBitSize,
6242                                       DAG, dl, VmovVT, VT.is128BitVector(),
6243                                       VMOVModImm);
6244       if (Val.getNode()) {
6245         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6246         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6247       }
6248 
6249       // Try an immediate VMVN.
6250       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6251       Val = isNEONModifiedImm(NegatedImm,
6252                                       SplatUndef.getZExtValue(), SplatBitSize,
6253                                       DAG, dl, VmovVT, VT.is128BitVector(),
6254                                       VMVNModImm);
6255       if (Val.getNode()) {
6256         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6257         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6258       }
6259 
6260       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6261       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6262         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6263         if (ImmVal != -1) {
6264           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6265           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6266         }
6267       }
6268     }
6269   }
6270 
6271   // Scan through the operands to see if only one value is used.
6272   //
6273   // As an optimisation, even if more than one value is used it may be more
6274   // profitable to splat with one value then change some lanes.
6275   //
6276   // Heuristically we decide to do this if the vector has a "dominant" value,
6277   // defined as splatted to more than half of the lanes.
6278   unsigned NumElts = VT.getVectorNumElements();
6279   bool isOnlyLowElement = true;
6280   bool usesOnlyOneValue = true;
6281   bool hasDominantValue = false;
6282   bool isConstant = true;
6283 
6284   // Map of the number of times a particular SDValue appears in the
6285   // element list.
6286   DenseMap<SDValue, unsigned> ValueCounts;
6287   SDValue Value;
6288   for (unsigned i = 0; i < NumElts; ++i) {
6289     SDValue V = Op.getOperand(i);
6290     if (V.isUndef())
6291       continue;
6292     if (i > 0)
6293       isOnlyLowElement = false;
6294     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6295       isConstant = false;
6296 
6297     ValueCounts.insert(std::make_pair(V, 0));
6298     unsigned &Count = ValueCounts[V];
6299 
6300     // Is this value dominant? (takes up more than half of the lanes)
6301     if (++Count > (NumElts / 2)) {
6302       hasDominantValue = true;
6303       Value = V;
6304     }
6305   }
6306   if (ValueCounts.size() != 1)
6307     usesOnlyOneValue = false;
6308   if (!Value.getNode() && !ValueCounts.empty())
6309     Value = ValueCounts.begin()->first;
6310 
6311   if (ValueCounts.empty())
6312     return DAG.getUNDEF(VT);
6313 
6314   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6315   // Keep going if we are hitting this case.
6316   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6317     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6318 
6319   unsigned EltSize = VT.getScalarSizeInBits();
6320 
6321   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6322   // i32 and try again.
6323   if (hasDominantValue && EltSize <= 32) {
6324     if (!isConstant) {
6325       SDValue N;
6326 
6327       // If we are VDUPing a value that comes directly from a vector, that will
6328       // cause an unnecessary move to and from a GPR, where instead we could
6329       // just use VDUPLANE. We can only do this if the lane being extracted
6330       // is at a constant index, as the VDUP from lane instructions only have
6331       // constant-index forms.
6332       ConstantSDNode *constIndex;
6333       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6334           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6335         // We need to create a new undef vector to use for the VDUPLANE if the
6336         // size of the vector from which we get the value is different than the
6337         // size of the vector that we need to create. We will insert the element
6338         // such that the register coalescer will remove unnecessary copies.
6339         if (VT != Value->getOperand(0).getValueType()) {
6340           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6341                              VT.getVectorNumElements();
6342           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6343                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6344                         Value, DAG.getConstant(index, dl, MVT::i32)),
6345                            DAG.getConstant(index, dl, MVT::i32));
6346         } else
6347           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6348                         Value->getOperand(0), Value->getOperand(1));
6349       } else
6350         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6351 
6352       if (!usesOnlyOneValue) {
6353         // The dominant value was splatted as 'N', but we now have to insert
6354         // all differing elements.
6355         for (unsigned I = 0; I < NumElts; ++I) {
6356           if (Op.getOperand(I) == Value)
6357             continue;
6358           SmallVector<SDValue, 3> Ops;
6359           Ops.push_back(N);
6360           Ops.push_back(Op.getOperand(I));
6361           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6362           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6363         }
6364       }
6365       return N;
6366     }
6367     if (VT.getVectorElementType().isFloatingPoint()) {
6368       SmallVector<SDValue, 8> Ops;
6369       for (unsigned i = 0; i < NumElts; ++i)
6370         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6371                                   Op.getOperand(i)));
6372       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6373       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6374       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6375       if (Val.getNode())
6376         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6377     }
6378     if (usesOnlyOneValue) {
6379       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6380       if (isConstant && Val.getNode())
6381         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6382     }
6383   }
6384 
6385   // If all elements are constants and the case above didn't get hit, fall back
6386   // to the default expansion, which will generate a load from the constant
6387   // pool.
6388   if (isConstant)
6389     return SDValue();
6390 
6391   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6392   if (NumElts >= 4) {
6393     SDValue shuffle = ReconstructShuffle(Op, DAG);
6394     if (shuffle != SDValue())
6395       return shuffle;
6396   }
6397 
6398   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6399     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6400     // into two 64-bit vectors; we might discover a better way to lower it.
6401     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6402     EVT ExtVT = VT.getVectorElementType();
6403     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6404     SDValue Lower =
6405         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6406     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6407       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6408     SDValue Upper = DAG.getBuildVector(
6409         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6410     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6411       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6412     if (Lower && Upper)
6413       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6414   }
6415 
6416   // Vectors with 32- or 64-bit elements can be built by directly assigning
6417   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6418   // will be legalized.
6419   if (EltSize >= 32) {
6420     // Do the expansion with floating-point types, since that is what the VFP
6421     // registers are defined to use, and since i64 is not legal.
6422     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6423     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6424     SmallVector<SDValue, 8> Ops;
6425     for (unsigned i = 0; i < NumElts; ++i)
6426       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6427     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6428     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6429   }
6430 
6431   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6432   // know the default expansion would otherwise fall back on something even
6433   // worse. For a vector with one or two non-undef values, that's
6434   // scalar_to_vector for the elements followed by a shuffle (provided the
6435   // shuffle is valid for the target) and materialization element by element
6436   // on the stack followed by a load for everything else.
6437   if (!isConstant && !usesOnlyOneValue) {
6438     SDValue Vec = DAG.getUNDEF(VT);
6439     for (unsigned i = 0 ; i < NumElts; ++i) {
6440       SDValue V = Op.getOperand(i);
6441       if (V.isUndef())
6442         continue;
6443       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6444       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6445     }
6446     return Vec;
6447   }
6448 
6449   return SDValue();
6450 }
6451 
6452 // Gather data to see if the operation can be modelled as a
6453 // shuffle in combination with VEXTs.
6454 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6455                                               SelectionDAG &DAG) const {
6456   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6457   SDLoc dl(Op);
6458   EVT VT = Op.getValueType();
6459   unsigned NumElts = VT.getVectorNumElements();
6460 
6461   struct ShuffleSourceInfo {
6462     SDValue Vec;
6463     unsigned MinElt = std::numeric_limits<unsigned>::max();
6464     unsigned MaxElt = 0;
6465 
6466     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6467     // be compatible with the shuffle we intend to construct. As a result
6468     // ShuffleVec will be some sliding window into the original Vec.
6469     SDValue ShuffleVec;
6470 
6471     // Code should guarantee that element i in Vec starts at element "WindowBase
6472     // + i * WindowScale in ShuffleVec".
6473     int WindowBase = 0;
6474     int WindowScale = 1;
6475 
6476     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6477 
6478     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6479   };
6480 
6481   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6482   // node.
6483   SmallVector<ShuffleSourceInfo, 2> Sources;
6484   for (unsigned i = 0; i < NumElts; ++i) {
6485     SDValue V = Op.getOperand(i);
6486     if (V.isUndef())
6487       continue;
6488     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6489       // A shuffle can only come from building a vector from various
6490       // elements of other vectors.
6491       return SDValue();
6492     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6493       // Furthermore, shuffles require a constant mask, whereas extractelts
6494       // accept variable indices.
6495       return SDValue();
6496     }
6497 
6498     // Add this element source to the list if it's not already there.
6499     SDValue SourceVec = V.getOperand(0);
6500     auto Source = llvm::find(Sources, SourceVec);
6501     if (Source == Sources.end())
6502       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6503 
6504     // Update the minimum and maximum lane number seen.
6505     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6506     Source->MinElt = std::min(Source->MinElt, EltNo);
6507     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6508   }
6509 
6510   // Currently only do something sane when at most two source vectors
6511   // are involved.
6512   if (Sources.size() > 2)
6513     return SDValue();
6514 
6515   // Find out the smallest element size among result and two sources, and use
6516   // it as element size to build the shuffle_vector.
6517   EVT SmallestEltTy = VT.getVectorElementType();
6518   for (auto &Source : Sources) {
6519     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6520     if (SrcEltTy.bitsLT(SmallestEltTy))
6521       SmallestEltTy = SrcEltTy;
6522   }
6523   unsigned ResMultiplier =
6524       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6525   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6526   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6527 
6528   // If the source vector is too wide or too narrow, we may nevertheless be able
6529   // to construct a compatible shuffle either by concatenating it with UNDEF or
6530   // extracting a suitable range of elements.
6531   for (auto &Src : Sources) {
6532     EVT SrcVT = Src.ShuffleVec.getValueType();
6533 
6534     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6535       continue;
6536 
6537     // This stage of the search produces a source with the same element type as
6538     // the original, but with a total width matching the BUILD_VECTOR output.
6539     EVT EltVT = SrcVT.getVectorElementType();
6540     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6541     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6542 
6543     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6544       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6545         return SDValue();
6546       // We can pad out the smaller vector for free, so if it's part of a
6547       // shuffle...
6548       Src.ShuffleVec =
6549           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6550                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6551       continue;
6552     }
6553 
6554     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6555       return SDValue();
6556 
6557     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6558       // Span too large for a VEXT to cope
6559       return SDValue();
6560     }
6561 
6562     if (Src.MinElt >= NumSrcElts) {
6563       // The extraction can just take the second half
6564       Src.ShuffleVec =
6565           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6566                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6567       Src.WindowBase = -NumSrcElts;
6568     } else if (Src.MaxElt < NumSrcElts) {
6569       // The extraction can just take the first half
6570       Src.ShuffleVec =
6571           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6572                       DAG.getConstant(0, dl, MVT::i32));
6573     } else {
6574       // An actual VEXT is needed
6575       SDValue VEXTSrc1 =
6576           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6577                       DAG.getConstant(0, dl, MVT::i32));
6578       SDValue VEXTSrc2 =
6579           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6580                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6581 
6582       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6583                                    VEXTSrc2,
6584                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6585       Src.WindowBase = -Src.MinElt;
6586     }
6587   }
6588 
6589   // Another possible incompatibility occurs from the vector element types. We
6590   // can fix this by bitcasting the source vectors to the same type we intend
6591   // for the shuffle.
6592   for (auto &Src : Sources) {
6593     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6594     if (SrcEltTy == SmallestEltTy)
6595       continue;
6596     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6597     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6598     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6599     Src.WindowBase *= Src.WindowScale;
6600   }
6601 
6602   // Final sanity check before we try to actually produce a shuffle.
6603   DEBUG(
6604     for (auto Src : Sources)
6605       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6606   );
6607 
6608   // The stars all align, our next step is to produce the mask for the shuffle.
6609   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6610   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6611   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6612     SDValue Entry = Op.getOperand(i);
6613     if (Entry.isUndef())
6614       continue;
6615 
6616     auto Src = llvm::find(Sources, Entry.getOperand(0));
6617     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6618 
6619     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6620     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6621     // segment.
6622     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6623     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6624                                VT.getScalarSizeInBits());
6625     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6626 
6627     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6628     // starting at the appropriate offset.
6629     int *LaneMask = &Mask[i * ResMultiplier];
6630 
6631     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6632     ExtractBase += NumElts * (Src - Sources.begin());
6633     for (int j = 0; j < LanesDefined; ++j)
6634       LaneMask[j] = ExtractBase + j;
6635   }
6636 
6637   // Final check before we try to produce nonsense...
6638   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6639     return SDValue();
6640 
6641   // We can't handle more than two sources. This should have already
6642   // been checked before this point.
6643   assert(Sources.size() <= 2 && "Too many sources!");
6644 
6645   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6646   for (unsigned i = 0; i < Sources.size(); ++i)
6647     ShuffleOps[i] = Sources[i].ShuffleVec;
6648 
6649   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6650                                          ShuffleOps[1], Mask);
6651   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6652 }
6653 
6654 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6655 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6656 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6657 /// are assumed to be legal.
6658 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6659   if (VT.getVectorNumElements() == 4 &&
6660       (VT.is128BitVector() || VT.is64BitVector())) {
6661     unsigned PFIndexes[4];
6662     for (unsigned i = 0; i != 4; ++i) {
6663       if (M[i] < 0)
6664         PFIndexes[i] = 8;
6665       else
6666         PFIndexes[i] = M[i];
6667     }
6668 
6669     // Compute the index in the perfect shuffle table.
6670     unsigned PFTableIndex =
6671       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6672     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6673     unsigned Cost = (PFEntry >> 30);
6674 
6675     if (Cost <= 4)
6676       return true;
6677   }
6678 
6679   bool ReverseVEXT, isV_UNDEF;
6680   unsigned Imm, WhichResult;
6681 
6682   unsigned EltSize = VT.getScalarSizeInBits();
6683   return (EltSize >= 32 ||
6684           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6685           isVREVMask(M, VT, 64) ||
6686           isVREVMask(M, VT, 32) ||
6687           isVREVMask(M, VT, 16) ||
6688           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6689           isVTBLMask(M, VT) ||
6690           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6691           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6692 }
6693 
6694 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6695 /// the specified operations to build the shuffle.
6696 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6697                                       SDValue RHS, SelectionDAG &DAG,
6698                                       const SDLoc &dl) {
6699   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6700   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6701   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6702 
6703   enum {
6704     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6705     OP_VREV,
6706     OP_VDUP0,
6707     OP_VDUP1,
6708     OP_VDUP2,
6709     OP_VDUP3,
6710     OP_VEXT1,
6711     OP_VEXT2,
6712     OP_VEXT3,
6713     OP_VUZPL, // VUZP, left result
6714     OP_VUZPR, // VUZP, right result
6715     OP_VZIPL, // VZIP, left result
6716     OP_VZIPR, // VZIP, right result
6717     OP_VTRNL, // VTRN, left result
6718     OP_VTRNR  // VTRN, right result
6719   };
6720 
6721   if (OpNum == OP_COPY) {
6722     if (LHSID == (1*9+2)*9+3) return LHS;
6723     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6724     return RHS;
6725   }
6726 
6727   SDValue OpLHS, OpRHS;
6728   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6729   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6730   EVT VT = OpLHS.getValueType();
6731 
6732   switch (OpNum) {
6733   default: llvm_unreachable("Unknown shuffle opcode!");
6734   case OP_VREV:
6735     // VREV divides the vector in half and swaps within the half.
6736     if (VT.getVectorElementType() == MVT::i32 ||
6737         VT.getVectorElementType() == MVT::f32)
6738       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6739     // vrev <4 x i16> -> VREV32
6740     if (VT.getVectorElementType() == MVT::i16)
6741       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6742     // vrev <4 x i8> -> VREV16
6743     assert(VT.getVectorElementType() == MVT::i8);
6744     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6745   case OP_VDUP0:
6746   case OP_VDUP1:
6747   case OP_VDUP2:
6748   case OP_VDUP3:
6749     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6750                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6751   case OP_VEXT1:
6752   case OP_VEXT2:
6753   case OP_VEXT3:
6754     return DAG.getNode(ARMISD::VEXT, dl, VT,
6755                        OpLHS, OpRHS,
6756                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6757   case OP_VUZPL:
6758   case OP_VUZPR:
6759     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6760                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6761   case OP_VZIPL:
6762   case OP_VZIPR:
6763     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6764                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6765   case OP_VTRNL:
6766   case OP_VTRNR:
6767     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6768                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6769   }
6770 }
6771 
6772 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6773                                        ArrayRef<int> ShuffleMask,
6774                                        SelectionDAG &DAG) {
6775   // Check to see if we can use the VTBL instruction.
6776   SDValue V1 = Op.getOperand(0);
6777   SDValue V2 = Op.getOperand(1);
6778   SDLoc DL(Op);
6779 
6780   SmallVector<SDValue, 8> VTBLMask;
6781   for (ArrayRef<int>::iterator
6782          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6783     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6784 
6785   if (V2.getNode()->isUndef())
6786     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6787                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6788 
6789   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6790                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6791 }
6792 
6793 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6794                                                       SelectionDAG &DAG) {
6795   SDLoc DL(Op);
6796   SDValue OpLHS = Op.getOperand(0);
6797   EVT VT = OpLHS.getValueType();
6798 
6799   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6800          "Expect an v8i16/v16i8 type");
6801   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6802   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6803   // extract the first 8 bytes into the top double word and the last 8 bytes
6804   // into the bottom double word. The v8i16 case is similar.
6805   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6806   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6807                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6808 }
6809 
6810 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6811   SDValue V1 = Op.getOperand(0);
6812   SDValue V2 = Op.getOperand(1);
6813   SDLoc dl(Op);
6814   EVT VT = Op.getValueType();
6815   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6816 
6817   // Convert shuffles that are directly supported on NEON to target-specific
6818   // DAG nodes, instead of keeping them as shuffles and matching them again
6819   // during code selection.  This is more efficient and avoids the possibility
6820   // of inconsistencies between legalization and selection.
6821   // FIXME: floating-point vectors should be canonicalized to integer vectors
6822   // of the same time so that they get CSEd properly.
6823   ArrayRef<int> ShuffleMask = SVN->getMask();
6824 
6825   unsigned EltSize = VT.getScalarSizeInBits();
6826   if (EltSize <= 32) {
6827     if (SVN->isSplat()) {
6828       int Lane = SVN->getSplatIndex();
6829       // If this is undef splat, generate it via "just" vdup, if possible.
6830       if (Lane == -1) Lane = 0;
6831 
6832       // Test if V1 is a SCALAR_TO_VECTOR.
6833       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6834         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6835       }
6836       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6837       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6838       // reaches it).
6839       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6840           !isa<ConstantSDNode>(V1.getOperand(0))) {
6841         bool IsScalarToVector = true;
6842         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6843           if (!V1.getOperand(i).isUndef()) {
6844             IsScalarToVector = false;
6845             break;
6846           }
6847         if (IsScalarToVector)
6848           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6849       }
6850       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6851                          DAG.getConstant(Lane, dl, MVT::i32));
6852     }
6853 
6854     bool ReverseVEXT;
6855     unsigned Imm;
6856     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6857       if (ReverseVEXT)
6858         std::swap(V1, V2);
6859       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6860                          DAG.getConstant(Imm, dl, MVT::i32));
6861     }
6862 
6863     if (isVREVMask(ShuffleMask, VT, 64))
6864       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6865     if (isVREVMask(ShuffleMask, VT, 32))
6866       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6867     if (isVREVMask(ShuffleMask, VT, 16))
6868       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6869 
6870     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6871       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6872                          DAG.getConstant(Imm, dl, MVT::i32));
6873     }
6874 
6875     // Check for Neon shuffles that modify both input vectors in place.
6876     // If both results are used, i.e., if there are two shuffles with the same
6877     // source operands and with masks corresponding to both results of one of
6878     // these operations, DAG memoization will ensure that a single node is
6879     // used for both shuffles.
6880     unsigned WhichResult;
6881     bool isV_UNDEF;
6882     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6883             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6884       if (isV_UNDEF)
6885         V2 = V1;
6886       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6887           .getValue(WhichResult);
6888     }
6889 
6890     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6891     // shuffles that produce a result larger than their operands with:
6892     //   shuffle(concat(v1, undef), concat(v2, undef))
6893     // ->
6894     //   shuffle(concat(v1, v2), undef)
6895     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6896     //
6897     // This is useful in the general case, but there are special cases where
6898     // native shuffles produce larger results: the two-result ops.
6899     //
6900     // Look through the concat when lowering them:
6901     //   shuffle(concat(v1, v2), undef)
6902     // ->
6903     //   concat(VZIP(v1, v2):0, :1)
6904     //
6905     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6906       SDValue SubV1 = V1->getOperand(0);
6907       SDValue SubV2 = V1->getOperand(1);
6908       EVT SubVT = SubV1.getValueType();
6909 
6910       // We expect these to have been canonicalized to -1.
6911       assert(llvm::all_of(ShuffleMask, [&](int i) {
6912         return i < (int)VT.getVectorNumElements();
6913       }) && "Unexpected shuffle index into UNDEF operand!");
6914 
6915       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6916               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6917         if (isV_UNDEF)
6918           SubV2 = SubV1;
6919         assert((WhichResult == 0) &&
6920                "In-place shuffle of concat can only have one result!");
6921         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6922                                   SubV1, SubV2);
6923         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6924                            Res.getValue(1));
6925       }
6926     }
6927   }
6928 
6929   // If the shuffle is not directly supported and it has 4 elements, use
6930   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6931   unsigned NumElts = VT.getVectorNumElements();
6932   if (NumElts == 4) {
6933     unsigned PFIndexes[4];
6934     for (unsigned i = 0; i != 4; ++i) {
6935       if (ShuffleMask[i] < 0)
6936         PFIndexes[i] = 8;
6937       else
6938         PFIndexes[i] = ShuffleMask[i];
6939     }
6940 
6941     // Compute the index in the perfect shuffle table.
6942     unsigned PFTableIndex =
6943       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6944     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6945     unsigned Cost = (PFEntry >> 30);
6946 
6947     if (Cost <= 4)
6948       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6949   }
6950 
6951   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6952   if (EltSize >= 32) {
6953     // Do the expansion with floating-point types, since that is what the VFP
6954     // registers are defined to use, and since i64 is not legal.
6955     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6956     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6957     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6958     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6959     SmallVector<SDValue, 8> Ops;
6960     for (unsigned i = 0; i < NumElts; ++i) {
6961       if (ShuffleMask[i] < 0)
6962         Ops.push_back(DAG.getUNDEF(EltVT));
6963       else
6964         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6965                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6966                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6967                                                   dl, MVT::i32)));
6968     }
6969     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6970     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6971   }
6972 
6973   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6974     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6975 
6976   if (VT == MVT::v8i8)
6977     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6978       return NewOp;
6979 
6980   return SDValue();
6981 }
6982 
6983 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6984   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6985   SDValue Lane = Op.getOperand(2);
6986   if (!isa<ConstantSDNode>(Lane))
6987     return SDValue();
6988 
6989   return Op;
6990 }
6991 
6992 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6993   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6994   SDValue Lane = Op.getOperand(1);
6995   if (!isa<ConstantSDNode>(Lane))
6996     return SDValue();
6997 
6998   SDValue Vec = Op.getOperand(0);
6999   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7000     SDLoc dl(Op);
7001     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7002   }
7003 
7004   return Op;
7005 }
7006 
7007 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7008   // The only time a CONCAT_VECTORS operation can have legal types is when
7009   // two 64-bit vectors are concatenated to a 128-bit vector.
7010   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7011          "unexpected CONCAT_VECTORS");
7012   SDLoc dl(Op);
7013   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7014   SDValue Op0 = Op.getOperand(0);
7015   SDValue Op1 = Op.getOperand(1);
7016   if (!Op0.isUndef())
7017     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7018                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7019                       DAG.getIntPtrConstant(0, dl));
7020   if (!Op1.isUndef())
7021     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7022                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7023                       DAG.getIntPtrConstant(1, dl));
7024   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7025 }
7026 
7027 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7028 /// element has been zero/sign-extended, depending on the isSigned parameter,
7029 /// from an integer type half its size.
7030 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7031                                    bool isSigned) {
7032   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7033   EVT VT = N->getValueType(0);
7034   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7035     SDNode *BVN = N->getOperand(0).getNode();
7036     if (BVN->getValueType(0) != MVT::v4i32 ||
7037         BVN->getOpcode() != ISD::BUILD_VECTOR)
7038       return false;
7039     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7040     unsigned HiElt = 1 - LoElt;
7041     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7042     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7043     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7044     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7045     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7046       return false;
7047     if (isSigned) {
7048       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7049           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7050         return true;
7051     } else {
7052       if (Hi0->isNullValue() && Hi1->isNullValue())
7053         return true;
7054     }
7055     return false;
7056   }
7057 
7058   if (N->getOpcode() != ISD::BUILD_VECTOR)
7059     return false;
7060 
7061   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7062     SDNode *Elt = N->getOperand(i).getNode();
7063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7064       unsigned EltSize = VT.getScalarSizeInBits();
7065       unsigned HalfSize = EltSize / 2;
7066       if (isSigned) {
7067         if (!isIntN(HalfSize, C->getSExtValue()))
7068           return false;
7069       } else {
7070         if (!isUIntN(HalfSize, C->getZExtValue()))
7071           return false;
7072       }
7073       continue;
7074     }
7075     return false;
7076   }
7077 
7078   return true;
7079 }
7080 
7081 /// isSignExtended - Check if a node is a vector value that is sign-extended
7082 /// or a constant BUILD_VECTOR with sign-extended elements.
7083 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7084   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7085     return true;
7086   if (isExtendedBUILD_VECTOR(N, DAG, true))
7087     return true;
7088   return false;
7089 }
7090 
7091 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7092 /// or a constant BUILD_VECTOR with zero-extended elements.
7093 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7094   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7095     return true;
7096   if (isExtendedBUILD_VECTOR(N, DAG, false))
7097     return true;
7098   return false;
7099 }
7100 
7101 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7102   if (OrigVT.getSizeInBits() >= 64)
7103     return OrigVT;
7104 
7105   assert(OrigVT.isSimple() && "Expecting a simple value type");
7106 
7107   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7108   switch (OrigSimpleTy) {
7109   default: llvm_unreachable("Unexpected Vector Type");
7110   case MVT::v2i8:
7111   case MVT::v2i16:
7112      return MVT::v2i32;
7113   case MVT::v4i8:
7114     return  MVT::v4i16;
7115   }
7116 }
7117 
7118 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7119 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7120 /// We insert the required extension here to get the vector to fill a D register.
7121 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7122                                             const EVT &OrigTy,
7123                                             const EVT &ExtTy,
7124                                             unsigned ExtOpcode) {
7125   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7126   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7127   // 64-bits we need to insert a new extension so that it will be 64-bits.
7128   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7129   if (OrigTy.getSizeInBits() >= 64)
7130     return N;
7131 
7132   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7133   EVT NewVT = getExtensionTo64Bits(OrigTy);
7134 
7135   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7136 }
7137 
7138 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7139 /// does not do any sign/zero extension. If the original vector is less
7140 /// than 64 bits, an appropriate extension will be added after the load to
7141 /// reach a total size of 64 bits. We have to add the extension separately
7142 /// because ARM does not have a sign/zero extending load for vectors.
7143 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7144   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7145 
7146   // The load already has the right type.
7147   if (ExtendedTy == LD->getMemoryVT())
7148     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7149                        LD->getBasePtr(), LD->getPointerInfo(),
7150                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7151 
7152   // We need to create a zextload/sextload. We cannot just create a load
7153   // followed by a zext/zext node because LowerMUL is also run during normal
7154   // operation legalization where we can't create illegal types.
7155   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7156                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7157                         LD->getMemoryVT(), LD->getAlignment(),
7158                         LD->getMemOperand()->getFlags());
7159 }
7160 
7161 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7162 /// extending load, or BUILD_VECTOR with extended elements, return the
7163 /// unextended value. The unextended vector should be 64 bits so that it can
7164 /// be used as an operand to a VMULL instruction. If the original vector size
7165 /// before extension is less than 64 bits we add a an extension to resize
7166 /// the vector to 64 bits.
7167 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7168   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7169     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7170                                         N->getOperand(0)->getValueType(0),
7171                                         N->getValueType(0),
7172                                         N->getOpcode());
7173 
7174   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7175     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7176            "Expected extending load");
7177 
7178     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7179     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7180     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7181     SDValue extLoad =
7182         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7183     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7184 
7185     return newLoad;
7186   }
7187 
7188   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7189   // have been legalized as a BITCAST from v4i32.
7190   if (N->getOpcode() == ISD::BITCAST) {
7191     SDNode *BVN = N->getOperand(0).getNode();
7192     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7193            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7194     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7195     return DAG.getBuildVector(
7196         MVT::v2i32, SDLoc(N),
7197         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7198   }
7199   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7200   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7201   EVT VT = N->getValueType(0);
7202   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7203   unsigned NumElts = VT.getVectorNumElements();
7204   MVT TruncVT = MVT::getIntegerVT(EltSize);
7205   SmallVector<SDValue, 8> Ops;
7206   SDLoc dl(N);
7207   for (unsigned i = 0; i != NumElts; ++i) {
7208     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7209     const APInt &CInt = C->getAPIntValue();
7210     // Element types smaller than 32 bits are not legal, so use i32 elements.
7211     // The values are implicitly truncated so sext vs. zext doesn't matter.
7212     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7213   }
7214   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7215 }
7216 
7217 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7218   unsigned Opcode = N->getOpcode();
7219   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7220     SDNode *N0 = N->getOperand(0).getNode();
7221     SDNode *N1 = N->getOperand(1).getNode();
7222     return N0->hasOneUse() && N1->hasOneUse() &&
7223       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7224   }
7225   return false;
7226 }
7227 
7228 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7229   unsigned Opcode = N->getOpcode();
7230   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7231     SDNode *N0 = N->getOperand(0).getNode();
7232     SDNode *N1 = N->getOperand(1).getNode();
7233     return N0->hasOneUse() && N1->hasOneUse() &&
7234       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7235   }
7236   return false;
7237 }
7238 
7239 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7240   // Multiplications are only custom-lowered for 128-bit vectors so that
7241   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7242   EVT VT = Op.getValueType();
7243   assert(VT.is128BitVector() && VT.isInteger() &&
7244          "unexpected type for custom-lowering ISD::MUL");
7245   SDNode *N0 = Op.getOperand(0).getNode();
7246   SDNode *N1 = Op.getOperand(1).getNode();
7247   unsigned NewOpc = 0;
7248   bool isMLA = false;
7249   bool isN0SExt = isSignExtended(N0, DAG);
7250   bool isN1SExt = isSignExtended(N1, DAG);
7251   if (isN0SExt && isN1SExt)
7252     NewOpc = ARMISD::VMULLs;
7253   else {
7254     bool isN0ZExt = isZeroExtended(N0, DAG);
7255     bool isN1ZExt = isZeroExtended(N1, DAG);
7256     if (isN0ZExt && isN1ZExt)
7257       NewOpc = ARMISD::VMULLu;
7258     else if (isN1SExt || isN1ZExt) {
7259       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7260       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7261       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7262         NewOpc = ARMISD::VMULLs;
7263         isMLA = true;
7264       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7265         NewOpc = ARMISD::VMULLu;
7266         isMLA = true;
7267       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7268         std::swap(N0, N1);
7269         NewOpc = ARMISD::VMULLu;
7270         isMLA = true;
7271       }
7272     }
7273 
7274     if (!NewOpc) {
7275       if (VT == MVT::v2i64)
7276         // Fall through to expand this.  It is not legal.
7277         return SDValue();
7278       else
7279         // Other vector multiplications are legal.
7280         return Op;
7281     }
7282   }
7283 
7284   // Legalize to a VMULL instruction.
7285   SDLoc DL(Op);
7286   SDValue Op0;
7287   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7288   if (!isMLA) {
7289     Op0 = SkipExtensionForVMULL(N0, DAG);
7290     assert(Op0.getValueType().is64BitVector() &&
7291            Op1.getValueType().is64BitVector() &&
7292            "unexpected types for extended operands to VMULL");
7293     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7294   }
7295 
7296   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7297   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7298   //   vmull q0, d4, d6
7299   //   vmlal q0, d5, d6
7300   // is faster than
7301   //   vaddl q0, d4, d5
7302   //   vmovl q1, d6
7303   //   vmul  q0, q0, q1
7304   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7305   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7306   EVT Op1VT = Op1.getValueType();
7307   return DAG.getNode(N0->getOpcode(), DL, VT,
7308                      DAG.getNode(NewOpc, DL, VT,
7309                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7310                      DAG.getNode(NewOpc, DL, VT,
7311                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7312 }
7313 
7314 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7315                               SelectionDAG &DAG) {
7316   // TODO: Should this propagate fast-math-flags?
7317 
7318   // Convert to float
7319   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7320   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7321   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7322   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7323   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7324   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7325   // Get reciprocal estimate.
7326   // float4 recip = vrecpeq_f32(yf);
7327   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7328                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7329                    Y);
7330   // Because char has a smaller range than uchar, we can actually get away
7331   // without any newton steps.  This requires that we use a weird bias
7332   // of 0xb000, however (again, this has been exhaustively tested).
7333   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7334   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7335   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7336   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7337   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7338   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7339   // Convert back to short.
7340   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7341   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7342   return X;
7343 }
7344 
7345 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7346                                SelectionDAG &DAG) {
7347   // TODO: Should this propagate fast-math-flags?
7348 
7349   SDValue N2;
7350   // Convert to float.
7351   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7352   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7353   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7354   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7355   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7356   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7357 
7358   // Use reciprocal estimate and one refinement step.
7359   // float4 recip = vrecpeq_f32(yf);
7360   // recip *= vrecpsq_f32(yf, recip);
7361   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7362                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7363                    N1);
7364   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7365                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7366                    N1, N2);
7367   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7368   // Because short has a smaller range than ushort, we can actually get away
7369   // with only a single newton step.  This requires that we use a weird bias
7370   // of 89, however (again, this has been exhaustively tested).
7371   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7372   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7373   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7374   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7375   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7376   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7377   // Convert back to integer and return.
7378   // return vmovn_s32(vcvt_s32_f32(result));
7379   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7380   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7381   return N0;
7382 }
7383 
7384 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7385   EVT VT = Op.getValueType();
7386   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7387          "unexpected type for custom-lowering ISD::SDIV");
7388 
7389   SDLoc dl(Op);
7390   SDValue N0 = Op.getOperand(0);
7391   SDValue N1 = Op.getOperand(1);
7392   SDValue N2, N3;
7393 
7394   if (VT == MVT::v8i8) {
7395     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7396     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7397 
7398     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7399                      DAG.getIntPtrConstant(4, dl));
7400     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7401                      DAG.getIntPtrConstant(4, dl));
7402     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7403                      DAG.getIntPtrConstant(0, dl));
7404     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7405                      DAG.getIntPtrConstant(0, dl));
7406 
7407     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7408     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7409 
7410     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7411     N0 = LowerCONCAT_VECTORS(N0, DAG);
7412 
7413     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7414     return N0;
7415   }
7416   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7417 }
7418 
7419 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7420   // TODO: Should this propagate fast-math-flags?
7421   EVT VT = Op.getValueType();
7422   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7423          "unexpected type for custom-lowering ISD::UDIV");
7424 
7425   SDLoc dl(Op);
7426   SDValue N0 = Op.getOperand(0);
7427   SDValue N1 = Op.getOperand(1);
7428   SDValue N2, N3;
7429 
7430   if (VT == MVT::v8i8) {
7431     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7432     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7433 
7434     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7435                      DAG.getIntPtrConstant(4, dl));
7436     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7437                      DAG.getIntPtrConstant(4, dl));
7438     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7439                      DAG.getIntPtrConstant(0, dl));
7440     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7441                      DAG.getIntPtrConstant(0, dl));
7442 
7443     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7444     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7445 
7446     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7447     N0 = LowerCONCAT_VECTORS(N0, DAG);
7448 
7449     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7450                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7451                                      MVT::i32),
7452                      N0);
7453     return N0;
7454   }
7455 
7456   // v4i16 sdiv ... Convert to float.
7457   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7458   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7459   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7460   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7461   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7462   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7463 
7464   // Use reciprocal estimate and two refinement steps.
7465   // float4 recip = vrecpeq_f32(yf);
7466   // recip *= vrecpsq_f32(yf, recip);
7467   // recip *= vrecpsq_f32(yf, recip);
7468   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7469                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7470                    BN1);
7471   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7472                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7473                    BN1, N2);
7474   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7475   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7476                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7477                    BN1, N2);
7478   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7479   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7480   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7481   // and that it will never cause us to return an answer too large).
7482   // float4 result = as_float4(as_int4(xf*recip) + 2);
7483   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7484   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7485   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7486   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7487   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7488   // Convert back to integer and return.
7489   // return vmovn_u32(vcvt_s32_f32(result));
7490   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7491   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7492   return N0;
7493 }
7494 
7495 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7496   EVT VT = Op.getNode()->getValueType(0);
7497   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7498 
7499   unsigned Opc;
7500   bool ExtraOp = false;
7501   switch (Op.getOpcode()) {
7502   default: llvm_unreachable("Invalid code");
7503   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7504   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7505   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7506   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7507   }
7508 
7509   if (!ExtraOp)
7510     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7511                        Op.getOperand(1));
7512   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7513                      Op.getOperand(1), Op.getOperand(2));
7514 }
7515 
7516 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7517   SDNode *N = Op.getNode();
7518   EVT VT = N->getValueType(0);
7519   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7520 
7521   SDValue Carry = Op.getOperand(2);
7522   EVT CarryVT = Carry.getValueType();
7523 
7524   SDLoc DL(Op);
7525 
7526   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7527 
7528   SDValue Result;
7529   if (Op.getOpcode() == ISD::ADDCARRY) {
7530     // This converts the boolean value carry into the carry flag.
7531     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7532 
7533     // Do the addition proper using the carry flag we wanted.
7534     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7535                          Op.getOperand(1), Carry.getValue(1));
7536 
7537     // Now convert the carry flag into a boolean value.
7538     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7539   } else {
7540     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7541     // have to invert the carry first.
7542     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7543                         DAG.getConstant(1, DL, MVT::i32), Carry);
7544     // This converts the boolean value carry into the carry flag.
7545     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7546 
7547     // Do the subtraction proper using the carry flag we wanted.
7548     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7549                          Op.getOperand(1), Carry.getValue(1));
7550 
7551     // Now convert the carry flag into a boolean value.
7552     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7553     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7554     // by ISD::SUBCARRY, so compute 1 - C.
7555     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7556                         DAG.getConstant(1, DL, MVT::i32), Carry);
7557   }
7558 
7559   // Return both values.
7560   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7561 }
7562 
7563 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7564   assert(Subtarget->isTargetDarwin());
7565 
7566   // For iOS, we want to call an alternative entry point: __sincos_stret,
7567   // return values are passed via sret.
7568   SDLoc dl(Op);
7569   SDValue Arg = Op.getOperand(0);
7570   EVT ArgVT = Arg.getValueType();
7571   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7572   auto PtrVT = getPointerTy(DAG.getDataLayout());
7573 
7574   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7576 
7577   // Pair of floats / doubles used to pass the result.
7578   Type *RetTy = StructType::get(ArgTy, ArgTy);
7579   auto &DL = DAG.getDataLayout();
7580 
7581   ArgListTy Args;
7582   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7583   SDValue SRet;
7584   if (ShouldUseSRet) {
7585     // Create stack object for sret.
7586     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7587     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7588     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7589     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7590 
7591     ArgListEntry Entry;
7592     Entry.Node = SRet;
7593     Entry.Ty = RetTy->getPointerTo();
7594     Entry.IsSExt = false;
7595     Entry.IsZExt = false;
7596     Entry.IsSRet = true;
7597     Args.push_back(Entry);
7598     RetTy = Type::getVoidTy(*DAG.getContext());
7599   }
7600 
7601   ArgListEntry Entry;
7602   Entry.Node = Arg;
7603   Entry.Ty = ArgTy;
7604   Entry.IsSExt = false;
7605   Entry.IsZExt = false;
7606   Args.push_back(Entry);
7607 
7608   RTLIB::Libcall LC =
7609       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7610   const char *LibcallName = getLibcallName(LC);
7611   CallingConv::ID CC = getLibcallCallingConv(LC);
7612   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7613 
7614   TargetLowering::CallLoweringInfo CLI(DAG);
7615   CLI.setDebugLoc(dl)
7616       .setChain(DAG.getEntryNode())
7617       .setCallee(CC, RetTy, Callee, std::move(Args))
7618       .setDiscardResult(ShouldUseSRet);
7619   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7620 
7621   if (!ShouldUseSRet)
7622     return CallResult.first;
7623 
7624   SDValue LoadSin =
7625       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7626 
7627   // Address of cos field.
7628   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7629                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7630   SDValue LoadCos =
7631       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7632 
7633   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7634   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7635                      LoadSin.getValue(0), LoadCos.getValue(0));
7636 }
7637 
7638 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7639                                                   bool Signed,
7640                                                   SDValue &Chain) const {
7641   EVT VT = Op.getValueType();
7642   assert((VT == MVT::i32 || VT == MVT::i64) &&
7643          "unexpected type for custom lowering DIV");
7644   SDLoc dl(Op);
7645 
7646   const auto &DL = DAG.getDataLayout();
7647   const auto &TLI = DAG.getTargetLoweringInfo();
7648 
7649   const char *Name = nullptr;
7650   if (Signed)
7651     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7652   else
7653     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7654 
7655   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7656 
7657   ARMTargetLowering::ArgListTy Args;
7658 
7659   for (auto AI : {1, 0}) {
7660     ArgListEntry Arg;
7661     Arg.Node = Op.getOperand(AI);
7662     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7663     Args.push_back(Arg);
7664   }
7665 
7666   CallLoweringInfo CLI(DAG);
7667   CLI.setDebugLoc(dl)
7668     .setChain(Chain)
7669     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7670                ES, std::move(Args));
7671 
7672   return LowerCallTo(CLI).first;
7673 }
7674 
7675 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7676                                             bool Signed) const {
7677   assert(Op.getValueType() == MVT::i32 &&
7678          "unexpected type for custom lowering DIV");
7679   SDLoc dl(Op);
7680 
7681   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7682                                DAG.getEntryNode(), Op.getOperand(1));
7683 
7684   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7685 }
7686 
7687 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7688   SDLoc DL(N);
7689   SDValue Op = N->getOperand(1);
7690   if (N->getValueType(0) == MVT::i32)
7691     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7692   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7693                            DAG.getConstant(0, DL, MVT::i32));
7694   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7695                            DAG.getConstant(1, DL, MVT::i32));
7696   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7697                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7698 }
7699 
7700 void ARMTargetLowering::ExpandDIV_Windows(
7701     SDValue Op, SelectionDAG &DAG, bool Signed,
7702     SmallVectorImpl<SDValue> &Results) const {
7703   const auto &DL = DAG.getDataLayout();
7704   const auto &TLI = DAG.getTargetLoweringInfo();
7705 
7706   assert(Op.getValueType() == MVT::i64 &&
7707          "unexpected type for custom lowering DIV");
7708   SDLoc dl(Op);
7709 
7710   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7711 
7712   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7713 
7714   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7715   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7716                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7717   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7718 
7719   Results.push_back(Lower);
7720   Results.push_back(Upper);
7721 }
7722 
7723 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7724   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7725     // Acquire/Release load/store is not legal for targets without a dmb or
7726     // equivalent available.
7727     return SDValue();
7728 
7729   // Monotonic load/store is legal for all targets.
7730   return Op;
7731 }
7732 
7733 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7734                                     SmallVectorImpl<SDValue> &Results,
7735                                     SelectionDAG &DAG,
7736                                     const ARMSubtarget *Subtarget) {
7737   SDLoc DL(N);
7738   // Under Power Management extensions, the cycle-count is:
7739   //    mrc p15, #0, <Rt>, c9, c13, #0
7740   SDValue Ops[] = { N->getOperand(0), // Chain
7741                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7742                     DAG.getConstant(15, DL, MVT::i32),
7743                     DAG.getConstant(0, DL, MVT::i32),
7744                     DAG.getConstant(9, DL, MVT::i32),
7745                     DAG.getConstant(13, DL, MVT::i32),
7746                     DAG.getConstant(0, DL, MVT::i32)
7747   };
7748 
7749   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7750                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7751   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7752                                 DAG.getConstant(0, DL, MVT::i32)));
7753   Results.push_back(Cycles32.getValue(1));
7754 }
7755 
7756 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7757   SDLoc dl(V.getNode());
7758   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7759   SDValue VHi = DAG.getAnyExtOrTrunc(
7760       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7761       dl, MVT::i32);
7762   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7763   if (isBigEndian)
7764     std::swap (VLo, VHi);
7765   SDValue RegClass =
7766       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7767   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7768   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7769   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7770   return SDValue(
7771       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7772 }
7773 
7774 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7775                                        SmallVectorImpl<SDValue> & Results,
7776                                        SelectionDAG &DAG) {
7777   assert(N->getValueType(0) == MVT::i64 &&
7778          "AtomicCmpSwap on types less than 64 should be legal");
7779   SDValue Ops[] = {N->getOperand(1),
7780                    createGPRPairNode(DAG, N->getOperand(2)),
7781                    createGPRPairNode(DAG, N->getOperand(3)),
7782                    N->getOperand(0)};
7783   SDNode *CmpSwap = DAG.getMachineNode(
7784       ARM::CMP_SWAP_64, SDLoc(N),
7785       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7786 
7787   MachineFunction &MF = DAG.getMachineFunction();
7788   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7789   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7790   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7791 
7792   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7793 
7794   Results.push_back(
7795       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7796                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7797   Results.push_back(
7798       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7799                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7800   Results.push_back(SDValue(CmpSwap, 2));
7801 }
7802 
7803 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7804                           SelectionDAG &DAG) {
7805   const auto &TLI = DAG.getTargetLoweringInfo();
7806 
7807   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7808          "Custom lowering is MSVCRT specific!");
7809 
7810   SDLoc dl(Op);
7811   SDValue Val = Op.getOperand(0);
7812   MVT Ty = Val->getSimpleValueType(0);
7813   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7814   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7815                                          TLI.getPointerTy(DAG.getDataLayout()));
7816 
7817   TargetLowering::ArgListTy Args;
7818   TargetLowering::ArgListEntry Entry;
7819 
7820   Entry.Node = Val;
7821   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7822   Entry.IsZExt = true;
7823   Args.push_back(Entry);
7824 
7825   Entry.Node = Exponent;
7826   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7827   Entry.IsZExt = true;
7828   Args.push_back(Entry);
7829 
7830   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7831 
7832   // In the in-chain to the call is the entry node  If we are emitting a
7833   // tailcall, the chain will be mutated if the node has a non-entry input
7834   // chain.
7835   SDValue InChain = DAG.getEntryNode();
7836   SDValue TCChain = InChain;
7837 
7838   const Function &F = DAG.getMachineFunction().getFunction();
7839   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7840               F.getReturnType() == LCRTy;
7841   if (IsTC)
7842     InChain = TCChain;
7843 
7844   TargetLowering::CallLoweringInfo CLI(DAG);
7845   CLI.setDebugLoc(dl)
7846       .setChain(InChain)
7847       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7848       .setTailCall(IsTC);
7849   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7850 
7851   // Return the chain (the DAG root) if it is a tail call
7852   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7853 }
7854 
7855 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7856   DEBUG(dbgs() << "Lowering node: "; Op.dump());
7857   switch (Op.getOpcode()) {
7858   default: llvm_unreachable("Don't know how to custom lower this!");
7859   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7860   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7861   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7862   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7863   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7864   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7865   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7866   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
7867   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7868   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7869   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7870   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7871   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7872   case ISD::SINT_TO_FP:
7873   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7874   case ISD::FP_TO_SINT:
7875   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7876   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7877   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7878   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7879   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7880   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7881   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7882   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7883                                                                Subtarget);
7884   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7885   case ISD::SHL:
7886   case ISD::SRL:
7887   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7888   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7889   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7890   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7891   case ISD::SRL_PARTS:
7892   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7893   case ISD::CTTZ:
7894   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7895   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7896   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7897   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7898   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7899   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7900   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7901   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7902   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7903   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7904   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7905   case ISD::MUL:           return LowerMUL(Op, DAG);
7906   case ISD::SDIV:
7907     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7908       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7909     return LowerSDIV(Op, DAG);
7910   case ISD::UDIV:
7911     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7912       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7913     return LowerUDIV(Op, DAG);
7914   case ISD::ADDC:
7915   case ISD::ADDE:
7916   case ISD::SUBC:
7917   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7918   case ISD::ADDCARRY:
7919   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
7920   case ISD::SADDO:
7921   case ISD::SSUBO:
7922     return LowerSignedALUO(Op, DAG);
7923   case ISD::UADDO:
7924   case ISD::USUBO:
7925     return LowerUnsignedALUO(Op, DAG);
7926   case ISD::ATOMIC_LOAD:
7927   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7928   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7929   case ISD::SDIVREM:
7930   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7931   case ISD::DYNAMIC_STACKALLOC:
7932     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7933       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7934     llvm_unreachable("Don't know how to custom lower this!");
7935   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7936   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7937   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7938   case ARMISD::WIN__DBZCHK: return SDValue();
7939   }
7940 }
7941 
7942 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7943                                  SelectionDAG &DAG) {
7944   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7945   unsigned Opc = 0;
7946   if (IntNo == Intrinsic::arm_smlald)
7947     Opc = ARMISD::SMLALD;
7948   else if (IntNo == Intrinsic::arm_smlaldx)
7949     Opc = ARMISD::SMLALDX;
7950   else if (IntNo == Intrinsic::arm_smlsld)
7951     Opc = ARMISD::SMLSLD;
7952   else if (IntNo == Intrinsic::arm_smlsldx)
7953     Opc = ARMISD::SMLSLDX;
7954   else
7955     return;
7956 
7957   SDLoc dl(N);
7958   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7959                            N->getOperand(3),
7960                            DAG.getConstant(0, dl, MVT::i32));
7961   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7962                            N->getOperand(3),
7963                            DAG.getConstant(1, dl, MVT::i32));
7964 
7965   SDValue LongMul = DAG.getNode(Opc, dl,
7966                                 DAG.getVTList(MVT::i32, MVT::i32),
7967                                 N->getOperand(1), N->getOperand(2),
7968                                 Lo, Hi);
7969   Results.push_back(LongMul.getValue(0));
7970   Results.push_back(LongMul.getValue(1));
7971 }
7972 
7973 /// ReplaceNodeResults - Replace the results of node with an illegal result
7974 /// type with new values built out of custom code.
7975 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7976                                            SmallVectorImpl<SDValue> &Results,
7977                                            SelectionDAG &DAG) const {
7978   SDValue Res;
7979   switch (N->getOpcode()) {
7980   default:
7981     llvm_unreachable("Don't know how to custom expand this!");
7982   case ISD::READ_REGISTER:
7983     ExpandREAD_REGISTER(N, Results, DAG);
7984     break;
7985   case ISD::BITCAST:
7986     Res = ExpandBITCAST(N, DAG);
7987     break;
7988   case ISD::SRL:
7989   case ISD::SRA:
7990     Res = Expand64BitShift(N, DAG, Subtarget);
7991     break;
7992   case ISD::SREM:
7993   case ISD::UREM:
7994     Res = LowerREM(N, DAG);
7995     break;
7996   case ISD::SDIVREM:
7997   case ISD::UDIVREM:
7998     Res = LowerDivRem(SDValue(N, 0), DAG);
7999     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8000     Results.push_back(Res.getValue(0));
8001     Results.push_back(Res.getValue(1));
8002     return;
8003   case ISD::READCYCLECOUNTER:
8004     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8005     return;
8006   case ISD::UDIV:
8007   case ISD::SDIV:
8008     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8009     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8010                              Results);
8011   case ISD::ATOMIC_CMP_SWAP:
8012     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8013     return;
8014   case ISD::INTRINSIC_WO_CHAIN:
8015     return ReplaceLongIntrinsic(N, Results, DAG);
8016   }
8017   if (Res.getNode())
8018     Results.push_back(Res);
8019 }
8020 
8021 //===----------------------------------------------------------------------===//
8022 //                           ARM Scheduler Hooks
8023 //===----------------------------------------------------------------------===//
8024 
8025 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8026 /// registers the function context.
8027 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8028                                                MachineBasicBlock *MBB,
8029                                                MachineBasicBlock *DispatchBB,
8030                                                int FI) const {
8031   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8032          "ROPI/RWPI not currently supported with SjLj");
8033   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8034   DebugLoc dl = MI.getDebugLoc();
8035   MachineFunction *MF = MBB->getParent();
8036   MachineRegisterInfo *MRI = &MF->getRegInfo();
8037   MachineConstantPool *MCP = MF->getConstantPool();
8038   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8039   const Function &F = MF->getFunction();
8040 
8041   bool isThumb = Subtarget->isThumb();
8042   bool isThumb2 = Subtarget->isThumb2();
8043 
8044   unsigned PCLabelId = AFI->createPICLabelUId();
8045   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8046   ARMConstantPoolValue *CPV =
8047     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8048   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8049 
8050   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8051                                            : &ARM::GPRRegClass;
8052 
8053   // Grab constant pool and fixed stack memory operands.
8054   MachineMemOperand *CPMMO =
8055       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8056                                MachineMemOperand::MOLoad, 4, 4);
8057 
8058   MachineMemOperand *FIMMOSt =
8059       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8060                                MachineMemOperand::MOStore, 4, 4);
8061 
8062   // Load the address of the dispatch MBB into the jump buffer.
8063   if (isThumb2) {
8064     // Incoming value: jbuf
8065     //   ldr.n  r5, LCPI1_1
8066     //   orr    r5, r5, #1
8067     //   add    r5, pc
8068     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8069     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8070     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8071         .addConstantPoolIndex(CPI)
8072         .addMemOperand(CPMMO)
8073         .add(predOps(ARMCC::AL));
8074     // Set the low bit because of thumb mode.
8075     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8076     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8077         .addReg(NewVReg1, RegState::Kill)
8078         .addImm(0x01)
8079         .add(predOps(ARMCC::AL))
8080         .add(condCodeOp());
8081     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8082     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8083       .addReg(NewVReg2, RegState::Kill)
8084       .addImm(PCLabelId);
8085     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8086         .addReg(NewVReg3, RegState::Kill)
8087         .addFrameIndex(FI)
8088         .addImm(36) // &jbuf[1] :: pc
8089         .addMemOperand(FIMMOSt)
8090         .add(predOps(ARMCC::AL));
8091   } else if (isThumb) {
8092     // Incoming value: jbuf
8093     //   ldr.n  r1, LCPI1_4
8094     //   add    r1, pc
8095     //   mov    r2, #1
8096     //   orrs   r1, r2
8097     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8098     //   str    r1, [r2]
8099     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8100     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8101         .addConstantPoolIndex(CPI)
8102         .addMemOperand(CPMMO)
8103         .add(predOps(ARMCC::AL));
8104     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8105     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8106       .addReg(NewVReg1, RegState::Kill)
8107       .addImm(PCLabelId);
8108     // Set the low bit because of thumb mode.
8109     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8110     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8111         .addReg(ARM::CPSR, RegState::Define)
8112         .addImm(1)
8113         .add(predOps(ARMCC::AL));
8114     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8115     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8116         .addReg(ARM::CPSR, RegState::Define)
8117         .addReg(NewVReg2, RegState::Kill)
8118         .addReg(NewVReg3, RegState::Kill)
8119         .add(predOps(ARMCC::AL));
8120     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8121     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8122             .addFrameIndex(FI)
8123             .addImm(36); // &jbuf[1] :: pc
8124     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8125         .addReg(NewVReg4, RegState::Kill)
8126         .addReg(NewVReg5, RegState::Kill)
8127         .addImm(0)
8128         .addMemOperand(FIMMOSt)
8129         .add(predOps(ARMCC::AL));
8130   } else {
8131     // Incoming value: jbuf
8132     //   ldr  r1, LCPI1_1
8133     //   add  r1, pc, r1
8134     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8135     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8136     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8137         .addConstantPoolIndex(CPI)
8138         .addImm(0)
8139         .addMemOperand(CPMMO)
8140         .add(predOps(ARMCC::AL));
8141     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8142     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8143         .addReg(NewVReg1, RegState::Kill)
8144         .addImm(PCLabelId)
8145         .add(predOps(ARMCC::AL));
8146     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8147         .addReg(NewVReg2, RegState::Kill)
8148         .addFrameIndex(FI)
8149         .addImm(36) // &jbuf[1] :: pc
8150         .addMemOperand(FIMMOSt)
8151         .add(predOps(ARMCC::AL));
8152   }
8153 }
8154 
8155 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8156                                               MachineBasicBlock *MBB) const {
8157   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8158   DebugLoc dl = MI.getDebugLoc();
8159   MachineFunction *MF = MBB->getParent();
8160   MachineRegisterInfo *MRI = &MF->getRegInfo();
8161   MachineFrameInfo &MFI = MF->getFrameInfo();
8162   int FI = MFI.getFunctionContextIndex();
8163 
8164   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8165                                                         : &ARM::GPRnopcRegClass;
8166 
8167   // Get a mapping of the call site numbers to all of the landing pads they're
8168   // associated with.
8169   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8170   unsigned MaxCSNum = 0;
8171   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8172        ++BB) {
8173     if (!BB->isEHPad()) continue;
8174 
8175     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8176     // pad.
8177     for (MachineBasicBlock::iterator
8178            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8179       if (!II->isEHLabel()) continue;
8180 
8181       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8182       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8183 
8184       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8185       for (SmallVectorImpl<unsigned>::iterator
8186              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8187            CSI != CSE; ++CSI) {
8188         CallSiteNumToLPad[*CSI].push_back(&*BB);
8189         MaxCSNum = std::max(MaxCSNum, *CSI);
8190       }
8191       break;
8192     }
8193   }
8194 
8195   // Get an ordered list of the machine basic blocks for the jump table.
8196   std::vector<MachineBasicBlock*> LPadList;
8197   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8198   LPadList.reserve(CallSiteNumToLPad.size());
8199   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8200     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8201     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8202            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8203       LPadList.push_back(*II);
8204       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8205     }
8206   }
8207 
8208   assert(!LPadList.empty() &&
8209          "No landing pad destinations for the dispatch jump table!");
8210 
8211   // Create the jump table and associated information.
8212   MachineJumpTableInfo *JTI =
8213     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8214   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8215 
8216   // Create the MBBs for the dispatch code.
8217 
8218   // Shove the dispatch's address into the return slot in the function context.
8219   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8220   DispatchBB->setIsEHPad();
8221 
8222   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8223   unsigned trap_opcode;
8224   if (Subtarget->isThumb())
8225     trap_opcode = ARM::tTRAP;
8226   else
8227     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8228 
8229   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8230   DispatchBB->addSuccessor(TrapBB);
8231 
8232   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8233   DispatchBB->addSuccessor(DispContBB);
8234 
8235   // Insert and MBBs.
8236   MF->insert(MF->end(), DispatchBB);
8237   MF->insert(MF->end(), DispContBB);
8238   MF->insert(MF->end(), TrapBB);
8239 
8240   // Insert code into the entry block that creates and registers the function
8241   // context.
8242   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8243 
8244   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8245       MachinePointerInfo::getFixedStack(*MF, FI),
8246       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8247 
8248   MachineInstrBuilder MIB;
8249   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8250 
8251   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8252   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8253 
8254   // Add a register mask with no preserved registers.  This results in all
8255   // registers being marked as clobbered. This can't work if the dispatch block
8256   // is in a Thumb1 function and is linked with ARM code which uses the FP
8257   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8258   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8259 
8260   bool IsPositionIndependent = isPositionIndependent();
8261   unsigned NumLPads = LPadList.size();
8262   if (Subtarget->isThumb2()) {
8263     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8264     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8265         .addFrameIndex(FI)
8266         .addImm(4)
8267         .addMemOperand(FIMMOLd)
8268         .add(predOps(ARMCC::AL));
8269 
8270     if (NumLPads < 256) {
8271       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8272           .addReg(NewVReg1)
8273           .addImm(LPadList.size())
8274           .add(predOps(ARMCC::AL));
8275     } else {
8276       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8277       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8278           .addImm(NumLPads & 0xFFFF)
8279           .add(predOps(ARMCC::AL));
8280 
8281       unsigned VReg2 = VReg1;
8282       if ((NumLPads & 0xFFFF0000) != 0) {
8283         VReg2 = MRI->createVirtualRegister(TRC);
8284         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8285             .addReg(VReg1)
8286             .addImm(NumLPads >> 16)
8287             .add(predOps(ARMCC::AL));
8288       }
8289 
8290       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8291           .addReg(NewVReg1)
8292           .addReg(VReg2)
8293           .add(predOps(ARMCC::AL));
8294     }
8295 
8296     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8297       .addMBB(TrapBB)
8298       .addImm(ARMCC::HI)
8299       .addReg(ARM::CPSR);
8300 
8301     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8302     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8303         .addJumpTableIndex(MJTI)
8304         .add(predOps(ARMCC::AL));
8305 
8306     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8307     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8308         .addReg(NewVReg3, RegState::Kill)
8309         .addReg(NewVReg1)
8310         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8311         .add(predOps(ARMCC::AL))
8312         .add(condCodeOp());
8313 
8314     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8315       .addReg(NewVReg4, RegState::Kill)
8316       .addReg(NewVReg1)
8317       .addJumpTableIndex(MJTI);
8318   } else if (Subtarget->isThumb()) {
8319     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8320     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8321         .addFrameIndex(FI)
8322         .addImm(1)
8323         .addMemOperand(FIMMOLd)
8324         .add(predOps(ARMCC::AL));
8325 
8326     if (NumLPads < 256) {
8327       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8328           .addReg(NewVReg1)
8329           .addImm(NumLPads)
8330           .add(predOps(ARMCC::AL));
8331     } else {
8332       MachineConstantPool *ConstantPool = MF->getConstantPool();
8333       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8334       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8335 
8336       // MachineConstantPool wants an explicit alignment.
8337       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8338       if (Align == 0)
8339         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8340       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8341 
8342       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8343       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8344           .addReg(VReg1, RegState::Define)
8345           .addConstantPoolIndex(Idx)
8346           .add(predOps(ARMCC::AL));
8347       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8348           .addReg(NewVReg1)
8349           .addReg(VReg1)
8350           .add(predOps(ARMCC::AL));
8351     }
8352 
8353     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8354       .addMBB(TrapBB)
8355       .addImm(ARMCC::HI)
8356       .addReg(ARM::CPSR);
8357 
8358     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8359     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8360         .addReg(ARM::CPSR, RegState::Define)
8361         .addReg(NewVReg1)
8362         .addImm(2)
8363         .add(predOps(ARMCC::AL));
8364 
8365     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8366     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8367         .addJumpTableIndex(MJTI)
8368         .add(predOps(ARMCC::AL));
8369 
8370     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8371     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8372         .addReg(ARM::CPSR, RegState::Define)
8373         .addReg(NewVReg2, RegState::Kill)
8374         .addReg(NewVReg3)
8375         .add(predOps(ARMCC::AL));
8376 
8377     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8378         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8379 
8380     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8381     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8382         .addReg(NewVReg4, RegState::Kill)
8383         .addImm(0)
8384         .addMemOperand(JTMMOLd)
8385         .add(predOps(ARMCC::AL));
8386 
8387     unsigned NewVReg6 = NewVReg5;
8388     if (IsPositionIndependent) {
8389       NewVReg6 = MRI->createVirtualRegister(TRC);
8390       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8391           .addReg(ARM::CPSR, RegState::Define)
8392           .addReg(NewVReg5, RegState::Kill)
8393           .addReg(NewVReg3)
8394           .add(predOps(ARMCC::AL));
8395     }
8396 
8397     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8398       .addReg(NewVReg6, RegState::Kill)
8399       .addJumpTableIndex(MJTI);
8400   } else {
8401     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8402     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8403         .addFrameIndex(FI)
8404         .addImm(4)
8405         .addMemOperand(FIMMOLd)
8406         .add(predOps(ARMCC::AL));
8407 
8408     if (NumLPads < 256) {
8409       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8410           .addReg(NewVReg1)
8411           .addImm(NumLPads)
8412           .add(predOps(ARMCC::AL));
8413     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8414       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8415       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8416           .addImm(NumLPads & 0xFFFF)
8417           .add(predOps(ARMCC::AL));
8418 
8419       unsigned VReg2 = VReg1;
8420       if ((NumLPads & 0xFFFF0000) != 0) {
8421         VReg2 = MRI->createVirtualRegister(TRC);
8422         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8423             .addReg(VReg1)
8424             .addImm(NumLPads >> 16)
8425             .add(predOps(ARMCC::AL));
8426       }
8427 
8428       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8429           .addReg(NewVReg1)
8430           .addReg(VReg2)
8431           .add(predOps(ARMCC::AL));
8432     } else {
8433       MachineConstantPool *ConstantPool = MF->getConstantPool();
8434       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8435       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8436 
8437       // MachineConstantPool wants an explicit alignment.
8438       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8439       if (Align == 0)
8440         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8441       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8442 
8443       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8444       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8445           .addReg(VReg1, RegState::Define)
8446           .addConstantPoolIndex(Idx)
8447           .addImm(0)
8448           .add(predOps(ARMCC::AL));
8449       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8450           .addReg(NewVReg1)
8451           .addReg(VReg1, RegState::Kill)
8452           .add(predOps(ARMCC::AL));
8453     }
8454 
8455     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8456       .addMBB(TrapBB)
8457       .addImm(ARMCC::HI)
8458       .addReg(ARM::CPSR);
8459 
8460     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8461     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8462         .addReg(NewVReg1)
8463         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8464         .add(predOps(ARMCC::AL))
8465         .add(condCodeOp());
8466     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8467     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8468         .addJumpTableIndex(MJTI)
8469         .add(predOps(ARMCC::AL));
8470 
8471     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8472         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8473     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8474     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8475         .addReg(NewVReg3, RegState::Kill)
8476         .addReg(NewVReg4)
8477         .addImm(0)
8478         .addMemOperand(JTMMOLd)
8479         .add(predOps(ARMCC::AL));
8480 
8481     if (IsPositionIndependent) {
8482       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8483         .addReg(NewVReg5, RegState::Kill)
8484         .addReg(NewVReg4)
8485         .addJumpTableIndex(MJTI);
8486     } else {
8487       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8488         .addReg(NewVReg5, RegState::Kill)
8489         .addJumpTableIndex(MJTI);
8490     }
8491   }
8492 
8493   // Add the jump table entries as successors to the MBB.
8494   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8495   for (std::vector<MachineBasicBlock*>::iterator
8496          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8497     MachineBasicBlock *CurMBB = *I;
8498     if (SeenMBBs.insert(CurMBB).second)
8499       DispContBB->addSuccessor(CurMBB);
8500   }
8501 
8502   // N.B. the order the invoke BBs are processed in doesn't matter here.
8503   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8504   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8505   for (MachineBasicBlock *BB : InvokeBBs) {
8506 
8507     // Remove the landing pad successor from the invoke block and replace it
8508     // with the new dispatch block.
8509     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8510                                                   BB->succ_end());
8511     while (!Successors.empty()) {
8512       MachineBasicBlock *SMBB = Successors.pop_back_val();
8513       if (SMBB->isEHPad()) {
8514         BB->removeSuccessor(SMBB);
8515         MBBLPads.push_back(SMBB);
8516       }
8517     }
8518 
8519     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8520     BB->normalizeSuccProbs();
8521 
8522     // Find the invoke call and mark all of the callee-saved registers as
8523     // 'implicit defined' so that they're spilled. This prevents code from
8524     // moving instructions to before the EH block, where they will never be
8525     // executed.
8526     for (MachineBasicBlock::reverse_iterator
8527            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8528       if (!II->isCall()) continue;
8529 
8530       DenseMap<unsigned, bool> DefRegs;
8531       for (MachineInstr::mop_iterator
8532              OI = II->operands_begin(), OE = II->operands_end();
8533            OI != OE; ++OI) {
8534         if (!OI->isReg()) continue;
8535         DefRegs[OI->getReg()] = true;
8536       }
8537 
8538       MachineInstrBuilder MIB(*MF, &*II);
8539 
8540       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8541         unsigned Reg = SavedRegs[i];
8542         if (Subtarget->isThumb2() &&
8543             !ARM::tGPRRegClass.contains(Reg) &&
8544             !ARM::hGPRRegClass.contains(Reg))
8545           continue;
8546         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8547           continue;
8548         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8549           continue;
8550         if (!DefRegs[Reg])
8551           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8552       }
8553 
8554       break;
8555     }
8556   }
8557 
8558   // Mark all former landing pads as non-landing pads. The dispatch is the only
8559   // landing pad now.
8560   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8561          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8562     (*I)->setIsEHPad(false);
8563 
8564   // The instruction is gone now.
8565   MI.eraseFromParent();
8566 }
8567 
8568 static
8569 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8570   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8571        E = MBB->succ_end(); I != E; ++I)
8572     if (*I != Succ)
8573       return *I;
8574   llvm_unreachable("Expecting a BB with two successors!");
8575 }
8576 
8577 /// Return the load opcode for a given load size. If load size >= 8,
8578 /// neon opcode will be returned.
8579 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8580   if (LdSize >= 8)
8581     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8582                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8583   if (IsThumb1)
8584     return LdSize == 4 ? ARM::tLDRi
8585                        : LdSize == 2 ? ARM::tLDRHi
8586                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8587   if (IsThumb2)
8588     return LdSize == 4 ? ARM::t2LDR_POST
8589                        : LdSize == 2 ? ARM::t2LDRH_POST
8590                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8591   return LdSize == 4 ? ARM::LDR_POST_IMM
8592                      : LdSize == 2 ? ARM::LDRH_POST
8593                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8594 }
8595 
8596 /// Return the store opcode for a given store size. If store size >= 8,
8597 /// neon opcode will be returned.
8598 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8599   if (StSize >= 8)
8600     return StSize == 16 ? ARM::VST1q32wb_fixed
8601                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8602   if (IsThumb1)
8603     return StSize == 4 ? ARM::tSTRi
8604                        : StSize == 2 ? ARM::tSTRHi
8605                                      : StSize == 1 ? ARM::tSTRBi : 0;
8606   if (IsThumb2)
8607     return StSize == 4 ? ARM::t2STR_POST
8608                        : StSize == 2 ? ARM::t2STRH_POST
8609                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8610   return StSize == 4 ? ARM::STR_POST_IMM
8611                      : StSize == 2 ? ARM::STRH_POST
8612                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8613 }
8614 
8615 /// Emit a post-increment load operation with given size. The instructions
8616 /// will be added to BB at Pos.
8617 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8618                        const TargetInstrInfo *TII, const DebugLoc &dl,
8619                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8620                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8621   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8622   assert(LdOpc != 0 && "Should have a load opcode");
8623   if (LdSize >= 8) {
8624     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8625         .addReg(AddrOut, RegState::Define)
8626         .addReg(AddrIn)
8627         .addImm(0)
8628         .add(predOps(ARMCC::AL));
8629   } else if (IsThumb1) {
8630     // load + update AddrIn
8631     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8632         .addReg(AddrIn)
8633         .addImm(0)
8634         .add(predOps(ARMCC::AL));
8635     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8636         .add(t1CondCodeOp())
8637         .addReg(AddrIn)
8638         .addImm(LdSize)
8639         .add(predOps(ARMCC::AL));
8640   } else if (IsThumb2) {
8641     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8642         .addReg(AddrOut, RegState::Define)
8643         .addReg(AddrIn)
8644         .addImm(LdSize)
8645         .add(predOps(ARMCC::AL));
8646   } else { // arm
8647     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8648         .addReg(AddrOut, RegState::Define)
8649         .addReg(AddrIn)
8650         .addReg(0)
8651         .addImm(LdSize)
8652         .add(predOps(ARMCC::AL));
8653   }
8654 }
8655 
8656 /// Emit a post-increment store operation with given size. The instructions
8657 /// will be added to BB at Pos.
8658 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8659                        const TargetInstrInfo *TII, const DebugLoc &dl,
8660                        unsigned StSize, unsigned Data, unsigned AddrIn,
8661                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8662   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8663   assert(StOpc != 0 && "Should have a store opcode");
8664   if (StSize >= 8) {
8665     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8666         .addReg(AddrIn)
8667         .addImm(0)
8668         .addReg(Data)
8669         .add(predOps(ARMCC::AL));
8670   } else if (IsThumb1) {
8671     // store + update AddrIn
8672     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8673         .addReg(Data)
8674         .addReg(AddrIn)
8675         .addImm(0)
8676         .add(predOps(ARMCC::AL));
8677     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8678         .add(t1CondCodeOp())
8679         .addReg(AddrIn)
8680         .addImm(StSize)
8681         .add(predOps(ARMCC::AL));
8682   } else if (IsThumb2) {
8683     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8684         .addReg(Data)
8685         .addReg(AddrIn)
8686         .addImm(StSize)
8687         .add(predOps(ARMCC::AL));
8688   } else { // arm
8689     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8690         .addReg(Data)
8691         .addReg(AddrIn)
8692         .addReg(0)
8693         .addImm(StSize)
8694         .add(predOps(ARMCC::AL));
8695   }
8696 }
8697 
8698 MachineBasicBlock *
8699 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8700                                    MachineBasicBlock *BB) const {
8701   // This pseudo instruction has 3 operands: dst, src, size
8702   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8703   // Otherwise, we will generate unrolled scalar copies.
8704   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8705   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8706   MachineFunction::iterator It = ++BB->getIterator();
8707 
8708   unsigned dest = MI.getOperand(0).getReg();
8709   unsigned src = MI.getOperand(1).getReg();
8710   unsigned SizeVal = MI.getOperand(2).getImm();
8711   unsigned Align = MI.getOperand(3).getImm();
8712   DebugLoc dl = MI.getDebugLoc();
8713 
8714   MachineFunction *MF = BB->getParent();
8715   MachineRegisterInfo &MRI = MF->getRegInfo();
8716   unsigned UnitSize = 0;
8717   const TargetRegisterClass *TRC = nullptr;
8718   const TargetRegisterClass *VecTRC = nullptr;
8719 
8720   bool IsThumb1 = Subtarget->isThumb1Only();
8721   bool IsThumb2 = Subtarget->isThumb2();
8722   bool IsThumb = Subtarget->isThumb();
8723 
8724   if (Align & 1) {
8725     UnitSize = 1;
8726   } else if (Align & 2) {
8727     UnitSize = 2;
8728   } else {
8729     // Check whether we can use NEON instructions.
8730     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8731         Subtarget->hasNEON()) {
8732       if ((Align % 16 == 0) && SizeVal >= 16)
8733         UnitSize = 16;
8734       else if ((Align % 8 == 0) && SizeVal >= 8)
8735         UnitSize = 8;
8736     }
8737     // Can't use NEON instructions.
8738     if (UnitSize == 0)
8739       UnitSize = 4;
8740   }
8741 
8742   // Select the correct opcode and register class for unit size load/store
8743   bool IsNeon = UnitSize >= 8;
8744   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8745   if (IsNeon)
8746     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8747                             : UnitSize == 8 ? &ARM::DPRRegClass
8748                                             : nullptr;
8749 
8750   unsigned BytesLeft = SizeVal % UnitSize;
8751   unsigned LoopSize = SizeVal - BytesLeft;
8752 
8753   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8754     // Use LDR and STR to copy.
8755     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8756     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8757     unsigned srcIn = src;
8758     unsigned destIn = dest;
8759     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8760       unsigned srcOut = MRI.createVirtualRegister(TRC);
8761       unsigned destOut = MRI.createVirtualRegister(TRC);
8762       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8763       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8764                  IsThumb1, IsThumb2);
8765       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8766                  IsThumb1, IsThumb2);
8767       srcIn = srcOut;
8768       destIn = destOut;
8769     }
8770 
8771     // Handle the leftover bytes with LDRB and STRB.
8772     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8773     // [destOut] = STRB_POST(scratch, destIn, 1)
8774     for (unsigned i = 0; i < BytesLeft; i++) {
8775       unsigned srcOut = MRI.createVirtualRegister(TRC);
8776       unsigned destOut = MRI.createVirtualRegister(TRC);
8777       unsigned scratch = MRI.createVirtualRegister(TRC);
8778       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8779                  IsThumb1, IsThumb2);
8780       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8781                  IsThumb1, IsThumb2);
8782       srcIn = srcOut;
8783       destIn = destOut;
8784     }
8785     MI.eraseFromParent(); // The instruction is gone now.
8786     return BB;
8787   }
8788 
8789   // Expand the pseudo op to a loop.
8790   // thisMBB:
8791   //   ...
8792   //   movw varEnd, # --> with thumb2
8793   //   movt varEnd, #
8794   //   ldrcp varEnd, idx --> without thumb2
8795   //   fallthrough --> loopMBB
8796   // loopMBB:
8797   //   PHI varPhi, varEnd, varLoop
8798   //   PHI srcPhi, src, srcLoop
8799   //   PHI destPhi, dst, destLoop
8800   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8801   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8802   //   subs varLoop, varPhi, #UnitSize
8803   //   bne loopMBB
8804   //   fallthrough --> exitMBB
8805   // exitMBB:
8806   //   epilogue to handle left-over bytes
8807   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8808   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8809   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8810   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8811   MF->insert(It, loopMBB);
8812   MF->insert(It, exitMBB);
8813 
8814   // Transfer the remainder of BB and its successor edges to exitMBB.
8815   exitMBB->splice(exitMBB->begin(), BB,
8816                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8817   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8818 
8819   // Load an immediate to varEnd.
8820   unsigned varEnd = MRI.createVirtualRegister(TRC);
8821   if (Subtarget->useMovt(*MF)) {
8822     unsigned Vtmp = varEnd;
8823     if ((LoopSize & 0xFFFF0000) != 0)
8824       Vtmp = MRI.createVirtualRegister(TRC);
8825     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8826         .addImm(LoopSize & 0xFFFF)
8827         .add(predOps(ARMCC::AL));
8828 
8829     if ((LoopSize & 0xFFFF0000) != 0)
8830       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8831           .addReg(Vtmp)
8832           .addImm(LoopSize >> 16)
8833           .add(predOps(ARMCC::AL));
8834   } else {
8835     MachineConstantPool *ConstantPool = MF->getConstantPool();
8836     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8837     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8838 
8839     // MachineConstantPool wants an explicit alignment.
8840     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8841     if (Align == 0)
8842       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8843     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8844 
8845     if (IsThumb)
8846       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8847           .addReg(varEnd, RegState::Define)
8848           .addConstantPoolIndex(Idx)
8849           .add(predOps(ARMCC::AL));
8850     else
8851       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8852           .addReg(varEnd, RegState::Define)
8853           .addConstantPoolIndex(Idx)
8854           .addImm(0)
8855           .add(predOps(ARMCC::AL));
8856   }
8857   BB->addSuccessor(loopMBB);
8858 
8859   // Generate the loop body:
8860   //   varPhi = PHI(varLoop, varEnd)
8861   //   srcPhi = PHI(srcLoop, src)
8862   //   destPhi = PHI(destLoop, dst)
8863   MachineBasicBlock *entryBB = BB;
8864   BB = loopMBB;
8865   unsigned varLoop = MRI.createVirtualRegister(TRC);
8866   unsigned varPhi = MRI.createVirtualRegister(TRC);
8867   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8868   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8869   unsigned destLoop = MRI.createVirtualRegister(TRC);
8870   unsigned destPhi = MRI.createVirtualRegister(TRC);
8871 
8872   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8873     .addReg(varLoop).addMBB(loopMBB)
8874     .addReg(varEnd).addMBB(entryBB);
8875   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8876     .addReg(srcLoop).addMBB(loopMBB)
8877     .addReg(src).addMBB(entryBB);
8878   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8879     .addReg(destLoop).addMBB(loopMBB)
8880     .addReg(dest).addMBB(entryBB);
8881 
8882   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8883   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8884   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8885   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8886              IsThumb1, IsThumb2);
8887   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8888              IsThumb1, IsThumb2);
8889 
8890   // Decrement loop variable by UnitSize.
8891   if (IsThumb1) {
8892     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8893         .add(t1CondCodeOp())
8894         .addReg(varPhi)
8895         .addImm(UnitSize)
8896         .add(predOps(ARMCC::AL));
8897   } else {
8898     MachineInstrBuilder MIB =
8899         BuildMI(*BB, BB->end(), dl,
8900                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8901     MIB.addReg(varPhi)
8902         .addImm(UnitSize)
8903         .add(predOps(ARMCC::AL))
8904         .add(condCodeOp());
8905     MIB->getOperand(5).setReg(ARM::CPSR);
8906     MIB->getOperand(5).setIsDef(true);
8907   }
8908   BuildMI(*BB, BB->end(), dl,
8909           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8910       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8911 
8912   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8913   BB->addSuccessor(loopMBB);
8914   BB->addSuccessor(exitMBB);
8915 
8916   // Add epilogue to handle BytesLeft.
8917   BB = exitMBB;
8918   auto StartOfExit = exitMBB->begin();
8919 
8920   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8921   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8922   unsigned srcIn = srcLoop;
8923   unsigned destIn = destLoop;
8924   for (unsigned i = 0; i < BytesLeft; i++) {
8925     unsigned srcOut = MRI.createVirtualRegister(TRC);
8926     unsigned destOut = MRI.createVirtualRegister(TRC);
8927     unsigned scratch = MRI.createVirtualRegister(TRC);
8928     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8929                IsThumb1, IsThumb2);
8930     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8931                IsThumb1, IsThumb2);
8932     srcIn = srcOut;
8933     destIn = destOut;
8934   }
8935 
8936   MI.eraseFromParent(); // The instruction is gone now.
8937   return BB;
8938 }
8939 
8940 MachineBasicBlock *
8941 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8942                                        MachineBasicBlock *MBB) const {
8943   const TargetMachine &TM = getTargetMachine();
8944   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8945   DebugLoc DL = MI.getDebugLoc();
8946 
8947   assert(Subtarget->isTargetWindows() &&
8948          "__chkstk is only supported on Windows");
8949   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8950 
8951   // __chkstk takes the number of words to allocate on the stack in R4, and
8952   // returns the stack adjustment in number of bytes in R4.  This will not
8953   // clober any other registers (other than the obvious lr).
8954   //
8955   // Although, technically, IP should be considered a register which may be
8956   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8957   // thumb-2 environment, so there is no interworking required.  As a result, we
8958   // do not expect a veneer to be emitted by the linker, clobbering IP.
8959   //
8960   // Each module receives its own copy of __chkstk, so no import thunk is
8961   // required, again, ensuring that IP is not clobbered.
8962   //
8963   // Finally, although some linkers may theoretically provide a trampoline for
8964   // out of range calls (which is quite common due to a 32M range limitation of
8965   // branches for Thumb), we can generate the long-call version via
8966   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8967   // IP.
8968 
8969   switch (TM.getCodeModel()) {
8970   case CodeModel::Small:
8971   case CodeModel::Medium:
8972   case CodeModel::Kernel:
8973     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8974         .add(predOps(ARMCC::AL))
8975         .addExternalSymbol("__chkstk")
8976         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8977         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8978         .addReg(ARM::R12,
8979                 RegState::Implicit | RegState::Define | RegState::Dead)
8980         .addReg(ARM::CPSR,
8981                 RegState::Implicit | RegState::Define | RegState::Dead);
8982     break;
8983   case CodeModel::Large: {
8984     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8985     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8986 
8987     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8988       .addExternalSymbol("__chkstk");
8989     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8990         .add(predOps(ARMCC::AL))
8991         .addReg(Reg, RegState::Kill)
8992         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8993         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8994         .addReg(ARM::R12,
8995                 RegState::Implicit | RegState::Define | RegState::Dead)
8996         .addReg(ARM::CPSR,
8997                 RegState::Implicit | RegState::Define | RegState::Dead);
8998     break;
8999   }
9000   }
9001 
9002   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9003       .addReg(ARM::SP, RegState::Kill)
9004       .addReg(ARM::R4, RegState::Kill)
9005       .setMIFlags(MachineInstr::FrameSetup)
9006       .add(predOps(ARMCC::AL))
9007       .add(condCodeOp());
9008 
9009   MI.eraseFromParent();
9010   return MBB;
9011 }
9012 
9013 MachineBasicBlock *
9014 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9015                                        MachineBasicBlock *MBB) const {
9016   DebugLoc DL = MI.getDebugLoc();
9017   MachineFunction *MF = MBB->getParent();
9018   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9019 
9020   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9021   MF->insert(++MBB->getIterator(), ContBB);
9022   ContBB->splice(ContBB->begin(), MBB,
9023                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9024   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9025   MBB->addSuccessor(ContBB);
9026 
9027   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9028   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9029   MF->push_back(TrapBB);
9030   MBB->addSuccessor(TrapBB);
9031 
9032   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9033       .addReg(MI.getOperand(0).getReg())
9034       .addImm(0)
9035       .add(predOps(ARMCC::AL));
9036   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9037       .addMBB(TrapBB)
9038       .addImm(ARMCC::EQ)
9039       .addReg(ARM::CPSR);
9040 
9041   MI.eraseFromParent();
9042   return ContBB;
9043 }
9044 
9045 MachineBasicBlock *
9046 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9047                                                MachineBasicBlock *BB) const {
9048   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9049   DebugLoc dl = MI.getDebugLoc();
9050   bool isThumb2 = Subtarget->isThumb2();
9051   switch (MI.getOpcode()) {
9052   default: {
9053     MI.print(errs());
9054     llvm_unreachable("Unexpected instr type to insert");
9055   }
9056 
9057   // Thumb1 post-indexed loads are really just single-register LDMs.
9058   case ARM::tLDR_postidx: {
9059     MachineOperand Def(MI.getOperand(1));
9060     if (TargetRegisterInfo::isPhysicalRegister(Def.getReg()))
9061       Def.setIsRenamable(false);
9062     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9063         .add(Def)  // Rn_wb
9064         .add(MI.getOperand(2))  // Rn
9065         .add(MI.getOperand(3))  // PredImm
9066         .add(MI.getOperand(4))  // PredReg
9067         .add(MI.getOperand(0)); // Rt
9068     MI.eraseFromParent();
9069     return BB;
9070   }
9071 
9072   // The Thumb2 pre-indexed stores have the same MI operands, they just
9073   // define them differently in the .td files from the isel patterns, so
9074   // they need pseudos.
9075   case ARM::t2STR_preidx:
9076     MI.setDesc(TII->get(ARM::t2STR_PRE));
9077     return BB;
9078   case ARM::t2STRB_preidx:
9079     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9080     return BB;
9081   case ARM::t2STRH_preidx:
9082     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9083     return BB;
9084 
9085   case ARM::STRi_preidx:
9086   case ARM::STRBi_preidx: {
9087     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9088                                                          : ARM::STRB_PRE_IMM;
9089     // Decode the offset.
9090     unsigned Offset = MI.getOperand(4).getImm();
9091     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9092     Offset = ARM_AM::getAM2Offset(Offset);
9093     if (isSub)
9094       Offset = -Offset;
9095 
9096     MachineMemOperand *MMO = *MI.memoperands_begin();
9097     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9098         .add(MI.getOperand(0)) // Rn_wb
9099         .add(MI.getOperand(1)) // Rt
9100         .add(MI.getOperand(2)) // Rn
9101         .addImm(Offset)        // offset (skip GPR==zero_reg)
9102         .add(MI.getOperand(5)) // pred
9103         .add(MI.getOperand(6))
9104         .addMemOperand(MMO);
9105     MI.eraseFromParent();
9106     return BB;
9107   }
9108   case ARM::STRr_preidx:
9109   case ARM::STRBr_preidx:
9110   case ARM::STRH_preidx: {
9111     unsigned NewOpc;
9112     switch (MI.getOpcode()) {
9113     default: llvm_unreachable("unexpected opcode!");
9114     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9115     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9116     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9117     }
9118     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9119     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9120       MIB.add(MI.getOperand(i));
9121     MI.eraseFromParent();
9122     return BB;
9123   }
9124 
9125   case ARM::tMOVCCr_pseudo: {
9126     // To "insert" a SELECT_CC instruction, we actually have to insert the
9127     // diamond control-flow pattern.  The incoming instruction knows the
9128     // destination vreg to set, the condition code register to branch on, the
9129     // true/false values to select between, and a branch opcode to use.
9130     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9131     MachineFunction::iterator It = ++BB->getIterator();
9132 
9133     //  thisMBB:
9134     //  ...
9135     //   TrueVal = ...
9136     //   cmpTY ccX, r1, r2
9137     //   bCC copy1MBB
9138     //   fallthrough --> copy0MBB
9139     MachineBasicBlock *thisMBB  = BB;
9140     MachineFunction *F = BB->getParent();
9141     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9142     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9143     F->insert(It, copy0MBB);
9144     F->insert(It, sinkMBB);
9145 
9146     // Transfer the remainder of BB and its successor edges to sinkMBB.
9147     sinkMBB->splice(sinkMBB->begin(), BB,
9148                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9149     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9150 
9151     BB->addSuccessor(copy0MBB);
9152     BB->addSuccessor(sinkMBB);
9153 
9154     BuildMI(BB, dl, TII->get(ARM::tBcc))
9155         .addMBB(sinkMBB)
9156         .addImm(MI.getOperand(3).getImm())
9157         .addReg(MI.getOperand(4).getReg());
9158 
9159     //  copy0MBB:
9160     //   %FalseValue = ...
9161     //   # fallthrough to sinkMBB
9162     BB = copy0MBB;
9163 
9164     // Update machine-CFG edges
9165     BB->addSuccessor(sinkMBB);
9166 
9167     //  sinkMBB:
9168     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9169     //  ...
9170     BB = sinkMBB;
9171     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9172         .addReg(MI.getOperand(1).getReg())
9173         .addMBB(copy0MBB)
9174         .addReg(MI.getOperand(2).getReg())
9175         .addMBB(thisMBB);
9176 
9177     MI.eraseFromParent(); // The pseudo instruction is gone now.
9178     return BB;
9179   }
9180 
9181   case ARM::BCCi64:
9182   case ARM::BCCZi64: {
9183     // If there is an unconditional branch to the other successor, remove it.
9184     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9185 
9186     // Compare both parts that make up the double comparison separately for
9187     // equality.
9188     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9189 
9190     unsigned LHS1 = MI.getOperand(1).getReg();
9191     unsigned LHS2 = MI.getOperand(2).getReg();
9192     if (RHSisZero) {
9193       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9194           .addReg(LHS1)
9195           .addImm(0)
9196           .add(predOps(ARMCC::AL));
9197       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9198         .addReg(LHS2).addImm(0)
9199         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9200     } else {
9201       unsigned RHS1 = MI.getOperand(3).getReg();
9202       unsigned RHS2 = MI.getOperand(4).getReg();
9203       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9204           .addReg(LHS1)
9205           .addReg(RHS1)
9206           .add(predOps(ARMCC::AL));
9207       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9208         .addReg(LHS2).addReg(RHS2)
9209         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9210     }
9211 
9212     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9213     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9214     if (MI.getOperand(0).getImm() == ARMCC::NE)
9215       std::swap(destMBB, exitMBB);
9216 
9217     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9218       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9219     if (isThumb2)
9220       BuildMI(BB, dl, TII->get(ARM::t2B))
9221           .addMBB(exitMBB)
9222           .add(predOps(ARMCC::AL));
9223     else
9224       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9225 
9226     MI.eraseFromParent(); // The pseudo instruction is gone now.
9227     return BB;
9228   }
9229 
9230   case ARM::Int_eh_sjlj_setjmp:
9231   case ARM::Int_eh_sjlj_setjmp_nofp:
9232   case ARM::tInt_eh_sjlj_setjmp:
9233   case ARM::t2Int_eh_sjlj_setjmp:
9234   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9235     return BB;
9236 
9237   case ARM::Int_eh_sjlj_setup_dispatch:
9238     EmitSjLjDispatchBlock(MI, BB);
9239     return BB;
9240 
9241   case ARM::ABS:
9242   case ARM::t2ABS: {
9243     // To insert an ABS instruction, we have to insert the
9244     // diamond control-flow pattern.  The incoming instruction knows the
9245     // source vreg to test against 0, the destination vreg to set,
9246     // the condition code register to branch on, the
9247     // true/false values to select between, and a branch opcode to use.
9248     // It transforms
9249     //     V1 = ABS V0
9250     // into
9251     //     V2 = MOVS V0
9252     //     BCC                      (branch to SinkBB if V0 >= 0)
9253     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9254     //     SinkBB: V1 = PHI(V2, V3)
9255     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9256     MachineFunction::iterator BBI = ++BB->getIterator();
9257     MachineFunction *Fn = BB->getParent();
9258     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9259     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9260     Fn->insert(BBI, RSBBB);
9261     Fn->insert(BBI, SinkBB);
9262 
9263     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9264     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9265     bool ABSSrcKIll = MI.getOperand(1).isKill();
9266     bool isThumb2 = Subtarget->isThumb2();
9267     MachineRegisterInfo &MRI = Fn->getRegInfo();
9268     // In Thumb mode S must not be specified if source register is the SP or
9269     // PC and if destination register is the SP, so restrict register class
9270     unsigned NewRsbDstReg =
9271       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9272 
9273     // Transfer the remainder of BB and its successor edges to sinkMBB.
9274     SinkBB->splice(SinkBB->begin(), BB,
9275                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9276     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9277 
9278     BB->addSuccessor(RSBBB);
9279     BB->addSuccessor(SinkBB);
9280 
9281     // fall through to SinkMBB
9282     RSBBB->addSuccessor(SinkBB);
9283 
9284     // insert a cmp at the end of BB
9285     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9286         .addReg(ABSSrcReg)
9287         .addImm(0)
9288         .add(predOps(ARMCC::AL));
9289 
9290     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9291     BuildMI(BB, dl,
9292       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9293       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9294 
9295     // insert rsbri in RSBBB
9296     // Note: BCC and rsbri will be converted into predicated rsbmi
9297     // by if-conversion pass
9298     BuildMI(*RSBBB, RSBBB->begin(), dl,
9299             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9300         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9301         .addImm(0)
9302         .add(predOps(ARMCC::AL))
9303         .add(condCodeOp());
9304 
9305     // insert PHI in SinkBB,
9306     // reuse ABSDstReg to not change uses of ABS instruction
9307     BuildMI(*SinkBB, SinkBB->begin(), dl,
9308       TII->get(ARM::PHI), ABSDstReg)
9309       .addReg(NewRsbDstReg).addMBB(RSBBB)
9310       .addReg(ABSSrcReg).addMBB(BB);
9311 
9312     // remove ABS instruction
9313     MI.eraseFromParent();
9314 
9315     // return last added BB
9316     return SinkBB;
9317   }
9318   case ARM::COPY_STRUCT_BYVAL_I32:
9319     ++NumLoopByVals;
9320     return EmitStructByval(MI, BB);
9321   case ARM::WIN__CHKSTK:
9322     return EmitLowered__chkstk(MI, BB);
9323   case ARM::WIN__DBZCHK:
9324     return EmitLowered__dbzchk(MI, BB);
9325   }
9326 }
9327 
9328 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9329 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9330 /// instead of as a custom inserter because we need the use list from the SDNode.
9331 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9332                                     MachineInstr &MI, const SDNode *Node) {
9333   bool isThumb1 = Subtarget->isThumb1Only();
9334 
9335   DebugLoc DL = MI.getDebugLoc();
9336   MachineFunction *MF = MI.getParent()->getParent();
9337   MachineRegisterInfo &MRI = MF->getRegInfo();
9338   MachineInstrBuilder MIB(*MF, MI);
9339 
9340   // If the new dst/src is unused mark it as dead.
9341   if (!Node->hasAnyUseOfValue(0)) {
9342     MI.getOperand(0).setIsDead(true);
9343   }
9344   if (!Node->hasAnyUseOfValue(1)) {
9345     MI.getOperand(1).setIsDead(true);
9346   }
9347 
9348   // The MEMCPY both defines and kills the scratch registers.
9349   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9350     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9351                                                          : &ARM::GPRRegClass);
9352     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9353   }
9354 }
9355 
9356 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9357                                                       SDNode *Node) const {
9358   if (MI.getOpcode() == ARM::MEMCPY) {
9359     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9360     return;
9361   }
9362 
9363   const MCInstrDesc *MCID = &MI.getDesc();
9364   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9365   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9366   // operand is still set to noreg. If needed, set the optional operand's
9367   // register to CPSR, and remove the redundant implicit def.
9368   //
9369   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9370 
9371   // Rename pseudo opcodes.
9372   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9373   unsigned ccOutIdx;
9374   if (NewOpc) {
9375     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9376     MCID = &TII->get(NewOpc);
9377 
9378     assert(MCID->getNumOperands() ==
9379            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9380         && "converted opcode should be the same except for cc_out"
9381            " (and, on Thumb1, pred)");
9382 
9383     MI.setDesc(*MCID);
9384 
9385     // Add the optional cc_out operand
9386     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9387 
9388     // On Thumb1, move all input operands to the end, then add the predicate
9389     if (Subtarget->isThumb1Only()) {
9390       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9391         MI.addOperand(MI.getOperand(1));
9392         MI.RemoveOperand(1);
9393       }
9394 
9395       // Restore the ties
9396       for (unsigned i = MI.getNumOperands(); i--;) {
9397         const MachineOperand& op = MI.getOperand(i);
9398         if (op.isReg() && op.isUse()) {
9399           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9400           if (DefIdx != -1)
9401             MI.tieOperands(DefIdx, i);
9402         }
9403       }
9404 
9405       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9406       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9407       ccOutIdx = 1;
9408     } else
9409       ccOutIdx = MCID->getNumOperands() - 1;
9410   } else
9411     ccOutIdx = MCID->getNumOperands() - 1;
9412 
9413   // Any ARM instruction that sets the 's' bit should specify an optional
9414   // "cc_out" operand in the last operand position.
9415   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9416     assert(!NewOpc && "Optional cc_out operand required");
9417     return;
9418   }
9419   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9420   // since we already have an optional CPSR def.
9421   bool definesCPSR = false;
9422   bool deadCPSR = false;
9423   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9424        ++i) {
9425     const MachineOperand &MO = MI.getOperand(i);
9426     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9427       definesCPSR = true;
9428       if (MO.isDead())
9429         deadCPSR = true;
9430       MI.RemoveOperand(i);
9431       break;
9432     }
9433   }
9434   if (!definesCPSR) {
9435     assert(!NewOpc && "Optional cc_out operand required");
9436     return;
9437   }
9438   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9439   if (deadCPSR) {
9440     assert(!MI.getOperand(ccOutIdx).getReg() &&
9441            "expect uninitialized optional cc_out operand");
9442     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9443     if (!Subtarget->isThumb1Only())
9444       return;
9445   }
9446 
9447   // If this instruction was defined with an optional CPSR def and its dag node
9448   // had a live implicit CPSR def, then activate the optional CPSR def.
9449   MachineOperand &MO = MI.getOperand(ccOutIdx);
9450   MO.setReg(ARM::CPSR);
9451   MO.setIsDef(true);
9452 }
9453 
9454 //===----------------------------------------------------------------------===//
9455 //                           ARM Optimization Hooks
9456 //===----------------------------------------------------------------------===//
9457 
9458 // Helper function that checks if N is a null or all ones constant.
9459 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9460   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9461 }
9462 
9463 // Return true if N is conditionally 0 or all ones.
9464 // Detects these expressions where cc is an i1 value:
9465 //
9466 //   (select cc 0, y)   [AllOnes=0]
9467 //   (select cc y, 0)   [AllOnes=0]
9468 //   (zext cc)          [AllOnes=0]
9469 //   (sext cc)          [AllOnes=0/1]
9470 //   (select cc -1, y)  [AllOnes=1]
9471 //   (select cc y, -1)  [AllOnes=1]
9472 //
9473 // Invert is set when N is the null/all ones constant when CC is false.
9474 // OtherOp is set to the alternative value of N.
9475 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9476                                        SDValue &CC, bool &Invert,
9477                                        SDValue &OtherOp,
9478                                        SelectionDAG &DAG) {
9479   switch (N->getOpcode()) {
9480   default: return false;
9481   case ISD::SELECT: {
9482     CC = N->getOperand(0);
9483     SDValue N1 = N->getOperand(1);
9484     SDValue N2 = N->getOperand(2);
9485     if (isZeroOrAllOnes(N1, AllOnes)) {
9486       Invert = false;
9487       OtherOp = N2;
9488       return true;
9489     }
9490     if (isZeroOrAllOnes(N2, AllOnes)) {
9491       Invert = true;
9492       OtherOp = N1;
9493       return true;
9494     }
9495     return false;
9496   }
9497   case ISD::ZERO_EXTEND:
9498     // (zext cc) can never be the all ones value.
9499     if (AllOnes)
9500       return false;
9501     LLVM_FALLTHROUGH;
9502   case ISD::SIGN_EXTEND: {
9503     SDLoc dl(N);
9504     EVT VT = N->getValueType(0);
9505     CC = N->getOperand(0);
9506     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9507       return false;
9508     Invert = !AllOnes;
9509     if (AllOnes)
9510       // When looking for an AllOnes constant, N is an sext, and the 'other'
9511       // value is 0.
9512       OtherOp = DAG.getConstant(0, dl, VT);
9513     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9514       // When looking for a 0 constant, N can be zext or sext.
9515       OtherOp = DAG.getConstant(1, dl, VT);
9516     else
9517       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9518                                 VT);
9519     return true;
9520   }
9521   }
9522 }
9523 
9524 // Combine a constant select operand into its use:
9525 //
9526 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9527 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9528 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9529 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9530 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9531 //
9532 // The transform is rejected if the select doesn't have a constant operand that
9533 // is null, or all ones when AllOnes is set.
9534 //
9535 // Also recognize sext/zext from i1:
9536 //
9537 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9538 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9539 //
9540 // These transformations eventually create predicated instructions.
9541 //
9542 // @param N       The node to transform.
9543 // @param Slct    The N operand that is a select.
9544 // @param OtherOp The other N operand (x above).
9545 // @param DCI     Context.
9546 // @param AllOnes Require the select constant to be all ones instead of null.
9547 // @returns The new node, or SDValue() on failure.
9548 static
9549 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9550                             TargetLowering::DAGCombinerInfo &DCI,
9551                             bool AllOnes = false) {
9552   SelectionDAG &DAG = DCI.DAG;
9553   EVT VT = N->getValueType(0);
9554   SDValue NonConstantVal;
9555   SDValue CCOp;
9556   bool SwapSelectOps;
9557   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9558                                   NonConstantVal, DAG))
9559     return SDValue();
9560 
9561   // Slct is now know to be the desired identity constant when CC is true.
9562   SDValue TrueVal = OtherOp;
9563   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9564                                  OtherOp, NonConstantVal);
9565   // Unless SwapSelectOps says CC should be false.
9566   if (SwapSelectOps)
9567     std::swap(TrueVal, FalseVal);
9568 
9569   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9570                      CCOp, TrueVal, FalseVal);
9571 }
9572 
9573 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9574 static
9575 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9576                                        TargetLowering::DAGCombinerInfo &DCI) {
9577   SDValue N0 = N->getOperand(0);
9578   SDValue N1 = N->getOperand(1);
9579   if (N0.getNode()->hasOneUse())
9580     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9581       return Result;
9582   if (N1.getNode()->hasOneUse())
9583     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9584       return Result;
9585   return SDValue();
9586 }
9587 
9588 static bool IsVUZPShuffleNode(SDNode *N) {
9589   // VUZP shuffle node.
9590   if (N->getOpcode() == ARMISD::VUZP)
9591     return true;
9592 
9593   // "VUZP" on i32 is an alias for VTRN.
9594   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9595     return true;
9596 
9597   return false;
9598 }
9599 
9600 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9601                                  TargetLowering::DAGCombinerInfo &DCI,
9602                                  const ARMSubtarget *Subtarget) {
9603   // Look for ADD(VUZP.0, VUZP.1).
9604   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9605       N0 == N1)
9606    return SDValue();
9607 
9608   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9609   if (!N->getValueType(0).is64BitVector())
9610     return SDValue();
9611 
9612   // Generate vpadd.
9613   SelectionDAG &DAG = DCI.DAG;
9614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9615   SDLoc dl(N);
9616   SDNode *Unzip = N0.getNode();
9617   EVT VT = N->getValueType(0);
9618 
9619   SmallVector<SDValue, 8> Ops;
9620   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9621                                 TLI.getPointerTy(DAG.getDataLayout())));
9622   Ops.push_back(Unzip->getOperand(0));
9623   Ops.push_back(Unzip->getOperand(1));
9624 
9625   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9626 }
9627 
9628 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9629                                       TargetLowering::DAGCombinerInfo &DCI,
9630                                       const ARMSubtarget *Subtarget) {
9631   // Check for two extended operands.
9632   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9633         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9634       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9635         N1.getOpcode() == ISD::ZERO_EXTEND))
9636     return SDValue();
9637 
9638   SDValue N00 = N0.getOperand(0);
9639   SDValue N10 = N1.getOperand(0);
9640 
9641   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9642   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9643       N00 == N10)
9644     return SDValue();
9645 
9646   // We only recognize Q register paddl here; this can't be reached until
9647   // after type legalization.
9648   if (!N00.getValueType().is64BitVector() ||
9649       !N0.getValueType().is128BitVector())
9650     return SDValue();
9651 
9652   // Generate vpaddl.
9653   SelectionDAG &DAG = DCI.DAG;
9654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655   SDLoc dl(N);
9656   EVT VT = N->getValueType(0);
9657 
9658   SmallVector<SDValue, 8> Ops;
9659   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9660   unsigned Opcode;
9661   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9662     Opcode = Intrinsic::arm_neon_vpaddls;
9663   else
9664     Opcode = Intrinsic::arm_neon_vpaddlu;
9665   Ops.push_back(DAG.getConstant(Opcode, dl,
9666                                 TLI.getPointerTy(DAG.getDataLayout())));
9667   EVT ElemTy = N00.getValueType().getVectorElementType();
9668   unsigned NumElts = VT.getVectorNumElements();
9669   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9670   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9671                                N00.getOperand(0), N00.getOperand(1));
9672   Ops.push_back(Concat);
9673 
9674   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9675 }
9676 
9677 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9678 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9679 // much easier to match.
9680 static SDValue
9681 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9682                                TargetLowering::DAGCombinerInfo &DCI,
9683                                const ARMSubtarget *Subtarget) {
9684   // Only perform optimization if after legalize, and if NEON is available. We
9685   // also expected both operands to be BUILD_VECTORs.
9686   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9687       || N0.getOpcode() != ISD::BUILD_VECTOR
9688       || N1.getOpcode() != ISD::BUILD_VECTOR)
9689     return SDValue();
9690 
9691   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9692   EVT VT = N->getValueType(0);
9693   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9694     return SDValue();
9695 
9696   // Check that the vector operands are of the right form.
9697   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9698   // operands, where N is the size of the formed vector.
9699   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9700   // index such that we have a pair wise add pattern.
9701 
9702   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9703   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9704     return SDValue();
9705   SDValue Vec = N0->getOperand(0)->getOperand(0);
9706   SDNode *V = Vec.getNode();
9707   unsigned nextIndex = 0;
9708 
9709   // For each operands to the ADD which are BUILD_VECTORs,
9710   // check to see if each of their operands are an EXTRACT_VECTOR with
9711   // the same vector and appropriate index.
9712   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9713     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9714         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9715 
9716       SDValue ExtVec0 = N0->getOperand(i);
9717       SDValue ExtVec1 = N1->getOperand(i);
9718 
9719       // First operand is the vector, verify its the same.
9720       if (V != ExtVec0->getOperand(0).getNode() ||
9721           V != ExtVec1->getOperand(0).getNode())
9722         return SDValue();
9723 
9724       // Second is the constant, verify its correct.
9725       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9726       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9727 
9728       // For the constant, we want to see all the even or all the odd.
9729       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9730           || C1->getZExtValue() != nextIndex+1)
9731         return SDValue();
9732 
9733       // Increment index.
9734       nextIndex+=2;
9735     } else
9736       return SDValue();
9737   }
9738 
9739   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9740   // we're using the entire input vector, otherwise there's a size/legality
9741   // mismatch somewhere.
9742   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9743       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9744     return SDValue();
9745 
9746   // Create VPADDL node.
9747   SelectionDAG &DAG = DCI.DAG;
9748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9749 
9750   SDLoc dl(N);
9751 
9752   // Build operand list.
9753   SmallVector<SDValue, 8> Ops;
9754   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9755                                 TLI.getPointerTy(DAG.getDataLayout())));
9756 
9757   // Input is the vector.
9758   Ops.push_back(Vec);
9759 
9760   // Get widened type and narrowed type.
9761   MVT widenType;
9762   unsigned numElem = VT.getVectorNumElements();
9763 
9764   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9765   switch (inputLaneType.getSimpleVT().SimpleTy) {
9766     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9767     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9768     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9769     default:
9770       llvm_unreachable("Invalid vector element type for padd optimization.");
9771   }
9772 
9773   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9774   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9775   return DAG.getNode(ExtOp, dl, VT, tmp);
9776 }
9777 
9778 static SDValue findMUL_LOHI(SDValue V) {
9779   if (V->getOpcode() == ISD::UMUL_LOHI ||
9780       V->getOpcode() == ISD::SMUL_LOHI)
9781     return V;
9782   return SDValue();
9783 }
9784 
9785 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9786                                         TargetLowering::DAGCombinerInfo &DCI,
9787                                         const ARMSubtarget *Subtarget) {
9788   if (Subtarget->isThumb()) {
9789     if (!Subtarget->hasDSP())
9790       return SDValue();
9791   } else if (!Subtarget->hasV5TEOps())
9792     return SDValue();
9793 
9794   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9795   // accumulates the product into a 64-bit value. The 16-bit values will
9796   // be sign extended somehow or SRA'd into 32-bit values
9797   // (addc (adde (mul 16bit, 16bit), lo), hi)
9798   SDValue Mul = AddcNode->getOperand(0);
9799   SDValue Lo = AddcNode->getOperand(1);
9800   if (Mul.getOpcode() != ISD::MUL) {
9801     Lo = AddcNode->getOperand(0);
9802     Mul = AddcNode->getOperand(1);
9803     if (Mul.getOpcode() != ISD::MUL)
9804       return SDValue();
9805   }
9806 
9807   SDValue SRA = AddeNode->getOperand(0);
9808   SDValue Hi = AddeNode->getOperand(1);
9809   if (SRA.getOpcode() != ISD::SRA) {
9810     SRA = AddeNode->getOperand(1);
9811     Hi = AddeNode->getOperand(0);
9812     if (SRA.getOpcode() != ISD::SRA)
9813       return SDValue();
9814   }
9815   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9816     if (Const->getZExtValue() != 31)
9817       return SDValue();
9818   } else
9819     return SDValue();
9820 
9821   if (SRA.getOperand(0) != Mul)
9822     return SDValue();
9823 
9824   SelectionDAG &DAG = DCI.DAG;
9825   SDLoc dl(AddcNode);
9826   unsigned Opcode = 0;
9827   SDValue Op0;
9828   SDValue Op1;
9829 
9830   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9831     Opcode = ARMISD::SMLALBB;
9832     Op0 = Mul.getOperand(0);
9833     Op1 = Mul.getOperand(1);
9834   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9835     Opcode = ARMISD::SMLALBT;
9836     Op0 = Mul.getOperand(0);
9837     Op1 = Mul.getOperand(1).getOperand(0);
9838   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9839     Opcode = ARMISD::SMLALTB;
9840     Op0 = Mul.getOperand(0).getOperand(0);
9841     Op1 = Mul.getOperand(1);
9842   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9843     Opcode = ARMISD::SMLALTT;
9844     Op0 = Mul->getOperand(0).getOperand(0);
9845     Op1 = Mul->getOperand(1).getOperand(0);
9846   }
9847 
9848   if (!Op0 || !Op1)
9849     return SDValue();
9850 
9851   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9852                               Op0, Op1, Lo, Hi);
9853   // Replace the ADDs' nodes uses by the MLA node's values.
9854   SDValue HiMLALResult(SMLAL.getNode(), 1);
9855   SDValue LoMLALResult(SMLAL.getNode(), 0);
9856 
9857   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9858   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9859 
9860   // Return original node to notify the driver to stop replacing.
9861   SDValue resNode(AddcNode, 0);
9862   return resNode;
9863 }
9864 
9865 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
9866                                      TargetLowering::DAGCombinerInfo &DCI,
9867                                      const ARMSubtarget *Subtarget) {
9868   // Look for multiply add opportunities.
9869   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9870   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9871   // a glue link from the first add to the second add.
9872   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9873   // a S/UMLAL instruction.
9874   //                  UMUL_LOHI
9875   //                 / :lo    \ :hi
9876   //                V          \          [no multiline comment]
9877   //    loAdd ->  ADDC         |
9878   //                 \ :carry /
9879   //                  V      V
9880   //                    ADDE   <- hiAdd
9881   //
9882   // In the special case where only the higher part of a signed result is used
9883   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
9884   // a constant with the exact value of 0x80000000, we recognize we are dealing
9885   // with a "rounded multiply and add" (or subtract) and transform it into
9886   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
9887 
9888   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
9889           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
9890          "Expect an ADDE or SUBE");
9891 
9892   assert(AddeSubeNode->getNumOperands() == 3 &&
9893          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
9894          "ADDE node has the wrong inputs");
9895 
9896   // Check that we are chained to the right ADDC or SUBC node.
9897   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
9898   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
9899        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
9900       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
9901        AddcSubcNode->getOpcode() != ARMISD::SUBC))
9902     return SDValue();
9903 
9904   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
9905   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
9906 
9907   // Check if the two operands are from the same mul_lohi node.
9908   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
9909     return SDValue();
9910 
9911   assert(AddcSubcNode->getNumValues() == 2 &&
9912          AddcSubcNode->getValueType(0) == MVT::i32 &&
9913          "Expect ADDC with two result values. First: i32");
9914 
9915   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9916   // maybe a SMLAL which multiplies two 16-bit values.
9917   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
9918       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
9919       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
9920       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
9921       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
9922     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
9923 
9924   // Check for the triangle shape.
9925   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
9926   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
9927 
9928   // Make sure that the ADDE/SUBE operands are not coming from the same node.
9929   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
9930     return SDValue();
9931 
9932   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
9933   bool IsLeftOperandMUL = false;
9934   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
9935   if (MULOp == SDValue())
9936     MULOp = findMUL_LOHI(AddeSubeOp1);
9937   else
9938     IsLeftOperandMUL = true;
9939   if (MULOp == SDValue())
9940     return SDValue();
9941 
9942   // Figure out the right opcode.
9943   unsigned Opc = MULOp->getOpcode();
9944   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9945 
9946   // Figure out the high and low input values to the MLAL node.
9947   SDValue *HiAddSub = nullptr;
9948   SDValue *LoMul = nullptr;
9949   SDValue *LowAddSub = nullptr;
9950 
9951   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
9952   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
9953     return SDValue();
9954 
9955   if (IsLeftOperandMUL)
9956     HiAddSub = &AddeSubeOp1;
9957   else
9958     HiAddSub = &AddeSubeOp0;
9959 
9960   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
9961   // whose low result is fed to the ADDC/SUBC we are checking.
9962 
9963   if (AddcSubcOp0 == MULOp.getValue(0)) {
9964     LoMul = &AddcSubcOp0;
9965     LowAddSub = &AddcSubcOp1;
9966   }
9967   if (AddcSubcOp1 == MULOp.getValue(0)) {
9968     LoMul = &AddcSubcOp1;
9969     LowAddSub = &AddcSubcOp0;
9970   }
9971 
9972   if (!LoMul)
9973     return SDValue();
9974 
9975   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
9976   // the replacement below will create a cycle.
9977   if (AddcSubcNode == HiAddSub->getNode() ||
9978       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
9979     return SDValue();
9980 
9981   // Create the merged node.
9982   SelectionDAG &DAG = DCI.DAG;
9983 
9984   // Start building operand list.
9985   SmallVector<SDValue, 8> Ops;
9986   Ops.push_back(LoMul->getOperand(0));
9987   Ops.push_back(LoMul->getOperand(1));
9988 
9989   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
9990   // the case, we must be doing signed multiplication and only use the higher
9991   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
9992   // addition or subtraction with the value of 0x800000.
9993   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
9994       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
9995       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
9996       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
9997           0x80000000) {
9998     Ops.push_back(*HiAddSub);
9999     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10000       FinalOpc = ARMISD::SMMLSR;
10001     } else {
10002       FinalOpc = ARMISD::SMMLAR;
10003     }
10004     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10005     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10006 
10007     return SDValue(AddeSubeNode, 0);
10008   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10009     // SMMLS is generated during instruction selection and the rest of this
10010     // function can not handle the case where AddcSubcNode is a SUBC.
10011     return SDValue();
10012 
10013   // Finish building the operand list for {U/S}MLAL
10014   Ops.push_back(*LowAddSub);
10015   Ops.push_back(*HiAddSub);
10016 
10017   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10018                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10019 
10020   // Replace the ADDs' nodes uses by the MLA node's values.
10021   SDValue HiMLALResult(MLALNode.getNode(), 1);
10022   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10023 
10024   SDValue LoMLALResult(MLALNode.getNode(), 0);
10025   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10026 
10027   // Return original node to notify the driver to stop replacing.
10028   return SDValue(AddeSubeNode, 0);
10029 }
10030 
10031 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10032                                       TargetLowering::DAGCombinerInfo &DCI,
10033                                       const ARMSubtarget *Subtarget) {
10034   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10035   // While trying to combine for the other MLAL nodes, first search for the
10036   // chance to use UMAAL. Check if Addc uses a node which has already
10037   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10038   // as the addend, and it's handled in PerformUMLALCombine.
10039 
10040   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10041     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10042 
10043   // Check that we have a glued ADDC node.
10044   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10045   if (AddcNode->getOpcode() != ARMISD::ADDC)
10046     return SDValue();
10047 
10048   // Find the converted UMAAL or quit if it doesn't exist.
10049   SDNode *UmlalNode = nullptr;
10050   SDValue AddHi;
10051   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10052     UmlalNode = AddcNode->getOperand(0).getNode();
10053     AddHi = AddcNode->getOperand(1);
10054   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10055     UmlalNode = AddcNode->getOperand(1).getNode();
10056     AddHi = AddcNode->getOperand(0);
10057   } else {
10058     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10059   }
10060 
10061   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10062   // the ADDC as well as Zero.
10063   if (!isNullConstant(UmlalNode->getOperand(3)))
10064     return SDValue();
10065 
10066   if ((isNullConstant(AddeNode->getOperand(0)) &&
10067        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10068       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10069        isNullConstant(AddeNode->getOperand(1)))) {
10070     SelectionDAG &DAG = DCI.DAG;
10071     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10072                       UmlalNode->getOperand(2), AddHi };
10073     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10074                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10075 
10076     // Replace the ADDs' nodes uses by the UMAAL node's values.
10077     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10078     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10079 
10080     // Return original node to notify the driver to stop replacing.
10081     return SDValue(AddeNode, 0);
10082   }
10083   return SDValue();
10084 }
10085 
10086 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10087                                    const ARMSubtarget *Subtarget) {
10088   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10089     return SDValue();
10090 
10091   // Check that we have a pair of ADDC and ADDE as operands.
10092   // Both addends of the ADDE must be zero.
10093   SDNode* AddcNode = N->getOperand(2).getNode();
10094   SDNode* AddeNode = N->getOperand(3).getNode();
10095   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10096       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10097       isNullConstant(AddeNode->getOperand(0)) &&
10098       isNullConstant(AddeNode->getOperand(1)) &&
10099       (AddeNode->getOperand(2).getNode() == AddcNode))
10100     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10101                        DAG.getVTList(MVT::i32, MVT::i32),
10102                        {N->getOperand(0), N->getOperand(1),
10103                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10104   else
10105     return SDValue();
10106 }
10107 
10108 static SDValue PerformAddcSubcCombine(SDNode *N,
10109                                       TargetLowering::DAGCombinerInfo &DCI,
10110                                       const ARMSubtarget *Subtarget) {
10111   SelectionDAG &DAG(DCI.DAG);
10112 
10113   if (N->getOpcode() == ARMISD::ADDC) {
10114     // (ADDC (ADDE 0, 0, C), -1) -> C
10115     SDValue LHS = N->getOperand(0);
10116     SDValue RHS = N->getOperand(1);
10117     if (LHS->getOpcode() == ARMISD::ADDE &&
10118         isNullConstant(LHS->getOperand(0)) &&
10119         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10120       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10121     }
10122   }
10123 
10124   if (Subtarget->isThumb1Only()) {
10125     SDValue RHS = N->getOperand(1);
10126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10127       int32_t imm = C->getSExtValue();
10128       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10129         SDLoc DL(N);
10130         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10131         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10132                                                            : ARMISD::ADDC;
10133         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10134       }
10135     }
10136   }
10137   return SDValue();
10138 }
10139 
10140 static SDValue PerformAddeSubeCombine(SDNode *N,
10141                                       TargetLowering::DAGCombinerInfo &DCI,
10142                                       const ARMSubtarget *Subtarget) {
10143   if (Subtarget->isThumb1Only()) {
10144     SelectionDAG &DAG = DCI.DAG;
10145     SDValue RHS = N->getOperand(1);
10146     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10147       int64_t imm = C->getSExtValue();
10148       if (imm < 0) {
10149         SDLoc DL(N);
10150 
10151         // The with-carry-in form matches bitwise not instead of the negation.
10152         // Effectively, the inverse interpretation of the carry flag already
10153         // accounts for part of the negation.
10154         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10155 
10156         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10157                                                            : ARMISD::ADDE;
10158         return DAG.getNode(Opcode, DL, N->getVTList(),
10159                            N->getOperand(0), RHS, N->getOperand(2));
10160       }
10161     }
10162   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10163     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10164   }
10165   return SDValue();
10166 }
10167 
10168 /// PerformADDECombine - Target-specific dag combine transform from
10169 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10170 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10171 static SDValue PerformADDECombine(SDNode *N,
10172                                   TargetLowering::DAGCombinerInfo &DCI,
10173                                   const ARMSubtarget *Subtarget) {
10174   // Only ARM and Thumb2 support UMLAL/SMLAL.
10175   if (Subtarget->isThumb1Only())
10176     return PerformAddeSubeCombine(N, DCI, Subtarget);
10177 
10178   // Only perform the checks after legalize when the pattern is available.
10179   if (DCI.isBeforeLegalize()) return SDValue();
10180 
10181   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10182 }
10183 
10184 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10185 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10186 /// called with the default operands, and if that fails, with commuted
10187 /// operands.
10188 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10189                                           TargetLowering::DAGCombinerInfo &DCI,
10190                                           const ARMSubtarget *Subtarget){
10191   // Attempt to create vpadd for this add.
10192   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10193     return Result;
10194 
10195   // Attempt to create vpaddl for this add.
10196   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10197     return Result;
10198   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10199                                                       Subtarget))
10200     return Result;
10201 
10202   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10203   if (N0.getNode()->hasOneUse())
10204     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10205       return Result;
10206   return SDValue();
10207 }
10208 
10209 static SDValue PerformSHLSimplify(SDNode *N,
10210                                 TargetLowering::DAGCombinerInfo &DCI,
10211                                 const ARMSubtarget *ST) {
10212   // Allow the generic combiner to identify potential bswaps.
10213   if (DCI.isBeforeLegalize())
10214     return SDValue();
10215 
10216   // DAG combiner will fold:
10217   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10218   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10219   // Other code patterns that can be also be modified have the following form:
10220   // b + ((a << 1) | 510)
10221   // b + ((a << 1) & 510)
10222   // b + ((a << 1) ^ 510)
10223   // b + ((a << 1) + 510)
10224 
10225   // Many instructions can  perform the shift for free, but it requires both
10226   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10227   // instruction will needed. So, unfold back to the original pattern if:
10228   // - if c1 and c2 are small enough that they don't require mov imms.
10229   // - the user(s) of the node can perform an shl
10230 
10231   // No shifted operands for 16-bit instructions.
10232   if (ST->isThumb() && ST->isThumb1Only())
10233     return SDValue();
10234 
10235   // Check that all the users could perform the shl themselves.
10236   for (auto U : N->uses()) {
10237     switch(U->getOpcode()) {
10238     default:
10239       return SDValue();
10240     case ISD::SUB:
10241     case ISD::ADD:
10242     case ISD::AND:
10243     case ISD::OR:
10244     case ISD::XOR:
10245     case ISD::SETCC:
10246     case ARMISD::CMP:
10247       // Check that its not already using a shl.
10248       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10249           U->getOperand(1).getOpcode() == ISD::SHL)
10250         return SDValue();
10251       break;
10252     }
10253   }
10254 
10255   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10256       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10257     return SDValue();
10258 
10259   if (N->getOperand(0).getOpcode() != ISD::SHL)
10260     return SDValue();
10261 
10262   SDValue SHL = N->getOperand(0);
10263 
10264   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10265   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10266   if (!C1ShlC2 || !C2)
10267     return SDValue();
10268 
10269   DEBUG(dbgs() << "Trying to simplify shl: "; N->dump());
10270 
10271   APInt C2Int = C2->getAPIntValue();
10272   APInt C1Int = C1ShlC2->getAPIntValue();
10273 
10274   // Check that performing a lshr will not lose any information.
10275   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10276                                      C2Int.getBitWidth() - C2->getZExtValue());
10277   if ((C1Int & Mask) != C1Int)
10278     return SDValue();
10279 
10280   // Shift the first constant.
10281   C1Int.lshrInPlace(C2Int);
10282 
10283   // The immediates are encoded as an 8-bit value that can be rotated.
10284   unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros();
10285   if (C1Int.getBitWidth() - Zeros > 8)
10286     return SDValue();
10287 
10288   Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros();
10289   if (C2Int.getBitWidth() - Zeros > 8)
10290     return SDValue();
10291 
10292   SelectionDAG &DAG = DCI.DAG;
10293   SDLoc dl(N);
10294   SDValue X = SHL.getOperand(0);
10295   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10296                               DAG.getConstant(C1Int, dl, MVT::i32));
10297   // Shift left to compensate for the lshr of C1Int.
10298   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10299 
10300   DAG.ReplaceAllUsesWith(SDValue(N, 0), Res);
10301   return SDValue(N, 0);
10302 }
10303 
10304 
10305 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10306 ///
10307 static SDValue PerformADDCombine(SDNode *N,
10308                                  TargetLowering::DAGCombinerInfo &DCI,
10309                                  const ARMSubtarget *Subtarget) {
10310   SDValue N0 = N->getOperand(0);
10311   SDValue N1 = N->getOperand(1);
10312 
10313   // Only works one way, because it needs an immediate operand.
10314   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10315     return Result;
10316 
10317   // First try with the default operand order.
10318   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10319     return Result;
10320 
10321   // If that didn't work, try again with the operands commuted.
10322   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10323 }
10324 
10325 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10326 ///
10327 static SDValue PerformSUBCombine(SDNode *N,
10328                                  TargetLowering::DAGCombinerInfo &DCI) {
10329   SDValue N0 = N->getOperand(0);
10330   SDValue N1 = N->getOperand(1);
10331 
10332   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10333   if (N1.getNode()->hasOneUse())
10334     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10335       return Result;
10336 
10337   return SDValue();
10338 }
10339 
10340 /// PerformVMULCombine
10341 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10342 /// special multiplier accumulator forwarding.
10343 ///   vmul d3, d0, d2
10344 ///   vmla d3, d1, d2
10345 /// is faster than
10346 ///   vadd d3, d0, d1
10347 ///   vmul d3, d3, d2
10348 //  However, for (A + B) * (A + B),
10349 //    vadd d2, d0, d1
10350 //    vmul d3, d0, d2
10351 //    vmla d3, d1, d2
10352 //  is slower than
10353 //    vadd d2, d0, d1
10354 //    vmul d3, d2, d2
10355 static SDValue PerformVMULCombine(SDNode *N,
10356                                   TargetLowering::DAGCombinerInfo &DCI,
10357                                   const ARMSubtarget *Subtarget) {
10358   if (!Subtarget->hasVMLxForwarding())
10359     return SDValue();
10360 
10361   SelectionDAG &DAG = DCI.DAG;
10362   SDValue N0 = N->getOperand(0);
10363   SDValue N1 = N->getOperand(1);
10364   unsigned Opcode = N0.getOpcode();
10365   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10366       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10367     Opcode = N1.getOpcode();
10368     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10369         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10370       return SDValue();
10371     std::swap(N0, N1);
10372   }
10373 
10374   if (N0 == N1)
10375     return SDValue();
10376 
10377   EVT VT = N->getValueType(0);
10378   SDLoc DL(N);
10379   SDValue N00 = N0->getOperand(0);
10380   SDValue N01 = N0->getOperand(1);
10381   return DAG.getNode(Opcode, DL, VT,
10382                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10383                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10384 }
10385 
10386 static SDValue PerformMULCombine(SDNode *N,
10387                                  TargetLowering::DAGCombinerInfo &DCI,
10388                                  const ARMSubtarget *Subtarget) {
10389   SelectionDAG &DAG = DCI.DAG;
10390 
10391   if (Subtarget->isThumb1Only())
10392     return SDValue();
10393 
10394   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10395     return SDValue();
10396 
10397   EVT VT = N->getValueType(0);
10398   if (VT.is64BitVector() || VT.is128BitVector())
10399     return PerformVMULCombine(N, DCI, Subtarget);
10400   if (VT != MVT::i32)
10401     return SDValue();
10402 
10403   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10404   if (!C)
10405     return SDValue();
10406 
10407   int64_t MulAmt = C->getSExtValue();
10408   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10409 
10410   ShiftAmt = ShiftAmt & (32 - 1);
10411   SDValue V = N->getOperand(0);
10412   SDLoc DL(N);
10413 
10414   SDValue Res;
10415   MulAmt >>= ShiftAmt;
10416 
10417   if (MulAmt >= 0) {
10418     if (isPowerOf2_32(MulAmt - 1)) {
10419       // (mul x, 2^N + 1) => (add (shl x, N), x)
10420       Res = DAG.getNode(ISD::ADD, DL, VT,
10421                         V,
10422                         DAG.getNode(ISD::SHL, DL, VT,
10423                                     V,
10424                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10425                                                     MVT::i32)));
10426     } else if (isPowerOf2_32(MulAmt + 1)) {
10427       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10428       Res = DAG.getNode(ISD::SUB, DL, VT,
10429                         DAG.getNode(ISD::SHL, DL, VT,
10430                                     V,
10431                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10432                                                     MVT::i32)),
10433                         V);
10434     } else
10435       return SDValue();
10436   } else {
10437     uint64_t MulAmtAbs = -MulAmt;
10438     if (isPowerOf2_32(MulAmtAbs + 1)) {
10439       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10440       Res = DAG.getNode(ISD::SUB, DL, VT,
10441                         V,
10442                         DAG.getNode(ISD::SHL, DL, VT,
10443                                     V,
10444                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10445                                                     MVT::i32)));
10446     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10447       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10448       Res = DAG.getNode(ISD::ADD, DL, VT,
10449                         V,
10450                         DAG.getNode(ISD::SHL, DL, VT,
10451                                     V,
10452                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10453                                                     MVT::i32)));
10454       Res = DAG.getNode(ISD::SUB, DL, VT,
10455                         DAG.getConstant(0, DL, MVT::i32), Res);
10456     } else
10457       return SDValue();
10458   }
10459 
10460   if (ShiftAmt != 0)
10461     Res = DAG.getNode(ISD::SHL, DL, VT,
10462                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10463 
10464   // Do not add new nodes to DAG combiner worklist.
10465   DCI.CombineTo(N, Res, false);
10466   return SDValue();
10467 }
10468 
10469 static SDValue PerformANDCombine(SDNode *N,
10470                                  TargetLowering::DAGCombinerInfo &DCI,
10471                                  const ARMSubtarget *Subtarget) {
10472   // Attempt to use immediate-form VBIC
10473   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10474   SDLoc dl(N);
10475   EVT VT = N->getValueType(0);
10476   SelectionDAG &DAG = DCI.DAG;
10477 
10478   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10479     return SDValue();
10480 
10481   APInt SplatBits, SplatUndef;
10482   unsigned SplatBitSize;
10483   bool HasAnyUndefs;
10484   if (BVN &&
10485       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10486     if (SplatBitSize <= 64) {
10487       EVT VbicVT;
10488       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10489                                       SplatUndef.getZExtValue(), SplatBitSize,
10490                                       DAG, dl, VbicVT, VT.is128BitVector(),
10491                                       OtherModImm);
10492       if (Val.getNode()) {
10493         SDValue Input =
10494           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10495         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10496         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10497       }
10498     }
10499   }
10500 
10501   if (!Subtarget->isThumb1Only()) {
10502     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10503     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10504       return Result;
10505 
10506     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10507       return Result;
10508   }
10509 
10510   return SDValue();
10511 }
10512 
10513 // Try combining OR nodes to SMULWB, SMULWT.
10514 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10515                                          TargetLowering::DAGCombinerInfo &DCI,
10516                                          const ARMSubtarget *Subtarget) {
10517   if (!Subtarget->hasV6Ops() ||
10518       (Subtarget->isThumb() &&
10519        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10520     return SDValue();
10521 
10522   SDValue SRL = OR->getOperand(0);
10523   SDValue SHL = OR->getOperand(1);
10524 
10525   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10526     SRL = OR->getOperand(1);
10527     SHL = OR->getOperand(0);
10528   }
10529   if (!isSRL16(SRL) || !isSHL16(SHL))
10530     return SDValue();
10531 
10532   // The first operands to the shifts need to be the two results from the
10533   // same smul_lohi node.
10534   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10535        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10536     return SDValue();
10537 
10538   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10539   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10540       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10541     return SDValue();
10542 
10543   // Now we have:
10544   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10545   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10546   // For SMUWB the 16-bit value will signed extended somehow.
10547   // For SMULWT only the SRA is required.
10548   // Check both sides of SMUL_LOHI
10549   SDValue OpS16 = SMULLOHI->getOperand(0);
10550   SDValue OpS32 = SMULLOHI->getOperand(1);
10551 
10552   SelectionDAG &DAG = DCI.DAG;
10553   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10554     OpS16 = OpS32;
10555     OpS32 = SMULLOHI->getOperand(0);
10556   }
10557 
10558   SDLoc dl(OR);
10559   unsigned Opcode = 0;
10560   if (isS16(OpS16, DAG))
10561     Opcode = ARMISD::SMULWB;
10562   else if (isSRA16(OpS16)) {
10563     Opcode = ARMISD::SMULWT;
10564     OpS16 = OpS16->getOperand(0);
10565   }
10566   else
10567     return SDValue();
10568 
10569   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10570   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10571   return SDValue(OR, 0);
10572 }
10573 
10574 static SDValue PerformORCombineToBFI(SDNode *N,
10575                                      TargetLowering::DAGCombinerInfo &DCI,
10576                                      const ARMSubtarget *Subtarget) {
10577   // BFI is only available on V6T2+
10578   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10579     return SDValue();
10580 
10581   EVT VT = N->getValueType(0);
10582   SDValue N0 = N->getOperand(0);
10583   SDValue N1 = N->getOperand(1);
10584   SelectionDAG &DAG = DCI.DAG;
10585   SDLoc DL(N);
10586   // 1) or (and A, mask), val => ARMbfi A, val, mask
10587   //      iff (val & mask) == val
10588   //
10589   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10590   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10591   //          && mask == ~mask2
10592   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10593   //          && ~mask == mask2
10594   //  (i.e., copy a bitfield value into another bitfield of the same width)
10595 
10596   if (VT != MVT::i32)
10597     return SDValue();
10598 
10599   SDValue N00 = N0.getOperand(0);
10600 
10601   // The value and the mask need to be constants so we can verify this is
10602   // actually a bitfield set. If the mask is 0xffff, we can do better
10603   // via a movt instruction, so don't use BFI in that case.
10604   SDValue MaskOp = N0.getOperand(1);
10605   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10606   if (!MaskC)
10607     return SDValue();
10608   unsigned Mask = MaskC->getZExtValue();
10609   if (Mask == 0xffff)
10610     return SDValue();
10611   SDValue Res;
10612   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10613   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10614   if (N1C) {
10615     unsigned Val = N1C->getZExtValue();
10616     if ((Val & ~Mask) != Val)
10617       return SDValue();
10618 
10619     if (ARM::isBitFieldInvertedMask(Mask)) {
10620       Val >>= countTrailingZeros(~Mask);
10621 
10622       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10623                         DAG.getConstant(Val, DL, MVT::i32),
10624                         DAG.getConstant(Mask, DL, MVT::i32));
10625 
10626       DCI.CombineTo(N, Res, false);
10627       // Return value from the original node to inform the combiner than N is
10628       // now dead.
10629       return SDValue(N, 0);
10630     }
10631   } else if (N1.getOpcode() == ISD::AND) {
10632     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10633     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10634     if (!N11C)
10635       return SDValue();
10636     unsigned Mask2 = N11C->getZExtValue();
10637 
10638     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10639     // as is to match.
10640     if (ARM::isBitFieldInvertedMask(Mask) &&
10641         (Mask == ~Mask2)) {
10642       // The pack halfword instruction works better for masks that fit it,
10643       // so use that when it's available.
10644       if (Subtarget->hasDSP() &&
10645           (Mask == 0xffff || Mask == 0xffff0000))
10646         return SDValue();
10647       // 2a
10648       unsigned amt = countTrailingZeros(Mask2);
10649       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10650                         DAG.getConstant(amt, DL, MVT::i32));
10651       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10652                         DAG.getConstant(Mask, DL, MVT::i32));
10653       DCI.CombineTo(N, Res, false);
10654       // Return value from the original node to inform the combiner than N is
10655       // now dead.
10656       return SDValue(N, 0);
10657     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10658                (~Mask == Mask2)) {
10659       // The pack halfword instruction works better for masks that fit it,
10660       // so use that when it's available.
10661       if (Subtarget->hasDSP() &&
10662           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10663         return SDValue();
10664       // 2b
10665       unsigned lsb = countTrailingZeros(Mask);
10666       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10667                         DAG.getConstant(lsb, DL, MVT::i32));
10668       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10669                         DAG.getConstant(Mask2, DL, MVT::i32));
10670       DCI.CombineTo(N, Res, false);
10671       // Return value from the original node to inform the combiner than N is
10672       // now dead.
10673       return SDValue(N, 0);
10674     }
10675   }
10676 
10677   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10678       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10679       ARM::isBitFieldInvertedMask(~Mask)) {
10680     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10681     // where lsb(mask) == #shamt and masked bits of B are known zero.
10682     SDValue ShAmt = N00.getOperand(1);
10683     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10684     unsigned LSB = countTrailingZeros(Mask);
10685     if (ShAmtC != LSB)
10686       return SDValue();
10687 
10688     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10689                       DAG.getConstant(~Mask, DL, MVT::i32));
10690 
10691     DCI.CombineTo(N, Res, false);
10692     // Return value from the original node to inform the combiner than N is
10693     // now dead.
10694     return SDValue(N, 0);
10695   }
10696 
10697   return SDValue();
10698 }
10699 
10700 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10701 static SDValue PerformORCombine(SDNode *N,
10702                                 TargetLowering::DAGCombinerInfo &DCI,
10703                                 const ARMSubtarget *Subtarget) {
10704   // Attempt to use immediate-form VORR
10705   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10706   SDLoc dl(N);
10707   EVT VT = N->getValueType(0);
10708   SelectionDAG &DAG = DCI.DAG;
10709 
10710   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10711     return SDValue();
10712 
10713   APInt SplatBits, SplatUndef;
10714   unsigned SplatBitSize;
10715   bool HasAnyUndefs;
10716   if (BVN && Subtarget->hasNEON() &&
10717       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10718     if (SplatBitSize <= 64) {
10719       EVT VorrVT;
10720       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10721                                       SplatUndef.getZExtValue(), SplatBitSize,
10722                                       DAG, dl, VorrVT, VT.is128BitVector(),
10723                                       OtherModImm);
10724       if (Val.getNode()) {
10725         SDValue Input =
10726           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10727         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10728         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10729       }
10730     }
10731   }
10732 
10733   if (!Subtarget->isThumb1Only()) {
10734     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10735     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10736       return Result;
10737     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10738       return Result;
10739   }
10740 
10741   SDValue N0 = N->getOperand(0);
10742   SDValue N1 = N->getOperand(1);
10743 
10744   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10745   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10746       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10747 
10748     // The code below optimizes (or (and X, Y), Z).
10749     // The AND operand needs to have a single user to make these optimizations
10750     // profitable.
10751     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10752       return SDValue();
10753 
10754     APInt SplatUndef;
10755     unsigned SplatBitSize;
10756     bool HasAnyUndefs;
10757 
10758     APInt SplatBits0, SplatBits1;
10759     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10760     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10761     // Ensure that the second operand of both ands are constants
10762     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10763                                       HasAnyUndefs) && !HasAnyUndefs) {
10764         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10765                                           HasAnyUndefs) && !HasAnyUndefs) {
10766             // Ensure that the bit width of the constants are the same and that
10767             // the splat arguments are logical inverses as per the pattern we
10768             // are trying to simplify.
10769             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10770                 SplatBits0 == ~SplatBits1) {
10771                 // Canonicalize the vector type to make instruction selection
10772                 // simpler.
10773                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10774                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10775                                              N0->getOperand(1),
10776                                              N0->getOperand(0),
10777                                              N1->getOperand(0));
10778                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10779             }
10780         }
10781     }
10782   }
10783 
10784   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10785   // reasonable.
10786   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
10787     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
10788       return Res;
10789   }
10790 
10791   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10792     return Result;
10793 
10794   return SDValue();
10795 }
10796 
10797 static SDValue PerformXORCombine(SDNode *N,
10798                                  TargetLowering::DAGCombinerInfo &DCI,
10799                                  const ARMSubtarget *Subtarget) {
10800   EVT VT = N->getValueType(0);
10801   SelectionDAG &DAG = DCI.DAG;
10802 
10803   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10804     return SDValue();
10805 
10806   if (!Subtarget->isThumb1Only()) {
10807     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10808     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10809       return Result;
10810 
10811     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10812       return Result;
10813   }
10814 
10815   return SDValue();
10816 }
10817 
10818 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10819 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10820 // their position in "to" (Rd).
10821 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10822   assert(N->getOpcode() == ARMISD::BFI);
10823 
10824   SDValue From = N->getOperand(1);
10825   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10826   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10827 
10828   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10829   // #C in the base of the SHR.
10830   if (From->getOpcode() == ISD::SRL &&
10831       isa<ConstantSDNode>(From->getOperand(1))) {
10832     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10833     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10834     FromMask <<= Shift.getLimitedValue(31);
10835     From = From->getOperand(0);
10836   }
10837 
10838   return From;
10839 }
10840 
10841 // If A and B contain one contiguous set of bits, does A | B == A . B?
10842 //
10843 // Neither A nor B must be zero.
10844 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10845   unsigned LastActiveBitInA =  A.countTrailingZeros();
10846   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10847   return LastActiveBitInA - 1 == FirstActiveBitInB;
10848 }
10849 
10850 static SDValue FindBFIToCombineWith(SDNode *N) {
10851   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10852   // if one exists.
10853   APInt ToMask, FromMask;
10854   SDValue From = ParseBFI(N, ToMask, FromMask);
10855   SDValue To = N->getOperand(0);
10856 
10857   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10858   // aren't compatible, but not if they set the same bit in their destination as
10859   // we do (or that of any BFI we're going to combine with).
10860   SDValue V = To;
10861   APInt CombinedToMask = ToMask;
10862   while (V.getOpcode() == ARMISD::BFI) {
10863     APInt NewToMask, NewFromMask;
10864     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10865     if (NewFrom != From) {
10866       // This BFI has a different base. Keep going.
10867       CombinedToMask |= NewToMask;
10868       V = V.getOperand(0);
10869       continue;
10870     }
10871 
10872     // Do the written bits conflict with any we've seen so far?
10873     if ((NewToMask & CombinedToMask).getBoolValue())
10874       // Conflicting bits - bail out because going further is unsafe.
10875       return SDValue();
10876 
10877     // Are the new bits contiguous when combined with the old bits?
10878     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10879         BitsProperlyConcatenate(FromMask, NewFromMask))
10880       return V;
10881     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10882         BitsProperlyConcatenate(NewFromMask, FromMask))
10883       return V;
10884 
10885     // We've seen a write to some bits, so track it.
10886     CombinedToMask |= NewToMask;
10887     // Keep going...
10888     V = V.getOperand(0);
10889   }
10890 
10891   return SDValue();
10892 }
10893 
10894 static SDValue PerformBFICombine(SDNode *N,
10895                                  TargetLowering::DAGCombinerInfo &DCI) {
10896   SDValue N1 = N->getOperand(1);
10897   if (N1.getOpcode() == ISD::AND) {
10898     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10899     // the bits being cleared by the AND are not demanded by the BFI.
10900     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10901     if (!N11C)
10902       return SDValue();
10903     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10904     unsigned LSB = countTrailingZeros(~InvMask);
10905     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10906     assert(Width <
10907                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10908            "undefined behavior");
10909     unsigned Mask = (1u << Width) - 1;
10910     unsigned Mask2 = N11C->getZExtValue();
10911     if ((Mask & (~Mask2)) == 0)
10912       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10913                              N->getOperand(0), N1.getOperand(0),
10914                              N->getOperand(2));
10915   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10916     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10917     // Keep track of any consecutive bits set that all come from the same base
10918     // value. We can combine these together into a single BFI.
10919     SDValue CombineBFI = FindBFIToCombineWith(N);
10920     if (CombineBFI == SDValue())
10921       return SDValue();
10922 
10923     // We've found a BFI.
10924     APInt ToMask1, FromMask1;
10925     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10926 
10927     APInt ToMask2, FromMask2;
10928     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10929     assert(From1 == From2);
10930     (void)From2;
10931 
10932     // First, unlink CombineBFI.
10933     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10934     // Then create a new BFI, combining the two together.
10935     APInt NewFromMask = FromMask1 | FromMask2;
10936     APInt NewToMask = ToMask1 | ToMask2;
10937 
10938     EVT VT = N->getValueType(0);
10939     SDLoc dl(N);
10940 
10941     if (NewFromMask[0] == 0)
10942       From1 = DCI.DAG.getNode(
10943         ISD::SRL, dl, VT, From1,
10944         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10945     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10946                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10947   }
10948   return SDValue();
10949 }
10950 
10951 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10952 /// ARMISD::VMOVRRD.
10953 static SDValue PerformVMOVRRDCombine(SDNode *N,
10954                                      TargetLowering::DAGCombinerInfo &DCI,
10955                                      const ARMSubtarget *Subtarget) {
10956   // vmovrrd(vmovdrr x, y) -> x,y
10957   SDValue InDouble = N->getOperand(0);
10958   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10959     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10960 
10961   // vmovrrd(load f64) -> (load i32), (load i32)
10962   SDNode *InNode = InDouble.getNode();
10963   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10964       InNode->getValueType(0) == MVT::f64 &&
10965       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10966       !cast<LoadSDNode>(InNode)->isVolatile()) {
10967     // TODO: Should this be done for non-FrameIndex operands?
10968     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10969 
10970     SelectionDAG &DAG = DCI.DAG;
10971     SDLoc DL(LD);
10972     SDValue BasePtr = LD->getBasePtr();
10973     SDValue NewLD1 =
10974         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10975                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10976 
10977     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10978                                     DAG.getConstant(4, DL, MVT::i32));
10979     SDValue NewLD2 = DAG.getLoad(
10980         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10981         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10982 
10983     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10984     if (DCI.DAG.getDataLayout().isBigEndian())
10985       std::swap (NewLD1, NewLD2);
10986     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10987     return Result;
10988   }
10989 
10990   return SDValue();
10991 }
10992 
10993 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10994 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10995 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10996   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10997   SDValue Op0 = N->getOperand(0);
10998   SDValue Op1 = N->getOperand(1);
10999   if (Op0.getOpcode() == ISD::BITCAST)
11000     Op0 = Op0.getOperand(0);
11001   if (Op1.getOpcode() == ISD::BITCAST)
11002     Op1 = Op1.getOperand(0);
11003   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11004       Op0.getNode() == Op1.getNode() &&
11005       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11006     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11007                        N->getValueType(0), Op0.getOperand(0));
11008   return SDValue();
11009 }
11010 
11011 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11012 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11013 /// i64 vector to have f64 elements, since the value can then be loaded
11014 /// directly into a VFP register.
11015 static bool hasNormalLoadOperand(SDNode *N) {
11016   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11017   for (unsigned i = 0; i < NumElts; ++i) {
11018     SDNode *Elt = N->getOperand(i).getNode();
11019     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11020       return true;
11021   }
11022   return false;
11023 }
11024 
11025 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11026 /// ISD::BUILD_VECTOR.
11027 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11028                                           TargetLowering::DAGCombinerInfo &DCI,
11029                                           const ARMSubtarget *Subtarget) {
11030   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11031   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11032   // into a pair of GPRs, which is fine when the value is used as a scalar,
11033   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11034   SelectionDAG &DAG = DCI.DAG;
11035   if (N->getNumOperands() == 2)
11036     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11037       return RV;
11038 
11039   // Load i64 elements as f64 values so that type legalization does not split
11040   // them up into i32 values.
11041   EVT VT = N->getValueType(0);
11042   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11043     return SDValue();
11044   SDLoc dl(N);
11045   SmallVector<SDValue, 8> Ops;
11046   unsigned NumElts = VT.getVectorNumElements();
11047   for (unsigned i = 0; i < NumElts; ++i) {
11048     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11049     Ops.push_back(V);
11050     // Make the DAGCombiner fold the bitcast.
11051     DCI.AddToWorklist(V.getNode());
11052   }
11053   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11054   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11055   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11056 }
11057 
11058 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11059 static SDValue
11060 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11061   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11062   // At that time, we may have inserted bitcasts from integer to float.
11063   // If these bitcasts have survived DAGCombine, change the lowering of this
11064   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11065   // force to use floating point types.
11066 
11067   // Make sure we can change the type of the vector.
11068   // This is possible iff:
11069   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11070   //    1.1. Vector is used only once.
11071   //    1.2. Use is a bit convert to an integer type.
11072   // 2. The size of its operands are 32-bits (64-bits are not legal).
11073   EVT VT = N->getValueType(0);
11074   EVT EltVT = VT.getVectorElementType();
11075 
11076   // Check 1.1. and 2.
11077   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11078     return SDValue();
11079 
11080   // By construction, the input type must be float.
11081   assert(EltVT == MVT::f32 && "Unexpected type!");
11082 
11083   // Check 1.2.
11084   SDNode *Use = *N->use_begin();
11085   if (Use->getOpcode() != ISD::BITCAST ||
11086       Use->getValueType(0).isFloatingPoint())
11087     return SDValue();
11088 
11089   // Check profitability.
11090   // Model is, if more than half of the relevant operands are bitcast from
11091   // i32, turn the build_vector into a sequence of insert_vector_elt.
11092   // Relevant operands are everything that is not statically
11093   // (i.e., at compile time) bitcasted.
11094   unsigned NumOfBitCastedElts = 0;
11095   unsigned NumElts = VT.getVectorNumElements();
11096   unsigned NumOfRelevantElts = NumElts;
11097   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11098     SDValue Elt = N->getOperand(Idx);
11099     if (Elt->getOpcode() == ISD::BITCAST) {
11100       // Assume only bit cast to i32 will go away.
11101       if (Elt->getOperand(0).getValueType() == MVT::i32)
11102         ++NumOfBitCastedElts;
11103     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11104       // Constants are statically casted, thus do not count them as
11105       // relevant operands.
11106       --NumOfRelevantElts;
11107   }
11108 
11109   // Check if more than half of the elements require a non-free bitcast.
11110   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11111     return SDValue();
11112 
11113   SelectionDAG &DAG = DCI.DAG;
11114   // Create the new vector type.
11115   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11116   // Check if the type is legal.
11117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11118   if (!TLI.isTypeLegal(VecVT))
11119     return SDValue();
11120 
11121   // Combine:
11122   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11123   // => BITCAST INSERT_VECTOR_ELT
11124   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11125   //                      (BITCAST EN), N.
11126   SDValue Vec = DAG.getUNDEF(VecVT);
11127   SDLoc dl(N);
11128   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11129     SDValue V = N->getOperand(Idx);
11130     if (V.isUndef())
11131       continue;
11132     if (V.getOpcode() == ISD::BITCAST &&
11133         V->getOperand(0).getValueType() == MVT::i32)
11134       // Fold obvious case.
11135       V = V.getOperand(0);
11136     else {
11137       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11138       // Make the DAGCombiner fold the bitcasts.
11139       DCI.AddToWorklist(V.getNode());
11140     }
11141     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11142     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11143   }
11144   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11145   // Make the DAGCombiner fold the bitcasts.
11146   DCI.AddToWorklist(Vec.getNode());
11147   return Vec;
11148 }
11149 
11150 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11151 /// ISD::INSERT_VECTOR_ELT.
11152 static SDValue PerformInsertEltCombine(SDNode *N,
11153                                        TargetLowering::DAGCombinerInfo &DCI) {
11154   // Bitcast an i64 load inserted into a vector to f64.
11155   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11156   EVT VT = N->getValueType(0);
11157   SDNode *Elt = N->getOperand(1).getNode();
11158   if (VT.getVectorElementType() != MVT::i64 ||
11159       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11160     return SDValue();
11161 
11162   SelectionDAG &DAG = DCI.DAG;
11163   SDLoc dl(N);
11164   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11165                                  VT.getVectorNumElements());
11166   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11167   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11168   // Make the DAGCombiner fold the bitcasts.
11169   DCI.AddToWorklist(Vec.getNode());
11170   DCI.AddToWorklist(V.getNode());
11171   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11172                                Vec, V, N->getOperand(2));
11173   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11174 }
11175 
11176 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11177 /// ISD::VECTOR_SHUFFLE.
11178 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11179   // The LLVM shufflevector instruction does not require the shuffle mask
11180   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11181   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11182   // operands do not match the mask length, they are extended by concatenating
11183   // them with undef vectors.  That is probably the right thing for other
11184   // targets, but for NEON it is better to concatenate two double-register
11185   // size vector operands into a single quad-register size vector.  Do that
11186   // transformation here:
11187   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11188   //   shuffle(concat(v1, v2), undef)
11189   SDValue Op0 = N->getOperand(0);
11190   SDValue Op1 = N->getOperand(1);
11191   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11192       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11193       Op0.getNumOperands() != 2 ||
11194       Op1.getNumOperands() != 2)
11195     return SDValue();
11196   SDValue Concat0Op1 = Op0.getOperand(1);
11197   SDValue Concat1Op1 = Op1.getOperand(1);
11198   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11199     return SDValue();
11200   // Skip the transformation if any of the types are illegal.
11201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11202   EVT VT = N->getValueType(0);
11203   if (!TLI.isTypeLegal(VT) ||
11204       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11205       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11206     return SDValue();
11207 
11208   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11209                                   Op0.getOperand(0), Op1.getOperand(0));
11210   // Translate the shuffle mask.
11211   SmallVector<int, 16> NewMask;
11212   unsigned NumElts = VT.getVectorNumElements();
11213   unsigned HalfElts = NumElts/2;
11214   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11215   for (unsigned n = 0; n < NumElts; ++n) {
11216     int MaskElt = SVN->getMaskElt(n);
11217     int NewElt = -1;
11218     if (MaskElt < (int)HalfElts)
11219       NewElt = MaskElt;
11220     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11221       NewElt = HalfElts + MaskElt - NumElts;
11222     NewMask.push_back(NewElt);
11223   }
11224   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11225                               DAG.getUNDEF(VT), NewMask);
11226 }
11227 
11228 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11229 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11230 /// base address updates.
11231 /// For generic load/stores, the memory type is assumed to be a vector.
11232 /// The caller is assumed to have checked legality.
11233 static SDValue CombineBaseUpdate(SDNode *N,
11234                                  TargetLowering::DAGCombinerInfo &DCI) {
11235   SelectionDAG &DAG = DCI.DAG;
11236   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11237                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11238   const bool isStore = N->getOpcode() == ISD::STORE;
11239   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11240   SDValue Addr = N->getOperand(AddrOpIdx);
11241   MemSDNode *MemN = cast<MemSDNode>(N);
11242   SDLoc dl(N);
11243 
11244   // Search for a use of the address operand that is an increment.
11245   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11246          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11247     SDNode *User = *UI;
11248     if (User->getOpcode() != ISD::ADD ||
11249         UI.getUse().getResNo() != Addr.getResNo())
11250       continue;
11251 
11252     // Check that the add is independent of the load/store.  Otherwise, folding
11253     // it would create a cycle.
11254     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11255       continue;
11256 
11257     // Find the new opcode for the updating load/store.
11258     bool isLoadOp = true;
11259     bool isLaneOp = false;
11260     unsigned NewOpc = 0;
11261     unsigned NumVecs = 0;
11262     if (isIntrinsic) {
11263       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11264       switch (IntNo) {
11265       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11266       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11267         NumVecs = 1; break;
11268       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11269         NumVecs = 2; break;
11270       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11271         NumVecs = 3; break;
11272       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11273         NumVecs = 4; break;
11274       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11275         NumVecs = 2; isLaneOp = true; break;
11276       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11277         NumVecs = 3; isLaneOp = true; break;
11278       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11279         NumVecs = 4; isLaneOp = true; break;
11280       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11281         NumVecs = 1; isLoadOp = false; break;
11282       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11283         NumVecs = 2; isLoadOp = false; break;
11284       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11285         NumVecs = 3; isLoadOp = false; break;
11286       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11287         NumVecs = 4; isLoadOp = false; break;
11288       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11289         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11290       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11291         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11292       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11293         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11294       }
11295     } else {
11296       isLaneOp = true;
11297       switch (N->getOpcode()) {
11298       default: llvm_unreachable("unexpected opcode for Neon base update");
11299       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11300       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11301       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11302       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11303       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11304         NumVecs = 1; isLaneOp = false; break;
11305       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11306         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11307       }
11308     }
11309 
11310     // Find the size of memory referenced by the load/store.
11311     EVT VecTy;
11312     if (isLoadOp) {
11313       VecTy = N->getValueType(0);
11314     } else if (isIntrinsic) {
11315       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11316     } else {
11317       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11318       VecTy = N->getOperand(1).getValueType();
11319     }
11320 
11321     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11322     if (isLaneOp)
11323       NumBytes /= VecTy.getVectorNumElements();
11324 
11325     // If the increment is a constant, it must match the memory ref size.
11326     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11327     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11328     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11329       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11330       // separate instructions that make it harder to use a non-constant update.
11331       continue;
11332     }
11333 
11334     // OK, we found an ADD we can fold into the base update.
11335     // Now, create a _UPD node, taking care of not breaking alignment.
11336 
11337     EVT AlignedVecTy = VecTy;
11338     unsigned Alignment = MemN->getAlignment();
11339 
11340     // If this is a less-than-standard-aligned load/store, change the type to
11341     // match the standard alignment.
11342     // The alignment is overlooked when selecting _UPD variants; and it's
11343     // easier to introduce bitcasts here than fix that.
11344     // There are 3 ways to get to this base-update combine:
11345     // - intrinsics: they are assumed to be properly aligned (to the standard
11346     //   alignment of the memory type), so we don't need to do anything.
11347     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11348     //   intrinsics, so, likewise, there's nothing to do.
11349     // - generic load/store instructions: the alignment is specified as an
11350     //   explicit operand, rather than implicitly as the standard alignment
11351     //   of the memory type (like the intrisics).  We need to change the
11352     //   memory type to match the explicit alignment.  That way, we don't
11353     //   generate non-standard-aligned ARMISD::VLDx nodes.
11354     if (isa<LSBaseSDNode>(N)) {
11355       if (Alignment == 0)
11356         Alignment = 1;
11357       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11358         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11359         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11360         assert(!isLaneOp && "Unexpected generic load/store lane.");
11361         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11362         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11363       }
11364       // Don't set an explicit alignment on regular load/stores that we want
11365       // to transform to VLD/VST 1_UPD nodes.
11366       // This matches the behavior of regular load/stores, which only get an
11367       // explicit alignment if the MMO alignment is larger than the standard
11368       // alignment of the memory type.
11369       // Intrinsics, however, always get an explicit alignment, set to the
11370       // alignment of the MMO.
11371       Alignment = 1;
11372     }
11373 
11374     // Create the new updating load/store node.
11375     // First, create an SDVTList for the new updating node's results.
11376     EVT Tys[6];
11377     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11378     unsigned n;
11379     for (n = 0; n < NumResultVecs; ++n)
11380       Tys[n] = AlignedVecTy;
11381     Tys[n++] = MVT::i32;
11382     Tys[n] = MVT::Other;
11383     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11384 
11385     // Then, gather the new node's operands.
11386     SmallVector<SDValue, 8> Ops;
11387     Ops.push_back(N->getOperand(0)); // incoming chain
11388     Ops.push_back(N->getOperand(AddrOpIdx));
11389     Ops.push_back(Inc);
11390 
11391     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11392       // Try to match the intrinsic's signature
11393       Ops.push_back(StN->getValue());
11394     } else {
11395       // Loads (and of course intrinsics) match the intrinsics' signature,
11396       // so just add all but the alignment operand.
11397       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11398         Ops.push_back(N->getOperand(i));
11399     }
11400 
11401     // For all node types, the alignment operand is always the last one.
11402     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11403 
11404     // If this is a non-standard-aligned STORE, the penultimate operand is the
11405     // stored value.  Bitcast it to the aligned type.
11406     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11407       SDValue &StVal = Ops[Ops.size()-2];
11408       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11409     }
11410 
11411     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11412     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11413                                            MemN->getMemOperand());
11414 
11415     // Update the uses.
11416     SmallVector<SDValue, 5> NewResults;
11417     for (unsigned i = 0; i < NumResultVecs; ++i)
11418       NewResults.push_back(SDValue(UpdN.getNode(), i));
11419 
11420     // If this is an non-standard-aligned LOAD, the first result is the loaded
11421     // value.  Bitcast it to the expected result type.
11422     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11423       SDValue &LdVal = NewResults[0];
11424       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11425     }
11426 
11427     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11428     DCI.CombineTo(N, NewResults);
11429     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11430 
11431     break;
11432   }
11433   return SDValue();
11434 }
11435 
11436 static SDValue PerformVLDCombine(SDNode *N,
11437                                  TargetLowering::DAGCombinerInfo &DCI) {
11438   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11439     return SDValue();
11440 
11441   return CombineBaseUpdate(N, DCI);
11442 }
11443 
11444 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11445 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11446 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11447 /// return true.
11448 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11449   SelectionDAG &DAG = DCI.DAG;
11450   EVT VT = N->getValueType(0);
11451   // vldN-dup instructions only support 64-bit vectors for N > 1.
11452   if (!VT.is64BitVector())
11453     return false;
11454 
11455   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11456   SDNode *VLD = N->getOperand(0).getNode();
11457   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11458     return false;
11459   unsigned NumVecs = 0;
11460   unsigned NewOpc = 0;
11461   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11462   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11463     NumVecs = 2;
11464     NewOpc = ARMISD::VLD2DUP;
11465   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11466     NumVecs = 3;
11467     NewOpc = ARMISD::VLD3DUP;
11468   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11469     NumVecs = 4;
11470     NewOpc = ARMISD::VLD4DUP;
11471   } else {
11472     return false;
11473   }
11474 
11475   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11476   // numbers match the load.
11477   unsigned VLDLaneNo =
11478     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11479   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11480        UI != UE; ++UI) {
11481     // Ignore uses of the chain result.
11482     if (UI.getUse().getResNo() == NumVecs)
11483       continue;
11484     SDNode *User = *UI;
11485     if (User->getOpcode() != ARMISD::VDUPLANE ||
11486         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11487       return false;
11488   }
11489 
11490   // Create the vldN-dup node.
11491   EVT Tys[5];
11492   unsigned n;
11493   for (n = 0; n < NumVecs; ++n)
11494     Tys[n] = VT;
11495   Tys[n] = MVT::Other;
11496   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11497   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11498   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11499   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11500                                            Ops, VLDMemInt->getMemoryVT(),
11501                                            VLDMemInt->getMemOperand());
11502 
11503   // Update the uses.
11504   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11505        UI != UE; ++UI) {
11506     unsigned ResNo = UI.getUse().getResNo();
11507     // Ignore uses of the chain result.
11508     if (ResNo == NumVecs)
11509       continue;
11510     SDNode *User = *UI;
11511     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11512   }
11513 
11514   // Now the vldN-lane intrinsic is dead except for its chain result.
11515   // Update uses of the chain.
11516   std::vector<SDValue> VLDDupResults;
11517   for (unsigned n = 0; n < NumVecs; ++n)
11518     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11519   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11520   DCI.CombineTo(VLD, VLDDupResults);
11521 
11522   return true;
11523 }
11524 
11525 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11526 /// ARMISD::VDUPLANE.
11527 static SDValue PerformVDUPLANECombine(SDNode *N,
11528                                       TargetLowering::DAGCombinerInfo &DCI) {
11529   SDValue Op = N->getOperand(0);
11530 
11531   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11532   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11533   if (CombineVLDDUP(N, DCI))
11534     return SDValue(N, 0);
11535 
11536   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11537   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11538   while (Op.getOpcode() == ISD::BITCAST)
11539     Op = Op.getOperand(0);
11540   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11541     return SDValue();
11542 
11543   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11544   unsigned EltSize = Op.getScalarValueSizeInBits();
11545   // The canonical VMOV for a zero vector uses a 32-bit element size.
11546   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11547   unsigned EltBits;
11548   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11549     EltSize = 8;
11550   EVT VT = N->getValueType(0);
11551   if (EltSize > VT.getScalarSizeInBits())
11552     return SDValue();
11553 
11554   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11555 }
11556 
11557 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11558 static SDValue PerformVDUPCombine(SDNode *N,
11559                                   TargetLowering::DAGCombinerInfo &DCI) {
11560   SelectionDAG &DAG = DCI.DAG;
11561   SDValue Op = N->getOperand(0);
11562 
11563   // Match VDUP(LOAD) -> VLD1DUP.
11564   // We match this pattern here rather than waiting for isel because the
11565   // transform is only legal for unindexed loads.
11566   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11567   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11568       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11569     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11570                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11571     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11572     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11573                                              Ops, LD->getMemoryVT(),
11574                                              LD->getMemOperand());
11575     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11576     return VLDDup;
11577   }
11578 
11579   return SDValue();
11580 }
11581 
11582 static SDValue PerformLOADCombine(SDNode *N,
11583                                   TargetLowering::DAGCombinerInfo &DCI) {
11584   EVT VT = N->getValueType(0);
11585 
11586   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11587   if (ISD::isNormalLoad(N) && VT.isVector() &&
11588       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11589     return CombineBaseUpdate(N, DCI);
11590 
11591   return SDValue();
11592 }
11593 
11594 /// PerformSTORECombine - Target-specific dag combine xforms for
11595 /// ISD::STORE.
11596 static SDValue PerformSTORECombine(SDNode *N,
11597                                    TargetLowering::DAGCombinerInfo &DCI) {
11598   StoreSDNode *St = cast<StoreSDNode>(N);
11599   if (St->isVolatile())
11600     return SDValue();
11601 
11602   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11603   // pack all of the elements in one place.  Next, store to memory in fewer
11604   // chunks.
11605   SDValue StVal = St->getValue();
11606   EVT VT = StVal.getValueType();
11607   if (St->isTruncatingStore() && VT.isVector()) {
11608     SelectionDAG &DAG = DCI.DAG;
11609     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11610     EVT StVT = St->getMemoryVT();
11611     unsigned NumElems = VT.getVectorNumElements();
11612     assert(StVT != VT && "Cannot truncate to the same type");
11613     unsigned FromEltSz = VT.getScalarSizeInBits();
11614     unsigned ToEltSz = StVT.getScalarSizeInBits();
11615 
11616     // From, To sizes and ElemCount must be pow of two
11617     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11618 
11619     // We are going to use the original vector elt for storing.
11620     // Accumulated smaller vector elements must be a multiple of the store size.
11621     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11622 
11623     unsigned SizeRatio  = FromEltSz / ToEltSz;
11624     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11625 
11626     // Create a type on which we perform the shuffle.
11627     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11628                                      NumElems*SizeRatio);
11629     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11630 
11631     SDLoc DL(St);
11632     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11633     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11634     for (unsigned i = 0; i < NumElems; ++i)
11635       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11636                           ? (i + 1) * SizeRatio - 1
11637                           : i * SizeRatio;
11638 
11639     // Can't shuffle using an illegal type.
11640     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11641 
11642     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11643                                 DAG.getUNDEF(WideVec.getValueType()),
11644                                 ShuffleVec);
11645     // At this point all of the data is stored at the bottom of the
11646     // register. We now need to save it to mem.
11647 
11648     // Find the largest store unit
11649     MVT StoreType = MVT::i8;
11650     for (MVT Tp : MVT::integer_valuetypes()) {
11651       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11652         StoreType = Tp;
11653     }
11654     // Didn't find a legal store type.
11655     if (!TLI.isTypeLegal(StoreType))
11656       return SDValue();
11657 
11658     // Bitcast the original vector into a vector of store-size units
11659     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11660             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11661     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11662     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11663     SmallVector<SDValue, 8> Chains;
11664     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11665                                         TLI.getPointerTy(DAG.getDataLayout()));
11666     SDValue BasePtr = St->getBasePtr();
11667 
11668     // Perform one or more big stores into memory.
11669     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11670     for (unsigned I = 0; I < E; I++) {
11671       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11672                                    StoreType, ShuffWide,
11673                                    DAG.getIntPtrConstant(I, DL));
11674       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11675                                 St->getPointerInfo(), St->getAlignment(),
11676                                 St->getMemOperand()->getFlags());
11677       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11678                             Increment);
11679       Chains.push_back(Ch);
11680     }
11681     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11682   }
11683 
11684   if (!ISD::isNormalStore(St))
11685     return SDValue();
11686 
11687   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11688   // ARM stores of arguments in the same cache line.
11689   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11690       StVal.getNode()->hasOneUse()) {
11691     SelectionDAG  &DAG = DCI.DAG;
11692     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11693     SDLoc DL(St);
11694     SDValue BasePtr = St->getBasePtr();
11695     SDValue NewST1 = DAG.getStore(
11696         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11697         BasePtr, St->getPointerInfo(), St->getAlignment(),
11698         St->getMemOperand()->getFlags());
11699 
11700     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11701                                     DAG.getConstant(4, DL, MVT::i32));
11702     return DAG.getStore(NewST1.getValue(0), DL,
11703                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11704                         OffsetPtr, St->getPointerInfo(),
11705                         std::min(4U, St->getAlignment() / 2),
11706                         St->getMemOperand()->getFlags());
11707   }
11708 
11709   if (StVal.getValueType() == MVT::i64 &&
11710       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11711 
11712     // Bitcast an i64 store extracted from a vector to f64.
11713     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11714     SelectionDAG &DAG = DCI.DAG;
11715     SDLoc dl(StVal);
11716     SDValue IntVec = StVal.getOperand(0);
11717     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11718                                    IntVec.getValueType().getVectorNumElements());
11719     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11720     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11721                                  Vec, StVal.getOperand(1));
11722     dl = SDLoc(N);
11723     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11724     // Make the DAGCombiner fold the bitcasts.
11725     DCI.AddToWorklist(Vec.getNode());
11726     DCI.AddToWorklist(ExtElt.getNode());
11727     DCI.AddToWorklist(V.getNode());
11728     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11729                         St->getPointerInfo(), St->getAlignment(),
11730                         St->getMemOperand()->getFlags(), St->getAAInfo());
11731   }
11732 
11733   // If this is a legal vector store, try to combine it into a VST1_UPD.
11734   if (ISD::isNormalStore(N) && VT.isVector() &&
11735       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11736     return CombineBaseUpdate(N, DCI);
11737 
11738   return SDValue();
11739 }
11740 
11741 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11742 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11743 /// when the VMUL has a constant operand that is a power of 2.
11744 ///
11745 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11746 ///  vmul.f32        d16, d17, d16
11747 ///  vcvt.s32.f32    d16, d16
11748 /// becomes:
11749 ///  vcvt.s32.f32    d16, d16, #3
11750 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11751                                   const ARMSubtarget *Subtarget) {
11752   if (!Subtarget->hasNEON())
11753     return SDValue();
11754 
11755   SDValue Op = N->getOperand(0);
11756   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11757       Op.getOpcode() != ISD::FMUL)
11758     return SDValue();
11759 
11760   SDValue ConstVec = Op->getOperand(1);
11761   if (!isa<BuildVectorSDNode>(ConstVec))
11762     return SDValue();
11763 
11764   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11765   uint32_t FloatBits = FloatTy.getSizeInBits();
11766   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11767   uint32_t IntBits = IntTy.getSizeInBits();
11768   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11769   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11770     // These instructions only exist converting from f32 to i32. We can handle
11771     // smaller integers by generating an extra truncate, but larger ones would
11772     // be lossy. We also can't handle more then 4 lanes, since these intructions
11773     // only support v2i32/v4i32 types.
11774     return SDValue();
11775   }
11776 
11777   BitVector UndefElements;
11778   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11779   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11780   if (C == -1 || C == 0 || C > 32)
11781     return SDValue();
11782 
11783   SDLoc dl(N);
11784   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11785   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11786     Intrinsic::arm_neon_vcvtfp2fxu;
11787   SDValue FixConv = DAG.getNode(
11788       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11789       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11790       DAG.getConstant(C, dl, MVT::i32));
11791 
11792   if (IntBits < FloatBits)
11793     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11794 
11795   return FixConv;
11796 }
11797 
11798 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11799 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11800 /// when the VDIV has a constant operand that is a power of 2.
11801 ///
11802 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11803 ///  vcvt.f32.s32    d16, d16
11804 ///  vdiv.f32        d16, d17, d16
11805 /// becomes:
11806 ///  vcvt.f32.s32    d16, d16, #3
11807 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11808                                   const ARMSubtarget *Subtarget) {
11809   if (!Subtarget->hasNEON())
11810     return SDValue();
11811 
11812   SDValue Op = N->getOperand(0);
11813   unsigned OpOpcode = Op.getNode()->getOpcode();
11814   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11815       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11816     return SDValue();
11817 
11818   SDValue ConstVec = N->getOperand(1);
11819   if (!isa<BuildVectorSDNode>(ConstVec))
11820     return SDValue();
11821 
11822   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11823   uint32_t FloatBits = FloatTy.getSizeInBits();
11824   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11825   uint32_t IntBits = IntTy.getSizeInBits();
11826   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11827   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11828     // These instructions only exist converting from i32 to f32. We can handle
11829     // smaller integers by generating an extra extend, but larger ones would
11830     // be lossy. We also can't handle more then 4 lanes, since these intructions
11831     // only support v2i32/v4i32 types.
11832     return SDValue();
11833   }
11834 
11835   BitVector UndefElements;
11836   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11837   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11838   if (C == -1 || C == 0 || C > 32)
11839     return SDValue();
11840 
11841   SDLoc dl(N);
11842   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11843   SDValue ConvInput = Op.getOperand(0);
11844   if (IntBits < FloatBits)
11845     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11846                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11847                             ConvInput);
11848 
11849   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11850     Intrinsic::arm_neon_vcvtfxu2fp;
11851   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11852                      Op.getValueType(),
11853                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11854                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11855 }
11856 
11857 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11858 /// operand of a vector shift operation, where all the elements of the
11859 /// build_vector must have the same constant integer value.
11860 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11861   // Ignore bit_converts.
11862   while (Op.getOpcode() == ISD::BITCAST)
11863     Op = Op.getOperand(0);
11864   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11865   APInt SplatBits, SplatUndef;
11866   unsigned SplatBitSize;
11867   bool HasAnyUndefs;
11868   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11869                                       HasAnyUndefs, ElementBits) ||
11870       SplatBitSize > ElementBits)
11871     return false;
11872   Cnt = SplatBits.getSExtValue();
11873   return true;
11874 }
11875 
11876 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11877 /// operand of a vector shift left operation.  That value must be in the range:
11878 ///   0 <= Value < ElementBits for a left shift; or
11879 ///   0 <= Value <= ElementBits for a long left shift.
11880 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11881   assert(VT.isVector() && "vector shift count is not a vector type");
11882   int64_t ElementBits = VT.getScalarSizeInBits();
11883   if (! getVShiftImm(Op, ElementBits, Cnt))
11884     return false;
11885   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11886 }
11887 
11888 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11889 /// operand of a vector shift right operation.  For a shift opcode, the value
11890 /// is positive, but for an intrinsic the value count must be negative. The
11891 /// absolute value must be in the range:
11892 ///   1 <= |Value| <= ElementBits for a right shift; or
11893 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11894 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11895                          int64_t &Cnt) {
11896   assert(VT.isVector() && "vector shift count is not a vector type");
11897   int64_t ElementBits = VT.getScalarSizeInBits();
11898   if (! getVShiftImm(Op, ElementBits, Cnt))
11899     return false;
11900   if (!isIntrinsic)
11901     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11902   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11903     Cnt = -Cnt;
11904     return true;
11905   }
11906   return false;
11907 }
11908 
11909 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11910 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11911   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11912   switch (IntNo) {
11913   default:
11914     // Don't do anything for most intrinsics.
11915     break;
11916 
11917   // Vector shifts: check for immediate versions and lower them.
11918   // Note: This is done during DAG combining instead of DAG legalizing because
11919   // the build_vectors for 64-bit vector element shift counts are generally
11920   // not legal, and it is hard to see their values after they get legalized to
11921   // loads from a constant pool.
11922   case Intrinsic::arm_neon_vshifts:
11923   case Intrinsic::arm_neon_vshiftu:
11924   case Intrinsic::arm_neon_vrshifts:
11925   case Intrinsic::arm_neon_vrshiftu:
11926   case Intrinsic::arm_neon_vrshiftn:
11927   case Intrinsic::arm_neon_vqshifts:
11928   case Intrinsic::arm_neon_vqshiftu:
11929   case Intrinsic::arm_neon_vqshiftsu:
11930   case Intrinsic::arm_neon_vqshiftns:
11931   case Intrinsic::arm_neon_vqshiftnu:
11932   case Intrinsic::arm_neon_vqshiftnsu:
11933   case Intrinsic::arm_neon_vqrshiftns:
11934   case Intrinsic::arm_neon_vqrshiftnu:
11935   case Intrinsic::arm_neon_vqrshiftnsu: {
11936     EVT VT = N->getOperand(1).getValueType();
11937     int64_t Cnt;
11938     unsigned VShiftOpc = 0;
11939 
11940     switch (IntNo) {
11941     case Intrinsic::arm_neon_vshifts:
11942     case Intrinsic::arm_neon_vshiftu:
11943       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11944         VShiftOpc = ARMISD::VSHL;
11945         break;
11946       }
11947       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11948         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11949                      ARMISD::VSHRs : ARMISD::VSHRu);
11950         break;
11951       }
11952       return SDValue();
11953 
11954     case Intrinsic::arm_neon_vrshifts:
11955     case Intrinsic::arm_neon_vrshiftu:
11956       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11957         break;
11958       return SDValue();
11959 
11960     case Intrinsic::arm_neon_vqshifts:
11961     case Intrinsic::arm_neon_vqshiftu:
11962       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11963         break;
11964       return SDValue();
11965 
11966     case Intrinsic::arm_neon_vqshiftsu:
11967       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11968         break;
11969       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11970 
11971     case Intrinsic::arm_neon_vrshiftn:
11972     case Intrinsic::arm_neon_vqshiftns:
11973     case Intrinsic::arm_neon_vqshiftnu:
11974     case Intrinsic::arm_neon_vqshiftnsu:
11975     case Intrinsic::arm_neon_vqrshiftns:
11976     case Intrinsic::arm_neon_vqrshiftnu:
11977     case Intrinsic::arm_neon_vqrshiftnsu:
11978       // Narrowing shifts require an immediate right shift.
11979       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11980         break;
11981       llvm_unreachable("invalid shift count for narrowing vector shift "
11982                        "intrinsic");
11983 
11984     default:
11985       llvm_unreachable("unhandled vector shift");
11986     }
11987 
11988     switch (IntNo) {
11989     case Intrinsic::arm_neon_vshifts:
11990     case Intrinsic::arm_neon_vshiftu:
11991       // Opcode already set above.
11992       break;
11993     case Intrinsic::arm_neon_vrshifts:
11994       VShiftOpc = ARMISD::VRSHRs; break;
11995     case Intrinsic::arm_neon_vrshiftu:
11996       VShiftOpc = ARMISD::VRSHRu; break;
11997     case Intrinsic::arm_neon_vrshiftn:
11998       VShiftOpc = ARMISD::VRSHRN; break;
11999     case Intrinsic::arm_neon_vqshifts:
12000       VShiftOpc = ARMISD::VQSHLs; break;
12001     case Intrinsic::arm_neon_vqshiftu:
12002       VShiftOpc = ARMISD::VQSHLu; break;
12003     case Intrinsic::arm_neon_vqshiftsu:
12004       VShiftOpc = ARMISD::VQSHLsu; break;
12005     case Intrinsic::arm_neon_vqshiftns:
12006       VShiftOpc = ARMISD::VQSHRNs; break;
12007     case Intrinsic::arm_neon_vqshiftnu:
12008       VShiftOpc = ARMISD::VQSHRNu; break;
12009     case Intrinsic::arm_neon_vqshiftnsu:
12010       VShiftOpc = ARMISD::VQSHRNsu; break;
12011     case Intrinsic::arm_neon_vqrshiftns:
12012       VShiftOpc = ARMISD::VQRSHRNs; break;
12013     case Intrinsic::arm_neon_vqrshiftnu:
12014       VShiftOpc = ARMISD::VQRSHRNu; break;
12015     case Intrinsic::arm_neon_vqrshiftnsu:
12016       VShiftOpc = ARMISD::VQRSHRNsu; break;
12017     }
12018 
12019     SDLoc dl(N);
12020     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12021                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12022   }
12023 
12024   case Intrinsic::arm_neon_vshiftins: {
12025     EVT VT = N->getOperand(1).getValueType();
12026     int64_t Cnt;
12027     unsigned VShiftOpc = 0;
12028 
12029     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12030       VShiftOpc = ARMISD::VSLI;
12031     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12032       VShiftOpc = ARMISD::VSRI;
12033     else {
12034       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12035     }
12036 
12037     SDLoc dl(N);
12038     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12039                        N->getOperand(1), N->getOperand(2),
12040                        DAG.getConstant(Cnt, dl, MVT::i32));
12041   }
12042 
12043   case Intrinsic::arm_neon_vqrshifts:
12044   case Intrinsic::arm_neon_vqrshiftu:
12045     // No immediate versions of these to check for.
12046     break;
12047   }
12048 
12049   return SDValue();
12050 }
12051 
12052 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12053 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12054 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12055 /// vector element shift counts are generally not legal, and it is hard to see
12056 /// their values after they get legalized to loads from a constant pool.
12057 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12058                                    const ARMSubtarget *ST) {
12059   EVT VT = N->getValueType(0);
12060   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12061     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12062     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12063     SDValue N1 = N->getOperand(1);
12064     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12065       SDValue N0 = N->getOperand(0);
12066       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12067           DAG.MaskedValueIsZero(N0.getOperand(0),
12068                                 APInt::getHighBitsSet(32, 16)))
12069         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12070     }
12071   }
12072 
12073   // Nothing to be done for scalar shifts.
12074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12075   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12076     return SDValue();
12077 
12078   assert(ST->hasNEON() && "unexpected vector shift");
12079   int64_t Cnt;
12080 
12081   switch (N->getOpcode()) {
12082   default: llvm_unreachable("unexpected shift opcode");
12083 
12084   case ISD::SHL:
12085     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12086       SDLoc dl(N);
12087       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12088                          DAG.getConstant(Cnt, dl, MVT::i32));
12089     }
12090     break;
12091 
12092   case ISD::SRA:
12093   case ISD::SRL:
12094     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12095       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12096                             ARMISD::VSHRs : ARMISD::VSHRu);
12097       SDLoc dl(N);
12098       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12099                          DAG.getConstant(Cnt, dl, MVT::i32));
12100     }
12101   }
12102   return SDValue();
12103 }
12104 
12105 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12106 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12107 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12108                                     const ARMSubtarget *ST) {
12109   SDValue N0 = N->getOperand(0);
12110 
12111   // Check for sign- and zero-extensions of vector extract operations of 8-
12112   // and 16-bit vector elements.  NEON supports these directly.  They are
12113   // handled during DAG combining because type legalization will promote them
12114   // to 32-bit types and it is messy to recognize the operations after that.
12115   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12116     SDValue Vec = N0.getOperand(0);
12117     SDValue Lane = N0.getOperand(1);
12118     EVT VT = N->getValueType(0);
12119     EVT EltVT = N0.getValueType();
12120     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12121 
12122     if (VT == MVT::i32 &&
12123         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12124         TLI.isTypeLegal(Vec.getValueType()) &&
12125         isa<ConstantSDNode>(Lane)) {
12126 
12127       unsigned Opc = 0;
12128       switch (N->getOpcode()) {
12129       default: llvm_unreachable("unexpected opcode");
12130       case ISD::SIGN_EXTEND:
12131         Opc = ARMISD::VGETLANEs;
12132         break;
12133       case ISD::ZERO_EXTEND:
12134       case ISD::ANY_EXTEND:
12135         Opc = ARMISD::VGETLANEu;
12136         break;
12137       }
12138       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12139     }
12140   }
12141 
12142   return SDValue();
12143 }
12144 
12145 static const APInt *isPowerOf2Constant(SDValue V) {
12146   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12147   if (!C)
12148     return nullptr;
12149   const APInt *CV = &C->getAPIntValue();
12150   return CV->isPowerOf2() ? CV : nullptr;
12151 }
12152 
12153 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12154   // If we have a CMOV, OR and AND combination such as:
12155   //   if (x & CN)
12156   //     y |= CM;
12157   //
12158   // And:
12159   //   * CN is a single bit;
12160   //   * All bits covered by CM are known zero in y
12161   //
12162   // Then we can convert this into a sequence of BFI instructions. This will
12163   // always be a win if CM is a single bit, will always be no worse than the
12164   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12165   // three bits (due to the extra IT instruction).
12166 
12167   SDValue Op0 = CMOV->getOperand(0);
12168   SDValue Op1 = CMOV->getOperand(1);
12169   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12170   auto CC = CCNode->getAPIntValue().getLimitedValue();
12171   SDValue CmpZ = CMOV->getOperand(4);
12172 
12173   // The compare must be against zero.
12174   if (!isNullConstant(CmpZ->getOperand(1)))
12175     return SDValue();
12176 
12177   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12178   SDValue And = CmpZ->getOperand(0);
12179   if (And->getOpcode() != ISD::AND)
12180     return SDValue();
12181   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12182   if (!AndC)
12183     return SDValue();
12184   SDValue X = And->getOperand(0);
12185 
12186   if (CC == ARMCC::EQ) {
12187     // We're performing an "equal to zero" compare. Swap the operands so we
12188     // canonicalize on a "not equal to zero" compare.
12189     std::swap(Op0, Op1);
12190   } else {
12191     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12192   }
12193 
12194   if (Op1->getOpcode() != ISD::OR)
12195     return SDValue();
12196 
12197   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12198   if (!OrC)
12199     return SDValue();
12200   SDValue Y = Op1->getOperand(0);
12201 
12202   if (Op0 != Y)
12203     return SDValue();
12204 
12205   // Now, is it profitable to continue?
12206   APInt OrCI = OrC->getAPIntValue();
12207   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12208   if (OrCI.countPopulation() > Heuristic)
12209     return SDValue();
12210 
12211   // Lastly, can we determine that the bits defined by OrCI
12212   // are zero in Y?
12213   KnownBits Known;
12214   DAG.computeKnownBits(Y, Known);
12215   if ((OrCI & Known.Zero) != OrCI)
12216     return SDValue();
12217 
12218   // OK, we can do the combine.
12219   SDValue V = Y;
12220   SDLoc dl(X);
12221   EVT VT = X.getValueType();
12222   unsigned BitInX = AndC->logBase2();
12223 
12224   if (BitInX != 0) {
12225     // We must shift X first.
12226     X = DAG.getNode(ISD::SRL, dl, VT, X,
12227                     DAG.getConstant(BitInX, dl, VT));
12228   }
12229 
12230   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12231        BitInY < NumActiveBits; ++BitInY) {
12232     if (OrCI[BitInY] == 0)
12233       continue;
12234     APInt Mask(VT.getSizeInBits(), 0);
12235     Mask.setBit(BitInY);
12236     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12237                     // Confusingly, the operand is an *inverted* mask.
12238                     DAG.getConstant(~Mask, dl, VT));
12239   }
12240 
12241   return V;
12242 }
12243 
12244 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12245 SDValue
12246 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12247   SDValue Cmp = N->getOperand(4);
12248   if (Cmp.getOpcode() != ARMISD::CMPZ)
12249     // Only looking at NE cases.
12250     return SDValue();
12251 
12252   EVT VT = N->getValueType(0);
12253   SDLoc dl(N);
12254   SDValue LHS = Cmp.getOperand(0);
12255   SDValue RHS = Cmp.getOperand(1);
12256   SDValue Chain = N->getOperand(0);
12257   SDValue BB = N->getOperand(1);
12258   SDValue ARMcc = N->getOperand(2);
12259   ARMCC::CondCodes CC =
12260     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12261 
12262   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12263   // -> (brcond Chain BB CC CPSR Cmp)
12264   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12265       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12266       LHS->getOperand(0)->hasOneUse()) {
12267     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12268     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12269     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12270     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12271     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12272         (LHS01C && LHS01C->getZExtValue() == 1) &&
12273         (LHS1C && LHS1C->getZExtValue() == 1) &&
12274         (RHSC && RHSC->getZExtValue() == 0)) {
12275       return DAG.getNode(
12276           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12277           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12278     }
12279   }
12280 
12281   return SDValue();
12282 }
12283 
12284 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12285 SDValue
12286 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12287   SDValue Cmp = N->getOperand(4);
12288   if (Cmp.getOpcode() != ARMISD::CMPZ)
12289     // Only looking at EQ and NE cases.
12290     return SDValue();
12291 
12292   EVT VT = N->getValueType(0);
12293   SDLoc dl(N);
12294   SDValue LHS = Cmp.getOperand(0);
12295   SDValue RHS = Cmp.getOperand(1);
12296   SDValue FalseVal = N->getOperand(0);
12297   SDValue TrueVal = N->getOperand(1);
12298   SDValue ARMcc = N->getOperand(2);
12299   ARMCC::CondCodes CC =
12300     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12301 
12302   // BFI is only available on V6T2+.
12303   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12304     SDValue R = PerformCMOVToBFICombine(N, DAG);
12305     if (R)
12306       return R;
12307   }
12308 
12309   // Simplify
12310   //   mov     r1, r0
12311   //   cmp     r1, x
12312   //   mov     r0, y
12313   //   moveq   r0, x
12314   // to
12315   //   cmp     r0, x
12316   //   movne   r0, y
12317   //
12318   //   mov     r1, r0
12319   //   cmp     r1, x
12320   //   mov     r0, x
12321   //   movne   r0, y
12322   // to
12323   //   cmp     r0, x
12324   //   movne   r0, y
12325   /// FIXME: Turn this into a target neutral optimization?
12326   SDValue Res;
12327   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12328     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12329                       N->getOperand(3), Cmp);
12330   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12331     SDValue ARMcc;
12332     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12333     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12334                       N->getOperand(3), NewCmp);
12335   }
12336 
12337   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12338   // -> (cmov F T CC CPSR Cmp)
12339   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12340     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12341     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12342     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12343     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12344         (LHS1C && LHS1C->getZExtValue() == 1) &&
12345         (RHSC && RHSC->getZExtValue() == 0)) {
12346       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12347                          LHS->getOperand(2), LHS->getOperand(3),
12348                          LHS->getOperand(4));
12349     }
12350   }
12351 
12352   if (Res.getNode()) {
12353     KnownBits Known;
12354     DAG.computeKnownBits(SDValue(N,0), Known);
12355     // Capture demanded bits information that would be otherwise lost.
12356     if (Known.Zero == 0xfffffffe)
12357       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12358                         DAG.getValueType(MVT::i1));
12359     else if (Known.Zero == 0xffffff00)
12360       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12361                         DAG.getValueType(MVT::i8));
12362     else if (Known.Zero == 0xffff0000)
12363       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12364                         DAG.getValueType(MVT::i16));
12365   }
12366 
12367   return Res;
12368 }
12369 
12370 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12371                                              DAGCombinerInfo &DCI) const {
12372   switch (N->getOpcode()) {
12373   default: break;
12374   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12375   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12376   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12377   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12378   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12379   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12380   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12381   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12382   case ARMISD::ADDC:
12383   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12384   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12385   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12386   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12387   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12388   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12389   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12390   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12391   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12392   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12393   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12394   case ISD::FP_TO_SINT:
12395   case ISD::FP_TO_UINT:
12396     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12397   case ISD::FDIV:
12398     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12399   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12400   case ISD::SHL:
12401   case ISD::SRA:
12402   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12403   case ISD::SIGN_EXTEND:
12404   case ISD::ZERO_EXTEND:
12405   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12406   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12407   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12408   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12409   case ARMISD::VLD1DUP:
12410   case ARMISD::VLD2DUP:
12411   case ARMISD::VLD3DUP:
12412   case ARMISD::VLD4DUP:
12413     return PerformVLDCombine(N, DCI);
12414   case ARMISD::BUILD_VECTOR:
12415     return PerformARMBUILD_VECTORCombine(N, DCI);
12416   case ARMISD::SMULWB: {
12417     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12418     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12419     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12420       return SDValue();
12421     break;
12422   }
12423   case ARMISD::SMULWT: {
12424     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12425     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12426     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12427       return SDValue();
12428     break;
12429   }
12430   case ARMISD::SMLALBB: {
12431     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12432     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12433     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12434         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12435       return SDValue();
12436     break;
12437   }
12438   case ARMISD::SMLALBT: {
12439     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12440     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12441     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12442     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12443     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12444         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12445       return SDValue();
12446     break;
12447   }
12448   case ARMISD::SMLALTB: {
12449     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12450     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12451     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12452     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12453     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12454         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12455       return SDValue();
12456     break;
12457   }
12458   case ARMISD::SMLALTT: {
12459     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12460     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12461     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12462         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12463       return SDValue();
12464     break;
12465   }
12466   case ISD::INTRINSIC_VOID:
12467   case ISD::INTRINSIC_W_CHAIN:
12468     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12469     case Intrinsic::arm_neon_vld1:
12470     case Intrinsic::arm_neon_vld2:
12471     case Intrinsic::arm_neon_vld3:
12472     case Intrinsic::arm_neon_vld4:
12473     case Intrinsic::arm_neon_vld2lane:
12474     case Intrinsic::arm_neon_vld3lane:
12475     case Intrinsic::arm_neon_vld4lane:
12476     case Intrinsic::arm_neon_vst1:
12477     case Intrinsic::arm_neon_vst2:
12478     case Intrinsic::arm_neon_vst3:
12479     case Intrinsic::arm_neon_vst4:
12480     case Intrinsic::arm_neon_vst2lane:
12481     case Intrinsic::arm_neon_vst3lane:
12482     case Intrinsic::arm_neon_vst4lane:
12483       return PerformVLDCombine(N, DCI);
12484     default: break;
12485     }
12486     break;
12487   }
12488   return SDValue();
12489 }
12490 
12491 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12492                                                           EVT VT) const {
12493   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12494 }
12495 
12496 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12497                                                        unsigned,
12498                                                        unsigned,
12499                                                        bool *Fast) const {
12500   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12501   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12502 
12503   switch (VT.getSimpleVT().SimpleTy) {
12504   default:
12505     return false;
12506   case MVT::i8:
12507   case MVT::i16:
12508   case MVT::i32: {
12509     // Unaligned access can use (for example) LRDB, LRDH, LDR
12510     if (AllowsUnaligned) {
12511       if (Fast)
12512         *Fast = Subtarget->hasV7Ops();
12513       return true;
12514     }
12515     return false;
12516   }
12517   case MVT::f64:
12518   case MVT::v2f64: {
12519     // For any little-endian targets with neon, we can support unaligned ld/st
12520     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12521     // A big-endian target may also explicitly support unaligned accesses
12522     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12523       if (Fast)
12524         *Fast = true;
12525       return true;
12526     }
12527     return false;
12528   }
12529   }
12530 }
12531 
12532 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12533                        unsigned AlignCheck) {
12534   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12535           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12536 }
12537 
12538 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12539                                            unsigned DstAlign, unsigned SrcAlign,
12540                                            bool IsMemset, bool ZeroMemset,
12541                                            bool MemcpyStrSrc,
12542                                            MachineFunction &MF) const {
12543   const Function &F = MF.getFunction();
12544 
12545   // See if we can use NEON instructions for this...
12546   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12547       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12548     bool Fast;
12549     if (Size >= 16 &&
12550         (memOpAlign(SrcAlign, DstAlign, 16) ||
12551          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12552       return MVT::v2f64;
12553     } else if (Size >= 8 &&
12554                (memOpAlign(SrcAlign, DstAlign, 8) ||
12555                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12556                  Fast))) {
12557       return MVT::f64;
12558     }
12559   }
12560 
12561   // Let the target-independent logic figure it out.
12562   return MVT::Other;
12563 }
12564 
12565 // 64-bit integers are split into their high and low parts and held in two
12566 // different registers, so the trunc is free since the low register can just
12567 // be used.
12568 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12569   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12570     return false;
12571   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12572   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12573   return (SrcBits == 64 && DestBits == 32);
12574 }
12575 
12576 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12577   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12578       !DstVT.isInteger())
12579     return false;
12580   unsigned SrcBits = SrcVT.getSizeInBits();
12581   unsigned DestBits = DstVT.getSizeInBits();
12582   return (SrcBits == 64 && DestBits == 32);
12583 }
12584 
12585 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12586   if (Val.getOpcode() != ISD::LOAD)
12587     return false;
12588 
12589   EVT VT1 = Val.getValueType();
12590   if (!VT1.isSimple() || !VT1.isInteger() ||
12591       !VT2.isSimple() || !VT2.isInteger())
12592     return false;
12593 
12594   switch (VT1.getSimpleVT().SimpleTy) {
12595   default: break;
12596   case MVT::i1:
12597   case MVT::i8:
12598   case MVT::i16:
12599     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12600     return true;
12601   }
12602 
12603   return false;
12604 }
12605 
12606 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12607   EVT VT = ExtVal.getValueType();
12608 
12609   if (!isTypeLegal(VT))
12610     return false;
12611 
12612   // Don't create a loadext if we can fold the extension into a wide/long
12613   // instruction.
12614   // If there's more than one user instruction, the loadext is desirable no
12615   // matter what.  There can be two uses by the same instruction.
12616   if (ExtVal->use_empty() ||
12617       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12618     return true;
12619 
12620   SDNode *U = *ExtVal->use_begin();
12621   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12622        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12623     return false;
12624 
12625   return true;
12626 }
12627 
12628 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12629   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12630     return false;
12631 
12632   if (!isTypeLegal(EVT::getEVT(Ty1)))
12633     return false;
12634 
12635   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12636 
12637   // Assuming the caller doesn't have a zeroext or signext return parameter,
12638   // truncation all the way down to i1 is valid.
12639   return true;
12640 }
12641 
12642 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12643                                                 const AddrMode &AM, Type *Ty,
12644                                                 unsigned AS) const {
12645   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12646     if (Subtarget->hasFPAO())
12647       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12648     return 0;
12649   }
12650   return -1;
12651 }
12652 
12653 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12654   if (V < 0)
12655     return false;
12656 
12657   unsigned Scale = 1;
12658   switch (VT.getSimpleVT().SimpleTy) {
12659   default: return false;
12660   case MVT::i1:
12661   case MVT::i8:
12662     // Scale == 1;
12663     break;
12664   case MVT::i16:
12665     // Scale == 2;
12666     Scale = 2;
12667     break;
12668   case MVT::i32:
12669     // Scale == 4;
12670     Scale = 4;
12671     break;
12672   }
12673 
12674   if ((V & (Scale - 1)) != 0)
12675     return false;
12676   V /= Scale;
12677   return V == (V & ((1LL << 5) - 1));
12678 }
12679 
12680 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12681                                       const ARMSubtarget *Subtarget) {
12682   bool isNeg = false;
12683   if (V < 0) {
12684     isNeg = true;
12685     V = - V;
12686   }
12687 
12688   switch (VT.getSimpleVT().SimpleTy) {
12689   default: return false;
12690   case MVT::i1:
12691   case MVT::i8:
12692   case MVT::i16:
12693   case MVT::i32:
12694     // + imm12 or - imm8
12695     if (isNeg)
12696       return V == (V & ((1LL << 8) - 1));
12697     return V == (V & ((1LL << 12) - 1));
12698   case MVT::f32:
12699   case MVT::f64:
12700     // Same as ARM mode. FIXME: NEON?
12701     if (!Subtarget->hasVFP2())
12702       return false;
12703     if ((V & 3) != 0)
12704       return false;
12705     V >>= 2;
12706     return V == (V & ((1LL << 8) - 1));
12707   }
12708 }
12709 
12710 /// isLegalAddressImmediate - Return true if the integer value can be used
12711 /// as the offset of the target addressing mode for load / store of the
12712 /// given type.
12713 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12714                                     const ARMSubtarget *Subtarget) {
12715   if (V == 0)
12716     return true;
12717 
12718   if (!VT.isSimple())
12719     return false;
12720 
12721   if (Subtarget->isThumb1Only())
12722     return isLegalT1AddressImmediate(V, VT);
12723   else if (Subtarget->isThumb2())
12724     return isLegalT2AddressImmediate(V, VT, Subtarget);
12725 
12726   // ARM mode.
12727   if (V < 0)
12728     V = - V;
12729   switch (VT.getSimpleVT().SimpleTy) {
12730   default: return false;
12731   case MVT::i1:
12732   case MVT::i8:
12733   case MVT::i32:
12734     // +- imm12
12735     return V == (V & ((1LL << 12) - 1));
12736   case MVT::i16:
12737     // +- imm8
12738     return V == (V & ((1LL << 8) - 1));
12739   case MVT::f32:
12740   case MVT::f64:
12741     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12742       return false;
12743     if ((V & 3) != 0)
12744       return false;
12745     V >>= 2;
12746     return V == (V & ((1LL << 8) - 1));
12747   }
12748 }
12749 
12750 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12751                                                       EVT VT) const {
12752   int Scale = AM.Scale;
12753   if (Scale < 0)
12754     return false;
12755 
12756   switch (VT.getSimpleVT().SimpleTy) {
12757   default: return false;
12758   case MVT::i1:
12759   case MVT::i8:
12760   case MVT::i16:
12761   case MVT::i32:
12762     if (Scale == 1)
12763       return true;
12764     // r + r << imm
12765     Scale = Scale & ~1;
12766     return Scale == 2 || Scale == 4 || Scale == 8;
12767   case MVT::i64:
12768     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12769     // version in Thumb mode.
12770     // r + r
12771     if (Scale == 1)
12772       return true;
12773     // r * 2 (this can be lowered to r + r).
12774     if (!AM.HasBaseReg && Scale == 2)
12775       return true;
12776     return false;
12777   case MVT::isVoid:
12778     // Note, we allow "void" uses (basically, uses that aren't loads or
12779     // stores), because arm allows folding a scale into many arithmetic
12780     // operations.  This should be made more precise and revisited later.
12781 
12782     // Allow r << imm, but the imm has to be a multiple of two.
12783     if (Scale & 1) return false;
12784     return isPowerOf2_32(Scale);
12785   }
12786 }
12787 
12788 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12789                                                       EVT VT) const {
12790   const int Scale = AM.Scale;
12791 
12792   // Negative scales are not supported in Thumb1.
12793   if (Scale < 0)
12794     return false;
12795 
12796   // Thumb1 addressing modes do not support register scaling excepting the
12797   // following cases:
12798   // 1. Scale == 1 means no scaling.
12799   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12800   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12801 }
12802 
12803 /// isLegalAddressingMode - Return true if the addressing mode represented
12804 /// by AM is legal for this target, for a load/store of the specified type.
12805 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12806                                               const AddrMode &AM, Type *Ty,
12807                                               unsigned AS, Instruction *I) const {
12808   EVT VT = getValueType(DL, Ty, true);
12809   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12810     return false;
12811 
12812   // Can never fold addr of global into load/store.
12813   if (AM.BaseGV)
12814     return false;
12815 
12816   switch (AM.Scale) {
12817   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12818     break;
12819   default:
12820     // ARM doesn't support any R+R*scale+imm addr modes.
12821     if (AM.BaseOffs)
12822       return false;
12823 
12824     if (!VT.isSimple())
12825       return false;
12826 
12827     if (Subtarget->isThumb1Only())
12828       return isLegalT1ScaledAddressingMode(AM, VT);
12829 
12830     if (Subtarget->isThumb2())
12831       return isLegalT2ScaledAddressingMode(AM, VT);
12832 
12833     int Scale = AM.Scale;
12834     switch (VT.getSimpleVT().SimpleTy) {
12835     default: return false;
12836     case MVT::i1:
12837     case MVT::i8:
12838     case MVT::i32:
12839       if (Scale < 0) Scale = -Scale;
12840       if (Scale == 1)
12841         return true;
12842       // r + r << imm
12843       return isPowerOf2_32(Scale & ~1);
12844     case MVT::i16:
12845     case MVT::i64:
12846       // r +/- r
12847       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
12848         return true;
12849       // r * 2 (this can be lowered to r + r).
12850       if (!AM.HasBaseReg && Scale == 2)
12851         return true;
12852       return false;
12853 
12854     case MVT::isVoid:
12855       // Note, we allow "void" uses (basically, uses that aren't loads or
12856       // stores), because arm allows folding a scale into many arithmetic
12857       // operations.  This should be made more precise and revisited later.
12858 
12859       // Allow r << imm, but the imm has to be a multiple of two.
12860       if (Scale & 1) return false;
12861       return isPowerOf2_32(Scale);
12862     }
12863   }
12864   return true;
12865 }
12866 
12867 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12868 /// icmp immediate, that is the target has icmp instructions which can compare
12869 /// a register against the immediate without having to materialize the
12870 /// immediate into a register.
12871 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12872   // Thumb2 and ARM modes can use cmn for negative immediates.
12873   if (!Subtarget->isThumb())
12874     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12875   if (Subtarget->isThumb2())
12876     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12877   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12878   return Imm >= 0 && Imm <= 255;
12879 }
12880 
12881 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12882 /// *or sub* immediate, that is the target has add or sub instructions which can
12883 /// add a register with the immediate without having to materialize the
12884 /// immediate into a register.
12885 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12886   // Same encoding for add/sub, just flip the sign.
12887   int64_t AbsImm = std::abs(Imm);
12888   if (!Subtarget->isThumb())
12889     return ARM_AM::getSOImmVal(AbsImm) != -1;
12890   if (Subtarget->isThumb2())
12891     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12892   // Thumb1 only has 8-bit unsigned immediate.
12893   return AbsImm >= 0 && AbsImm <= 255;
12894 }
12895 
12896 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12897                                       bool isSEXTLoad, SDValue &Base,
12898                                       SDValue &Offset, bool &isInc,
12899                                       SelectionDAG &DAG) {
12900   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12901     return false;
12902 
12903   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12904     // AddressingMode 3
12905     Base = Ptr->getOperand(0);
12906     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12907       int RHSC = (int)RHS->getZExtValue();
12908       if (RHSC < 0 && RHSC > -256) {
12909         assert(Ptr->getOpcode() == ISD::ADD);
12910         isInc = false;
12911         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12912         return true;
12913       }
12914     }
12915     isInc = (Ptr->getOpcode() == ISD::ADD);
12916     Offset = Ptr->getOperand(1);
12917     return true;
12918   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12919     // AddressingMode 2
12920     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12921       int RHSC = (int)RHS->getZExtValue();
12922       if (RHSC < 0 && RHSC > -0x1000) {
12923         assert(Ptr->getOpcode() == ISD::ADD);
12924         isInc = false;
12925         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12926         Base = Ptr->getOperand(0);
12927         return true;
12928       }
12929     }
12930 
12931     if (Ptr->getOpcode() == ISD::ADD) {
12932       isInc = true;
12933       ARM_AM::ShiftOpc ShOpcVal=
12934         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12935       if (ShOpcVal != ARM_AM::no_shift) {
12936         Base = Ptr->getOperand(1);
12937         Offset = Ptr->getOperand(0);
12938       } else {
12939         Base = Ptr->getOperand(0);
12940         Offset = Ptr->getOperand(1);
12941       }
12942       return true;
12943     }
12944 
12945     isInc = (Ptr->getOpcode() == ISD::ADD);
12946     Base = Ptr->getOperand(0);
12947     Offset = Ptr->getOperand(1);
12948     return true;
12949   }
12950 
12951   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12952   return false;
12953 }
12954 
12955 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12956                                      bool isSEXTLoad, SDValue &Base,
12957                                      SDValue &Offset, bool &isInc,
12958                                      SelectionDAG &DAG) {
12959   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12960     return false;
12961 
12962   Base = Ptr->getOperand(0);
12963   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12964     int RHSC = (int)RHS->getZExtValue();
12965     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12966       assert(Ptr->getOpcode() == ISD::ADD);
12967       isInc = false;
12968       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12969       return true;
12970     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12971       isInc = Ptr->getOpcode() == ISD::ADD;
12972       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12973       return true;
12974     }
12975   }
12976 
12977   return false;
12978 }
12979 
12980 /// getPreIndexedAddressParts - returns true by value, base pointer and
12981 /// offset pointer and addressing mode by reference if the node's address
12982 /// can be legally represented as pre-indexed load / store address.
12983 bool
12984 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12985                                              SDValue &Offset,
12986                                              ISD::MemIndexedMode &AM,
12987                                              SelectionDAG &DAG) const {
12988   if (Subtarget->isThumb1Only())
12989     return false;
12990 
12991   EVT VT;
12992   SDValue Ptr;
12993   bool isSEXTLoad = false;
12994   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12995     Ptr = LD->getBasePtr();
12996     VT  = LD->getMemoryVT();
12997     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12998   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12999     Ptr = ST->getBasePtr();
13000     VT  = ST->getMemoryVT();
13001   } else
13002     return false;
13003 
13004   bool isInc;
13005   bool isLegal = false;
13006   if (Subtarget->isThumb2())
13007     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13008                                        Offset, isInc, DAG);
13009   else
13010     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13011                                         Offset, isInc, DAG);
13012   if (!isLegal)
13013     return false;
13014 
13015   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13016   return true;
13017 }
13018 
13019 /// getPostIndexedAddressParts - returns true by value, base pointer and
13020 /// offset pointer and addressing mode by reference if this node can be
13021 /// combined with a load / store to form a post-indexed load / store.
13022 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13023                                                    SDValue &Base,
13024                                                    SDValue &Offset,
13025                                                    ISD::MemIndexedMode &AM,
13026                                                    SelectionDAG &DAG) const {
13027   EVT VT;
13028   SDValue Ptr;
13029   bool isSEXTLoad = false, isNonExt;
13030   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13031     VT  = LD->getMemoryVT();
13032     Ptr = LD->getBasePtr();
13033     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13034     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13035   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13036     VT  = ST->getMemoryVT();
13037     Ptr = ST->getBasePtr();
13038     isNonExt = !ST->isTruncatingStore();
13039   } else
13040     return false;
13041 
13042   if (Subtarget->isThumb1Only()) {
13043     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13044     // must be non-extending/truncating, i32, with an offset of 4.
13045     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13046     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13047       return false;
13048     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13049     if (!RHS || RHS->getZExtValue() != 4)
13050       return false;
13051 
13052     Offset = Op->getOperand(1);
13053     Base = Op->getOperand(0);
13054     AM = ISD::POST_INC;
13055     return true;
13056   }
13057 
13058   bool isInc;
13059   bool isLegal = false;
13060   if (Subtarget->isThumb2())
13061     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13062                                        isInc, DAG);
13063   else
13064     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13065                                         isInc, DAG);
13066   if (!isLegal)
13067     return false;
13068 
13069   if (Ptr != Base) {
13070     // Swap base ptr and offset to catch more post-index load / store when
13071     // it's legal. In Thumb2 mode, offset must be an immediate.
13072     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13073         !Subtarget->isThumb2())
13074       std::swap(Base, Offset);
13075 
13076     // Post-indexed load / store update the base pointer.
13077     if (Ptr != Base)
13078       return false;
13079   }
13080 
13081   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13082   return true;
13083 }
13084 
13085 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13086                                                       KnownBits &Known,
13087                                                       const APInt &DemandedElts,
13088                                                       const SelectionDAG &DAG,
13089                                                       unsigned Depth) const {
13090   unsigned BitWidth = Known.getBitWidth();
13091   Known.resetAll();
13092   switch (Op.getOpcode()) {
13093   default: break;
13094   case ARMISD::ADDC:
13095   case ARMISD::ADDE:
13096   case ARMISD::SUBC:
13097   case ARMISD::SUBE:
13098     // Special cases when we convert a carry to a boolean.
13099     if (Op.getResNo() == 0) {
13100       SDValue LHS = Op.getOperand(0);
13101       SDValue RHS = Op.getOperand(1);
13102       // (ADDE 0, 0, C) will give us a single bit.
13103       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13104           isNullConstant(RHS)) {
13105         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13106         return;
13107       }
13108     }
13109     break;
13110   case ARMISD::CMOV: {
13111     // Bits are known zero/one if known on the LHS and RHS.
13112     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13113     if (Known.isUnknown())
13114       return;
13115 
13116     KnownBits KnownRHS;
13117     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13118     Known.Zero &= KnownRHS.Zero;
13119     Known.One  &= KnownRHS.One;
13120     return;
13121   }
13122   case ISD::INTRINSIC_W_CHAIN: {
13123     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13124     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13125     switch (IntID) {
13126     default: return;
13127     case Intrinsic::arm_ldaex:
13128     case Intrinsic::arm_ldrex: {
13129       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13130       unsigned MemBits = VT.getScalarSizeInBits();
13131       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13132       return;
13133     }
13134     }
13135   }
13136   case ARMISD::BFI: {
13137     // Conservatively, we can recurse down the first operand
13138     // and just mask out all affected bits.
13139     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13140 
13141     // The operand to BFI is already a mask suitable for removing the bits it
13142     // sets.
13143     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13144     const APInt &Mask = CI->getAPIntValue();
13145     Known.Zero &= Mask;
13146     Known.One &= Mask;
13147     return;
13148   }
13149   }
13150 }
13151 
13152 //===----------------------------------------------------------------------===//
13153 //                           ARM Inline Assembly Support
13154 //===----------------------------------------------------------------------===//
13155 
13156 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13157   // Looking for "rev" which is V6+.
13158   if (!Subtarget->hasV6Ops())
13159     return false;
13160 
13161   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13162   std::string AsmStr = IA->getAsmString();
13163   SmallVector<StringRef, 4> AsmPieces;
13164   SplitString(AsmStr, AsmPieces, ";\n");
13165 
13166   switch (AsmPieces.size()) {
13167   default: return false;
13168   case 1:
13169     AsmStr = AsmPieces[0];
13170     AsmPieces.clear();
13171     SplitString(AsmStr, AsmPieces, " \t,");
13172 
13173     // rev $0, $1
13174     if (AsmPieces.size() == 3 &&
13175         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13176         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13177       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13178       if (Ty && Ty->getBitWidth() == 32)
13179         return IntrinsicLowering::LowerToByteSwap(CI);
13180     }
13181     break;
13182   }
13183 
13184   return false;
13185 }
13186 
13187 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13188   // At this point, we have to lower this constraint to something else, so we
13189   // lower it to an "r" or "w". However, by doing this we will force the result
13190   // to be in register, while the X constraint is much more permissive.
13191   //
13192   // Although we are correct (we are free to emit anything, without
13193   // constraints), we might break use cases that would expect us to be more
13194   // efficient and emit something else.
13195   if (!Subtarget->hasVFP2())
13196     return "r";
13197   if (ConstraintVT.isFloatingPoint())
13198     return "w";
13199   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13200      (ConstraintVT.getSizeInBits() == 64 ||
13201       ConstraintVT.getSizeInBits() == 128))
13202     return "w";
13203 
13204   return "r";
13205 }
13206 
13207 /// getConstraintType - Given a constraint letter, return the type of
13208 /// constraint it is for this target.
13209 ARMTargetLowering::ConstraintType
13210 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13211   if (Constraint.size() == 1) {
13212     switch (Constraint[0]) {
13213     default:  break;
13214     case 'l': return C_RegisterClass;
13215     case 'w': return C_RegisterClass;
13216     case 'h': return C_RegisterClass;
13217     case 'x': return C_RegisterClass;
13218     case 't': return C_RegisterClass;
13219     case 'j': return C_Other; // Constant for movw.
13220       // An address with a single base register. Due to the way we
13221       // currently handle addresses it is the same as an 'r' memory constraint.
13222     case 'Q': return C_Memory;
13223     }
13224   } else if (Constraint.size() == 2) {
13225     switch (Constraint[0]) {
13226     default: break;
13227     // All 'U+' constraints are addresses.
13228     case 'U': return C_Memory;
13229     }
13230   }
13231   return TargetLowering::getConstraintType(Constraint);
13232 }
13233 
13234 /// Examine constraint type and operand type and determine a weight value.
13235 /// This object must already have been set up with the operand type
13236 /// and the current alternative constraint selected.
13237 TargetLowering::ConstraintWeight
13238 ARMTargetLowering::getSingleConstraintMatchWeight(
13239     AsmOperandInfo &info, const char *constraint) const {
13240   ConstraintWeight weight = CW_Invalid;
13241   Value *CallOperandVal = info.CallOperandVal;
13242     // If we don't have a value, we can't do a match,
13243     // but allow it at the lowest weight.
13244   if (!CallOperandVal)
13245     return CW_Default;
13246   Type *type = CallOperandVal->getType();
13247   // Look at the constraint type.
13248   switch (*constraint) {
13249   default:
13250     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13251     break;
13252   case 'l':
13253     if (type->isIntegerTy()) {
13254       if (Subtarget->isThumb())
13255         weight = CW_SpecificReg;
13256       else
13257         weight = CW_Register;
13258     }
13259     break;
13260   case 'w':
13261     if (type->isFloatingPointTy())
13262       weight = CW_Register;
13263     break;
13264   }
13265   return weight;
13266 }
13267 
13268 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13269 
13270 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13271     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13272   if (Constraint.size() == 1) {
13273     // GCC ARM Constraint Letters
13274     switch (Constraint[0]) {
13275     case 'l': // Low regs or general regs.
13276       if (Subtarget->isThumb())
13277         return RCPair(0U, &ARM::tGPRRegClass);
13278       return RCPair(0U, &ARM::GPRRegClass);
13279     case 'h': // High regs or no regs.
13280       if (Subtarget->isThumb())
13281         return RCPair(0U, &ARM::hGPRRegClass);
13282       break;
13283     case 'r':
13284       if (Subtarget->isThumb1Only())
13285         return RCPair(0U, &ARM::tGPRRegClass);
13286       return RCPair(0U, &ARM::GPRRegClass);
13287     case 'w':
13288       if (VT == MVT::Other)
13289         break;
13290       if (VT == MVT::f32)
13291         return RCPair(0U, &ARM::SPRRegClass);
13292       if (VT.getSizeInBits() == 64)
13293         return RCPair(0U, &ARM::DPRRegClass);
13294       if (VT.getSizeInBits() == 128)
13295         return RCPair(0U, &ARM::QPRRegClass);
13296       break;
13297     case 'x':
13298       if (VT == MVT::Other)
13299         break;
13300       if (VT == MVT::f32)
13301         return RCPair(0U, &ARM::SPR_8RegClass);
13302       if (VT.getSizeInBits() == 64)
13303         return RCPair(0U, &ARM::DPR_8RegClass);
13304       if (VT.getSizeInBits() == 128)
13305         return RCPair(0U, &ARM::QPR_8RegClass);
13306       break;
13307     case 't':
13308       if (VT == MVT::f32 || VT == MVT::i32)
13309         return RCPair(0U, &ARM::SPRRegClass);
13310       break;
13311     }
13312   }
13313   if (StringRef("{cc}").equals_lower(Constraint))
13314     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13315 
13316   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13317 }
13318 
13319 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13320 /// vector.  If it is invalid, don't add anything to Ops.
13321 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13322                                                      std::string &Constraint,
13323                                                      std::vector<SDValue>&Ops,
13324                                                      SelectionDAG &DAG) const {
13325   SDValue Result;
13326 
13327   // Currently only support length 1 constraints.
13328   if (Constraint.length() != 1) return;
13329 
13330   char ConstraintLetter = Constraint[0];
13331   switch (ConstraintLetter) {
13332   default: break;
13333   case 'j':
13334   case 'I': case 'J': case 'K': case 'L':
13335   case 'M': case 'N': case 'O':
13336     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13337     if (!C)
13338       return;
13339 
13340     int64_t CVal64 = C->getSExtValue();
13341     int CVal = (int) CVal64;
13342     // None of these constraints allow values larger than 32 bits.  Check
13343     // that the value fits in an int.
13344     if (CVal != CVal64)
13345       return;
13346 
13347     switch (ConstraintLetter) {
13348       case 'j':
13349         // Constant suitable for movw, must be between 0 and
13350         // 65535.
13351         if (Subtarget->hasV6T2Ops())
13352           if (CVal >= 0 && CVal <= 65535)
13353             break;
13354         return;
13355       case 'I':
13356         if (Subtarget->isThumb1Only()) {
13357           // This must be a constant between 0 and 255, for ADD
13358           // immediates.
13359           if (CVal >= 0 && CVal <= 255)
13360             break;
13361         } else if (Subtarget->isThumb2()) {
13362           // A constant that can be used as an immediate value in a
13363           // data-processing instruction.
13364           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13365             break;
13366         } else {
13367           // A constant that can be used as an immediate value in a
13368           // data-processing instruction.
13369           if (ARM_AM::getSOImmVal(CVal) != -1)
13370             break;
13371         }
13372         return;
13373 
13374       case 'J':
13375         if (Subtarget->isThumb1Only()) {
13376           // This must be a constant between -255 and -1, for negated ADD
13377           // immediates. This can be used in GCC with an "n" modifier that
13378           // prints the negated value, for use with SUB instructions. It is
13379           // not useful otherwise but is implemented for compatibility.
13380           if (CVal >= -255 && CVal <= -1)
13381             break;
13382         } else {
13383           // This must be a constant between -4095 and 4095. It is not clear
13384           // what this constraint is intended for. Implemented for
13385           // compatibility with GCC.
13386           if (CVal >= -4095 && CVal <= 4095)
13387             break;
13388         }
13389         return;
13390 
13391       case 'K':
13392         if (Subtarget->isThumb1Only()) {
13393           // A 32-bit value where only one byte has a nonzero value. Exclude
13394           // zero to match GCC. This constraint is used by GCC internally for
13395           // constants that can be loaded with a move/shift combination.
13396           // It is not useful otherwise but is implemented for compatibility.
13397           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13398             break;
13399         } else if (Subtarget->isThumb2()) {
13400           // A constant whose bitwise inverse can be used as an immediate
13401           // value in a data-processing instruction. This can be used in GCC
13402           // with a "B" modifier that prints the inverted value, for use with
13403           // BIC and MVN instructions. It is not useful otherwise but is
13404           // implemented for compatibility.
13405           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13406             break;
13407         } else {
13408           // A constant whose bitwise inverse can be used as an immediate
13409           // value in a data-processing instruction. This can be used in GCC
13410           // with a "B" modifier that prints the inverted value, for use with
13411           // BIC and MVN instructions. It is not useful otherwise but is
13412           // implemented for compatibility.
13413           if (ARM_AM::getSOImmVal(~CVal) != -1)
13414             break;
13415         }
13416         return;
13417 
13418       case 'L':
13419         if (Subtarget->isThumb1Only()) {
13420           // This must be a constant between -7 and 7,
13421           // for 3-operand ADD/SUB immediate instructions.
13422           if (CVal >= -7 && CVal < 7)
13423             break;
13424         } else if (Subtarget->isThumb2()) {
13425           // A constant whose negation can be used as an immediate value in a
13426           // data-processing instruction. This can be used in GCC with an "n"
13427           // modifier that prints the negated value, for use with SUB
13428           // instructions. It is not useful otherwise but is implemented for
13429           // compatibility.
13430           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13431             break;
13432         } else {
13433           // A constant whose negation can be used as an immediate value in a
13434           // data-processing instruction. This can be used in GCC with an "n"
13435           // modifier that prints the negated value, for use with SUB
13436           // instructions. It is not useful otherwise but is implemented for
13437           // compatibility.
13438           if (ARM_AM::getSOImmVal(-CVal) != -1)
13439             break;
13440         }
13441         return;
13442 
13443       case 'M':
13444         if (Subtarget->isThumb1Only()) {
13445           // This must be a multiple of 4 between 0 and 1020, for
13446           // ADD sp + immediate.
13447           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13448             break;
13449         } else {
13450           // A power of two or a constant between 0 and 32.  This is used in
13451           // GCC for the shift amount on shifted register operands, but it is
13452           // useful in general for any shift amounts.
13453           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13454             break;
13455         }
13456         return;
13457 
13458       case 'N':
13459         if (Subtarget->isThumb()) {  // FIXME thumb2
13460           // This must be a constant between 0 and 31, for shift amounts.
13461           if (CVal >= 0 && CVal <= 31)
13462             break;
13463         }
13464         return;
13465 
13466       case 'O':
13467         if (Subtarget->isThumb()) {  // FIXME thumb2
13468           // This must be a multiple of 4 between -508 and 508, for
13469           // ADD/SUB sp = sp + immediate.
13470           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13471             break;
13472         }
13473         return;
13474     }
13475     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13476     break;
13477   }
13478 
13479   if (Result.getNode()) {
13480     Ops.push_back(Result);
13481     return;
13482   }
13483   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13484 }
13485 
13486 static RTLIB::Libcall getDivRemLibcall(
13487     const SDNode *N, MVT::SimpleValueType SVT) {
13488   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13489           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13490          "Unhandled Opcode in getDivRemLibcall");
13491   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13492                   N->getOpcode() == ISD::SREM;
13493   RTLIB::Libcall LC;
13494   switch (SVT) {
13495   default: llvm_unreachable("Unexpected request for libcall!");
13496   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13497   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13498   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13499   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13500   }
13501   return LC;
13502 }
13503 
13504 static TargetLowering::ArgListTy getDivRemArgList(
13505     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13506   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13507           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13508          "Unhandled Opcode in getDivRemArgList");
13509   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13510                   N->getOpcode() == ISD::SREM;
13511   TargetLowering::ArgListTy Args;
13512   TargetLowering::ArgListEntry Entry;
13513   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13514     EVT ArgVT = N->getOperand(i).getValueType();
13515     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13516     Entry.Node = N->getOperand(i);
13517     Entry.Ty = ArgTy;
13518     Entry.IsSExt = isSigned;
13519     Entry.IsZExt = !isSigned;
13520     Args.push_back(Entry);
13521   }
13522   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13523     std::swap(Args[0], Args[1]);
13524   return Args;
13525 }
13526 
13527 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13528   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13529           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13530           Subtarget->isTargetWindows()) &&
13531          "Register-based DivRem lowering only");
13532   unsigned Opcode = Op->getOpcode();
13533   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13534          "Invalid opcode for Div/Rem lowering");
13535   bool isSigned = (Opcode == ISD::SDIVREM);
13536   EVT VT = Op->getValueType(0);
13537   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13538   SDLoc dl(Op);
13539 
13540   // If the target has hardware divide, use divide + multiply + subtract:
13541   //     div = a / b
13542   //     rem = a - b * div
13543   //     return {div, rem}
13544   // This should be lowered into UDIV/SDIV + MLS later on.
13545   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13546                                         : Subtarget->hasDivideInARMMode();
13547   if (hasDivide && Op->getValueType(0).isSimple() &&
13548       Op->getSimpleValueType(0) == MVT::i32) {
13549     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13550     const SDValue Dividend = Op->getOperand(0);
13551     const SDValue Divisor = Op->getOperand(1);
13552     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13553     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13554     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13555 
13556     SDValue Values[2] = {Div, Rem};
13557     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13558   }
13559 
13560   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13561                                        VT.getSimpleVT().SimpleTy);
13562   SDValue InChain = DAG.getEntryNode();
13563 
13564   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13565                                                     DAG.getContext(),
13566                                                     Subtarget);
13567 
13568   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13569                                          getPointerTy(DAG.getDataLayout()));
13570 
13571   Type *RetTy = StructType::get(Ty, Ty);
13572 
13573   if (Subtarget->isTargetWindows())
13574     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13575 
13576   TargetLowering::CallLoweringInfo CLI(DAG);
13577   CLI.setDebugLoc(dl).setChain(InChain)
13578     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13579     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13580 
13581   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13582   return CallInfo.first;
13583 }
13584 
13585 // Lowers REM using divmod helpers
13586 // see RTABI section 4.2/4.3
13587 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13588   // Build return types (div and rem)
13589   std::vector<Type*> RetTyParams;
13590   Type *RetTyElement;
13591 
13592   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13593   default: llvm_unreachable("Unexpected request for libcall!");
13594   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13595   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13596   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13597   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13598   }
13599 
13600   RetTyParams.push_back(RetTyElement);
13601   RetTyParams.push_back(RetTyElement);
13602   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13603   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13604 
13605   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13606                                                              SimpleTy);
13607   SDValue InChain = DAG.getEntryNode();
13608   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13609                                                     Subtarget);
13610   bool isSigned = N->getOpcode() == ISD::SREM;
13611   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13612                                          getPointerTy(DAG.getDataLayout()));
13613 
13614   if (Subtarget->isTargetWindows())
13615     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13616 
13617   // Lower call
13618   CallLoweringInfo CLI(DAG);
13619   CLI.setChain(InChain)
13620      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13621      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13622   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13623 
13624   // Return second (rem) result operand (first contains div)
13625   SDNode *ResNode = CallResult.first.getNode();
13626   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13627   return ResNode->getOperand(1);
13628 }
13629 
13630 SDValue
13631 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13632   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13633   SDLoc DL(Op);
13634 
13635   // Get the inputs.
13636   SDValue Chain = Op.getOperand(0);
13637   SDValue Size  = Op.getOperand(1);
13638 
13639   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13640                               DAG.getConstant(2, DL, MVT::i32));
13641 
13642   SDValue Flag;
13643   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13644   Flag = Chain.getValue(1);
13645 
13646   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13647   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13648 
13649   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13650   Chain = NewSP.getValue(1);
13651 
13652   SDValue Ops[2] = { NewSP, Chain };
13653   return DAG.getMergeValues(Ops, DL);
13654 }
13655 
13656 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13657   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13658          "Unexpected type for custom-lowering FP_EXTEND");
13659 
13660   RTLIB::Libcall LC;
13661   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13662 
13663   SDValue SrcVal = Op.getOperand(0);
13664   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13665                      SDLoc(Op)).first;
13666 }
13667 
13668 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13669   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13670          Subtarget->isFPOnlySP() &&
13671          "Unexpected type for custom-lowering FP_ROUND");
13672 
13673   RTLIB::Libcall LC;
13674   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13675 
13676   SDValue SrcVal = Op.getOperand(0);
13677   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13678                      SDLoc(Op)).first;
13679 }
13680 
13681 bool
13682 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13683   // The ARM target isn't yet aware of offsets.
13684   return false;
13685 }
13686 
13687 bool ARM::isBitFieldInvertedMask(unsigned v) {
13688   if (v == 0xffffffff)
13689     return false;
13690 
13691   // there can be 1's on either or both "outsides", all the "inside"
13692   // bits must be 0's
13693   return isShiftedMask_32(~v);
13694 }
13695 
13696 /// isFPImmLegal - Returns true if the target can instruction select the
13697 /// specified FP immediate natively. If false, the legalizer will
13698 /// materialize the FP immediate as a load from a constant pool.
13699 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13700   if (!Subtarget->hasVFP3())
13701     return false;
13702   if (VT == MVT::f32)
13703     return ARM_AM::getFP32Imm(Imm) != -1;
13704   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13705     return ARM_AM::getFP64Imm(Imm) != -1;
13706   return false;
13707 }
13708 
13709 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13710 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13711 /// specified in the intrinsic calls.
13712 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13713                                            const CallInst &I,
13714                                            MachineFunction &MF,
13715                                            unsigned Intrinsic) const {
13716   switch (Intrinsic) {
13717   case Intrinsic::arm_neon_vld1:
13718   case Intrinsic::arm_neon_vld2:
13719   case Intrinsic::arm_neon_vld3:
13720   case Intrinsic::arm_neon_vld4:
13721   case Intrinsic::arm_neon_vld2lane:
13722   case Intrinsic::arm_neon_vld3lane:
13723   case Intrinsic::arm_neon_vld4lane: {
13724     Info.opc = ISD::INTRINSIC_W_CHAIN;
13725     // Conservatively set memVT to the entire set of vectors loaded.
13726     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13727     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13728     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13729     Info.ptrVal = I.getArgOperand(0);
13730     Info.offset = 0;
13731     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13732     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13733     // volatile loads with NEON intrinsics not supported
13734     Info.flags = MachineMemOperand::MOLoad;
13735     return true;
13736   }
13737   case Intrinsic::arm_neon_vst1:
13738   case Intrinsic::arm_neon_vst2:
13739   case Intrinsic::arm_neon_vst3:
13740   case Intrinsic::arm_neon_vst4:
13741   case Intrinsic::arm_neon_vst2lane:
13742   case Intrinsic::arm_neon_vst3lane:
13743   case Intrinsic::arm_neon_vst4lane: {
13744     Info.opc = ISD::INTRINSIC_VOID;
13745     // Conservatively set memVT to the entire set of vectors stored.
13746     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13747     unsigned NumElts = 0;
13748     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13749       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13750       if (!ArgTy->isVectorTy())
13751         break;
13752       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13753     }
13754     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13755     Info.ptrVal = I.getArgOperand(0);
13756     Info.offset = 0;
13757     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13758     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13759     // volatile stores with NEON intrinsics not supported
13760     Info.flags = MachineMemOperand::MOStore;
13761     return true;
13762   }
13763   case Intrinsic::arm_ldaex:
13764   case Intrinsic::arm_ldrex: {
13765     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13766     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13767     Info.opc = ISD::INTRINSIC_W_CHAIN;
13768     Info.memVT = MVT::getVT(PtrTy->getElementType());
13769     Info.ptrVal = I.getArgOperand(0);
13770     Info.offset = 0;
13771     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13772     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13773     return true;
13774   }
13775   case Intrinsic::arm_stlex:
13776   case Intrinsic::arm_strex: {
13777     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13778     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13779     Info.opc = ISD::INTRINSIC_W_CHAIN;
13780     Info.memVT = MVT::getVT(PtrTy->getElementType());
13781     Info.ptrVal = I.getArgOperand(1);
13782     Info.offset = 0;
13783     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13784     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13785     return true;
13786   }
13787   case Intrinsic::arm_stlexd:
13788   case Intrinsic::arm_strexd:
13789     Info.opc = ISD::INTRINSIC_W_CHAIN;
13790     Info.memVT = MVT::i64;
13791     Info.ptrVal = I.getArgOperand(2);
13792     Info.offset = 0;
13793     Info.align = 8;
13794     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13795     return true;
13796 
13797   case Intrinsic::arm_ldaexd:
13798   case Intrinsic::arm_ldrexd:
13799     Info.opc = ISD::INTRINSIC_W_CHAIN;
13800     Info.memVT = MVT::i64;
13801     Info.ptrVal = I.getArgOperand(0);
13802     Info.offset = 0;
13803     Info.align = 8;
13804     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13805     return true;
13806 
13807   default:
13808     break;
13809   }
13810 
13811   return false;
13812 }
13813 
13814 /// \brief Returns true if it is beneficial to convert a load of a constant
13815 /// to just the constant itself.
13816 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13817                                                           Type *Ty) const {
13818   assert(Ty->isIntegerTy());
13819 
13820   unsigned Bits = Ty->getPrimitiveSizeInBits();
13821   if (Bits == 0 || Bits > 32)
13822     return false;
13823   return true;
13824 }
13825 
13826 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13827                                                 unsigned Index) const {
13828   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13829     return false;
13830 
13831   return (Index == 0 || Index == ResVT.getVectorNumElements());
13832 }
13833 
13834 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13835                                         ARM_MB::MemBOpt Domain) const {
13836   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13837 
13838   // First, if the target has no DMB, see what fallback we can use.
13839   if (!Subtarget->hasDataBarrier()) {
13840     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13841     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13842     // here.
13843     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13844       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13845       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13846                         Builder.getInt32(0), Builder.getInt32(7),
13847                         Builder.getInt32(10), Builder.getInt32(5)};
13848       return Builder.CreateCall(MCR, args);
13849     } else {
13850       // Instead of using barriers, atomic accesses on these subtargets use
13851       // libcalls.
13852       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13853     }
13854   } else {
13855     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13856     // Only a full system barrier exists in the M-class architectures.
13857     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13858     Constant *CDomain = Builder.getInt32(Domain);
13859     return Builder.CreateCall(DMB, CDomain);
13860   }
13861 }
13862 
13863 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13864 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13865                                                  Instruction *Inst,
13866                                                  AtomicOrdering Ord) const {
13867   switch (Ord) {
13868   case AtomicOrdering::NotAtomic:
13869   case AtomicOrdering::Unordered:
13870     llvm_unreachable("Invalid fence: unordered/non-atomic");
13871   case AtomicOrdering::Monotonic:
13872   case AtomicOrdering::Acquire:
13873     return nullptr; // Nothing to do
13874   case AtomicOrdering::SequentiallyConsistent:
13875     if (!Inst->hasAtomicStore())
13876       return nullptr; // Nothing to do
13877     LLVM_FALLTHROUGH;
13878   case AtomicOrdering::Release:
13879   case AtomicOrdering::AcquireRelease:
13880     if (Subtarget->preferISHSTBarriers())
13881       return makeDMB(Builder, ARM_MB::ISHST);
13882     // FIXME: add a comment with a link to documentation justifying this.
13883     else
13884       return makeDMB(Builder, ARM_MB::ISH);
13885   }
13886   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13887 }
13888 
13889 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13890                                                   Instruction *Inst,
13891                                                   AtomicOrdering Ord) const {
13892   switch (Ord) {
13893   case AtomicOrdering::NotAtomic:
13894   case AtomicOrdering::Unordered:
13895     llvm_unreachable("Invalid fence: unordered/not-atomic");
13896   case AtomicOrdering::Monotonic:
13897   case AtomicOrdering::Release:
13898     return nullptr; // Nothing to do
13899   case AtomicOrdering::Acquire:
13900   case AtomicOrdering::AcquireRelease:
13901   case AtomicOrdering::SequentiallyConsistent:
13902     return makeDMB(Builder, ARM_MB::ISH);
13903   }
13904   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13905 }
13906 
13907 // Loads and stores less than 64-bits are already atomic; ones above that
13908 // are doomed anyway, so defer to the default libcall and blame the OS when
13909 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13910 // anything for those.
13911 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13912   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13913   return (Size == 64) && !Subtarget->isMClass();
13914 }
13915 
13916 // Loads and stores less than 64-bits are already atomic; ones above that
13917 // are doomed anyway, so defer to the default libcall and blame the OS when
13918 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13919 // anything for those.
13920 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13921 // guarantee, see DDI0406C ARM architecture reference manual,
13922 // sections A8.8.72-74 LDRD)
13923 TargetLowering::AtomicExpansionKind
13924 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13925   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13926   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13927                                                   : AtomicExpansionKind::None;
13928 }
13929 
13930 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13931 // and up to 64 bits on the non-M profiles
13932 TargetLowering::AtomicExpansionKind
13933 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13934   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13935   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13936   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13937              ? AtomicExpansionKind::LLSC
13938              : AtomicExpansionKind::None;
13939 }
13940 
13941 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13942     AtomicCmpXchgInst *AI) const {
13943   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13944   // implement cmpxchg without spilling. If the address being exchanged is also
13945   // on the stack and close enough to the spill slot, this can lead to a
13946   // situation where the monitor always gets cleared and the atomic operation
13947   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13948   bool hasAtomicCmpXchg =
13949       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13950   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13951 }
13952 
13953 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13954     const Instruction *I) const {
13955   return InsertFencesForAtomic;
13956 }
13957 
13958 // This has so far only been implemented for MachO.
13959 bool ARMTargetLowering::useLoadStackGuardNode() const {
13960   return Subtarget->isTargetMachO();
13961 }
13962 
13963 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13964                                                   unsigned &Cost) const {
13965   // If we do not have NEON, vector types are not natively supported.
13966   if (!Subtarget->hasNEON())
13967     return false;
13968 
13969   // Floating point values and vector values map to the same register file.
13970   // Therefore, although we could do a store extract of a vector type, this is
13971   // better to leave at float as we have more freedom in the addressing mode for
13972   // those.
13973   if (VectorTy->isFPOrFPVectorTy())
13974     return false;
13975 
13976   // If the index is unknown at compile time, this is very expensive to lower
13977   // and it is not possible to combine the store with the extract.
13978   if (!isa<ConstantInt>(Idx))
13979     return false;
13980 
13981   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13982   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13983   // We can do a store + vector extract on any vector that fits perfectly in a D
13984   // or Q register.
13985   if (BitWidth == 64 || BitWidth == 128) {
13986     Cost = 0;
13987     return true;
13988   }
13989   return false;
13990 }
13991 
13992 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13993   return Subtarget->hasV6T2Ops();
13994 }
13995 
13996 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13997   return Subtarget->hasV6T2Ops();
13998 }
13999 
14000 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14001                                          AtomicOrdering Ord) const {
14002   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14003   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14004   bool IsAcquire = isAcquireOrStronger(Ord);
14005 
14006   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14007   // intrinsic must return {i32, i32} and we have to recombine them into a
14008   // single i64 here.
14009   if (ValTy->getPrimitiveSizeInBits() == 64) {
14010     Intrinsic::ID Int =
14011         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14012     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14013 
14014     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14015     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14016 
14017     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14018     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14019     if (!Subtarget->isLittle())
14020       std::swap (Lo, Hi);
14021     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14022     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14023     return Builder.CreateOr(
14024         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14025   }
14026 
14027   Type *Tys[] = { Addr->getType() };
14028   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14029   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14030 
14031   return Builder.CreateTruncOrBitCast(
14032       Builder.CreateCall(Ldrex, Addr),
14033       cast<PointerType>(Addr->getType())->getElementType());
14034 }
14035 
14036 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14037     IRBuilder<> &Builder) const {
14038   if (!Subtarget->hasV7Ops())
14039     return;
14040   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14041   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14042 }
14043 
14044 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14045                                                Value *Addr,
14046                                                AtomicOrdering Ord) const {
14047   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14048   bool IsRelease = isReleaseOrStronger(Ord);
14049 
14050   // Since the intrinsics must have legal type, the i64 intrinsics take two
14051   // parameters: "i32, i32". We must marshal Val into the appropriate form
14052   // before the call.
14053   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14054     Intrinsic::ID Int =
14055         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14056     Function *Strex = Intrinsic::getDeclaration(M, Int);
14057     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14058 
14059     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14060     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14061     if (!Subtarget->isLittle())
14062       std::swap(Lo, Hi);
14063     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14064     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14065   }
14066 
14067   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14068   Type *Tys[] = { Addr->getType() };
14069   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14070 
14071   return Builder.CreateCall(
14072       Strex, {Builder.CreateZExtOrBitCast(
14073                   Val, Strex->getFunctionType()->getParamType(0)),
14074               Addr});
14075 }
14076 
14077 /// A helper function for determining the number of interleaved accesses we
14078 /// will generate when lowering accesses of the given type.
14079 unsigned
14080 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14081                                              const DataLayout &DL) const {
14082   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14083 }
14084 
14085 bool ARMTargetLowering::isLegalInterleavedAccessType(
14086     VectorType *VecTy, const DataLayout &DL) const {
14087 
14088   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14089   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14090 
14091   // Ensure the vector doesn't have f16 elements. Even though we could do an
14092   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14093   // f32.
14094   if (VecTy->getElementType()->isHalfTy())
14095     return false;
14096 
14097   // Ensure the number of vector elements is greater than 1.
14098   if (VecTy->getNumElements() < 2)
14099     return false;
14100 
14101   // Ensure the element type is legal.
14102   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14103     return false;
14104 
14105   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14106   // 128 will be split into multiple interleaved accesses.
14107   return VecSize == 64 || VecSize % 128 == 0;
14108 }
14109 
14110 /// \brief Lower an interleaved load into a vldN intrinsic.
14111 ///
14112 /// E.g. Lower an interleaved load (Factor = 2):
14113 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14114 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14115 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14116 ///
14117 ///      Into:
14118 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14119 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14120 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14121 bool ARMTargetLowering::lowerInterleavedLoad(
14122     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14123     ArrayRef<unsigned> Indices, unsigned Factor) const {
14124   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14125          "Invalid interleave factor");
14126   assert(!Shuffles.empty() && "Empty shufflevector input");
14127   assert(Shuffles.size() == Indices.size() &&
14128          "Unmatched number of shufflevectors and indices");
14129 
14130   VectorType *VecTy = Shuffles[0]->getType();
14131   Type *EltTy = VecTy->getVectorElementType();
14132 
14133   const DataLayout &DL = LI->getModule()->getDataLayout();
14134 
14135   // Skip if we do not have NEON and skip illegal vector types. We can
14136   // "legalize" wide vector types into multiple interleaved accesses as long as
14137   // the vector types are divisible by 128.
14138   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14139     return false;
14140 
14141   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14142 
14143   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14144   // load integer vectors first and then convert to pointer vectors.
14145   if (EltTy->isPointerTy())
14146     VecTy =
14147         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14148 
14149   IRBuilder<> Builder(LI);
14150 
14151   // The base address of the load.
14152   Value *BaseAddr = LI->getPointerOperand();
14153 
14154   if (NumLoads > 1) {
14155     // If we're going to generate more than one load, reset the sub-vector type
14156     // to something legal.
14157     VecTy = VectorType::get(VecTy->getVectorElementType(),
14158                             VecTy->getVectorNumElements() / NumLoads);
14159 
14160     // We will compute the pointer operand of each load from the original base
14161     // address using GEPs. Cast the base address to a pointer to the scalar
14162     // element type.
14163     BaseAddr = Builder.CreateBitCast(
14164         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14165                       LI->getPointerAddressSpace()));
14166   }
14167 
14168   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14169 
14170   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14171   Type *Tys[] = {VecTy, Int8Ptr};
14172   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14173                                             Intrinsic::arm_neon_vld3,
14174                                             Intrinsic::arm_neon_vld4};
14175   Function *VldnFunc =
14176       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14177 
14178   // Holds sub-vectors extracted from the load intrinsic return values. The
14179   // sub-vectors are associated with the shufflevector instructions they will
14180   // replace.
14181   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14182 
14183   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14184     // If we're generating more than one load, compute the base address of
14185     // subsequent loads as an offset from the previous.
14186     if (LoadCount > 0)
14187       BaseAddr = Builder.CreateConstGEP1_32(
14188           BaseAddr, VecTy->getVectorNumElements() * Factor);
14189 
14190     SmallVector<Value *, 2> Ops;
14191     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14192     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14193 
14194     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14195 
14196     // Replace uses of each shufflevector with the corresponding vector loaded
14197     // by ldN.
14198     for (unsigned i = 0; i < Shuffles.size(); i++) {
14199       ShuffleVectorInst *SV = Shuffles[i];
14200       unsigned Index = Indices[i];
14201 
14202       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14203 
14204       // Convert the integer vector to pointer vector if the element is pointer.
14205       if (EltTy->isPointerTy())
14206         SubVec = Builder.CreateIntToPtr(
14207             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14208                                     VecTy->getVectorNumElements()));
14209 
14210       SubVecs[SV].push_back(SubVec);
14211     }
14212   }
14213 
14214   // Replace uses of the shufflevector instructions with the sub-vectors
14215   // returned by the load intrinsic. If a shufflevector instruction is
14216   // associated with more than one sub-vector, those sub-vectors will be
14217   // concatenated into a single wide vector.
14218   for (ShuffleVectorInst *SVI : Shuffles) {
14219     auto &SubVec = SubVecs[SVI];
14220     auto *WideVec =
14221         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14222     SVI->replaceAllUsesWith(WideVec);
14223   }
14224 
14225   return true;
14226 }
14227 
14228 /// \brief Lower an interleaved store into a vstN intrinsic.
14229 ///
14230 /// E.g. Lower an interleaved store (Factor = 3):
14231 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14232 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14233 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14234 ///
14235 ///      Into:
14236 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14237 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14238 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14239 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14240 ///
14241 /// Note that the new shufflevectors will be removed and we'll only generate one
14242 /// vst3 instruction in CodeGen.
14243 ///
14244 /// Example for a more general valid mask (Factor 3). Lower:
14245 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14246 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14247 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14248 ///
14249 ///      Into:
14250 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14251 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14252 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14253 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14254 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14255                                               ShuffleVectorInst *SVI,
14256                                               unsigned Factor) const {
14257   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14258          "Invalid interleave factor");
14259 
14260   VectorType *VecTy = SVI->getType();
14261   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14262          "Invalid interleaved store");
14263 
14264   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14265   Type *EltTy = VecTy->getVectorElementType();
14266   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14267 
14268   const DataLayout &DL = SI->getModule()->getDataLayout();
14269 
14270   // Skip if we do not have NEON and skip illegal vector types. We can
14271   // "legalize" wide vector types into multiple interleaved accesses as long as
14272   // the vector types are divisible by 128.
14273   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14274     return false;
14275 
14276   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14277 
14278   Value *Op0 = SVI->getOperand(0);
14279   Value *Op1 = SVI->getOperand(1);
14280   IRBuilder<> Builder(SI);
14281 
14282   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14283   // vectors to integer vectors.
14284   if (EltTy->isPointerTy()) {
14285     Type *IntTy = DL.getIntPtrType(EltTy);
14286 
14287     // Convert to the corresponding integer vector.
14288     Type *IntVecTy =
14289         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14290     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14291     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14292 
14293     SubVecTy = VectorType::get(IntTy, LaneLen);
14294   }
14295 
14296   // The base address of the store.
14297   Value *BaseAddr = SI->getPointerOperand();
14298 
14299   if (NumStores > 1) {
14300     // If we're going to generate more than one store, reset the lane length
14301     // and sub-vector type to something legal.
14302     LaneLen /= NumStores;
14303     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14304 
14305     // We will compute the pointer operand of each store from the original base
14306     // address using GEPs. Cast the base address to a pointer to the scalar
14307     // element type.
14308     BaseAddr = Builder.CreateBitCast(
14309         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14310                       SI->getPointerAddressSpace()));
14311   }
14312 
14313   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14314 
14315   auto Mask = SVI->getShuffleMask();
14316 
14317   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14318   Type *Tys[] = {Int8Ptr, SubVecTy};
14319   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14320                                              Intrinsic::arm_neon_vst3,
14321                                              Intrinsic::arm_neon_vst4};
14322 
14323   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14324     // If we generating more than one store, we compute the base address of
14325     // subsequent stores as an offset from the previous.
14326     if (StoreCount > 0)
14327       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14328 
14329     SmallVector<Value *, 6> Ops;
14330     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14331 
14332     Function *VstNFunc =
14333         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14334 
14335     // Split the shufflevector operands into sub vectors for the new vstN call.
14336     for (unsigned i = 0; i < Factor; i++) {
14337       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14338       if (Mask[IdxI] >= 0) {
14339         Ops.push_back(Builder.CreateShuffleVector(
14340             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14341       } else {
14342         unsigned StartMask = 0;
14343         for (unsigned j = 1; j < LaneLen; j++) {
14344           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14345           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14346             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14347             break;
14348           }
14349         }
14350         // Note: If all elements in a chunk are undefs, StartMask=0!
14351         // Note: Filling undef gaps with random elements is ok, since
14352         // those elements were being written anyway (with undefs).
14353         // In the case of all undefs we're defaulting to using elems from 0
14354         // Note: StartMask cannot be negative, it's checked in
14355         // isReInterleaveMask
14356         Ops.push_back(Builder.CreateShuffleVector(
14357             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14358       }
14359     }
14360 
14361     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14362     Builder.CreateCall(VstNFunc, Ops);
14363   }
14364   return true;
14365 }
14366 
14367 enum HABaseType {
14368   HA_UNKNOWN = 0,
14369   HA_FLOAT,
14370   HA_DOUBLE,
14371   HA_VECT64,
14372   HA_VECT128
14373 };
14374 
14375 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14376                                    uint64_t &Members) {
14377   if (auto *ST = dyn_cast<StructType>(Ty)) {
14378     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14379       uint64_t SubMembers = 0;
14380       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14381         return false;
14382       Members += SubMembers;
14383     }
14384   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14385     uint64_t SubMembers = 0;
14386     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14387       return false;
14388     Members += SubMembers * AT->getNumElements();
14389   } else if (Ty->isFloatTy()) {
14390     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14391       return false;
14392     Members = 1;
14393     Base = HA_FLOAT;
14394   } else if (Ty->isDoubleTy()) {
14395     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14396       return false;
14397     Members = 1;
14398     Base = HA_DOUBLE;
14399   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14400     Members = 1;
14401     switch (Base) {
14402     case HA_FLOAT:
14403     case HA_DOUBLE:
14404       return false;
14405     case HA_VECT64:
14406       return VT->getBitWidth() == 64;
14407     case HA_VECT128:
14408       return VT->getBitWidth() == 128;
14409     case HA_UNKNOWN:
14410       switch (VT->getBitWidth()) {
14411       case 64:
14412         Base = HA_VECT64;
14413         return true;
14414       case 128:
14415         Base = HA_VECT128;
14416         return true;
14417       default:
14418         return false;
14419       }
14420     }
14421   }
14422 
14423   return (Members > 0 && Members <= 4);
14424 }
14425 
14426 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14427 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14428 /// passing according to AAPCS rules.
14429 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14430     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14431   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14432       CallingConv::ARM_AAPCS_VFP)
14433     return false;
14434 
14435   HABaseType Base = HA_UNKNOWN;
14436   uint64_t Members = 0;
14437   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14438   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14439 
14440   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14441   return IsHA || IsIntArray;
14442 }
14443 
14444 unsigned ARMTargetLowering::getExceptionPointerRegister(
14445     const Constant *PersonalityFn) const {
14446   // Platforms which do not use SjLj EH may return values in these registers
14447   // via the personality function.
14448   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14449 }
14450 
14451 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14452     const Constant *PersonalityFn) const {
14453   // Platforms which do not use SjLj EH may return values in these registers
14454   // via the personality function.
14455   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14456 }
14457 
14458 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14459   // Update IsSplitCSR in ARMFunctionInfo.
14460   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14461   AFI->setIsSplitCSR(true);
14462 }
14463 
14464 void ARMTargetLowering::insertCopiesSplitCSR(
14465     MachineBasicBlock *Entry,
14466     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14467   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14468   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14469   if (!IStart)
14470     return;
14471 
14472   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14473   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14474   MachineBasicBlock::iterator MBBI = Entry->begin();
14475   for (const MCPhysReg *I = IStart; *I; ++I) {
14476     const TargetRegisterClass *RC = nullptr;
14477     if (ARM::GPRRegClass.contains(*I))
14478       RC = &ARM::GPRRegClass;
14479     else if (ARM::DPRRegClass.contains(*I))
14480       RC = &ARM::DPRRegClass;
14481     else
14482       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14483 
14484     unsigned NewVR = MRI->createVirtualRegister(RC);
14485     // Create copy from CSR to a virtual register.
14486     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14487     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14488     // nounwind. If we want to generalize this later, we may need to emit
14489     // CFI pseudo-instructions.
14490     assert(Entry->getParent()->getFunction().hasFnAttribute(
14491                Attribute::NoUnwind) &&
14492            "Function should be nounwind in insertCopiesSplitCSR!");
14493     Entry->addLiveIn(*I);
14494     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14495         .addReg(*I);
14496 
14497     // Insert the copy-back instructions right before the terminator.
14498     for (auto *Exit : Exits)
14499       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14500               TII->get(TargetOpcode::COPY), *I)
14501           .addReg(NewVR);
14502   }
14503 }
14504 
14505 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14506   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14507   TargetLoweringBase::finalizeLowering(MF);
14508 }
14509