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 "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "arm-isel"
58 
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62 
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67 
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72 
73 namespace {
74   class ARMCCState : public CCState {
75   public:
ARMCCState(CallingConv::ID CC,bool isVarArg,MachineFunction & MF,SmallVectorImpl<CCValAssign> & locs,LLVMContext & C,ParmContext PC)76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
78                ParmContext PC)
79         : CCState(CC, isVarArg, MF, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87 
88 // The APCS parameter registers.
89 static const MCPhysReg GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92 
addTypeForNEON(MVT VT,MVT PromotedLdStVT,MVT PromotedBitwiseVT)93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98 
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102 
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132 
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142 
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151 
addDRTypeForNEON(MVT VT)152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156 
addQRTypeForNEON(MVT VT)157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161 
ARMTargetLowering(const TargetMachine & TM,const ARMSubtarget & STI)162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167 
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169 
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
174       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179 
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185 
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195 
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204 
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214 
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223 
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231 
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235 
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247 
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, nullptr);
250   setLibcallName(RTLIB::SRL_I128, nullptr);
251   setLibcallName(RTLIB::SRA_I128, nullptr);
252 
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254       !Subtarget->isTargetWindows()) {
255     static const struct {
256       const RTLIB::Libcall Op;
257       const char * const Name;
258       const CallingConv::ID CC;
259       const ISD::CondCode Cond;
260     } LibraryCalls[] = {
261       // Double-precision floating-point arithmetic helper functions
262       // RTABI chapter 4.1.2, Table 2
263       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267 
268       // Double-precision floating-point comparison helper functions
269       // RTABI chapter 4.1.2, Table 3
270       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278 
279       // Single-precision floating-point arithmetic helper functions
280       // RTABI chapter 4.1.2, Table 4
281       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285 
286       // Single-precision floating-point comparison helper functions
287       // RTABI chapter 4.1.2, Table 5
288       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296 
297       // Floating-point to integer conversions.
298       // RTABI chapter 4.1.2, Table 6
299       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 
308       // Conversions between floating types.
309       // RTABI chapter 4.1.2, Table 7
310       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 
314       // Integer to floating-point conversions.
315       // RTABI chapter 4.1.2, Table 8
316       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 
325       // Long long helper functions
326       // RTABI chapter 4.2, Table 9
327       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 
332       // Integer division functions
333       // RTABI chapter 4.3.1
334       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 
343       // Memory operations
344       // RTABI chapter 4.3.4
345       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348     };
349 
350     for (const auto &LC : LibraryCalls) {
351       setLibcallName(LC.Op, LC.Name);
352       setLibcallCallingConv(LC.Op, LC.CC);
353       if (LC.Cond != ISD::SETCC_INVALID)
354         setCmpLibcallCC(LC.Op, LC.Cond);
355     }
356   }
357 
358   if (Subtarget->isTargetWindows()) {
359     static const struct {
360       const RTLIB::Libcall Op;
361       const char * const Name;
362       const CallingConv::ID CC;
363     } LibraryCalls[] = {
364       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372     };
373 
374     for (const auto &LC : LibraryCalls) {
375       setLibcallName(LC.Op, LC.Name);
376       setLibcallCallingConv(LC.Op, LC.CC);
377     }
378   }
379 
380   // Use divmod compiler-rt calls for iOS 5.0 and later.
381   if (Subtarget->getTargetTriple().isiOS() &&
382       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
385   }
386 
387   // The half <-> float conversion functions are always soft-float, but are
388   // needed for some targets which use a hard-float calling convention by
389   // default.
390   if (Subtarget->isAAPCS_ABI()) {
391     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394   } else {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
398   }
399 
400   if (Subtarget->isThumb1Only())
401     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402   else
403     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
405       !Subtarget->isThumb1Only()) {
406     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
408   }
409 
410   for (MVT VT : MVT::vector_valuetypes()) {
411     for (MVT InnerVT : MVT::vector_valuetypes()) {
412       setTruncStoreAction(VT, InnerVT, Expand);
413       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
416     }
417 
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422 
423     setOperationAction(ISD::BSWAP, VT, Expand);
424   }
425 
426   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428 
429   if (Subtarget->hasNEON()) {
430     addDRTypeForNEON(MVT::v2f32);
431     addDRTypeForNEON(MVT::v8i8);
432     addDRTypeForNEON(MVT::v4i16);
433     addDRTypeForNEON(MVT::v2i32);
434     addDRTypeForNEON(MVT::v1i64);
435 
436     addQRTypeForNEON(MVT::v4f32);
437     addQRTypeForNEON(MVT::v2f64);
438     addQRTypeForNEON(MVT::v16i8);
439     addQRTypeForNEON(MVT::v8i16);
440     addQRTypeForNEON(MVT::v4i32);
441     addQRTypeForNEON(MVT::v2i64);
442 
443     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
444     // neither Neon nor VFP support any arithmetic operations on it.
445     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
446     // supported for v4f32.
447     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
448     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
449     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
450     // FIXME: Code duplication: FDIV and FREM are expanded always, see
451     // ARMTargetLowering::addTypeForNEON method for details.
452     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
453     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
454     // FIXME: Create unittest.
455     // In another words, find a way when "copysign" appears in DAG with vector
456     // operands.
457     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
458     // FIXME: Code duplication: SETCC has custom operation action, see
459     // ARMTargetLowering::addTypeForNEON method for details.
460     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
461     // FIXME: Create unittest for FNEG and for FABS.
462     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
463     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
465     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
466     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
468     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
473     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
474     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
475     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
476     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
477     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
479     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
481 
482     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
483     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
484     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
486     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
491     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
492     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
493     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
494     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
497 
498     // Mark v2f32 intrinsics.
499     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
500     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
501     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
503     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
508     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
509     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
510     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
511     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
513     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
514 
515     // Neon does not support some operations on v1i64 and v2i64 types.
516     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
517     // Custom handling for some quad-vector types to detect VMULL.
518     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
519     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
521     // Custom handling for some vector types to avoid expensive expansions
522     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
527     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
528     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
529     // a destination type that is wider than the source, and nor does
530     // it have a FP_TO_[SU]INT instruction with a narrower destination than
531     // source.
532     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
535     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
536 
537     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
538     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
539 
540     // NEON does not have single instruction CTPOP for vectors with element
541     // types wider than 8-bits.  However, custom lowering can leverage the
542     // v8i8/v16i8 vcnt instruction.
543     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
547 
548     // NEON only has FMA instructions as of VFP4.
549     if (!Subtarget->hasVFP4()) {
550       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
551       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
552     }
553 
554     setTargetDAGCombine(ISD::INTRINSIC_VOID);
555     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
556     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
557     setTargetDAGCombine(ISD::SHL);
558     setTargetDAGCombine(ISD::SRL);
559     setTargetDAGCombine(ISD::SRA);
560     setTargetDAGCombine(ISD::SIGN_EXTEND);
561     setTargetDAGCombine(ISD::ZERO_EXTEND);
562     setTargetDAGCombine(ISD::ANY_EXTEND);
563     setTargetDAGCombine(ISD::SELECT_CC);
564     setTargetDAGCombine(ISD::BUILD_VECTOR);
565     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
566     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
567     setTargetDAGCombine(ISD::STORE);
568     setTargetDAGCombine(ISD::FP_TO_SINT);
569     setTargetDAGCombine(ISD::FP_TO_UINT);
570     setTargetDAGCombine(ISD::FDIV);
571     setTargetDAGCombine(ISD::LOAD);
572 
573     // It is legal to extload from v4i8 to v4i16 or v4i32.
574     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
575                    MVT::v2i32}) {
576       for (MVT VT : MVT::integer_vector_valuetypes()) {
577         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
578         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
579         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
580       }
581     }
582   }
583 
584   // ARM and Thumb2 support UMLAL/SMLAL.
585   if (!Subtarget->isThumb1Only())
586     setTargetDAGCombine(ISD::ADDC);
587 
588   if (Subtarget->isFPOnlySP()) {
589     // When targetting a floating-point unit with only single-precision
590     // operations, f64 is legal for the few double-precision instructions which
591     // are present However, no double-precision operations other than moves,
592     // loads and stores are provided by the hardware.
593     setOperationAction(ISD::FADD,       MVT::f64, Expand);
594     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
595     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
596     setOperationAction(ISD::FMA,        MVT::f64, Expand);
597     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
598     setOperationAction(ISD::FREM,       MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
600     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
601     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
602     setOperationAction(ISD::FABS,       MVT::f64, Expand);
603     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
604     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
606     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
607     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
609     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
610     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
611     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
612     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
613     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
614     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
615     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
616     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
617     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
618     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
619     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
621     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
622     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
623     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627 
628   computeRegisterProperties(Subtarget->getRegisterInfo());
629 
630   // ARM does not have floating-point extending loads.
631   for (MVT VT : MVT::fp_valuetypes()) {
632     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
633     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
634   }
635 
636   // ... or truncating stores
637   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
638   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
639   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
640 
641   // ARM does not have i1 sign extending load.
642   for (MVT VT : MVT::integer_valuetypes())
643     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
644 
645   // ARM supports all 4 flavors of integer indexed load / store.
646   if (!Subtarget->isThumb1Only()) {
647     for (unsigned im = (unsigned)ISD::PRE_INC;
648          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
649       setIndexedLoadAction(im,  MVT::i1,  Legal);
650       setIndexedLoadAction(im,  MVT::i8,  Legal);
651       setIndexedLoadAction(im,  MVT::i16, Legal);
652       setIndexedLoadAction(im,  MVT::i32, Legal);
653       setIndexedStoreAction(im, MVT::i1,  Legal);
654       setIndexedStoreAction(im, MVT::i8,  Legal);
655       setIndexedStoreAction(im, MVT::i16, Legal);
656       setIndexedStoreAction(im, MVT::i32, Legal);
657     }
658   }
659 
660   setOperationAction(ISD::SADDO, MVT::i32, Custom);
661   setOperationAction(ISD::UADDO, MVT::i32, Custom);
662   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
663   setOperationAction(ISD::USUBO, MVT::i32, Custom);
664 
665   // i64 operation support.
666   setOperationAction(ISD::MUL,     MVT::i64, Expand);
667   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
668   if (Subtarget->isThumb1Only()) {
669     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
670     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
671   }
672   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
673       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
674     setOperationAction(ISD::MULHS, MVT::i32, Expand);
675 
676   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
678   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
679   setOperationAction(ISD::SRL,       MVT::i64, Custom);
680   setOperationAction(ISD::SRA,       MVT::i64, Custom);
681 
682   if (!Subtarget->isThumb1Only()) {
683     // FIXME: We should do this for Thumb1 as well.
684     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
685     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
686     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
687     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
688   }
689 
690   // ARM does not have ROTL.
691   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
692   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
693   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
694   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
695     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
696 
697   // These just redirect to CTTZ and CTLZ on ARM.
698   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
699   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
700 
701   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
702 
703   // Only ARMv6 has BSWAP.
704   if (!Subtarget->hasV6Ops())
705     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
706 
707   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
708       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
709     // These are expanded into libcalls if the cpu doesn't have HW divider.
710     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
711     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
712   }
713 
714   // FIXME: Also set divmod for SREM on EABI
715   setOperationAction(ISD::SREM,  MVT::i32, Expand);
716   setOperationAction(ISD::UREM,  MVT::i32, Expand);
717   // Register based DivRem for AEABI (RTABI 4.2)
718   if (Subtarget->isTargetAEABI()) {
719     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
721     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
722     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
723     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
725     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
726     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
727 
728     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
736 
737     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
739   } else {
740     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
741     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
742   }
743 
744   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
745   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
746   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
747   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
748   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
749 
750   setOperationAction(ISD::TRAP, MVT::Other, Legal);
751 
752   // Use the default implementation.
753   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
754   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
755   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
756   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
757   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
758   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
759 
760   if (!Subtarget->isTargetMachO()) {
761     // Non-MachO platforms may return values in these registers via the
762     // personality function.
763     setExceptionPointerRegister(ARM::R0);
764     setExceptionSelectorRegister(ARM::R1);
765   }
766 
767   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
768     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
769   else
770     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
771 
772   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
773   // the default expansion. If we are targeting a single threaded system,
774   // then set them all for expand so we can lower them later into their
775   // non-atomic form.
776   if (TM.Options.ThreadModel == ThreadModel::Single)
777     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
778   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
779     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
780     // to ldrex/strex loops already.
781     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
782 
783     // On v8, we have particularly efficient implementations of atomic fences
784     // if they can be combined with nearby atomic loads and stores.
785     if (!Subtarget->hasV8Ops()) {
786       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
787       setInsertFencesForAtomic(true);
788     }
789   } else {
790     // If there's anything we can use as a barrier, go through custom lowering
791     // for ATOMIC_FENCE.
792     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
793                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
794 
795     // Set them all for expansion, which will force libcalls.
796     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
807     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
808     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
809     // Unordered/Monotonic case.
810     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
811     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
812   }
813 
814   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
815 
816   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
817   if (!Subtarget->hasV6Ops()) {
818     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
819     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
820   }
821   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
822 
823   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
824       !Subtarget->isThumb1Only()) {
825     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
826     // iff target supports vfp2.
827     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
828     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
829   }
830 
831   // We want to custom lower some of our intrinsics.
832   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
833   if (Subtarget->isTargetDarwin()) {
834     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
835     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
836     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
837   }
838 
839   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
840   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
841   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
842   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
843   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
844   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
846   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
847   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
848 
849   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
850   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
851   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
852   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
853   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
854 
855   // We don't support sin/cos/fmod/copysign/pow
856   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
857   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
858   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
859   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
860   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
861   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
862   setOperationAction(ISD::FREM,      MVT::f64, Expand);
863   setOperationAction(ISD::FREM,      MVT::f32, Expand);
864   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
865       !Subtarget->isThumb1Only()) {
866     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
867     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
868   }
869   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
870   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
871 
872   if (!Subtarget->hasVFP4()) {
873     setOperationAction(ISD::FMA, MVT::f64, Expand);
874     setOperationAction(ISD::FMA, MVT::f32, Expand);
875   }
876 
877   // Various VFP goodness
878   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884 
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891 
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903 
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929 
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932 
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934 
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940 
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948 
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952 
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955 
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958 
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass *, uint8_t>
findRepresentativeClass(const TargetRegisterInfo * TRI,MVT VT) const970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
971                                            MVT VT) const {
972   const TargetRegisterClass *RRC = nullptr;
973   uint8_t Cost = 1;
974   switch (VT.SimpleTy) {
975   default:
976     return TargetLowering::findRepresentativeClass(TRI, VT);
977   // Use DPR as representative register class for all floating point
978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979   // the cost is 1 for both f32 and f64.
980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982     RRC = &ARM::DPRRegClass;
983     // When NEON is used for SP, only half of the register file is available
984     // because operations that define both SP and DP results will be constrained
985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
986     // coalescing by double-counting the SP regs. See the FIXME above.
987     if (Subtarget->useNEONForSinglePrecisionFP())
988       Cost = 2;
989     break;
990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991   case MVT::v4f32: case MVT::v2f64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 2;
994     break;
995   case MVT::v4i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 4;
998     break;
999   case MVT::v8i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 8;
1002     break;
1003   }
1004   return std::make_pair(RRC, Cost);
1005 }
1006 
getTargetNodeName(unsigned Opcode) const1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008   switch (Opcode) {
1009   default: return nullptr;
1010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1013   case ARMISD::CALL:          return "ARMISD::CALL";
1014   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1015   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1016   case ARMISD::tCALL:         return "ARMISD::tCALL";
1017   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1018   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1019   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1020   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1021   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1022   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1023   case ARMISD::CMP:           return "ARMISD::CMP";
1024   case ARMISD::CMN:           return "ARMISD::CMN";
1025   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1026   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1027   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1028   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1029   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1030 
1031   case ARMISD::CMOV:          return "ARMISD::CMOV";
1032 
1033   case ARMISD::RBIT:          return "ARMISD::RBIT";
1034 
1035   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1036   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1037   case ARMISD::RRX:           return "ARMISD::RRX";
1038 
1039   case ARMISD::ADDC:          return "ARMISD::ADDC";
1040   case ARMISD::ADDE:          return "ARMISD::ADDE";
1041   case ARMISD::SUBC:          return "ARMISD::SUBC";
1042   case ARMISD::SUBE:          return "ARMISD::SUBE";
1043 
1044   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1045   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1046 
1047   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1048   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1049 
1050   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1051 
1052   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1053 
1054   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1055 
1056   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1057 
1058   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1059 
1060   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1061 
1062   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1063   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1064   case ARMISD::VCGE:          return "ARMISD::VCGE";
1065   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1066   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1067   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1068   case ARMISD::VCGT:          return "ARMISD::VCGT";
1069   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1070   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1071   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1072   case ARMISD::VTST:          return "ARMISD::VTST";
1073 
1074   case ARMISD::VSHL:          return "ARMISD::VSHL";
1075   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1076   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1077   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1078   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1079   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1080   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1081   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1082   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1083   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1084   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1085   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1086   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1087   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1088   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1089   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1090   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1091   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1092   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1093   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1094   case ARMISD::VDUP:          return "ARMISD::VDUP";
1095   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1096   case ARMISD::VEXT:          return "ARMISD::VEXT";
1097   case ARMISD::VREV64:        return "ARMISD::VREV64";
1098   case ARMISD::VREV32:        return "ARMISD::VREV32";
1099   case ARMISD::VREV16:        return "ARMISD::VREV16";
1100   case ARMISD::VZIP:          return "ARMISD::VZIP";
1101   case ARMISD::VUZP:          return "ARMISD::VUZP";
1102   case ARMISD::VTRN:          return "ARMISD::VTRN";
1103   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1104   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1105   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1106   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1107   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1108   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1109   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1110   case ARMISD::FMAX:          return "ARMISD::FMAX";
1111   case ARMISD::FMIN:          return "ARMISD::FMIN";
1112   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1113   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1114   case ARMISD::BFI:           return "ARMISD::BFI";
1115   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1116   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1117   case ARMISD::VBSL:          return "ARMISD::VBSL";
1118   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1119   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1120   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1121   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1122   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1123   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1124   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1125   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1126   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1127   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1128   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1129   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1130   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1131   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1132   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1133   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1134   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1135   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1136   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1137   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1138   }
1139 }
1140 
getSetCCResultType(LLVMContext &,EVT VT) const1141 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1142   if (!VT.isVector()) return getPointerTy();
1143   return VT.changeVectorElementTypeToInteger();
1144 }
1145 
1146 /// getRegClassFor - Return the register class that should be used for the
1147 /// specified value type.
getRegClassFor(MVT VT) const1148 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1149   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1150   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1151   // load / store 4 to 8 consecutive D registers.
1152   if (Subtarget->hasNEON()) {
1153     if (VT == MVT::v4i64)
1154       return &ARM::QQPRRegClass;
1155     if (VT == MVT::v8i64)
1156       return &ARM::QQQQPRRegClass;
1157   }
1158   return TargetLowering::getRegClassFor(VT);
1159 }
1160 
1161 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1162 // source/dest is aligned and the copy size is large enough. We therefore want
1163 // to align such objects passed to memory intrinsics.
shouldAlignPointerArgs(CallInst * CI,unsigned & MinSize,unsigned & PrefAlign) const1164 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1165                                                unsigned &PrefAlign) const {
1166   if (!isa<MemIntrinsic>(CI))
1167     return false;
1168   MinSize = 8;
1169   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1170   // cycle faster than 4-byte aligned LDM.
1171   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1172   return true;
1173 }
1174 
1175 // Create a fast isel object.
1176 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const1177 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1178                                   const TargetLibraryInfo *libInfo) const {
1179   return ARM::createFastISel(funcInfo, libInfo);
1180 }
1181 
getSchedulingPreference(SDNode * N) const1182 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1183   unsigned NumVals = N->getNumValues();
1184   if (!NumVals)
1185     return Sched::RegPressure;
1186 
1187   for (unsigned i = 0; i != NumVals; ++i) {
1188     EVT VT = N->getValueType(i);
1189     if (VT == MVT::Glue || VT == MVT::Other)
1190       continue;
1191     if (VT.isFloatingPoint() || VT.isVector())
1192       return Sched::ILP;
1193   }
1194 
1195   if (!N->isMachineOpcode())
1196     return Sched::RegPressure;
1197 
1198   // Load are scheduled for latency even if there instruction itinerary
1199   // is not available.
1200   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1201   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1202 
1203   if (MCID.getNumDefs() == 0)
1204     return Sched::RegPressure;
1205   if (!Itins->isEmpty() &&
1206       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1207     return Sched::ILP;
1208 
1209   return Sched::RegPressure;
1210 }
1211 
1212 //===----------------------------------------------------------------------===//
1213 // Lowering Code
1214 //===----------------------------------------------------------------------===//
1215 
1216 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
IntCCToARMCC(ISD::CondCode CC)1217 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1218   switch (CC) {
1219   default: llvm_unreachable("Unknown condition code!");
1220   case ISD::SETNE:  return ARMCC::NE;
1221   case ISD::SETEQ:  return ARMCC::EQ;
1222   case ISD::SETGT:  return ARMCC::GT;
1223   case ISD::SETGE:  return ARMCC::GE;
1224   case ISD::SETLT:  return ARMCC::LT;
1225   case ISD::SETLE:  return ARMCC::LE;
1226   case ISD::SETUGT: return ARMCC::HI;
1227   case ISD::SETUGE: return ARMCC::HS;
1228   case ISD::SETULT: return ARMCC::LO;
1229   case ISD::SETULE: return ARMCC::LS;
1230   }
1231 }
1232 
1233 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
FPCCToARMCC(ISD::CondCode CC,ARMCC::CondCodes & CondCode,ARMCC::CondCodes & CondCode2)1234 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1235                         ARMCC::CondCodes &CondCode2) {
1236   CondCode2 = ARMCC::AL;
1237   switch (CC) {
1238   default: llvm_unreachable("Unknown FP condition!");
1239   case ISD::SETEQ:
1240   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1241   case ISD::SETGT:
1242   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1243   case ISD::SETGE:
1244   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1245   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1246   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1247   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1248   case ISD::SETO:   CondCode = ARMCC::VC; break;
1249   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1250   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1251   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1252   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1253   case ISD::SETLT:
1254   case ISD::SETULT: CondCode = ARMCC::LT; break;
1255   case ISD::SETLE:
1256   case ISD::SETULE: CondCode = ARMCC::LE; break;
1257   case ISD::SETNE:
1258   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259   }
1260 }
1261 
1262 //===----------------------------------------------------------------------===//
1263 //                      Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1265 
1266 #include "ARMGenCallingConv.inc"
1267 
1268 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1269 /// account presence of floating point hardware and calling convention
1270 /// limitations, such as support for variadic functions.
1271 CallingConv::ID
getEffectiveCallingConv(CallingConv::ID CC,bool isVarArg) const1272 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1273                                            bool isVarArg) const {
1274   switch (CC) {
1275   default:
1276     llvm_unreachable("Unsupported calling convention");
1277   case CallingConv::ARM_AAPCS:
1278   case CallingConv::ARM_APCS:
1279   case CallingConv::GHC:
1280     return CC;
1281   case CallingConv::ARM_AAPCS_VFP:
1282     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1283   case CallingConv::C:
1284     if (!Subtarget->isAAPCS_ABI())
1285       return CallingConv::ARM_APCS;
1286     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1287              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1288              !isVarArg)
1289       return CallingConv::ARM_AAPCS_VFP;
1290     else
1291       return CallingConv::ARM_AAPCS;
1292   case CallingConv::Fast:
1293     if (!Subtarget->isAAPCS_ABI()) {
1294       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295         return CallingConv::Fast;
1296       return CallingConv::ARM_APCS;
1297     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1298       return CallingConv::ARM_AAPCS_VFP;
1299     else
1300       return CallingConv::ARM_AAPCS;
1301   }
1302 }
1303 
1304 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1305 /// CallingConvention.
CCAssignFnForNode(CallingConv::ID CC,bool Return,bool isVarArg) const1306 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1307                                                  bool Return,
1308                                                  bool isVarArg) const {
1309   switch (getEffectiveCallingConv(CC, isVarArg)) {
1310   default:
1311     llvm_unreachable("Unsupported calling convention");
1312   case CallingConv::ARM_APCS:
1313     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1314   case CallingConv::ARM_AAPCS:
1315     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1316   case CallingConv::ARM_AAPCS_VFP:
1317     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1318   case CallingConv::Fast:
1319     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1320   case CallingConv::GHC:
1321     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1322   }
1323 }
1324 
1325 /// LowerCallResult - Lower the result values of a call into the
1326 /// appropriate copies out of appropriate physical registers.
1327 SDValue
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,SDLoc dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool isThisReturn,SDValue ThisVal) const1328 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1329                                    CallingConv::ID CallConv, bool isVarArg,
1330                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1331                                    SDLoc dl, SelectionDAG &DAG,
1332                                    SmallVectorImpl<SDValue> &InVals,
1333                                    bool isThisReturn, SDValue ThisVal) const {
1334 
1335   // Assign locations to each value returned by this call.
1336   SmallVector<CCValAssign, 16> RVLocs;
1337   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1338                     *DAG.getContext(), Call);
1339   CCInfo.AnalyzeCallResult(Ins,
1340                            CCAssignFnForNode(CallConv, /* Return*/ true,
1341                                              isVarArg));
1342 
1343   // Copy all of the result registers out of their specified physreg.
1344   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1345     CCValAssign VA = RVLocs[i];
1346 
1347     // Pass 'this' value directly from the argument to return value, to avoid
1348     // reg unit interference
1349     if (i == 0 && isThisReturn) {
1350       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1351              "unexpected return calling convention register assignment");
1352       InVals.push_back(ThisVal);
1353       continue;
1354     }
1355 
1356     SDValue Val;
1357     if (VA.needsCustom()) {
1358       // Handle f64 or half of a v2f64.
1359       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1360                                       InFlag);
1361       Chain = Lo.getValue(1);
1362       InFlag = Lo.getValue(2);
1363       VA = RVLocs[++i]; // skip ahead to next loc
1364       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1365                                       InFlag);
1366       Chain = Hi.getValue(1);
1367       InFlag = Hi.getValue(2);
1368       if (!Subtarget->isLittle())
1369         std::swap (Lo, Hi);
1370       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1371 
1372       if (VA.getLocVT() == MVT::v2f64) {
1373         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1374         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1375                           DAG.getConstant(0, MVT::i32));
1376 
1377         VA = RVLocs[++i]; // skip ahead to next loc
1378         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379         Chain = Lo.getValue(1);
1380         InFlag = Lo.getValue(2);
1381         VA = RVLocs[++i]; // skip ahead to next loc
1382         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1383         Chain = Hi.getValue(1);
1384         InFlag = Hi.getValue(2);
1385         if (!Subtarget->isLittle())
1386           std::swap (Lo, Hi);
1387         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1388         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1389                           DAG.getConstant(1, MVT::i32));
1390       }
1391     } else {
1392       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1393                                InFlag);
1394       Chain = Val.getValue(1);
1395       InFlag = Val.getValue(2);
1396     }
1397 
1398     switch (VA.getLocInfo()) {
1399     default: llvm_unreachable("Unknown loc info!");
1400     case CCValAssign::Full: break;
1401     case CCValAssign::BCvt:
1402       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1403       break;
1404     }
1405 
1406     InVals.push_back(Val);
1407   }
1408 
1409   return Chain;
1410 }
1411 
1412 /// LowerMemOpCallTo - Store the argument to the stack.
1413 SDValue
LowerMemOpCallTo(SDValue Chain,SDValue StackPtr,SDValue Arg,SDLoc dl,SelectionDAG & DAG,const CCValAssign & VA,ISD::ArgFlagsTy Flags) const1414 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1415                                     SDValue StackPtr, SDValue Arg,
1416                                     SDLoc dl, SelectionDAG &DAG,
1417                                     const CCValAssign &VA,
1418                                     ISD::ArgFlagsTy Flags) const {
1419   unsigned LocMemOffset = VA.getLocMemOffset();
1420   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1421   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1422   return DAG.getStore(Chain, dl, Arg, PtrOff,
1423                       MachinePointerInfo::getStack(LocMemOffset),
1424                       false, false, 0);
1425 }
1426 
PassF64ArgInRegs(SDLoc dl,SelectionDAG & DAG,SDValue Chain,SDValue & Arg,RegsToPassVector & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,SDValue & StackPtr,SmallVectorImpl<SDValue> & MemOpChains,ISD::ArgFlagsTy Flags) const1427 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1428                                          SDValue Chain, SDValue &Arg,
1429                                          RegsToPassVector &RegsToPass,
1430                                          CCValAssign &VA, CCValAssign &NextVA,
1431                                          SDValue &StackPtr,
1432                                          SmallVectorImpl<SDValue> &MemOpChains,
1433                                          ISD::ArgFlagsTy Flags) const {
1434 
1435   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1436                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1437   unsigned id = Subtarget->isLittle() ? 0 : 1;
1438   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1439 
1440   if (NextVA.isRegLoc())
1441     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1442   else {
1443     assert(NextVA.isMemLoc());
1444     if (!StackPtr.getNode())
1445       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1446 
1447     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1448                                            dl, DAG, NextVA,
1449                                            Flags));
1450   }
1451 }
1452 
1453 /// LowerCall - Lowering a call into a callseq_start <-
1454 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1455 /// nodes.
1456 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const1457 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1458                              SmallVectorImpl<SDValue> &InVals) const {
1459   SelectionDAG &DAG                     = CLI.DAG;
1460   SDLoc &dl                          = CLI.DL;
1461   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1462   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1463   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1464   SDValue Chain                         = CLI.Chain;
1465   SDValue Callee                        = CLI.Callee;
1466   bool &isTailCall                      = CLI.IsTailCall;
1467   CallingConv::ID CallConv              = CLI.CallConv;
1468   bool doesNotRet                       = CLI.DoesNotReturn;
1469   bool isVarArg                         = CLI.IsVarArg;
1470 
1471   MachineFunction &MF = DAG.getMachineFunction();
1472   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1473   bool isThisReturn   = false;
1474   bool isSibCall      = false;
1475 
1476   // Disable tail calls if they're not supported.
1477   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1478     isTailCall = false;
1479 
1480   if (isTailCall) {
1481     // Check if it's really possible to do a tail call.
1482     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1483                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1484                                                    Outs, OutVals, Ins, DAG);
1485     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1486       report_fatal_error("failed to perform tail call elimination on a call "
1487                          "site marked musttail");
1488     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1489     // detected sibcalls.
1490     if (isTailCall) {
1491       ++NumTailCalls;
1492       isSibCall = true;
1493     }
1494   }
1495 
1496   // Analyze operands of the call, assigning locations to each operand.
1497   SmallVector<CCValAssign, 16> ArgLocs;
1498   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1499                     *DAG.getContext(), Call);
1500   CCInfo.AnalyzeCallOperands(Outs,
1501                              CCAssignFnForNode(CallConv, /* Return*/ false,
1502                                                isVarArg));
1503 
1504   // Get a count of how many bytes are to be pushed on the stack.
1505   unsigned NumBytes = CCInfo.getNextStackOffset();
1506 
1507   // For tail calls, memory operands are available in our caller's stack.
1508   if (isSibCall)
1509     NumBytes = 0;
1510 
1511   // Adjust the stack pointer for the new arguments...
1512   // These operations are automatically eliminated by the prolog/epilog pass
1513   if (!isSibCall)
1514     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1515                                  dl);
1516 
1517   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1518 
1519   RegsToPassVector RegsToPass;
1520   SmallVector<SDValue, 8> MemOpChains;
1521 
1522   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1523   // of tail call optimization, arguments are handled later.
1524   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1525        i != e;
1526        ++i, ++realArgIdx) {
1527     CCValAssign &VA = ArgLocs[i];
1528     SDValue Arg = OutVals[realArgIdx];
1529     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1530     bool isByVal = Flags.isByVal();
1531 
1532     // Promote the value if needed.
1533     switch (VA.getLocInfo()) {
1534     default: llvm_unreachable("Unknown loc info!");
1535     case CCValAssign::Full: break;
1536     case CCValAssign::SExt:
1537       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::ZExt:
1540       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::AExt:
1543       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1544       break;
1545     case CCValAssign::BCvt:
1546       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1547       break;
1548     }
1549 
1550     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1551     if (VA.needsCustom()) {
1552       if (VA.getLocVT() == MVT::v2f64) {
1553         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1554                                   DAG.getConstant(0, MVT::i32));
1555         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1556                                   DAG.getConstant(1, MVT::i32));
1557 
1558         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1559                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1560 
1561         VA = ArgLocs[++i]; // skip ahead to next loc
1562         if (VA.isRegLoc()) {
1563           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1564                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1565         } else {
1566           assert(VA.isMemLoc());
1567 
1568           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1569                                                  dl, DAG, VA, Flags));
1570         }
1571       } else {
1572         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1573                          StackPtr, MemOpChains, Flags);
1574       }
1575     } else if (VA.isRegLoc()) {
1576       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1577         assert(VA.getLocVT() == MVT::i32 &&
1578                "unexpected calling convention register assignment");
1579         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1580                "unexpected use of 'returned'");
1581         isThisReturn = true;
1582       }
1583       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1584     } else if (isByVal) {
1585       assert(VA.isMemLoc());
1586       unsigned offset = 0;
1587 
1588       // True if this byval aggregate will be split between registers
1589       // and memory.
1590       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1591       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1592 
1593       if (CurByValIdx < ByValArgsCount) {
1594 
1595         unsigned RegBegin, RegEnd;
1596         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1597 
1598         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1599         unsigned int i, j;
1600         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1601           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1602           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1603           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1604                                      MachinePointerInfo(),
1605                                      false, false, false,
1606                                      DAG.InferPtrAlignment(AddArg));
1607           MemOpChains.push_back(Load.getValue(1));
1608           RegsToPass.push_back(std::make_pair(j, Load));
1609         }
1610 
1611         // If parameter size outsides register area, "offset" value
1612         // helps us to calculate stack slot for remained part properly.
1613         offset = RegEnd - RegBegin;
1614 
1615         CCInfo.nextInRegsParam();
1616       }
1617 
1618       if (Flags.getByValSize() > 4*offset) {
1619         unsigned LocMemOffset = VA.getLocMemOffset();
1620         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1621         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1622                                   StkPtrOff);
1623         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1624         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1625         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1626                                            MVT::i32);
1627         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1628 
1629         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1630         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1631         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1632                                           Ops));
1633       }
1634     } else if (!isSibCall) {
1635       assert(VA.isMemLoc());
1636 
1637       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1638                                              dl, DAG, VA, Flags));
1639     }
1640   }
1641 
1642   if (!MemOpChains.empty())
1643     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1644 
1645   // Build a sequence of copy-to-reg nodes chained together with token chain
1646   // and flag operands which copy the outgoing args into the appropriate regs.
1647   SDValue InFlag;
1648   // Tail call byval lowering might overwrite argument registers so in case of
1649   // tail call optimization the copies to registers are lowered later.
1650   if (!isTailCall)
1651     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1652       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1653                                RegsToPass[i].second, InFlag);
1654       InFlag = Chain.getValue(1);
1655     }
1656 
1657   // For tail calls lower the arguments to the 'real' stack slot.
1658   if (isTailCall) {
1659     // Force all the incoming stack arguments to be loaded from the stack
1660     // before any new outgoing arguments are stored to the stack, because the
1661     // outgoing stack slots may alias the incoming argument stack slots, and
1662     // the alias isn't otherwise explicit. This is slightly more conservative
1663     // than necessary, because it means that each store effectively depends
1664     // on every argument instead of just those arguments it would clobber.
1665 
1666     // Do not flag preceding copytoreg stuff together with the following stuff.
1667     InFlag = SDValue();
1668     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1669       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1670                                RegsToPass[i].second, InFlag);
1671       InFlag = Chain.getValue(1);
1672     }
1673     InFlag = SDValue();
1674   }
1675 
1676   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1677   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1678   // node so that legalize doesn't hack it.
1679   bool isDirect = false;
1680   bool isARMFunc = false;
1681   bool isLocalARMFunc = false;
1682   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1683 
1684   if (EnableARMLongCalls) {
1685     assert((Subtarget->isTargetWindows() ||
1686             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1687            "long-calls with non-static relocation model!");
1688     // Handle a global address or an external symbol. If it's not one of
1689     // those, the target's already in a register, so we don't need to do
1690     // anything extra.
1691     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1692       const GlobalValue *GV = G->getGlobal();
1693       // Create a constant pool entry for the callee address
1694       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1695       ARMConstantPoolValue *CPV =
1696         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1697 
1698       // Get the address of the callee into a register
1699       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1700       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1701       Callee = DAG.getLoad(getPointerTy(), dl,
1702                            DAG.getEntryNode(), CPAddr,
1703                            MachinePointerInfo::getConstantPool(),
1704                            false, false, false, 0);
1705     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1706       const char *Sym = S->getSymbol();
1707 
1708       // Create a constant pool entry for the callee address
1709       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1710       ARMConstantPoolValue *CPV =
1711         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1712                                       ARMPCLabelIndex, 0);
1713       // Get the address of the callee into a register
1714       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1715       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1716       Callee = DAG.getLoad(getPointerTy(), dl,
1717                            DAG.getEntryNode(), CPAddr,
1718                            MachinePointerInfo::getConstantPool(),
1719                            false, false, false, 0);
1720     }
1721   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1722     const GlobalValue *GV = G->getGlobal();
1723     isDirect = true;
1724     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1725     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1726                    getTargetMachine().getRelocationModel() != Reloc::Static;
1727     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1728     // ARM call to a local ARM function is predicable.
1729     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1730     // tBX takes a register source operand.
1731     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1732       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1733       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1734                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1735                                                       0, ARMII::MO_NONLAZY));
1736       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1737                            MachinePointerInfo::getGOT(), false, false, true, 0);
1738     } else if (Subtarget->isTargetCOFF()) {
1739       assert(Subtarget->isTargetWindows() &&
1740              "Windows is the only supported COFF target");
1741       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1742                                  ? ARMII::MO_DLLIMPORT
1743                                  : ARMII::MO_NO_FLAG;
1744       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1745                                           TargetFlags);
1746       if (GV->hasDLLImportStorageClass())
1747         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1748                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1749                                          Callee), MachinePointerInfo::getGOT(),
1750                              false, false, false, 0);
1751     } else {
1752       // On ELF targets for PIC code, direct calls should go through the PLT
1753       unsigned OpFlags = 0;
1754       if (Subtarget->isTargetELF() &&
1755           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1756         OpFlags = ARMII::MO_PLT;
1757       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1758     }
1759   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1760     isDirect = true;
1761     bool isStub = Subtarget->isTargetMachO() &&
1762                   getTargetMachine().getRelocationModel() != Reloc::Static;
1763     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1764     // tBX takes a register source operand.
1765     const char *Sym = S->getSymbol();
1766     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1767       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1768       ARMConstantPoolValue *CPV =
1769         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1770                                       ARMPCLabelIndex, 4);
1771       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1772       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1773       Callee = DAG.getLoad(getPointerTy(), dl,
1774                            DAG.getEntryNode(), CPAddr,
1775                            MachinePointerInfo::getConstantPool(),
1776                            false, false, false, 0);
1777       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1778       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1779                            getPointerTy(), Callee, PICLabel);
1780     } else {
1781       unsigned OpFlags = 0;
1782       // On ELF targets for PIC code, direct calls should go through the PLT
1783       if (Subtarget->isTargetELF() &&
1784                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1785         OpFlags = ARMII::MO_PLT;
1786       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1787     }
1788   }
1789 
1790   // FIXME: handle tail calls differently.
1791   unsigned CallOpc;
1792   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1793   if (Subtarget->isThumb()) {
1794     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1795       CallOpc = ARMISD::CALL_NOLINK;
1796     else
1797       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1798   } else {
1799     if (!isDirect && !Subtarget->hasV5TOps())
1800       CallOpc = ARMISD::CALL_NOLINK;
1801     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1802                // Emit regular call when code size is the priority
1803                !HasMinSizeAttr)
1804       // "mov lr, pc; b _foo" to avoid confusing the RSP
1805       CallOpc = ARMISD::CALL_NOLINK;
1806     else
1807       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1808   }
1809 
1810   std::vector<SDValue> Ops;
1811   Ops.push_back(Chain);
1812   Ops.push_back(Callee);
1813 
1814   // Add argument registers to the end of the list so that they are known live
1815   // into the call.
1816   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1817     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1818                                   RegsToPass[i].second.getValueType()));
1819 
1820   // Add a register mask operand representing the call-preserved registers.
1821   if (!isTailCall) {
1822     const uint32_t *Mask;
1823     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1824     if (isThisReturn) {
1825       // For 'this' returns, use the R0-preserving mask if applicable
1826       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1827       if (!Mask) {
1828         // Set isThisReturn to false if the calling convention is not one that
1829         // allows 'returned' to be modeled in this way, so LowerCallResult does
1830         // not try to pass 'this' straight through
1831         isThisReturn = false;
1832         Mask = ARI->getCallPreservedMask(MF, CallConv);
1833       }
1834     } else
1835       Mask = ARI->getCallPreservedMask(MF, CallConv);
1836 
1837     assert(Mask && "Missing call preserved mask for calling convention");
1838     Ops.push_back(DAG.getRegisterMask(Mask));
1839   }
1840 
1841   if (InFlag.getNode())
1842     Ops.push_back(InFlag);
1843 
1844   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845   if (isTailCall)
1846     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847 
1848   // Returns a chain and a flag for retval copy to use.
1849   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850   InFlag = Chain.getValue(1);
1851 
1852   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1854   if (!Ins.empty())
1855     InFlag = Chain.getValue(1);
1856 
1857   // Handle result values, copying them out of physregs into vregs that we
1858   // return.
1859   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860                          InVals, isThisReturn,
1861                          isThisReturn ? OutVals[0] : SDValue());
1862 }
1863 
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack.  Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1867 /// this.
HandleByVal(CCState * State,unsigned & Size,unsigned Align) const1868 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1869                                     unsigned Align) const {
1870   assert((State->getCallOrPrologue() == Prologue ||
1871           State->getCallOrPrologue() == Call) &&
1872          "unhandled ParmContext");
1873 
1874   // Byval (as with any stack) slots are always at least 4 byte aligned.
1875   Align = std::max(Align, 4U);
1876 
1877   unsigned Reg = State->AllocateReg(GPRArgRegs);
1878   if (!Reg)
1879     return;
1880 
1881   unsigned AlignInRegs = Align / 4;
1882   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1883   for (unsigned i = 0; i < Waste; ++i)
1884     Reg = State->AllocateReg(GPRArgRegs);
1885 
1886   if (!Reg)
1887     return;
1888 
1889   unsigned Excess = 4 * (ARM::R4 - Reg);
1890 
1891   // Special case when NSAA != SP and parameter size greater than size of
1892   // all remained GPR regs. In that case we can't split parameter, we must
1893   // send it to stack. We also must set NCRN to R4, so waste all
1894   // remained registers.
1895   const unsigned NSAAOffset = State->getNextStackOffset();
1896   if (NSAAOffset != 0 && Size > Excess) {
1897     while (State->AllocateReg(GPRArgRegs))
1898       ;
1899     return;
1900   }
1901 
1902   // First register for byval parameter is the first register that wasn't
1903   // allocated before this method call, so it would be "reg".
1904   // If parameter is small enough to be saved in range [reg, r4), then
1905   // the end (first after last) register would be reg + param-size-in-regs,
1906   // else parameter would be splitted between registers and stack,
1907   // end register would be r4 in this case.
1908   unsigned ByValRegBegin = Reg;
1909   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1910   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1911   // Note, first register is allocated in the beginning of function already,
1912   // allocate remained amount of registers we need.
1913   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1914     State->AllocateReg(GPRArgRegs);
1915   // A byval parameter that is split between registers and memory needs its
1916   // size truncated here.
1917   // In the case where the entire structure fits in registers, we set the
1918   // size in memory to zero.
1919   Size = std::max<int>(Size - Excess, 0);
1920 }
1921 
1922 
1923 /// MatchingStackOffset - Return true if the given stack call argument is
1924 /// already available in the same position (relatively) of the caller's
1925 /// incoming argument stack.
1926 static
MatchingStackOffset(SDValue Arg,unsigned Offset,ISD::ArgFlagsTy Flags,MachineFrameInfo * MFI,const MachineRegisterInfo * MRI,const TargetInstrInfo * TII)1927 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1928                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1929                          const TargetInstrInfo *TII) {
1930   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1931   int FI = INT_MAX;
1932   if (Arg.getOpcode() == ISD::CopyFromReg) {
1933     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1934     if (!TargetRegisterInfo::isVirtualRegister(VR))
1935       return false;
1936     MachineInstr *Def = MRI->getVRegDef(VR);
1937     if (!Def)
1938       return false;
1939     if (!Flags.isByVal()) {
1940       if (!TII->isLoadFromStackSlot(Def, FI))
1941         return false;
1942     } else {
1943       return false;
1944     }
1945   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1946     if (Flags.isByVal())
1947       // ByVal argument is passed in as a pointer but it's now being
1948       // dereferenced. e.g.
1949       // define @foo(%struct.X* %A) {
1950       //   tail call @bar(%struct.X* byval %A)
1951       // }
1952       return false;
1953     SDValue Ptr = Ld->getBasePtr();
1954     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1955     if (!FINode)
1956       return false;
1957     FI = FINode->getIndex();
1958   } else
1959     return false;
1960 
1961   assert(FI != INT_MAX);
1962   if (!MFI->isFixedObjectIndex(FI))
1963     return false;
1964   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1965 }
1966 
1967 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1968 /// for tail call optimization. Targets which want to do tail call
1969 /// optimization should implement this function.
1970 bool
IsEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,bool isCalleeStructRet,bool isCallerStructRet,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const1971 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1972                                                      CallingConv::ID CalleeCC,
1973                                                      bool isVarArg,
1974                                                      bool isCalleeStructRet,
1975                                                      bool isCallerStructRet,
1976                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1977                                     const SmallVectorImpl<SDValue> &OutVals,
1978                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1979                                                      SelectionDAG& DAG) const {
1980   const Function *CallerF = DAG.getMachineFunction().getFunction();
1981   CallingConv::ID CallerCC = CallerF->getCallingConv();
1982   bool CCMatch = CallerCC == CalleeCC;
1983 
1984   // Look for obvious safe cases to perform tail call optimization that do not
1985   // require ABI changes. This is what gcc calls sibcall.
1986 
1987   // Do not sibcall optimize vararg calls unless the call site is not passing
1988   // any arguments.
1989   if (isVarArg && !Outs.empty())
1990     return false;
1991 
1992   // Exception-handling functions need a special set of instructions to indicate
1993   // a return to the hardware. Tail-calling another function would probably
1994   // break this.
1995   if (CallerF->hasFnAttribute("interrupt"))
1996     return false;
1997 
1998   // Also avoid sibcall optimization if either caller or callee uses struct
1999   // return semantics.
2000   if (isCalleeStructRet || isCallerStructRet)
2001     return false;
2002 
2003   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2004   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2005   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2006   // support in the assembler and linker to be used. This would need to be
2007   // fixed to fully support tail calls in Thumb1.
2008   //
2009   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2010   // LR.  This means if we need to reload LR, it takes an extra instructions,
2011   // which outweighs the value of the tail call; but here we don't know yet
2012   // whether LR is going to be used.  Probably the right approach is to
2013   // generate the tail call here and turn it back into CALL/RET in
2014   // emitEpilogue if LR is used.
2015 
2016   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2017   // but we need to make sure there are enough registers; the only valid
2018   // registers are the 4 used for parameters.  We don't currently do this
2019   // case.
2020   if (Subtarget->isThumb1Only())
2021     return false;
2022 
2023   // Externally-defined functions with weak linkage should not be
2024   // tail-called on ARM when the OS does not support dynamic
2025   // pre-emption of symbols, as the AAELF spec requires normal calls
2026   // to undefined weak functions to be replaced with a NOP or jump to the
2027   // next instruction. The behaviour of branch instructions in this
2028   // situation (as used for tail calls) is implementation-defined, so we
2029   // cannot rely on the linker replacing the tail call with a return.
2030   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2031     const GlobalValue *GV = G->getGlobal();
2032     const Triple TT(getTargetMachine().getTargetTriple());
2033     if (GV->hasExternalWeakLinkage() &&
2034         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2035       return false;
2036   }
2037 
2038   // If the calling conventions do not match, then we'd better make sure the
2039   // results are returned in the same way as what the caller expects.
2040   if (!CCMatch) {
2041     SmallVector<CCValAssign, 16> RVLocs1;
2042     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2043                        *DAG.getContext(), Call);
2044     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2045 
2046     SmallVector<CCValAssign, 16> RVLocs2;
2047     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2048                        *DAG.getContext(), Call);
2049     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2050 
2051     if (RVLocs1.size() != RVLocs2.size())
2052       return false;
2053     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2054       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2055         return false;
2056       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2057         return false;
2058       if (RVLocs1[i].isRegLoc()) {
2059         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2060           return false;
2061       } else {
2062         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2063           return false;
2064       }
2065     }
2066   }
2067 
2068   // If Caller's vararg or byval argument has been split between registers and
2069   // stack, do not perform tail call, since part of the argument is in caller's
2070   // local frame.
2071   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2072                                       getInfo<ARMFunctionInfo>();
2073   if (AFI_Caller->getArgRegsSaveSize())
2074     return false;
2075 
2076   // If the callee takes no arguments then go on to check the results of the
2077   // call.
2078   if (!Outs.empty()) {
2079     // Check if stack adjustment is needed. For now, do not do this if any
2080     // argument is passed on the stack.
2081     SmallVector<CCValAssign, 16> ArgLocs;
2082     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2083                       *DAG.getContext(), Call);
2084     CCInfo.AnalyzeCallOperands(Outs,
2085                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2086     if (CCInfo.getNextStackOffset()) {
2087       MachineFunction &MF = DAG.getMachineFunction();
2088 
2089       // Check if the arguments are already laid out in the right way as
2090       // the caller's fixed stack objects.
2091       MachineFrameInfo *MFI = MF.getFrameInfo();
2092       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2093       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2094       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2095            i != e;
2096            ++i, ++realArgIdx) {
2097         CCValAssign &VA = ArgLocs[i];
2098         EVT RegVT = VA.getLocVT();
2099         SDValue Arg = OutVals[realArgIdx];
2100         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2101         if (VA.getLocInfo() == CCValAssign::Indirect)
2102           return false;
2103         if (VA.needsCustom()) {
2104           // f64 and vector types are split into multiple registers or
2105           // register/stack-slot combinations.  The types will not match
2106           // the registers; give up on memory f64 refs until we figure
2107           // out what to do about this.
2108           if (!VA.isRegLoc())
2109             return false;
2110           if (!ArgLocs[++i].isRegLoc())
2111             return false;
2112           if (RegVT == MVT::v2f64) {
2113             if (!ArgLocs[++i].isRegLoc())
2114               return false;
2115             if (!ArgLocs[++i].isRegLoc())
2116               return false;
2117           }
2118         } else if (!VA.isRegLoc()) {
2119           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2120                                    MFI, MRI, TII))
2121             return false;
2122         }
2123       }
2124     }
2125   }
2126 
2127   return true;
2128 }
2129 
2130 bool
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2131 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2132                                   MachineFunction &MF, bool isVarArg,
2133                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2134                                   LLVMContext &Context) const {
2135   SmallVector<CCValAssign, 16> RVLocs;
2136   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2137   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2138                                                     isVarArg));
2139 }
2140 
LowerInterruptReturn(SmallVectorImpl<SDValue> & RetOps,SDLoc DL,SelectionDAG & DAG)2141 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2142                                     SDLoc DL, SelectionDAG &DAG) {
2143   const MachineFunction &MF = DAG.getMachineFunction();
2144   const Function *F = MF.getFunction();
2145 
2146   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2147 
2148   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2149   // version of the "preferred return address". These offsets affect the return
2150   // instruction if this is a return from PL1 without hypervisor extensions.
2151   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2152   //    SWI:     0      "subs pc, lr, #0"
2153   //    ABORT:   +4     "subs pc, lr, #4"
2154   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2155   // UNDEF varies depending on where the exception came from ARM or Thumb
2156   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2157 
2158   int64_t LROffset;
2159   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2160       IntKind == "ABORT")
2161     LROffset = 4;
2162   else if (IntKind == "SWI" || IntKind == "UNDEF")
2163     LROffset = 0;
2164   else
2165     report_fatal_error("Unsupported interrupt attribute. If present, value "
2166                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2167 
2168   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2169 
2170   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2171 }
2172 
2173 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,SDLoc dl,SelectionDAG & DAG) const2174 ARMTargetLowering::LowerReturn(SDValue Chain,
2175                                CallingConv::ID CallConv, bool isVarArg,
2176                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2177                                const SmallVectorImpl<SDValue> &OutVals,
2178                                SDLoc dl, SelectionDAG &DAG) const {
2179 
2180   // CCValAssign - represent the assignment of the return value to a location.
2181   SmallVector<CCValAssign, 16> RVLocs;
2182 
2183   // CCState - Info about the registers and stack slots.
2184   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2185                     *DAG.getContext(), Call);
2186 
2187   // Analyze outgoing return values.
2188   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2189                                                isVarArg));
2190 
2191   SDValue Flag;
2192   SmallVector<SDValue, 4> RetOps;
2193   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2194   bool isLittleEndian = Subtarget->isLittle();
2195 
2196   MachineFunction &MF = DAG.getMachineFunction();
2197   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2198   AFI->setReturnRegsCount(RVLocs.size());
2199 
2200   // Copy the result values into the output registers.
2201   for (unsigned i = 0, realRVLocIdx = 0;
2202        i != RVLocs.size();
2203        ++i, ++realRVLocIdx) {
2204     CCValAssign &VA = RVLocs[i];
2205     assert(VA.isRegLoc() && "Can only return in registers!");
2206 
2207     SDValue Arg = OutVals[realRVLocIdx];
2208 
2209     switch (VA.getLocInfo()) {
2210     default: llvm_unreachable("Unknown loc info!");
2211     case CCValAssign::Full: break;
2212     case CCValAssign::BCvt:
2213       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2214       break;
2215     }
2216 
2217     if (VA.needsCustom()) {
2218       if (VA.getLocVT() == MVT::v2f64) {
2219         // Extract the first half and return it in two registers.
2220         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2221                                    DAG.getConstant(0, MVT::i32));
2222         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2223                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2224 
2225         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2226                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2227                                  Flag);
2228         Flag = Chain.getValue(1);
2229         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2230         VA = RVLocs[++i]; // skip ahead to next loc
2231         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2232                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2233                                  Flag);
2234         Flag = Chain.getValue(1);
2235         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2236         VA = RVLocs[++i]; // skip ahead to next loc
2237 
2238         // Extract the 2nd half and fall through to handle it as an f64 value.
2239         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2240                           DAG.getConstant(1, MVT::i32));
2241       }
2242       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2243       // available.
2244       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2245                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2246       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2248                                Flag);
2249       Flag = Chain.getValue(1);
2250       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251       VA = RVLocs[++i]; // skip ahead to next loc
2252       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2253                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2254                                Flag);
2255     } else
2256       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2257 
2258     // Guarantee that all emitted copies are
2259     // stuck together, avoiding something bad.
2260     Flag = Chain.getValue(1);
2261     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2262   }
2263 
2264   // Update chain and glue.
2265   RetOps[0] = Chain;
2266   if (Flag.getNode())
2267     RetOps.push_back(Flag);
2268 
2269   // CPUs which aren't M-class use a special sequence to return from
2270   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2271   // though we use "subs pc, lr, #N").
2272   //
2273   // M-class CPUs actually use a normal return sequence with a special
2274   // (hardware-provided) value in LR, so the normal code path works.
2275   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2276       !Subtarget->isMClass()) {
2277     if (Subtarget->isThumb1Only())
2278       report_fatal_error("interrupt attribute is not supported in Thumb1");
2279     return LowerInterruptReturn(RetOps, dl, DAG);
2280   }
2281 
2282   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2283 }
2284 
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const2285 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2286   if (N->getNumValues() != 1)
2287     return false;
2288   if (!N->hasNUsesOfValue(1, 0))
2289     return false;
2290 
2291   SDValue TCChain = Chain;
2292   SDNode *Copy = *N->use_begin();
2293   if (Copy->getOpcode() == ISD::CopyToReg) {
2294     // If the copy has a glue operand, we conservatively assume it isn't safe to
2295     // perform a tail call.
2296     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2297       return false;
2298     TCChain = Copy->getOperand(0);
2299   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2300     SDNode *VMov = Copy;
2301     // f64 returned in a pair of GPRs.
2302     SmallPtrSet<SDNode*, 2> Copies;
2303     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2304          UI != UE; ++UI) {
2305       if (UI->getOpcode() != ISD::CopyToReg)
2306         return false;
2307       Copies.insert(*UI);
2308     }
2309     if (Copies.size() > 2)
2310       return false;
2311 
2312     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2313          UI != UE; ++UI) {
2314       SDValue UseChain = UI->getOperand(0);
2315       if (Copies.count(UseChain.getNode()))
2316         // Second CopyToReg
2317         Copy = *UI;
2318       else {
2319         // We are at the top of this chain.
2320         // If the copy has a glue operand, we conservatively assume it
2321         // isn't safe to perform a tail call.
2322         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2323           return false;
2324         // First CopyToReg
2325         TCChain = UseChain;
2326       }
2327     }
2328   } else if (Copy->getOpcode() == ISD::BITCAST) {
2329     // f32 returned in a single GPR.
2330     if (!Copy->hasOneUse())
2331       return false;
2332     Copy = *Copy->use_begin();
2333     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2334       return false;
2335     // If the copy has a glue operand, we conservatively assume it isn't safe to
2336     // perform a tail call.
2337     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338       return false;
2339     TCChain = Copy->getOperand(0);
2340   } else {
2341     return false;
2342   }
2343 
2344   bool HasRet = false;
2345   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2346        UI != UE; ++UI) {
2347     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2348         UI->getOpcode() != ARMISD::INTRET_FLAG)
2349       return false;
2350     HasRet = true;
2351   }
2352 
2353   if (!HasRet)
2354     return false;
2355 
2356   Chain = TCChain;
2357   return true;
2358 }
2359 
mayBeEmittedAsTailCall(CallInst * CI) const2360 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2361   if (!Subtarget->supportsTailCall())
2362     return false;
2363 
2364   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2365     return false;
2366 
2367   return !Subtarget->isThumb1Only();
2368 }
2369 
2370 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2371 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2372 // one of the above mentioned nodes. It has to be wrapped because otherwise
2373 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2374 // be used to form addressing mode. These wrapped nodes will be selected
2375 // into MOVi.
LowerConstantPool(SDValue Op,SelectionDAG & DAG)2376 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2377   EVT PtrVT = Op.getValueType();
2378   // FIXME there is no actual debug info here
2379   SDLoc dl(Op);
2380   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2381   SDValue Res;
2382   if (CP->isMachineConstantPoolEntry())
2383     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2384                                     CP->getAlignment());
2385   else
2386     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2387                                     CP->getAlignment());
2388   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2389 }
2390 
getJumpTableEncoding() const2391 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2392   return MachineJumpTableInfo::EK_Inline;
2393 }
2394 
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const2395 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2396                                              SelectionDAG &DAG) const {
2397   MachineFunction &MF = DAG.getMachineFunction();
2398   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2399   unsigned ARMPCLabelIndex = 0;
2400   SDLoc DL(Op);
2401   EVT PtrVT = getPointerTy();
2402   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2403   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2404   SDValue CPAddr;
2405   if (RelocM == Reloc::Static) {
2406     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2407   } else {
2408     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2409     ARMPCLabelIndex = AFI->createPICLabelUId();
2410     ARMConstantPoolValue *CPV =
2411       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2412                                       ARMCP::CPBlockAddress, PCAdj);
2413     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2414   }
2415   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2416   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2417                                MachinePointerInfo::getConstantPool(),
2418                                false, false, false, 0);
2419   if (RelocM == Reloc::Static)
2420     return Result;
2421   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2422   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2423 }
2424 
2425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2426 SDValue
LowerToTLSGeneralDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG) const2427 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2428                                                  SelectionDAG &DAG) const {
2429   SDLoc dl(GA);
2430   EVT PtrVT = getPointerTy();
2431   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2432   MachineFunction &MF = DAG.getMachineFunction();
2433   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2435   ARMConstantPoolValue *CPV =
2436     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2437                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2438   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2439   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2440   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2441                          MachinePointerInfo::getConstantPool(),
2442                          false, false, false, 0);
2443   SDValue Chain = Argument.getValue(1);
2444 
2445   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2446   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2447 
2448   // call __tls_get_addr.
2449   ArgListTy Args;
2450   ArgListEntry Entry;
2451   Entry.Node = Argument;
2452   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2453   Args.push_back(Entry);
2454 
2455   // FIXME: is there useful debug info available here?
2456   TargetLowering::CallLoweringInfo CLI(DAG);
2457   CLI.setDebugLoc(dl).setChain(Chain)
2458     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2459                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2460                0);
2461 
2462   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2463   return CallResult.first;
2464 }
2465 
2466 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2467 // "local exec" model.
2468 SDValue
LowerToTLSExecModels(GlobalAddressSDNode * GA,SelectionDAG & DAG,TLSModel::Model model) const2469 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2470                                         SelectionDAG &DAG,
2471                                         TLSModel::Model model) const {
2472   const GlobalValue *GV = GA->getGlobal();
2473   SDLoc dl(GA);
2474   SDValue Offset;
2475   SDValue Chain = DAG.getEntryNode();
2476   EVT PtrVT = getPointerTy();
2477   // Get the Thread Pointer
2478   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2479 
2480   if (model == TLSModel::InitialExec) {
2481     MachineFunction &MF = DAG.getMachineFunction();
2482     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2483     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2484     // Initial exec model.
2485     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486     ARMConstantPoolValue *CPV =
2487       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2488                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2489                                       true);
2490     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2492     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493                          MachinePointerInfo::getConstantPool(),
2494                          false, false, false, 0);
2495     Chain = Offset.getValue(1);
2496 
2497     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2498     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2499 
2500     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501                          MachinePointerInfo::getConstantPool(),
2502                          false, false, false, 0);
2503   } else {
2504     // local exec model
2505     assert(model == TLSModel::LocalExec);
2506     ARMConstantPoolValue *CPV =
2507       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2508     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2509     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2510     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2511                          MachinePointerInfo::getConstantPool(),
2512                          false, false, false, 0);
2513   }
2514 
2515   // The address of the thread local variable is the add of the thread
2516   // pointer with the offset of the variable.
2517   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2518 }
2519 
2520 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const2521 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2522   // TODO: implement the "local dynamic" model
2523   assert(Subtarget->isTargetELF() &&
2524          "TLS not implemented for non-ELF targets");
2525   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2526 
2527   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2528 
2529   switch (model) {
2530     case TLSModel::GeneralDynamic:
2531     case TLSModel::LocalDynamic:
2532       return LowerToTLSGeneralDynamicModel(GA, DAG);
2533     case TLSModel::InitialExec:
2534     case TLSModel::LocalExec:
2535       return LowerToTLSExecModels(GA, DAG, model);
2536   }
2537   llvm_unreachable("bogus TLS model");
2538 }
2539 
LowerGlobalAddressELF(SDValue Op,SelectionDAG & DAG) const2540 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2541                                                  SelectionDAG &DAG) const {
2542   EVT PtrVT = getPointerTy();
2543   SDLoc dl(Op);
2544   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2545   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2546     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2547     ARMConstantPoolValue *CPV =
2548       ARMConstantPoolConstant::Create(GV,
2549                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2550     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2552     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2553                                  CPAddr,
2554                                  MachinePointerInfo::getConstantPool(),
2555                                  false, false, false, 0);
2556     SDValue Chain = Result.getValue(1);
2557     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2558     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2559     if (!UseGOTOFF)
2560       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2561                            MachinePointerInfo::getGOT(),
2562                            false, false, false, 0);
2563     return Result;
2564   }
2565 
2566   // If we have T2 ops, we can materialize the address directly via movt/movw
2567   // pair. This is always cheaper.
2568   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2569     ++NumMovwMovt;
2570     // FIXME: Once remat is capable of dealing with instructions with register
2571     // operands, expand this into two nodes.
2572     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2573                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2574   } else {
2575     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2576     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2577     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2578                        MachinePointerInfo::getConstantPool(),
2579                        false, false, false, 0);
2580   }
2581 }
2582 
LowerGlobalAddressDarwin(SDValue Op,SelectionDAG & DAG) const2583 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2584                                                     SelectionDAG &DAG) const {
2585   EVT PtrVT = getPointerTy();
2586   SDLoc dl(Op);
2587   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2588   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2589 
2590   if (Subtarget->useMovt(DAG.getMachineFunction()))
2591     ++NumMovwMovt;
2592 
2593   // FIXME: Once remat is capable of dealing with instructions with register
2594   // operands, expand this into multiple nodes
2595   unsigned Wrapper =
2596       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2597 
2598   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2599   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2600 
2601   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2602     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2603                          MachinePointerInfo::getGOT(), false, false, false, 0);
2604   return Result;
2605 }
2606 
LowerGlobalAddressWindows(SDValue Op,SelectionDAG & DAG) const2607 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2608                                                      SelectionDAG &DAG) const {
2609   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2610   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2611          "Windows on ARM expects to use movw/movt");
2612 
2613   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2614   const ARMII::TOF TargetFlags =
2615     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2616   EVT PtrVT = getPointerTy();
2617   SDValue Result;
2618   SDLoc DL(Op);
2619 
2620   ++NumMovwMovt;
2621 
2622   // FIXME: Once remat is capable of dealing with instructions with register
2623   // operands, expand this into two nodes.
2624   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2625                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2626                                                   TargetFlags));
2627   if (GV->hasDLLImportStorageClass())
2628     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2629                          MachinePointerInfo::getGOT(), false, false, false, 0);
2630   return Result;
2631 }
2632 
LowerGLOBAL_OFFSET_TABLE(SDValue Op,SelectionDAG & DAG) const2633 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2634                                                     SelectionDAG &DAG) const {
2635   assert(Subtarget->isTargetELF() &&
2636          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2637   MachineFunction &MF = DAG.getMachineFunction();
2638   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2639   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2640   EVT PtrVT = getPointerTy();
2641   SDLoc dl(Op);
2642   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2643   ARMConstantPoolValue *CPV =
2644     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2645                                   ARMPCLabelIndex, PCAdj);
2646   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2647   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2648   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2649                                MachinePointerInfo::getConstantPool(),
2650                                false, false, false, 0);
2651   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2653 }
2654 
2655 SDValue
LowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const2656 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2657   SDLoc dl(Op);
2658   SDValue Val = DAG.getConstant(0, MVT::i32);
2659   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2660                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2661                      Op.getOperand(1), Val);
2662 }
2663 
2664 SDValue
LowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const2665 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2666   SDLoc dl(Op);
2667   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2668                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2669 }
2670 
2671 SDValue
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const2672 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2673                                           const ARMSubtarget *Subtarget) const {
2674   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2675   SDLoc dl(Op);
2676   switch (IntNo) {
2677   default: return SDValue();    // Don't custom lower most intrinsics.
2678   case Intrinsic::arm_rbit: {
2679     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2680            "RBIT intrinsic must have i32 type!");
2681     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2682   }
2683   case Intrinsic::arm_thread_pointer: {
2684     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2685     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2686   }
2687   case Intrinsic::eh_sjlj_lsda: {
2688     MachineFunction &MF = DAG.getMachineFunction();
2689     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2690     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2691     EVT PtrVT = getPointerTy();
2692     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2693     SDValue CPAddr;
2694     unsigned PCAdj = (RelocM != Reloc::PIC_)
2695       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2696     ARMConstantPoolValue *CPV =
2697       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2698                                       ARMCP::CPLSDA, PCAdj);
2699     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2701     SDValue Result =
2702       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2703                   MachinePointerInfo::getConstantPool(),
2704                   false, false, false, 0);
2705 
2706     if (RelocM == Reloc::PIC_) {
2707       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2708       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2709     }
2710     return Result;
2711   }
2712   case Intrinsic::arm_neon_vmulls:
2713   case Intrinsic::arm_neon_vmullu: {
2714     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2715       ? ARMISD::VMULLs : ARMISD::VMULLu;
2716     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2717                        Op.getOperand(1), Op.getOperand(2));
2718   }
2719   }
2720 }
2721 
LowerATOMIC_FENCE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)2722 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2723                                  const ARMSubtarget *Subtarget) {
2724   // FIXME: handle "fence singlethread" more efficiently.
2725   SDLoc dl(Op);
2726   if (!Subtarget->hasDataBarrier()) {
2727     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2728     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2729     // here.
2730     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2731            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2732     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2733                        DAG.getConstant(0, MVT::i32));
2734   }
2735 
2736   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2737   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2738   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2739   if (Subtarget->isMClass()) {
2740     // Only a full system barrier exists in the M-class architectures.
2741     Domain = ARM_MB::SY;
2742   } else if (Subtarget->isSwift() && Ord == Release) {
2743     // Swift happens to implement ISHST barriers in a way that's compatible with
2744     // Release semantics but weaker than ISH so we'd be fools not to use
2745     // it. Beware: other processors probably don't!
2746     Domain = ARM_MB::ISHST;
2747   }
2748 
2749   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2750                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2751                      DAG.getConstant(Domain, MVT::i32));
2752 }
2753 
LowerPREFETCH(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)2754 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2755                              const ARMSubtarget *Subtarget) {
2756   // ARM pre v5TE and Thumb1 does not have preload instructions.
2757   if (!(Subtarget->isThumb2() ||
2758         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2759     // Just preserve the chain.
2760     return Op.getOperand(0);
2761 
2762   SDLoc dl(Op);
2763   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2764   if (!isRead &&
2765       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2766     // ARMv7 with MP extension has PLDW.
2767     return Op.getOperand(0);
2768 
2769   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2770   if (Subtarget->isThumb()) {
2771     // Invert the bits.
2772     isRead = ~isRead & 1;
2773     isData = ~isData & 1;
2774   }
2775 
2776   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2777                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2778                      DAG.getConstant(isData, MVT::i32));
2779 }
2780 
LowerVASTART(SDValue Op,SelectionDAG & DAG)2781 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2782   MachineFunction &MF = DAG.getMachineFunction();
2783   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2784 
2785   // vastart just stores the address of the VarArgsFrameIndex slot into the
2786   // memory location argument.
2787   SDLoc dl(Op);
2788   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2789   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2790   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2791   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2792                       MachinePointerInfo(SV), false, false, 0);
2793 }
2794 
2795 SDValue
GetF64FormalArgument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,SDLoc dl) const2796 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2797                                         SDValue &Root, SelectionDAG &DAG,
2798                                         SDLoc dl) const {
2799   MachineFunction &MF = DAG.getMachineFunction();
2800   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2801 
2802   const TargetRegisterClass *RC;
2803   if (AFI->isThumb1OnlyFunction())
2804     RC = &ARM::tGPRRegClass;
2805   else
2806     RC = &ARM::GPRRegClass;
2807 
2808   // Transform the arguments stored in physical registers into virtual ones.
2809   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2810   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2811 
2812   SDValue ArgValue2;
2813   if (NextVA.isMemLoc()) {
2814     MachineFrameInfo *MFI = MF.getFrameInfo();
2815     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2816 
2817     // Create load node to retrieve arguments from the stack.
2818     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2819     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2820                             MachinePointerInfo::getFixedStack(FI),
2821                             false, false, false, 0);
2822   } else {
2823     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2824     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2825   }
2826   if (!Subtarget->isLittle())
2827     std::swap (ArgValue, ArgValue2);
2828   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2829 }
2830 
2831 // The remaining GPRs hold either the beginning of variable-argument
2832 // data, or the beginning of an aggregate passed by value (usually
2833 // byval).  Either way, we allocate stack slots adjacent to the data
2834 // provided by our caller, and store the unallocated registers there.
2835 // If this is a variadic function, the va_list pointer will begin with
2836 // these values; otherwise, this reassembles a (byval) structure that
2837 // was split between registers and memory.
2838 // Return: The frame index registers were stored into.
2839 int
StoreByValRegs(CCState & CCInfo,SelectionDAG & DAG,SDLoc dl,SDValue & Chain,const Value * OrigArg,unsigned InRegsParamRecordIdx,int ArgOffset,unsigned ArgSize) const2840 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2841                                   SDLoc dl, SDValue &Chain,
2842                                   const Value *OrigArg,
2843                                   unsigned InRegsParamRecordIdx,
2844                                   int ArgOffset,
2845                                   unsigned ArgSize) const {
2846   // Currently, two use-cases possible:
2847   // Case #1. Non-var-args function, and we meet first byval parameter.
2848   //          Setup first unallocated register as first byval register;
2849   //          eat all remained registers
2850   //          (these two actions are performed by HandleByVal method).
2851   //          Then, here, we initialize stack frame with
2852   //          "store-reg" instructions.
2853   // Case #2. Var-args function, that doesn't contain byval parameters.
2854   //          The same: eat all remained unallocated registers,
2855   //          initialize stack frame.
2856 
2857   MachineFunction &MF = DAG.getMachineFunction();
2858   MachineFrameInfo *MFI = MF.getFrameInfo();
2859   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2860   unsigned RBegin, REnd;
2861   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2862     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2863   } else {
2864     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2865     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2866     REnd = ARM::R4;
2867   }
2868 
2869   if (REnd != RBegin)
2870     ArgOffset = -4 * (ARM::R4 - RBegin);
2871 
2872   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2873   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2874 
2875   SmallVector<SDValue, 4> MemOps;
2876   const TargetRegisterClass *RC =
2877       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2878 
2879   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2880     unsigned VReg = MF.addLiveIn(Reg, RC);
2881     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2882     SDValue Store =
2883         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2884                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2885     MemOps.push_back(Store);
2886     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2887                       DAG.getConstant(4, getPointerTy()));
2888   }
2889 
2890   if (!MemOps.empty())
2891     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2892   return FrameIndex;
2893 }
2894 
2895 // Setup stack frame, the va_list pointer will start from.
2896 void
VarArgStyleRegisters(CCState & CCInfo,SelectionDAG & DAG,SDLoc dl,SDValue & Chain,unsigned ArgOffset,unsigned TotalArgRegsSaveSize,bool ForceMutable) const2897 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2898                                         SDLoc dl, SDValue &Chain,
2899                                         unsigned ArgOffset,
2900                                         unsigned TotalArgRegsSaveSize,
2901                                         bool ForceMutable) const {
2902   MachineFunction &MF = DAG.getMachineFunction();
2903   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904 
2905   // Try to store any remaining integer argument regs
2906   // to their spots on the stack so that they may be loaded by deferencing
2907   // the result of va_next.
2908   // If there is no regs to be stored, just point address after last
2909   // argument passed via stack.
2910   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2911                                   CCInfo.getInRegsParamsCount(),
2912                                   CCInfo.getNextStackOffset(), 4);
2913   AFI->setVarArgsFrameIndex(FrameIndex);
2914 }
2915 
2916 SDValue
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,SDLoc dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const2917 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2918                                         CallingConv::ID CallConv, bool isVarArg,
2919                                         const SmallVectorImpl<ISD::InputArg>
2920                                           &Ins,
2921                                         SDLoc dl, SelectionDAG &DAG,
2922                                         SmallVectorImpl<SDValue> &InVals)
2923                                           const {
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   MachineFrameInfo *MFI = MF.getFrameInfo();
2926 
2927   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928 
2929   // Assign locations to all of the incoming arguments.
2930   SmallVector<CCValAssign, 16> ArgLocs;
2931   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2932                     *DAG.getContext(), Prologue);
2933   CCInfo.AnalyzeFormalArguments(Ins,
2934                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2935                                                   isVarArg));
2936 
2937   SmallVector<SDValue, 16> ArgValues;
2938   SDValue ArgValue;
2939   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2940   unsigned CurArgIdx = 0;
2941 
2942   // Initially ArgRegsSaveSize is zero.
2943   // Then we increase this value each time we meet byval parameter.
2944   // We also increase this value in case of varargs function.
2945   AFI->setArgRegsSaveSize(0);
2946 
2947   // Calculate the amount of stack space that we need to allocate to store
2948   // byval and variadic arguments that are passed in registers.
2949   // We need to know this before we allocate the first byval or variadic
2950   // argument, as they will be allocated a stack slot below the CFA (Canonical
2951   // Frame Address, the stack pointer at entry to the function).
2952   unsigned ArgRegBegin = ARM::R4;
2953   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2954     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2955       break;
2956 
2957     CCValAssign &VA = ArgLocs[i];
2958     unsigned Index = VA.getValNo();
2959     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2960     if (!Flags.isByVal())
2961       continue;
2962 
2963     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2964     unsigned RBegin, REnd;
2965     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2966     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2967 
2968     CCInfo.nextInRegsParam();
2969   }
2970   CCInfo.rewindByValRegsInfo();
2971 
2972   int lastInsIndex = -1;
2973   if (isVarArg && MFI->hasVAStart()) {
2974     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2975     if (RegIdx != array_lengthof(GPRArgRegs))
2976       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2977   }
2978 
2979   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2980   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2981 
2982   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2983     CCValAssign &VA = ArgLocs[i];
2984     if (Ins[VA.getValNo()].isOrigArg()) {
2985       std::advance(CurOrigArg,
2986                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2987       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2988     }
2989     // Arguments stored in registers.
2990     if (VA.isRegLoc()) {
2991       EVT RegVT = VA.getLocVT();
2992 
2993       if (VA.needsCustom()) {
2994         // f64 and vector types are split up into multiple registers or
2995         // combinations of registers and stack slots.
2996         if (VA.getLocVT() == MVT::v2f64) {
2997           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2998                                                    Chain, DAG, dl);
2999           VA = ArgLocs[++i]; // skip ahead to next loc
3000           SDValue ArgValue2;
3001           if (VA.isMemLoc()) {
3002             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3003             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3004             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3005                                     MachinePointerInfo::getFixedStack(FI),
3006                                     false, false, false, 0);
3007           } else {
3008             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3009                                              Chain, DAG, dl);
3010           }
3011           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3012           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3013                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3014           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3015                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3016         } else
3017           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3018 
3019       } else {
3020         const TargetRegisterClass *RC;
3021 
3022         if (RegVT == MVT::f32)
3023           RC = &ARM::SPRRegClass;
3024         else if (RegVT == MVT::f64)
3025           RC = &ARM::DPRRegClass;
3026         else if (RegVT == MVT::v2f64)
3027           RC = &ARM::QPRRegClass;
3028         else if (RegVT == MVT::i32)
3029           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3030                                            : &ARM::GPRRegClass;
3031         else
3032           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3033 
3034         // Transform the arguments in physical registers into virtual ones.
3035         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3036         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3037       }
3038 
3039       // If this is an 8 or 16-bit value, it is really passed promoted
3040       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3041       // truncate to the right size.
3042       switch (VA.getLocInfo()) {
3043       default: llvm_unreachable("Unknown loc info!");
3044       case CCValAssign::Full: break;
3045       case CCValAssign::BCvt:
3046         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3047         break;
3048       case CCValAssign::SExt:
3049         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3050                                DAG.getValueType(VA.getValVT()));
3051         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3052         break;
3053       case CCValAssign::ZExt:
3054         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3055                                DAG.getValueType(VA.getValVT()));
3056         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3057         break;
3058       }
3059 
3060       InVals.push_back(ArgValue);
3061 
3062     } else { // VA.isRegLoc()
3063 
3064       // sanity check
3065       assert(VA.isMemLoc());
3066       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3067 
3068       int index = VA.getValNo();
3069 
3070       // Some Ins[] entries become multiple ArgLoc[] entries.
3071       // Process them only once.
3072       if (index != lastInsIndex)
3073         {
3074           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3075           // FIXME: For now, all byval parameter objects are marked mutable.
3076           // This can be changed with more analysis.
3077           // In case of tail call optimization mark all arguments mutable.
3078           // Since they could be overwritten by lowering of arguments in case of
3079           // a tail call.
3080           if (Flags.isByVal()) {
3081             assert(Ins[index].isOrigArg() &&
3082                    "Byval arguments cannot be implicit");
3083             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3084 
3085             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3086                                             CurByValIndex, VA.getLocMemOffset(),
3087                                             Flags.getByValSize());
3088             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3089             CCInfo.nextInRegsParam();
3090           } else {
3091             unsigned FIOffset = VA.getLocMemOffset();
3092             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3093                                             FIOffset, true);
3094 
3095             // Create load nodes to retrieve arguments from the stack.
3096             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3097             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3098                                          MachinePointerInfo::getFixedStack(FI),
3099                                          false, false, false, 0));
3100           }
3101           lastInsIndex = index;
3102         }
3103     }
3104   }
3105 
3106   // varargs
3107   if (isVarArg && MFI->hasVAStart())
3108     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3109                          CCInfo.getNextStackOffset(),
3110                          TotalArgRegsSaveSize);
3111 
3112   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3113 
3114   return Chain;
3115 }
3116 
3117 /// isFloatingPointZero - Return true if this is +0.0.
isFloatingPointZero(SDValue Op)3118 static bool isFloatingPointZero(SDValue Op) {
3119   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3120     return CFP->getValueAPF().isPosZero();
3121   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3122     // Maybe this has already been legalized into the constant pool?
3123     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3124       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3125       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3126         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3127           return CFP->getValueAPF().isPosZero();
3128     }
3129   } else if (Op->getOpcode() == ISD::BITCAST &&
3130              Op->getValueType(0) == MVT::f64) {
3131     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3132     // created by LowerConstantFP().
3133     SDValue BitcastOp = Op->getOperand(0);
3134     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3135       SDValue MoveOp = BitcastOp->getOperand(0);
3136       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3137           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3138         return true;
3139       }
3140     }
3141   }
3142   return false;
3143 }
3144 
3145 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3146 /// the given operands.
3147 SDValue
getARMCmp(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue & ARMcc,SelectionDAG & DAG,SDLoc dl) const3148 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3149                              SDValue &ARMcc, SelectionDAG &DAG,
3150                              SDLoc dl) const {
3151   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3152     unsigned C = RHSC->getZExtValue();
3153     if (!isLegalICmpImmediate(C)) {
3154       // Constant does not fit, try adjusting it by one?
3155       switch (CC) {
3156       default: break;
3157       case ISD::SETLT:
3158       case ISD::SETGE:
3159         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3160           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3161           RHS = DAG.getConstant(C-1, MVT::i32);
3162         }
3163         break;
3164       case ISD::SETULT:
3165       case ISD::SETUGE:
3166         if (C != 0 && isLegalICmpImmediate(C-1)) {
3167           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3168           RHS = DAG.getConstant(C-1, MVT::i32);
3169         }
3170         break;
3171       case ISD::SETLE:
3172       case ISD::SETGT:
3173         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3174           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3175           RHS = DAG.getConstant(C+1, MVT::i32);
3176         }
3177         break;
3178       case ISD::SETULE:
3179       case ISD::SETUGT:
3180         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3181           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3182           RHS = DAG.getConstant(C+1, MVT::i32);
3183         }
3184         break;
3185       }
3186     }
3187   }
3188 
3189   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3190   ARMISD::NodeType CompareType;
3191   switch (CondCode) {
3192   default:
3193     CompareType = ARMISD::CMP;
3194     break;
3195   case ARMCC::EQ:
3196   case ARMCC::NE:
3197     // Uses only Z Flag
3198     CompareType = ARMISD::CMPZ;
3199     break;
3200   }
3201   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3202   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3203 }
3204 
3205 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3206 SDValue
getVFPCmp(SDValue LHS,SDValue RHS,SelectionDAG & DAG,SDLoc dl) const3207 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3208                              SDLoc dl) const {
3209   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3210   SDValue Cmp;
3211   if (!isFloatingPointZero(RHS))
3212     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3213   else
3214     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3215   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3216 }
3217 
3218 /// duplicateCmp - Glue values can have only one use, so this function
3219 /// duplicates a comparison node.
3220 SDValue
duplicateCmp(SDValue Cmp,SelectionDAG & DAG) const3221 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3222   unsigned Opc = Cmp.getOpcode();
3223   SDLoc DL(Cmp);
3224   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3225     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3226 
3227   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3228   Cmp = Cmp.getOperand(0);
3229   Opc = Cmp.getOpcode();
3230   if (Opc == ARMISD::CMPFP)
3231     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3232   else {
3233     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3234     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3235   }
3236   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3237 }
3238 
3239 std::pair<SDValue, SDValue>
getARMXALUOOp(SDValue Op,SelectionDAG & DAG,SDValue & ARMcc) const3240 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3241                                  SDValue &ARMcc) const {
3242   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3243 
3244   SDValue Value, OverflowCmp;
3245   SDValue LHS = Op.getOperand(0);
3246   SDValue RHS = Op.getOperand(1);
3247 
3248 
3249   // FIXME: We are currently always generating CMPs because we don't support
3250   // generating CMN through the backend. This is not as good as the natural
3251   // CMP case because it causes a register dependency and cannot be folded
3252   // later.
3253 
3254   switch (Op.getOpcode()) {
3255   default:
3256     llvm_unreachable("Unknown overflow instruction!");
3257   case ISD::SADDO:
3258     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3259     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3260     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3261     break;
3262   case ISD::UADDO:
3263     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3264     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3265     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3266     break;
3267   case ISD::SSUBO:
3268     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3269     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3270     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3271     break;
3272   case ISD::USUBO:
3273     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3274     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3275     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3276     break;
3277   } // switch (...)
3278 
3279   return std::make_pair(Value, OverflowCmp);
3280 }
3281 
3282 
3283 SDValue
LowerXALUO(SDValue Op,SelectionDAG & DAG) const3284 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3285   // Let legalize expand this if it isn't a legal type yet.
3286   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3287     return SDValue();
3288 
3289   SDValue Value, OverflowCmp;
3290   SDValue ARMcc;
3291   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3292   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3293   // We use 0 and 1 as false and true values.
3294   SDValue TVal = DAG.getConstant(1, MVT::i32);
3295   SDValue FVal = DAG.getConstant(0, MVT::i32);
3296   EVT VT = Op.getValueType();
3297 
3298   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3299                                  ARMcc, CCR, OverflowCmp);
3300 
3301   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3302   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3303 }
3304 
3305 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const3306 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3307   SDValue Cond = Op.getOperand(0);
3308   SDValue SelectTrue = Op.getOperand(1);
3309   SDValue SelectFalse = Op.getOperand(2);
3310   SDLoc dl(Op);
3311   unsigned Opc = Cond.getOpcode();
3312 
3313   if (Cond.getResNo() == 1 &&
3314       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3315        Opc == ISD::USUBO)) {
3316     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3317       return SDValue();
3318 
3319     SDValue Value, OverflowCmp;
3320     SDValue ARMcc;
3321     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3322     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3323     EVT VT = Op.getValueType();
3324 
3325     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3326                    OverflowCmp, DAG);
3327   }
3328 
3329   // Convert:
3330   //
3331   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3332   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3333   //
3334   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3335     const ConstantSDNode *CMOVTrue =
3336       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3337     const ConstantSDNode *CMOVFalse =
3338       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3339 
3340     if (CMOVTrue && CMOVFalse) {
3341       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3342       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3343 
3344       SDValue True;
3345       SDValue False;
3346       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3347         True = SelectTrue;
3348         False = SelectFalse;
3349       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3350         True = SelectFalse;
3351         False = SelectTrue;
3352       }
3353 
3354       if (True.getNode() && False.getNode()) {
3355         EVT VT = Op.getValueType();
3356         SDValue ARMcc = Cond.getOperand(2);
3357         SDValue CCR = Cond.getOperand(3);
3358         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3359         assert(True.getValueType() == VT);
3360         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3361       }
3362     }
3363   }
3364 
3365   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3366   // undefined bits before doing a full-word comparison with zero.
3367   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3368                      DAG.getConstant(1, Cond.getValueType()));
3369 
3370   return DAG.getSelectCC(dl, Cond,
3371                          DAG.getConstant(0, Cond.getValueType()),
3372                          SelectTrue, SelectFalse, ISD::SETNE);
3373 }
3374 
getInverseCCForVSEL(ISD::CondCode CC)3375 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3376   if (CC == ISD::SETNE)
3377     return ISD::SETEQ;
3378   return ISD::getSetCCInverse(CC, true);
3379 }
3380 
checkVSELConstraints(ISD::CondCode CC,ARMCC::CondCodes & CondCode,bool & swpCmpOps,bool & swpVselOps)3381 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3382                                  bool &swpCmpOps, bool &swpVselOps) {
3383   // Start by selecting the GE condition code for opcodes that return true for
3384   // 'equality'
3385   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3386       CC == ISD::SETULE)
3387     CondCode = ARMCC::GE;
3388 
3389   // and GT for opcodes that return false for 'equality'.
3390   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3391            CC == ISD::SETULT)
3392     CondCode = ARMCC::GT;
3393 
3394   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3395   // to swap the compare operands.
3396   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3397       CC == ISD::SETULT)
3398     swpCmpOps = true;
3399 
3400   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3401   // If we have an unordered opcode, we need to swap the operands to the VSEL
3402   // instruction (effectively negating the condition).
3403   //
3404   // This also has the effect of swapping which one of 'less' or 'greater'
3405   // returns true, so we also swap the compare operands. It also switches
3406   // whether we return true for 'equality', so we compensate by picking the
3407   // opposite condition code to our original choice.
3408   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3409       CC == ISD::SETUGT) {
3410     swpCmpOps = !swpCmpOps;
3411     swpVselOps = !swpVselOps;
3412     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3413   }
3414 
3415   // 'ordered' is 'anything but unordered', so use the VS condition code and
3416   // swap the VSEL operands.
3417   if (CC == ISD::SETO) {
3418     CondCode = ARMCC::VS;
3419     swpVselOps = true;
3420   }
3421 
3422   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3423   // code and swap the VSEL operands.
3424   if (CC == ISD::SETUNE) {
3425     CondCode = ARMCC::EQ;
3426     swpVselOps = true;
3427   }
3428 }
3429 
getCMOV(SDLoc dl,EVT VT,SDValue FalseVal,SDValue TrueVal,SDValue ARMcc,SDValue CCR,SDValue Cmp,SelectionDAG & DAG) const3430 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3431                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3432                                    SDValue Cmp, SelectionDAG &DAG) const {
3433   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3434     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3435                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3436     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3437                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3438 
3439     SDValue TrueLow = TrueVal.getValue(0);
3440     SDValue TrueHigh = TrueVal.getValue(1);
3441     SDValue FalseLow = FalseVal.getValue(0);
3442     SDValue FalseHigh = FalseVal.getValue(1);
3443 
3444     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3445                               ARMcc, CCR, Cmp);
3446     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3447                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3448 
3449     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3450   } else {
3451     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3452                        Cmp);
3453   }
3454 }
3455 
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const3456 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3457   EVT VT = Op.getValueType();
3458   SDValue LHS = Op.getOperand(0);
3459   SDValue RHS = Op.getOperand(1);
3460   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3461   SDValue TrueVal = Op.getOperand(2);
3462   SDValue FalseVal = Op.getOperand(3);
3463   SDLoc dl(Op);
3464 
3465   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3466     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3467                                                     dl);
3468 
3469     // If softenSetCCOperands only returned one value, we should compare it to
3470     // zero.
3471     if (!RHS.getNode()) {
3472       RHS = DAG.getConstant(0, LHS.getValueType());
3473       CC = ISD::SETNE;
3474     }
3475   }
3476 
3477   if (LHS.getValueType() == MVT::i32) {
3478     // Try to generate VSEL on ARMv8.
3479     // The VSEL instruction can't use all the usual ARM condition
3480     // codes: it only has two bits to select the condition code, so it's
3481     // constrained to use only GE, GT, VS and EQ.
3482     //
3483     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3484     // swap the operands of the previous compare instruction (effectively
3485     // inverting the compare condition, swapping 'less' and 'greater') and
3486     // sometimes need to swap the operands to the VSEL (which inverts the
3487     // condition in the sense of firing whenever the previous condition didn't)
3488     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3489                                     TrueVal.getValueType() == MVT::f64)) {
3490       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3491       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3492           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3493         CC = getInverseCCForVSEL(CC);
3494         std::swap(TrueVal, FalseVal);
3495       }
3496     }
3497 
3498     SDValue ARMcc;
3499     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3500     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3501     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3502   }
3503 
3504   ARMCC::CondCodes CondCode, CondCode2;
3505   FPCCToARMCC(CC, CondCode, CondCode2);
3506 
3507   // Try to generate VMAXNM/VMINNM on ARMv8.
3508   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3509                                   TrueVal.getValueType() == MVT::f64)) {
3510     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3511     // same operands, as follows:
3512     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3513     //   select c, a, b
3514     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3515     // We only do this transformation in UnsafeFPMath and for no-NaNs
3516     // comparisons, because signed zeros and NaNs are handled differently than
3517     // the original code sequence.
3518     // FIXME: There are more cases that can be transformed even with NaNs,
3519     // signed zeroes and safe math.  E.g. in the following, the result will be
3520     // FalseVal if a is a NaN or -0./0. and that's what vmaxnm will give, too.
3521     //   c = fcmp ogt, a, 0. ; select c, a, 0. => vmaxnm a, 0.
3522     // FIXME: There is similar code that allows some extensions in
3523     // AArch64TargetLowering::LowerSELECT_CC that should be shared with this
3524     // code.
3525     if (getTargetMachine().Options.UnsafeFPMath) {
3526       if (LHS == TrueVal && RHS == FalseVal) {
3527         if (CC == ISD::SETGT || CC == ISD::SETGE)
3528           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3529         if (CC == ISD::SETLT || CC == ISD::SETLE)
3530           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3531       } else if (LHS == FalseVal && RHS == TrueVal) {
3532         if (CC == ISD::SETLT || CC == ISD::SETLE)
3533           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3534         if (CC == ISD::SETGT || CC == ISD::SETGE)
3535           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3536       }
3537     }
3538 
3539     bool swpCmpOps = false;
3540     bool swpVselOps = false;
3541     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3542 
3543     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3544         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3545       if (swpCmpOps)
3546         std::swap(LHS, RHS);
3547       if (swpVselOps)
3548         std::swap(TrueVal, FalseVal);
3549     }
3550   }
3551 
3552   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3553   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3554   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3555   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3556   if (CondCode2 != ARMCC::AL) {
3557     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3558     // FIXME: Needs another CMP because flag can have but one use.
3559     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3560     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3561   }
3562   return Result;
3563 }
3564 
3565 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3566 /// to morph to an integer compare sequence.
canChangeToInt(SDValue Op,bool & SeenZero,const ARMSubtarget * Subtarget)3567 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3568                            const ARMSubtarget *Subtarget) {
3569   SDNode *N = Op.getNode();
3570   if (!N->hasOneUse())
3571     // Otherwise it requires moving the value from fp to integer registers.
3572     return false;
3573   if (!N->getNumValues())
3574     return false;
3575   EVT VT = Op.getValueType();
3576   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3577     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3578     // vmrs are very slow, e.g. cortex-a8.
3579     return false;
3580 
3581   if (isFloatingPointZero(Op)) {
3582     SeenZero = true;
3583     return true;
3584   }
3585   return ISD::isNormalLoad(N);
3586 }
3587 
bitcastf32Toi32(SDValue Op,SelectionDAG & DAG)3588 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3589   if (isFloatingPointZero(Op))
3590     return DAG.getConstant(0, MVT::i32);
3591 
3592   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3593     return DAG.getLoad(MVT::i32, SDLoc(Op),
3594                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3595                        Ld->isVolatile(), Ld->isNonTemporal(),
3596                        Ld->isInvariant(), Ld->getAlignment());
3597 
3598   llvm_unreachable("Unknown VFP cmp argument!");
3599 }
3600 
expandf64Toi32(SDValue Op,SelectionDAG & DAG,SDValue & RetVal1,SDValue & RetVal2)3601 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3602                            SDValue &RetVal1, SDValue &RetVal2) {
3603   if (isFloatingPointZero(Op)) {
3604     RetVal1 = DAG.getConstant(0, MVT::i32);
3605     RetVal2 = DAG.getConstant(0, MVT::i32);
3606     return;
3607   }
3608 
3609   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3610     SDValue Ptr = Ld->getBasePtr();
3611     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3612                           Ld->getChain(), Ptr,
3613                           Ld->getPointerInfo(),
3614                           Ld->isVolatile(), Ld->isNonTemporal(),
3615                           Ld->isInvariant(), Ld->getAlignment());
3616 
3617     EVT PtrType = Ptr.getValueType();
3618     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3619     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3620                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3621     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3622                           Ld->getChain(), NewPtr,
3623                           Ld->getPointerInfo().getWithOffset(4),
3624                           Ld->isVolatile(), Ld->isNonTemporal(),
3625                           Ld->isInvariant(), NewAlign);
3626     return;
3627   }
3628 
3629   llvm_unreachable("Unknown VFP cmp argument!");
3630 }
3631 
3632 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3633 /// f32 and even f64 comparisons to integer ones.
3634 SDValue
OptimizeVFPBrcond(SDValue Op,SelectionDAG & DAG) const3635 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3636   SDValue Chain = Op.getOperand(0);
3637   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3638   SDValue LHS = Op.getOperand(2);
3639   SDValue RHS = Op.getOperand(3);
3640   SDValue Dest = Op.getOperand(4);
3641   SDLoc dl(Op);
3642 
3643   bool LHSSeenZero = false;
3644   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3645   bool RHSSeenZero = false;
3646   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3647   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3648     // If unsafe fp math optimization is enabled and there are no other uses of
3649     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3650     // to an integer comparison.
3651     if (CC == ISD::SETOEQ)
3652       CC = ISD::SETEQ;
3653     else if (CC == ISD::SETUNE)
3654       CC = ISD::SETNE;
3655 
3656     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3657     SDValue ARMcc;
3658     if (LHS.getValueType() == MVT::f32) {
3659       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3660                         bitcastf32Toi32(LHS, DAG), Mask);
3661       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3662                         bitcastf32Toi32(RHS, DAG), Mask);
3663       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3664       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3665       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3666                          Chain, Dest, ARMcc, CCR, Cmp);
3667     }
3668 
3669     SDValue LHS1, LHS2;
3670     SDValue RHS1, RHS2;
3671     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3672     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3673     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3674     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3675     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3676     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3677     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3678     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3679     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3680   }
3681 
3682   return SDValue();
3683 }
3684 
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const3685 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3686   SDValue Chain = Op.getOperand(0);
3687   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3688   SDValue LHS = Op.getOperand(2);
3689   SDValue RHS = Op.getOperand(3);
3690   SDValue Dest = Op.getOperand(4);
3691   SDLoc dl(Op);
3692 
3693   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3694     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3695                                                     dl);
3696 
3697     // If softenSetCCOperands only returned one value, we should compare it to
3698     // zero.
3699     if (!RHS.getNode()) {
3700       RHS = DAG.getConstant(0, LHS.getValueType());
3701       CC = ISD::SETNE;
3702     }
3703   }
3704 
3705   if (LHS.getValueType() == MVT::i32) {
3706     SDValue ARMcc;
3707     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3708     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3709     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3710                        Chain, Dest, ARMcc, CCR, Cmp);
3711   }
3712 
3713   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3714 
3715   if (getTargetMachine().Options.UnsafeFPMath &&
3716       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3717        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3718     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3719     if (Result.getNode())
3720       return Result;
3721   }
3722 
3723   ARMCC::CondCodes CondCode, CondCode2;
3724   FPCCToARMCC(CC, CondCode, CondCode2);
3725 
3726   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3727   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3728   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3729   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3730   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3731   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3732   if (CondCode2 != ARMCC::AL) {
3733     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3734     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3735     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3736   }
3737   return Res;
3738 }
3739 
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const3740 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3741   SDValue Chain = Op.getOperand(0);
3742   SDValue Table = Op.getOperand(1);
3743   SDValue Index = Op.getOperand(2);
3744   SDLoc dl(Op);
3745 
3746   EVT PTy = getPointerTy();
3747   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3748   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3749   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3750   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3751   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3752   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3753   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3754   if (Subtarget->isThumb2()) {
3755     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3756     // which does another jump to the destination. This also makes it easier
3757     // to translate it to TBB / TBH later.
3758     // FIXME: This might not work if the function is extremely large.
3759     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3760                        Addr, Op.getOperand(2), JTI, UId);
3761   }
3762   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3763     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3764                        MachinePointerInfo::getJumpTable(),
3765                        false, false, false, 0);
3766     Chain = Addr.getValue(1);
3767     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3768     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3769   } else {
3770     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3771                        MachinePointerInfo::getJumpTable(),
3772                        false, false, false, 0);
3773     Chain = Addr.getValue(1);
3774     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3775   }
3776 }
3777 
LowerVectorFP_TO_INT(SDValue Op,SelectionDAG & DAG)3778 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3779   EVT VT = Op.getValueType();
3780   SDLoc dl(Op);
3781 
3782   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3783     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3784       return Op;
3785     return DAG.UnrollVectorOp(Op.getNode());
3786   }
3787 
3788   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3789          "Invalid type for custom lowering!");
3790   if (VT != MVT::v4i16)
3791     return DAG.UnrollVectorOp(Op.getNode());
3792 
3793   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3794   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3795 }
3796 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const3797 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3798   EVT VT = Op.getValueType();
3799   if (VT.isVector())
3800     return LowerVectorFP_TO_INT(Op, DAG);
3801   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3802     RTLIB::Libcall LC;
3803     if (Op.getOpcode() == ISD::FP_TO_SINT)
3804       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3805                               Op.getValueType());
3806     else
3807       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3808                               Op.getValueType());
3809     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3810                        /*isSigned*/ false, SDLoc(Op)).first;
3811   }
3812 
3813   return Op;
3814 }
3815 
LowerVectorINT_TO_FP(SDValue Op,SelectionDAG & DAG)3816 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3817   EVT VT = Op.getValueType();
3818   SDLoc dl(Op);
3819 
3820   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3821     if (VT.getVectorElementType() == MVT::f32)
3822       return Op;
3823     return DAG.UnrollVectorOp(Op.getNode());
3824   }
3825 
3826   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3827          "Invalid type for custom lowering!");
3828   if (VT != MVT::v4f32)
3829     return DAG.UnrollVectorOp(Op.getNode());
3830 
3831   unsigned CastOpc;
3832   unsigned Opc;
3833   switch (Op.getOpcode()) {
3834   default: llvm_unreachable("Invalid opcode!");
3835   case ISD::SINT_TO_FP:
3836     CastOpc = ISD::SIGN_EXTEND;
3837     Opc = ISD::SINT_TO_FP;
3838     break;
3839   case ISD::UINT_TO_FP:
3840     CastOpc = ISD::ZERO_EXTEND;
3841     Opc = ISD::UINT_TO_FP;
3842     break;
3843   }
3844 
3845   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3846   return DAG.getNode(Opc, dl, VT, Op);
3847 }
3848 
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG) const3849 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3850   EVT VT = Op.getValueType();
3851   if (VT.isVector())
3852     return LowerVectorINT_TO_FP(Op, DAG);
3853   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3854     RTLIB::Libcall LC;
3855     if (Op.getOpcode() == ISD::SINT_TO_FP)
3856       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3857                               Op.getValueType());
3858     else
3859       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3860                               Op.getValueType());
3861     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3862                        /*isSigned*/ false, SDLoc(Op)).first;
3863   }
3864 
3865   return Op;
3866 }
3867 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const3868 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3869   // Implement fcopysign with a fabs and a conditional fneg.
3870   SDValue Tmp0 = Op.getOperand(0);
3871   SDValue Tmp1 = Op.getOperand(1);
3872   SDLoc dl(Op);
3873   EVT VT = Op.getValueType();
3874   EVT SrcVT = Tmp1.getValueType();
3875   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3876     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3877   bool UseNEON = !InGPR && Subtarget->hasNEON();
3878 
3879   if (UseNEON) {
3880     // Use VBSL to copy the sign bit.
3881     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3882     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3883                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3884     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3885     if (VT == MVT::f64)
3886       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3887                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3888                          DAG.getConstant(32, MVT::i32));
3889     else /*if (VT == MVT::f32)*/
3890       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3891     if (SrcVT == MVT::f32) {
3892       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3893       if (VT == MVT::f64)
3894         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3895                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3896                            DAG.getConstant(32, MVT::i32));
3897     } else if (VT == MVT::f32)
3898       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3899                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3900                          DAG.getConstant(32, MVT::i32));
3901     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3902     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3903 
3904     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3905                                             MVT::i32);
3906     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3907     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3908                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3909 
3910     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3911                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3912                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3913     if (VT == MVT::f32) {
3914       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3915       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3916                         DAG.getConstant(0, MVT::i32));
3917     } else {
3918       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3919     }
3920 
3921     return Res;
3922   }
3923 
3924   // Bitcast operand 1 to i32.
3925   if (SrcVT == MVT::f64)
3926     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3927                        Tmp1).getValue(1);
3928   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3929 
3930   // Or in the signbit with integer operations.
3931   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3932   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3933   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3934   if (VT == MVT::f32) {
3935     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3936                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3937     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3938                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3939   }
3940 
3941   // f64: Or the high part with signbit and then combine two parts.
3942   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3943                      Tmp0);
3944   SDValue Lo = Tmp0.getValue(0);
3945   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3946   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3947   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3948 }
3949 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const3950 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3951   MachineFunction &MF = DAG.getMachineFunction();
3952   MachineFrameInfo *MFI = MF.getFrameInfo();
3953   MFI->setReturnAddressIsTaken(true);
3954 
3955   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3956     return SDValue();
3957 
3958   EVT VT = Op.getValueType();
3959   SDLoc dl(Op);
3960   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3961   if (Depth) {
3962     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3963     SDValue Offset = DAG.getConstant(4, MVT::i32);
3964     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3965                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3966                        MachinePointerInfo(), false, false, false, 0);
3967   }
3968 
3969   // Return LR, which contains the return address. Mark it an implicit live-in.
3970   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3971   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3972 }
3973 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const3974 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3975   const ARMBaseRegisterInfo &ARI =
3976     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3977   MachineFunction &MF = DAG.getMachineFunction();
3978   MachineFrameInfo *MFI = MF.getFrameInfo();
3979   MFI->setFrameAddressIsTaken(true);
3980 
3981   EVT VT = Op.getValueType();
3982   SDLoc dl(Op);  // FIXME probably not meaningful
3983   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3984   unsigned FrameReg = ARI.getFrameRegister(MF);
3985   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3986   while (Depth--)
3987     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3988                             MachinePointerInfo(),
3989                             false, false, false, 0);
3990   return FrameAddr;
3991 }
3992 
3993 // FIXME? Maybe this could be a TableGen attribute on some registers and
3994 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,EVT VT) const3995 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3996                                               EVT VT) const {
3997   unsigned Reg = StringSwitch<unsigned>(RegName)
3998                        .Case("sp", ARM::SP)
3999                        .Default(0);
4000   if (Reg)
4001     return Reg;
4002   report_fatal_error("Invalid register name global variable");
4003 }
4004 
4005 /// ExpandBITCAST - If the target supports VFP, this function is called to
4006 /// expand a bit convert where either the source or destination type is i64 to
4007 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4008 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4009 /// vectors), since the legalizer won't know what to do with that.
ExpandBITCAST(SDNode * N,SelectionDAG & DAG)4010 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4012   SDLoc dl(N);
4013   SDValue Op = N->getOperand(0);
4014 
4015   // This function is only supposed to be called for i64 types, either as the
4016   // source or destination of the bit convert.
4017   EVT SrcVT = Op.getValueType();
4018   EVT DstVT = N->getValueType(0);
4019   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4020          "ExpandBITCAST called for non-i64 type");
4021 
4022   // Turn i64->f64 into VMOVDRR.
4023   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4024     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4025                              DAG.getConstant(0, MVT::i32));
4026     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4027                              DAG.getConstant(1, MVT::i32));
4028     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4029                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4030   }
4031 
4032   // Turn f64->i64 into VMOVRRD.
4033   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4034     SDValue Cvt;
4035     if (TLI.isBigEndian() && SrcVT.isVector() &&
4036         SrcVT.getVectorNumElements() > 1)
4037       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4038                         DAG.getVTList(MVT::i32, MVT::i32),
4039                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4040     else
4041       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4042                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4043     // Merge the pieces into a single i64 value.
4044     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4045   }
4046 
4047   return SDValue();
4048 }
4049 
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4051 /// Zero vectors are used to represent vector negation and in those cases
4052 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4053 /// not support i64 elements, so sometimes the zero vectors will need to be
4054 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4055 /// zero vector.
getZeroVector(EVT VT,SelectionDAG & DAG,SDLoc dl)4056 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4057   assert(VT.isVector() && "Expected a vector type");
4058   // The canonical modified immediate encoding of a zero vector is....0!
4059   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4060   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4061   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4062   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4063 }
4064 
4065 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4066 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftRightParts(SDValue Op,SelectionDAG & DAG) const4067 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4068                                                 SelectionDAG &DAG) const {
4069   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4070   EVT VT = Op.getValueType();
4071   unsigned VTBits = VT.getSizeInBits();
4072   SDLoc dl(Op);
4073   SDValue ShOpLo = Op.getOperand(0);
4074   SDValue ShOpHi = Op.getOperand(1);
4075   SDValue ShAmt  = Op.getOperand(2);
4076   SDValue ARMcc;
4077   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4078 
4079   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4080 
4081   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4082                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4083   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4084   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4085                                    DAG.getConstant(VTBits, MVT::i32));
4086   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4087   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4088   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4089 
4090   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4091   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4092                           ARMcc, DAG, dl);
4093   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4094   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4095                            CCR, Cmp);
4096 
4097   SDValue Ops[2] = { Lo, Hi };
4098   return DAG.getMergeValues(Ops, dl);
4099 }
4100 
4101 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4102 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftLeftParts(SDValue Op,SelectionDAG & DAG) const4103 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4104                                                SelectionDAG &DAG) const {
4105   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4106   EVT VT = Op.getValueType();
4107   unsigned VTBits = VT.getSizeInBits();
4108   SDLoc dl(Op);
4109   SDValue ShOpLo = Op.getOperand(0);
4110   SDValue ShOpHi = Op.getOperand(1);
4111   SDValue ShAmt  = Op.getOperand(2);
4112   SDValue ARMcc;
4113 
4114   assert(Op.getOpcode() == ISD::SHL_PARTS);
4115   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4116                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4117   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4118   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4119                                    DAG.getConstant(VTBits, MVT::i32));
4120   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4121   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4122 
4123   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4124   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4125   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4126                           ARMcc, DAG, dl);
4127   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4128   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4129                            CCR, Cmp);
4130 
4131   SDValue Ops[2] = { Lo, Hi };
4132   return DAG.getMergeValues(Ops, dl);
4133 }
4134 
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const4135 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4136                                             SelectionDAG &DAG) const {
4137   // The rounding mode is in bits 23:22 of the FPSCR.
4138   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4139   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4140   // so that the shift + and get folded into a bitfield extract.
4141   SDLoc dl(Op);
4142   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4143                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4144                                               MVT::i32));
4145   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4146                                   DAG.getConstant(1U << 22, MVT::i32));
4147   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4148                               DAG.getConstant(22, MVT::i32));
4149   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4150                      DAG.getConstant(3, MVT::i32));
4151 }
4152 
LowerCTTZ(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4153 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4154                          const ARMSubtarget *ST) {
4155   EVT VT = N->getValueType(0);
4156   SDLoc dl(N);
4157 
4158   if (!ST->hasV6T2Ops())
4159     return SDValue();
4160 
4161   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4162   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4163 }
4164 
4165 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4166 /// for each 16-bit element from operand, repeated.  The basic idea is to
4167 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4168 ///
4169 /// Trace for v4i16:
4170 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4171 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4172 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4173 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4174 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4175 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4176 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4177 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
getCTPOP16BitCounts(SDNode * N,SelectionDAG & DAG)4178 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4179   EVT VT = N->getValueType(0);
4180   SDLoc DL(N);
4181 
4182   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4183   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4184   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4185   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4186   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4187   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4188 }
4189 
4190 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4191 /// bit-count for each 16-bit element from the operand.  We need slightly
4192 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4193 /// 64/128-bit registers.
4194 ///
4195 /// Trace for v4i16:
4196 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4197 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4198 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4199 /// v4i16:Extracted = [k0    k1    k2    k3    ]
lowerCTPOP16BitElements(SDNode * N,SelectionDAG & DAG)4200 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4201   EVT VT = N->getValueType(0);
4202   SDLoc DL(N);
4203 
4204   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4205   if (VT.is64BitVector()) {
4206     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4207     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4208                        DAG.getIntPtrConstant(0));
4209   } else {
4210     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4211                                     BitCounts, DAG.getIntPtrConstant(0));
4212     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4213   }
4214 }
4215 
4216 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4217 /// bit-count for each 32-bit element from the operand.  The idea here is
4218 /// to split the vector into 16-bit elements, leverage the 16-bit count
4219 /// routine, and then combine the results.
4220 ///
4221 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4222 /// input    = [v0    v1    ] (vi: 32-bit elements)
4223 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4224 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4225 /// vrev: N0 = [k1 k0 k3 k2 ]
4226 ///            [k0 k1 k2 k3 ]
4227 ///       N1 =+[k1 k0 k3 k2 ]
4228 ///            [k0 k2 k1 k3 ]
4229 ///       N2 =+[k1 k3 k0 k2 ]
4230 ///            [k0    k2    k1    k3    ]
4231 /// Extended =+[k1    k3    k0    k2    ]
4232 ///            [k0    k2    ]
4233 /// Extracted=+[k1    k3    ]
4234 ///
lowerCTPOP32BitElements(SDNode * N,SelectionDAG & DAG)4235 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4236   EVT VT = N->getValueType(0);
4237   SDLoc DL(N);
4238 
4239   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4240 
4241   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4242   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4243   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4244   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4245   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4246 
4247   if (VT.is64BitVector()) {
4248     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4249     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4250                        DAG.getIntPtrConstant(0));
4251   } else {
4252     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4253                                     DAG.getIntPtrConstant(0));
4254     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4255   }
4256 }
4257 
LowerCTPOP(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4258 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4259                           const ARMSubtarget *ST) {
4260   EVT VT = N->getValueType(0);
4261 
4262   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4263   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4264           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4265          "Unexpected type for custom ctpop lowering");
4266 
4267   if (VT.getVectorElementType() == MVT::i32)
4268     return lowerCTPOP32BitElements(N, DAG);
4269   else
4270     return lowerCTPOP16BitElements(N, DAG);
4271 }
4272 
LowerShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4273 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4274                           const ARMSubtarget *ST) {
4275   EVT VT = N->getValueType(0);
4276   SDLoc dl(N);
4277 
4278   if (!VT.isVector())
4279     return SDValue();
4280 
4281   // Lower vector shifts on NEON to use VSHL.
4282   assert(ST->hasNEON() && "unexpected vector shift");
4283 
4284   // Left shifts translate directly to the vshiftu intrinsic.
4285   if (N->getOpcode() == ISD::SHL)
4286     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4287                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4288                        N->getOperand(0), N->getOperand(1));
4289 
4290   assert((N->getOpcode() == ISD::SRA ||
4291           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4292 
4293   // NEON uses the same intrinsics for both left and right shifts.  For
4294   // right shifts, the shift amounts are negative, so negate the vector of
4295   // shift amounts.
4296   EVT ShiftVT = N->getOperand(1).getValueType();
4297   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4298                                      getZeroVector(ShiftVT, DAG, dl),
4299                                      N->getOperand(1));
4300   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4301                              Intrinsic::arm_neon_vshifts :
4302                              Intrinsic::arm_neon_vshiftu);
4303   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4304                      DAG.getConstant(vshiftInt, MVT::i32),
4305                      N->getOperand(0), NegatedCount);
4306 }
4307 
Expand64BitShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4308 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4309                                 const ARMSubtarget *ST) {
4310   EVT VT = N->getValueType(0);
4311   SDLoc dl(N);
4312 
4313   // We can get here for a node like i32 = ISD::SHL i32, i64
4314   if (VT != MVT::i64)
4315     return SDValue();
4316 
4317   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4318          "Unknown shift to lower!");
4319 
4320   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4321   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4322       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4323     return SDValue();
4324 
4325   // If we are in thumb mode, we don't have RRX.
4326   if (ST->isThumb1Only()) return SDValue();
4327 
4328   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4329   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4330                            DAG.getConstant(0, MVT::i32));
4331   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4332                            DAG.getConstant(1, MVT::i32));
4333 
4334   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4335   // captures the result into a carry flag.
4336   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4337   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4338 
4339   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4340   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4341 
4342   // Merge the pieces into a single i64 value.
4343  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4344 }
4345 
LowerVSETCC(SDValue Op,SelectionDAG & DAG)4346 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4347   SDValue TmpOp0, TmpOp1;
4348   bool Invert = false;
4349   bool Swap = false;
4350   unsigned Opc = 0;
4351 
4352   SDValue Op0 = Op.getOperand(0);
4353   SDValue Op1 = Op.getOperand(1);
4354   SDValue CC = Op.getOperand(2);
4355   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4356   EVT VT = Op.getValueType();
4357   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4358   SDLoc dl(Op);
4359 
4360   if (Op1.getValueType().isFloatingPoint()) {
4361     switch (SetCCOpcode) {
4362     default: llvm_unreachable("Illegal FP comparison");
4363     case ISD::SETUNE:
4364     case ISD::SETNE:  Invert = true; // Fallthrough
4365     case ISD::SETOEQ:
4366     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4367     case ISD::SETOLT:
4368     case ISD::SETLT: Swap = true; // Fallthrough
4369     case ISD::SETOGT:
4370     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4371     case ISD::SETOLE:
4372     case ISD::SETLE:  Swap = true; // Fallthrough
4373     case ISD::SETOGE:
4374     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4375     case ISD::SETUGE: Swap = true; // Fallthrough
4376     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4377     case ISD::SETUGT: Swap = true; // Fallthrough
4378     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4379     case ISD::SETUEQ: Invert = true; // Fallthrough
4380     case ISD::SETONE:
4381       // Expand this to (OLT | OGT).
4382       TmpOp0 = Op0;
4383       TmpOp1 = Op1;
4384       Opc = ISD::OR;
4385       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4386       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4387       break;
4388     case ISD::SETUO: Invert = true; // Fallthrough
4389     case ISD::SETO:
4390       // Expand this to (OLT | OGE).
4391       TmpOp0 = Op0;
4392       TmpOp1 = Op1;
4393       Opc = ISD::OR;
4394       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4395       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4396       break;
4397     }
4398   } else {
4399     // Integer comparisons.
4400     switch (SetCCOpcode) {
4401     default: llvm_unreachable("Illegal integer comparison");
4402     case ISD::SETNE:  Invert = true;
4403     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4404     case ISD::SETLT:  Swap = true;
4405     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4406     case ISD::SETLE:  Swap = true;
4407     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4408     case ISD::SETULT: Swap = true;
4409     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4410     case ISD::SETULE: Swap = true;
4411     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4412     }
4413 
4414     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4415     if (Opc == ARMISD::VCEQ) {
4416 
4417       SDValue AndOp;
4418       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4419         AndOp = Op0;
4420       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4421         AndOp = Op1;
4422 
4423       // Ignore bitconvert.
4424       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4425         AndOp = AndOp.getOperand(0);
4426 
4427       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4428         Opc = ARMISD::VTST;
4429         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4430         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4431         Invert = !Invert;
4432       }
4433     }
4434   }
4435 
4436   if (Swap)
4437     std::swap(Op0, Op1);
4438 
4439   // If one of the operands is a constant vector zero, attempt to fold the
4440   // comparison to a specialized compare-against-zero form.
4441   SDValue SingleOp;
4442   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4443     SingleOp = Op0;
4444   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4445     if (Opc == ARMISD::VCGE)
4446       Opc = ARMISD::VCLEZ;
4447     else if (Opc == ARMISD::VCGT)
4448       Opc = ARMISD::VCLTZ;
4449     SingleOp = Op1;
4450   }
4451 
4452   SDValue Result;
4453   if (SingleOp.getNode()) {
4454     switch (Opc) {
4455     case ARMISD::VCEQ:
4456       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4457     case ARMISD::VCGE:
4458       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4459     case ARMISD::VCLEZ:
4460       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4461     case ARMISD::VCGT:
4462       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4463     case ARMISD::VCLTZ:
4464       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4465     default:
4466       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4467     }
4468   } else {
4469      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4470   }
4471 
4472   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4473 
4474   if (Invert)
4475     Result = DAG.getNOT(dl, Result, VT);
4476 
4477   return Result;
4478 }
4479 
4480 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4481 /// valid vector constant for a NEON instruction with a "modified immediate"
4482 /// operand (e.g., VMOV).  If so, return the encoded value.
isNEONModifiedImm(uint64_t SplatBits,uint64_t SplatUndef,unsigned SplatBitSize,SelectionDAG & DAG,EVT & VT,bool is128Bits,NEONModImmType type)4483 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4484                                  unsigned SplatBitSize, SelectionDAG &DAG,
4485                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4486   unsigned OpCmode, Imm;
4487 
4488   // SplatBitSize is set to the smallest size that splats the vector, so a
4489   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4490   // immediate instructions others than VMOV do not support the 8-bit encoding
4491   // of a zero vector, and the default encoding of zero is supposed to be the
4492   // 32-bit version.
4493   if (SplatBits == 0)
4494     SplatBitSize = 32;
4495 
4496   switch (SplatBitSize) {
4497   case 8:
4498     if (type != VMOVModImm)
4499       return SDValue();
4500     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4501     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4502     OpCmode = 0xe;
4503     Imm = SplatBits;
4504     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4505     break;
4506 
4507   case 16:
4508     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4509     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4510     if ((SplatBits & ~0xff) == 0) {
4511       // Value = 0x00nn: Op=x, Cmode=100x.
4512       OpCmode = 0x8;
4513       Imm = SplatBits;
4514       break;
4515     }
4516     if ((SplatBits & ~0xff00) == 0) {
4517       // Value = 0xnn00: Op=x, Cmode=101x.
4518       OpCmode = 0xa;
4519       Imm = SplatBits >> 8;
4520       break;
4521     }
4522     return SDValue();
4523 
4524   case 32:
4525     // NEON's 32-bit VMOV supports splat values where:
4526     // * only one byte is nonzero, or
4527     // * the least significant byte is 0xff and the second byte is nonzero, or
4528     // * the least significant 2 bytes are 0xff and the third is nonzero.
4529     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4530     if ((SplatBits & ~0xff) == 0) {
4531       // Value = 0x000000nn: Op=x, Cmode=000x.
4532       OpCmode = 0;
4533       Imm = SplatBits;
4534       break;
4535     }
4536     if ((SplatBits & ~0xff00) == 0) {
4537       // Value = 0x0000nn00: Op=x, Cmode=001x.
4538       OpCmode = 0x2;
4539       Imm = SplatBits >> 8;
4540       break;
4541     }
4542     if ((SplatBits & ~0xff0000) == 0) {
4543       // Value = 0x00nn0000: Op=x, Cmode=010x.
4544       OpCmode = 0x4;
4545       Imm = SplatBits >> 16;
4546       break;
4547     }
4548     if ((SplatBits & ~0xff000000) == 0) {
4549       // Value = 0xnn000000: Op=x, Cmode=011x.
4550       OpCmode = 0x6;
4551       Imm = SplatBits >> 24;
4552       break;
4553     }
4554 
4555     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4556     if (type == OtherModImm) return SDValue();
4557 
4558     if ((SplatBits & ~0xffff) == 0 &&
4559         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4560       // Value = 0x0000nnff: Op=x, Cmode=1100.
4561       OpCmode = 0xc;
4562       Imm = SplatBits >> 8;
4563       break;
4564     }
4565 
4566     if ((SplatBits & ~0xffffff) == 0 &&
4567         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4568       // Value = 0x00nnffff: Op=x, Cmode=1101.
4569       OpCmode = 0xd;
4570       Imm = SplatBits >> 16;
4571       break;
4572     }
4573 
4574     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4575     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4576     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4577     // and fall through here to test for a valid 64-bit splat.  But, then the
4578     // caller would also need to check and handle the change in size.
4579     return SDValue();
4580 
4581   case 64: {
4582     if (type != VMOVModImm)
4583       return SDValue();
4584     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4585     uint64_t BitMask = 0xff;
4586     uint64_t Val = 0;
4587     unsigned ImmMask = 1;
4588     Imm = 0;
4589     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4590       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4591         Val |= BitMask;
4592         Imm |= ImmMask;
4593       } else if ((SplatBits & BitMask) != 0) {
4594         return SDValue();
4595       }
4596       BitMask <<= 8;
4597       ImmMask <<= 1;
4598     }
4599 
4600     if (DAG.getTargetLoweringInfo().isBigEndian())
4601       // swap higher and lower 32 bit word
4602       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4603 
4604     // Op=1, Cmode=1110.
4605     OpCmode = 0x1e;
4606     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4607     break;
4608   }
4609 
4610   default:
4611     llvm_unreachable("unexpected size for isNEONModifiedImm");
4612   }
4613 
4614   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4615   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4616 }
4617 
LowerConstantFP(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const4618 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4619                                            const ARMSubtarget *ST) const {
4620   if (!ST->hasVFP3())
4621     return SDValue();
4622 
4623   bool IsDouble = Op.getValueType() == MVT::f64;
4624   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4625 
4626   // Use the default (constant pool) lowering for double constants when we have
4627   // an SP-only FPU
4628   if (IsDouble && Subtarget->isFPOnlySP())
4629     return SDValue();
4630 
4631   // Try splatting with a VMOV.f32...
4632   APFloat FPVal = CFP->getValueAPF();
4633   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4634 
4635   if (ImmVal != -1) {
4636     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4637       // We have code in place to select a valid ConstantFP already, no need to
4638       // do any mangling.
4639       return Op;
4640     }
4641 
4642     // It's a float and we are trying to use NEON operations where
4643     // possible. Lower it to a splat followed by an extract.
4644     SDLoc DL(Op);
4645     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4646     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4647                                       NewVal);
4648     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4649                        DAG.getConstant(0, MVT::i32));
4650   }
4651 
4652   // The rest of our options are NEON only, make sure that's allowed before
4653   // proceeding..
4654   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4655     return SDValue();
4656 
4657   EVT VMovVT;
4658   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4659 
4660   // It wouldn't really be worth bothering for doubles except for one very
4661   // important value, which does happen to match: 0.0. So make sure we don't do
4662   // anything stupid.
4663   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4664     return SDValue();
4665 
4666   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4667   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4668                                      false, VMOVModImm);
4669   if (NewVal != SDValue()) {
4670     SDLoc DL(Op);
4671     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4672                                       NewVal);
4673     if (IsDouble)
4674       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4675 
4676     // It's a float: cast and extract a vector element.
4677     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4678                                        VecConstant);
4679     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4680                        DAG.getConstant(0, MVT::i32));
4681   }
4682 
4683   // Finally, try a VMVN.i32
4684   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4685                              false, VMVNModImm);
4686   if (NewVal != SDValue()) {
4687     SDLoc DL(Op);
4688     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4689 
4690     if (IsDouble)
4691       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4692 
4693     // It's a float: cast and extract a vector element.
4694     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4695                                        VecConstant);
4696     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4697                        DAG.getConstant(0, MVT::i32));
4698   }
4699 
4700   return SDValue();
4701 }
4702 
4703 // check if an VEXT instruction can handle the shuffle mask when the
4704 // vector sources of the shuffle are the same.
isSingletonVEXTMask(ArrayRef<int> M,EVT VT,unsigned & Imm)4705 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4706   unsigned NumElts = VT.getVectorNumElements();
4707 
4708   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4709   if (M[0] < 0)
4710     return false;
4711 
4712   Imm = M[0];
4713 
4714   // If this is a VEXT shuffle, the immediate value is the index of the first
4715   // element.  The other shuffle indices must be the successive elements after
4716   // the first one.
4717   unsigned ExpectedElt = Imm;
4718   for (unsigned i = 1; i < NumElts; ++i) {
4719     // Increment the expected index.  If it wraps around, just follow it
4720     // back to index zero and keep going.
4721     ++ExpectedElt;
4722     if (ExpectedElt == NumElts)
4723       ExpectedElt = 0;
4724 
4725     if (M[i] < 0) continue; // ignore UNDEF indices
4726     if (ExpectedElt != static_cast<unsigned>(M[i]))
4727       return false;
4728   }
4729 
4730   return true;
4731 }
4732 
4733 
isVEXTMask(ArrayRef<int> M,EVT VT,bool & ReverseVEXT,unsigned & Imm)4734 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4735                        bool &ReverseVEXT, unsigned &Imm) {
4736   unsigned NumElts = VT.getVectorNumElements();
4737   ReverseVEXT = false;
4738 
4739   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4740   if (M[0] < 0)
4741     return false;
4742 
4743   Imm = M[0];
4744 
4745   // If this is a VEXT shuffle, the immediate value is the index of the first
4746   // element.  The other shuffle indices must be the successive elements after
4747   // the first one.
4748   unsigned ExpectedElt = Imm;
4749   for (unsigned i = 1; i < NumElts; ++i) {
4750     // Increment the expected index.  If it wraps around, it may still be
4751     // a VEXT but the source vectors must be swapped.
4752     ExpectedElt += 1;
4753     if (ExpectedElt == NumElts * 2) {
4754       ExpectedElt = 0;
4755       ReverseVEXT = true;
4756     }
4757 
4758     if (M[i] < 0) continue; // ignore UNDEF indices
4759     if (ExpectedElt != static_cast<unsigned>(M[i]))
4760       return false;
4761   }
4762 
4763   // Adjust the index value if the source operands will be swapped.
4764   if (ReverseVEXT)
4765     Imm -= NumElts;
4766 
4767   return true;
4768 }
4769 
4770 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4771 /// instruction with the specified blocksize.  (The order of the elements
4772 /// within each block of the vector is reversed.)
isVREVMask(ArrayRef<int> M,EVT VT,unsigned BlockSize)4773 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4774   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4775          "Only possible block sizes for VREV are: 16, 32, 64");
4776 
4777   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4778   if (EltSz == 64)
4779     return false;
4780 
4781   unsigned NumElts = VT.getVectorNumElements();
4782   unsigned BlockElts = M[0] + 1;
4783   // If the first shuffle index is UNDEF, be optimistic.
4784   if (M[0] < 0)
4785     BlockElts = BlockSize / EltSz;
4786 
4787   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4788     return false;
4789 
4790   for (unsigned i = 0; i < NumElts; ++i) {
4791     if (M[i] < 0) continue; // ignore UNDEF indices
4792     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4793       return false;
4794   }
4795 
4796   return true;
4797 }
4798 
isVTBLMask(ArrayRef<int> M,EVT VT)4799 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4800   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4801   // range, then 0 is placed into the resulting vector. So pretty much any mask
4802   // of 8 elements can work here.
4803   return VT == MVT::v8i8 && M.size() == 8;
4804 }
4805 
isVTRNMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4806 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4807   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4808   if (EltSz == 64)
4809     return false;
4810 
4811   unsigned NumElts = VT.getVectorNumElements();
4812   WhichResult = (M[0] == 0 ? 0 : 1);
4813   for (unsigned i = 0; i < NumElts; i += 2) {
4814     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4815         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4816       return false;
4817   }
4818   return true;
4819 }
4820 
4821 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4822 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4823 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
isVTRN_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4824 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4825   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4826   if (EltSz == 64)
4827     return false;
4828 
4829   unsigned NumElts = VT.getVectorNumElements();
4830   WhichResult = (M[0] == 0 ? 0 : 1);
4831   for (unsigned i = 0; i < NumElts; i += 2) {
4832     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4833         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4834       return false;
4835   }
4836   return true;
4837 }
4838 
isVUZPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4839 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4840   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4841   if (EltSz == 64)
4842     return false;
4843 
4844   unsigned NumElts = VT.getVectorNumElements();
4845   WhichResult = (M[0] == 0 ? 0 : 1);
4846   for (unsigned i = 0; i != NumElts; ++i) {
4847     if (M[i] < 0) continue; // ignore UNDEF indices
4848     if ((unsigned) M[i] != 2 * i + WhichResult)
4849       return false;
4850   }
4851 
4852   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4853   if (VT.is64BitVector() && EltSz == 32)
4854     return false;
4855 
4856   return true;
4857 }
4858 
4859 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4860 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4861 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
isVUZP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4862 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4863   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4864   if (EltSz == 64)
4865     return false;
4866 
4867   unsigned Half = VT.getVectorNumElements() / 2;
4868   WhichResult = (M[0] == 0 ? 0 : 1);
4869   for (unsigned j = 0; j != 2; ++j) {
4870     unsigned Idx = WhichResult;
4871     for (unsigned i = 0; i != Half; ++i) {
4872       int MIdx = M[i + j * Half];
4873       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4874         return false;
4875       Idx += 2;
4876     }
4877   }
4878 
4879   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4880   if (VT.is64BitVector() && EltSz == 32)
4881     return false;
4882 
4883   return true;
4884 }
4885 
isVZIPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4886 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4887   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4888   if (EltSz == 64)
4889     return false;
4890 
4891   unsigned NumElts = VT.getVectorNumElements();
4892   WhichResult = (M[0] == 0 ? 0 : 1);
4893   unsigned Idx = WhichResult * NumElts / 2;
4894   for (unsigned i = 0; i != NumElts; i += 2) {
4895     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4896         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4897       return false;
4898     Idx += 1;
4899   }
4900 
4901   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4902   if (VT.is64BitVector() && EltSz == 32)
4903     return false;
4904 
4905   return true;
4906 }
4907 
4908 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4909 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4910 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
isVZIP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4911 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4912   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4913   if (EltSz == 64)
4914     return false;
4915 
4916   unsigned NumElts = VT.getVectorNumElements();
4917   WhichResult = (M[0] == 0 ? 0 : 1);
4918   unsigned Idx = WhichResult * NumElts / 2;
4919   for (unsigned i = 0; i != NumElts; i += 2) {
4920     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4921         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4922       return false;
4923     Idx += 1;
4924   }
4925 
4926   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4927   if (VT.is64BitVector() && EltSz == 32)
4928     return false;
4929 
4930   return true;
4931 }
4932 
4933 /// \return true if this is a reverse operation on an vector.
isReverseMask(ArrayRef<int> M,EVT VT)4934 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4935   unsigned NumElts = VT.getVectorNumElements();
4936   // Make sure the mask has the right size.
4937   if (NumElts != M.size())
4938       return false;
4939 
4940   // Look for <15, ..., 3, -1, 1, 0>.
4941   for (unsigned i = 0; i != NumElts; ++i)
4942     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4943       return false;
4944 
4945   return true;
4946 }
4947 
4948 // If N is an integer constant that can be moved into a register in one
4949 // instruction, return an SDValue of such a constant (will become a MOV
4950 // instruction).  Otherwise return null.
IsSingleInstrConstant(SDValue N,SelectionDAG & DAG,const ARMSubtarget * ST,SDLoc dl)4951 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4952                                      const ARMSubtarget *ST, SDLoc dl) {
4953   uint64_t Val;
4954   if (!isa<ConstantSDNode>(N))
4955     return SDValue();
4956   Val = cast<ConstantSDNode>(N)->getZExtValue();
4957 
4958   if (ST->isThumb1Only()) {
4959     if (Val <= 255 || ~Val <= 255)
4960       return DAG.getConstant(Val, MVT::i32);
4961   } else {
4962     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4963       return DAG.getConstant(Val, MVT::i32);
4964   }
4965   return SDValue();
4966 }
4967 
4968 // If this is a case we can't handle, return null and let the default
4969 // expansion code take care of it.
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const4970 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4971                                              const ARMSubtarget *ST) const {
4972   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4973   SDLoc dl(Op);
4974   EVT VT = Op.getValueType();
4975 
4976   APInt SplatBits, SplatUndef;
4977   unsigned SplatBitSize;
4978   bool HasAnyUndefs;
4979   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4980     if (SplatBitSize <= 64) {
4981       // Check if an immediate VMOV works.
4982       EVT VmovVT;
4983       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4984                                       SplatUndef.getZExtValue(), SplatBitSize,
4985                                       DAG, VmovVT, VT.is128BitVector(),
4986                                       VMOVModImm);
4987       if (Val.getNode()) {
4988         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4989         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4990       }
4991 
4992       // Try an immediate VMVN.
4993       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4994       Val = isNEONModifiedImm(NegatedImm,
4995                                       SplatUndef.getZExtValue(), SplatBitSize,
4996                                       DAG, VmovVT, VT.is128BitVector(),
4997                                       VMVNModImm);
4998       if (Val.getNode()) {
4999         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5000         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5001       }
5002 
5003       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5004       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5005         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5006         if (ImmVal != -1) {
5007           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5008           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5009         }
5010       }
5011     }
5012   }
5013 
5014   // Scan through the operands to see if only one value is used.
5015   //
5016   // As an optimisation, even if more than one value is used it may be more
5017   // profitable to splat with one value then change some lanes.
5018   //
5019   // Heuristically we decide to do this if the vector has a "dominant" value,
5020   // defined as splatted to more than half of the lanes.
5021   unsigned NumElts = VT.getVectorNumElements();
5022   bool isOnlyLowElement = true;
5023   bool usesOnlyOneValue = true;
5024   bool hasDominantValue = false;
5025   bool isConstant = true;
5026 
5027   // Map of the number of times a particular SDValue appears in the
5028   // element list.
5029   DenseMap<SDValue, unsigned> ValueCounts;
5030   SDValue Value;
5031   for (unsigned i = 0; i < NumElts; ++i) {
5032     SDValue V = Op.getOperand(i);
5033     if (V.getOpcode() == ISD::UNDEF)
5034       continue;
5035     if (i > 0)
5036       isOnlyLowElement = false;
5037     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5038       isConstant = false;
5039 
5040     ValueCounts.insert(std::make_pair(V, 0));
5041     unsigned &Count = ValueCounts[V];
5042 
5043     // Is this value dominant? (takes up more than half of the lanes)
5044     if (++Count > (NumElts / 2)) {
5045       hasDominantValue = true;
5046       Value = V;
5047     }
5048   }
5049   if (ValueCounts.size() != 1)
5050     usesOnlyOneValue = false;
5051   if (!Value.getNode() && ValueCounts.size() > 0)
5052     Value = ValueCounts.begin()->first;
5053 
5054   if (ValueCounts.size() == 0)
5055     return DAG.getUNDEF(VT);
5056 
5057   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5058   // Keep going if we are hitting this case.
5059   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5060     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5061 
5062   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5063 
5064   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5065   // i32 and try again.
5066   if (hasDominantValue && EltSize <= 32) {
5067     if (!isConstant) {
5068       SDValue N;
5069 
5070       // If we are VDUPing a value that comes directly from a vector, that will
5071       // cause an unnecessary move to and from a GPR, where instead we could
5072       // just use VDUPLANE. We can only do this if the lane being extracted
5073       // is at a constant index, as the VDUP from lane instructions only have
5074       // constant-index forms.
5075       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5076           isa<ConstantSDNode>(Value->getOperand(1))) {
5077         // We need to create a new undef vector to use for the VDUPLANE if the
5078         // size of the vector from which we get the value is different than the
5079         // size of the vector that we need to create. We will insert the element
5080         // such that the register coalescer will remove unnecessary copies.
5081         if (VT != Value->getOperand(0).getValueType()) {
5082           ConstantSDNode *constIndex;
5083           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5084           assert(constIndex && "The index is not a constant!");
5085           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5086                              VT.getVectorNumElements();
5087           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5088                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5089                         Value, DAG.getConstant(index, MVT::i32)),
5090                            DAG.getConstant(index, MVT::i32));
5091         } else
5092           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5093                         Value->getOperand(0), Value->getOperand(1));
5094       } else
5095         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5096 
5097       if (!usesOnlyOneValue) {
5098         // The dominant value was splatted as 'N', but we now have to insert
5099         // all differing elements.
5100         for (unsigned I = 0; I < NumElts; ++I) {
5101           if (Op.getOperand(I) == Value)
5102             continue;
5103           SmallVector<SDValue, 3> Ops;
5104           Ops.push_back(N);
5105           Ops.push_back(Op.getOperand(I));
5106           Ops.push_back(DAG.getConstant(I, MVT::i32));
5107           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5108         }
5109       }
5110       return N;
5111     }
5112     if (VT.getVectorElementType().isFloatingPoint()) {
5113       SmallVector<SDValue, 8> Ops;
5114       for (unsigned i = 0; i < NumElts; ++i)
5115         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5116                                   Op.getOperand(i)));
5117       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5118       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5119       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5120       if (Val.getNode())
5121         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5122     }
5123     if (usesOnlyOneValue) {
5124       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5125       if (isConstant && Val.getNode())
5126         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5127     }
5128   }
5129 
5130   // If all elements are constants and the case above didn't get hit, fall back
5131   // to the default expansion, which will generate a load from the constant
5132   // pool.
5133   if (isConstant)
5134     return SDValue();
5135 
5136   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5137   if (NumElts >= 4) {
5138     SDValue shuffle = ReconstructShuffle(Op, DAG);
5139     if (shuffle != SDValue())
5140       return shuffle;
5141   }
5142 
5143   // Vectors with 32- or 64-bit elements can be built by directly assigning
5144   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5145   // will be legalized.
5146   if (EltSize >= 32) {
5147     // Do the expansion with floating-point types, since that is what the VFP
5148     // registers are defined to use, and since i64 is not legal.
5149     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5150     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5151     SmallVector<SDValue, 8> Ops;
5152     for (unsigned i = 0; i < NumElts; ++i)
5153       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5154     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5155     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5156   }
5157 
5158   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5159   // know the default expansion would otherwise fall back on something even
5160   // worse. For a vector with one or two non-undef values, that's
5161   // scalar_to_vector for the elements followed by a shuffle (provided the
5162   // shuffle is valid for the target) and materialization element by element
5163   // on the stack followed by a load for everything else.
5164   if (!isConstant && !usesOnlyOneValue) {
5165     SDValue Vec = DAG.getUNDEF(VT);
5166     for (unsigned i = 0 ; i < NumElts; ++i) {
5167       SDValue V = Op.getOperand(i);
5168       if (V.getOpcode() == ISD::UNDEF)
5169         continue;
5170       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5171       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5172     }
5173     return Vec;
5174   }
5175 
5176   return SDValue();
5177 }
5178 
5179 // Gather data to see if the operation can be modelled as a
5180 // shuffle in combination with VEXTs.
ReconstructShuffle(SDValue Op,SelectionDAG & DAG) const5181 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5182                                               SelectionDAG &DAG) const {
5183   SDLoc dl(Op);
5184   EVT VT = Op.getValueType();
5185   unsigned NumElts = VT.getVectorNumElements();
5186 
5187   SmallVector<SDValue, 2> SourceVecs;
5188   SmallVector<unsigned, 2> MinElts;
5189   SmallVector<unsigned, 2> MaxElts;
5190 
5191   for (unsigned i = 0; i < NumElts; ++i) {
5192     SDValue V = Op.getOperand(i);
5193     if (V.getOpcode() == ISD::UNDEF)
5194       continue;
5195     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5196       // A shuffle can only come from building a vector from various
5197       // elements of other vectors.
5198       return SDValue();
5199     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5200                VT.getVectorElementType()) {
5201       // This code doesn't know how to handle shuffles where the vector
5202       // element types do not match (this happens because type legalization
5203       // promotes the return type of EXTRACT_VECTOR_ELT).
5204       // FIXME: It might be appropriate to extend this code to handle
5205       // mismatched types.
5206       return SDValue();
5207     }
5208 
5209     // Record this extraction against the appropriate vector if possible...
5210     SDValue SourceVec = V.getOperand(0);
5211     // If the element number isn't a constant, we can't effectively
5212     // analyze what's going on.
5213     if (!isa<ConstantSDNode>(V.getOperand(1)))
5214       return SDValue();
5215     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5216     bool FoundSource = false;
5217     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5218       if (SourceVecs[j] == SourceVec) {
5219         if (MinElts[j] > EltNo)
5220           MinElts[j] = EltNo;
5221         if (MaxElts[j] < EltNo)
5222           MaxElts[j] = EltNo;
5223         FoundSource = true;
5224         break;
5225       }
5226     }
5227 
5228     // Or record a new source if not...
5229     if (!FoundSource) {
5230       SourceVecs.push_back(SourceVec);
5231       MinElts.push_back(EltNo);
5232       MaxElts.push_back(EltNo);
5233     }
5234   }
5235 
5236   // Currently only do something sane when at most two source vectors
5237   // involved.
5238   if (SourceVecs.size() > 2)
5239     return SDValue();
5240 
5241   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5242   int VEXTOffsets[2] = {0, 0};
5243 
5244   // This loop extracts the usage patterns of the source vectors
5245   // and prepares appropriate SDValues for a shuffle if possible.
5246   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5247     if (SourceVecs[i].getValueType() == VT) {
5248       // No VEXT necessary
5249       ShuffleSrcs[i] = SourceVecs[i];
5250       VEXTOffsets[i] = 0;
5251       continue;
5252     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5253       // It probably isn't worth padding out a smaller vector just to
5254       // break it down again in a shuffle.
5255       return SDValue();
5256     }
5257 
5258     // Since only 64-bit and 128-bit vectors are legal on ARM and
5259     // we've eliminated the other cases...
5260     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5261            "unexpected vector sizes in ReconstructShuffle");
5262 
5263     if (MaxElts[i] - MinElts[i] >= NumElts) {
5264       // Span too large for a VEXT to cope
5265       return SDValue();
5266     }
5267 
5268     if (MinElts[i] >= NumElts) {
5269       // The extraction can just take the second half
5270       VEXTOffsets[i] = NumElts;
5271       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5272                                    SourceVecs[i],
5273                                    DAG.getIntPtrConstant(NumElts));
5274     } else if (MaxElts[i] < NumElts) {
5275       // The extraction can just take the first half
5276       VEXTOffsets[i] = 0;
5277       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5278                                    SourceVecs[i],
5279                                    DAG.getIntPtrConstant(0));
5280     } else {
5281       // An actual VEXT is needed
5282       VEXTOffsets[i] = MinElts[i];
5283       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5284                                      SourceVecs[i],
5285                                      DAG.getIntPtrConstant(0));
5286       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5287                                      SourceVecs[i],
5288                                      DAG.getIntPtrConstant(NumElts));
5289       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5290                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5291     }
5292   }
5293 
5294   SmallVector<int, 8> Mask;
5295 
5296   for (unsigned i = 0; i < NumElts; ++i) {
5297     SDValue Entry = Op.getOperand(i);
5298     if (Entry.getOpcode() == ISD::UNDEF) {
5299       Mask.push_back(-1);
5300       continue;
5301     }
5302 
5303     SDValue ExtractVec = Entry.getOperand(0);
5304     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5305                                           .getOperand(1))->getSExtValue();
5306     if (ExtractVec == SourceVecs[0]) {
5307       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5308     } else {
5309       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5310     }
5311   }
5312 
5313   // Final check before we try to produce nonsense...
5314   if (isShuffleMaskLegal(Mask, VT))
5315     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5316                                 &Mask[0]);
5317 
5318   return SDValue();
5319 }
5320 
5321 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5322 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5323 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5324 /// are assumed to be legal.
5325 bool
isShuffleMaskLegal(const SmallVectorImpl<int> & M,EVT VT) const5326 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5327                                       EVT VT) const {
5328   if (VT.getVectorNumElements() == 4 &&
5329       (VT.is128BitVector() || VT.is64BitVector())) {
5330     unsigned PFIndexes[4];
5331     for (unsigned i = 0; i != 4; ++i) {
5332       if (M[i] < 0)
5333         PFIndexes[i] = 8;
5334       else
5335         PFIndexes[i] = M[i];
5336     }
5337 
5338     // Compute the index in the perfect shuffle table.
5339     unsigned PFTableIndex =
5340       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5341     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5342     unsigned Cost = (PFEntry >> 30);
5343 
5344     if (Cost <= 4)
5345       return true;
5346   }
5347 
5348   bool ReverseVEXT;
5349   unsigned Imm, WhichResult;
5350 
5351   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5352   return (EltSize >= 32 ||
5353           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5354           isVREVMask(M, VT, 64) ||
5355           isVREVMask(M, VT, 32) ||
5356           isVREVMask(M, VT, 16) ||
5357           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5358           isVTBLMask(M, VT) ||
5359           isVTRNMask(M, VT, WhichResult) ||
5360           isVUZPMask(M, VT, WhichResult) ||
5361           isVZIPMask(M, VT, WhichResult) ||
5362           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5363           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5364           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5365           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5366 }
5367 
5368 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5369 /// the specified operations to build the shuffle.
GeneratePerfectShuffle(unsigned PFEntry,SDValue LHS,SDValue RHS,SelectionDAG & DAG,SDLoc dl)5370 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5371                                       SDValue RHS, SelectionDAG &DAG,
5372                                       SDLoc dl) {
5373   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5374   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5375   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5376 
5377   enum {
5378     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5379     OP_VREV,
5380     OP_VDUP0,
5381     OP_VDUP1,
5382     OP_VDUP2,
5383     OP_VDUP3,
5384     OP_VEXT1,
5385     OP_VEXT2,
5386     OP_VEXT3,
5387     OP_VUZPL, // VUZP, left result
5388     OP_VUZPR, // VUZP, right result
5389     OP_VZIPL, // VZIP, left result
5390     OP_VZIPR, // VZIP, right result
5391     OP_VTRNL, // VTRN, left result
5392     OP_VTRNR  // VTRN, right result
5393   };
5394 
5395   if (OpNum == OP_COPY) {
5396     if (LHSID == (1*9+2)*9+3) return LHS;
5397     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5398     return RHS;
5399   }
5400 
5401   SDValue OpLHS, OpRHS;
5402   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5403   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5404   EVT VT = OpLHS.getValueType();
5405 
5406   switch (OpNum) {
5407   default: llvm_unreachable("Unknown shuffle opcode!");
5408   case OP_VREV:
5409     // VREV divides the vector in half and swaps within the half.
5410     if (VT.getVectorElementType() == MVT::i32 ||
5411         VT.getVectorElementType() == MVT::f32)
5412       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5413     // vrev <4 x i16> -> VREV32
5414     if (VT.getVectorElementType() == MVT::i16)
5415       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5416     // vrev <4 x i8> -> VREV16
5417     assert(VT.getVectorElementType() == MVT::i8);
5418     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5419   case OP_VDUP0:
5420   case OP_VDUP1:
5421   case OP_VDUP2:
5422   case OP_VDUP3:
5423     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5424                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5425   case OP_VEXT1:
5426   case OP_VEXT2:
5427   case OP_VEXT3:
5428     return DAG.getNode(ARMISD::VEXT, dl, VT,
5429                        OpLHS, OpRHS,
5430                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5431   case OP_VUZPL:
5432   case OP_VUZPR:
5433     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5434                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5435   case OP_VZIPL:
5436   case OP_VZIPR:
5437     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5438                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5439   case OP_VTRNL:
5440   case OP_VTRNR:
5441     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5442                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5443   }
5444 }
5445 
LowerVECTOR_SHUFFLEv8i8(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)5446 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5447                                        ArrayRef<int> ShuffleMask,
5448                                        SelectionDAG &DAG) {
5449   // Check to see if we can use the VTBL instruction.
5450   SDValue V1 = Op.getOperand(0);
5451   SDValue V2 = Op.getOperand(1);
5452   SDLoc DL(Op);
5453 
5454   SmallVector<SDValue, 8> VTBLMask;
5455   for (ArrayRef<int>::iterator
5456          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5457     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5458 
5459   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5460     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5461                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5462 
5463   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5464                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5465 }
5466 
LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,SelectionDAG & DAG)5467 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5468                                                       SelectionDAG &DAG) {
5469   SDLoc DL(Op);
5470   SDValue OpLHS = Op.getOperand(0);
5471   EVT VT = OpLHS.getValueType();
5472 
5473   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5474          "Expect an v8i16/v16i8 type");
5475   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5476   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5477   // extract the first 8 bytes into the top double word and the last 8 bytes
5478   // into the bottom double word. The v8i16 case is similar.
5479   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5480   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5481                      DAG.getConstant(ExtractNum, MVT::i32));
5482 }
5483 
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG)5484 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5485   SDValue V1 = Op.getOperand(0);
5486   SDValue V2 = Op.getOperand(1);
5487   SDLoc dl(Op);
5488   EVT VT = Op.getValueType();
5489   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5490 
5491   // Convert shuffles that are directly supported on NEON to target-specific
5492   // DAG nodes, instead of keeping them as shuffles and matching them again
5493   // during code selection.  This is more efficient and avoids the possibility
5494   // of inconsistencies between legalization and selection.
5495   // FIXME: floating-point vectors should be canonicalized to integer vectors
5496   // of the same time so that they get CSEd properly.
5497   ArrayRef<int> ShuffleMask = SVN->getMask();
5498 
5499   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5500   if (EltSize <= 32) {
5501     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5502       int Lane = SVN->getSplatIndex();
5503       // If this is undef splat, generate it via "just" vdup, if possible.
5504       if (Lane == -1) Lane = 0;
5505 
5506       // Test if V1 is a SCALAR_TO_VECTOR.
5507       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5508         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5509       }
5510       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5511       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5512       // reaches it).
5513       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5514           !isa<ConstantSDNode>(V1.getOperand(0))) {
5515         bool IsScalarToVector = true;
5516         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5517           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5518             IsScalarToVector = false;
5519             break;
5520           }
5521         if (IsScalarToVector)
5522           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5523       }
5524       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5525                          DAG.getConstant(Lane, MVT::i32));
5526     }
5527 
5528     bool ReverseVEXT;
5529     unsigned Imm;
5530     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5531       if (ReverseVEXT)
5532         std::swap(V1, V2);
5533       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5534                          DAG.getConstant(Imm, MVT::i32));
5535     }
5536 
5537     if (isVREVMask(ShuffleMask, VT, 64))
5538       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5539     if (isVREVMask(ShuffleMask, VT, 32))
5540       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5541     if (isVREVMask(ShuffleMask, VT, 16))
5542       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5543 
5544     if (V2->getOpcode() == ISD::UNDEF &&
5545         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5546       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5547                          DAG.getConstant(Imm, MVT::i32));
5548     }
5549 
5550     // Check for Neon shuffles that modify both input vectors in place.
5551     // If both results are used, i.e., if there are two shuffles with the same
5552     // source operands and with masks corresponding to both results of one of
5553     // these operations, DAG memoization will ensure that a single node is
5554     // used for both shuffles.
5555     unsigned WhichResult;
5556     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5557       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5558                          V1, V2).getValue(WhichResult);
5559     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5560       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5561                          V1, V2).getValue(WhichResult);
5562     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5563       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5564                          V1, V2).getValue(WhichResult);
5565 
5566     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5567       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5568                          V1, V1).getValue(WhichResult);
5569     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5570       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5571                          V1, V1).getValue(WhichResult);
5572     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5573       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5574                          V1, V1).getValue(WhichResult);
5575   }
5576 
5577   // If the shuffle is not directly supported and it has 4 elements, use
5578   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5579   unsigned NumElts = VT.getVectorNumElements();
5580   if (NumElts == 4) {
5581     unsigned PFIndexes[4];
5582     for (unsigned i = 0; i != 4; ++i) {
5583       if (ShuffleMask[i] < 0)
5584         PFIndexes[i] = 8;
5585       else
5586         PFIndexes[i] = ShuffleMask[i];
5587     }
5588 
5589     // Compute the index in the perfect shuffle table.
5590     unsigned PFTableIndex =
5591       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5592     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5593     unsigned Cost = (PFEntry >> 30);
5594 
5595     if (Cost <= 4)
5596       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5597   }
5598 
5599   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5600   if (EltSize >= 32) {
5601     // Do the expansion with floating-point types, since that is what the VFP
5602     // registers are defined to use, and since i64 is not legal.
5603     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5604     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5605     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5606     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5607     SmallVector<SDValue, 8> Ops;
5608     for (unsigned i = 0; i < NumElts; ++i) {
5609       if (ShuffleMask[i] < 0)
5610         Ops.push_back(DAG.getUNDEF(EltVT));
5611       else
5612         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5613                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5614                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5615                                                   MVT::i32)));
5616     }
5617     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5618     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5619   }
5620 
5621   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5622     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5623 
5624   if (VT == MVT::v8i8) {
5625     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5626     if (NewOp.getNode())
5627       return NewOp;
5628   }
5629 
5630   return SDValue();
5631 }
5632 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG)5633 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5634   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5635   SDValue Lane = Op.getOperand(2);
5636   if (!isa<ConstantSDNode>(Lane))
5637     return SDValue();
5638 
5639   return Op;
5640 }
5641 
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG)5642 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5643   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5644   SDValue Lane = Op.getOperand(1);
5645   if (!isa<ConstantSDNode>(Lane))
5646     return SDValue();
5647 
5648   SDValue Vec = Op.getOperand(0);
5649   if (Op.getValueType() == MVT::i32 &&
5650       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5651     SDLoc dl(Op);
5652     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5653   }
5654 
5655   return Op;
5656 }
5657 
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG)5658 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5659   // The only time a CONCAT_VECTORS operation can have legal types is when
5660   // two 64-bit vectors are concatenated to a 128-bit vector.
5661   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5662          "unexpected CONCAT_VECTORS");
5663   SDLoc dl(Op);
5664   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5665   SDValue Op0 = Op.getOperand(0);
5666   SDValue Op1 = Op.getOperand(1);
5667   if (Op0.getOpcode() != ISD::UNDEF)
5668     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5669                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5670                       DAG.getIntPtrConstant(0));
5671   if (Op1.getOpcode() != ISD::UNDEF)
5672     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5673                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5674                       DAG.getIntPtrConstant(1));
5675   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5676 }
5677 
5678 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5679 /// element has been zero/sign-extended, depending on the isSigned parameter,
5680 /// from an integer type half its size.
isExtendedBUILD_VECTOR(SDNode * N,SelectionDAG & DAG,bool isSigned)5681 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5682                                    bool isSigned) {
5683   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5684   EVT VT = N->getValueType(0);
5685   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5686     SDNode *BVN = N->getOperand(0).getNode();
5687     if (BVN->getValueType(0) != MVT::v4i32 ||
5688         BVN->getOpcode() != ISD::BUILD_VECTOR)
5689       return false;
5690     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5691     unsigned HiElt = 1 - LoElt;
5692     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5693     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5694     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5695     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5696     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5697       return false;
5698     if (isSigned) {
5699       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5700           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5701         return true;
5702     } else {
5703       if (Hi0->isNullValue() && Hi1->isNullValue())
5704         return true;
5705     }
5706     return false;
5707   }
5708 
5709   if (N->getOpcode() != ISD::BUILD_VECTOR)
5710     return false;
5711 
5712   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5713     SDNode *Elt = N->getOperand(i).getNode();
5714     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5715       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5716       unsigned HalfSize = EltSize / 2;
5717       if (isSigned) {
5718         if (!isIntN(HalfSize, C->getSExtValue()))
5719           return false;
5720       } else {
5721         if (!isUIntN(HalfSize, C->getZExtValue()))
5722           return false;
5723       }
5724       continue;
5725     }
5726     return false;
5727   }
5728 
5729   return true;
5730 }
5731 
5732 /// isSignExtended - Check if a node is a vector value that is sign-extended
5733 /// or a constant BUILD_VECTOR with sign-extended elements.
isSignExtended(SDNode * N,SelectionDAG & DAG)5734 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5735   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5736     return true;
5737   if (isExtendedBUILD_VECTOR(N, DAG, true))
5738     return true;
5739   return false;
5740 }
5741 
5742 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5743 /// or a constant BUILD_VECTOR with zero-extended elements.
isZeroExtended(SDNode * N,SelectionDAG & DAG)5744 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5745   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5746     return true;
5747   if (isExtendedBUILD_VECTOR(N, DAG, false))
5748     return true;
5749   return false;
5750 }
5751 
getExtensionTo64Bits(const EVT & OrigVT)5752 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5753   if (OrigVT.getSizeInBits() >= 64)
5754     return OrigVT;
5755 
5756   assert(OrigVT.isSimple() && "Expecting a simple value type");
5757 
5758   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5759   switch (OrigSimpleTy) {
5760   default: llvm_unreachable("Unexpected Vector Type");
5761   case MVT::v2i8:
5762   case MVT::v2i16:
5763      return MVT::v2i32;
5764   case MVT::v4i8:
5765     return  MVT::v4i16;
5766   }
5767 }
5768 
5769 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5770 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5771 /// We insert the required extension here to get the vector to fill a D register.
AddRequiredExtensionForVMULL(SDValue N,SelectionDAG & DAG,const EVT & OrigTy,const EVT & ExtTy,unsigned ExtOpcode)5772 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5773                                             const EVT &OrigTy,
5774                                             const EVT &ExtTy,
5775                                             unsigned ExtOpcode) {
5776   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5777   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5778   // 64-bits we need to insert a new extension so that it will be 64-bits.
5779   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5780   if (OrigTy.getSizeInBits() >= 64)
5781     return N;
5782 
5783   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5784   EVT NewVT = getExtensionTo64Bits(OrigTy);
5785 
5786   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5787 }
5788 
5789 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5790 /// does not do any sign/zero extension. If the original vector is less
5791 /// than 64 bits, an appropriate extension will be added after the load to
5792 /// reach a total size of 64 bits. We have to add the extension separately
5793 /// because ARM does not have a sign/zero extending load for vectors.
SkipLoadExtensionForVMULL(LoadSDNode * LD,SelectionDAG & DAG)5794 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5795   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5796 
5797   // The load already has the right type.
5798   if (ExtendedTy == LD->getMemoryVT())
5799     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5800                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5801                 LD->isNonTemporal(), LD->isInvariant(),
5802                 LD->getAlignment());
5803 
5804   // We need to create a zextload/sextload. We cannot just create a load
5805   // followed by a zext/zext node because LowerMUL is also run during normal
5806   // operation legalization where we can't create illegal types.
5807   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5808                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5809                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5810                         LD->isNonTemporal(), LD->getAlignment());
5811 }
5812 
5813 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5814 /// extending load, or BUILD_VECTOR with extended elements, return the
5815 /// unextended value. The unextended vector should be 64 bits so that it can
5816 /// be used as an operand to a VMULL instruction. If the original vector size
5817 /// before extension is less than 64 bits we add a an extension to resize
5818 /// the vector to 64 bits.
SkipExtensionForVMULL(SDNode * N,SelectionDAG & DAG)5819 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5820   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5821     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5822                                         N->getOperand(0)->getValueType(0),
5823                                         N->getValueType(0),
5824                                         N->getOpcode());
5825 
5826   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5827     return SkipLoadExtensionForVMULL(LD, DAG);
5828 
5829   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5830   // have been legalized as a BITCAST from v4i32.
5831   if (N->getOpcode() == ISD::BITCAST) {
5832     SDNode *BVN = N->getOperand(0).getNode();
5833     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5834            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5835     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5836     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5837                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5838   }
5839   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5840   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5841   EVT VT = N->getValueType(0);
5842   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5843   unsigned NumElts = VT.getVectorNumElements();
5844   MVT TruncVT = MVT::getIntegerVT(EltSize);
5845   SmallVector<SDValue, 8> Ops;
5846   for (unsigned i = 0; i != NumElts; ++i) {
5847     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5848     const APInt &CInt = C->getAPIntValue();
5849     // Element types smaller than 32 bits are not legal, so use i32 elements.
5850     // The values are implicitly truncated so sext vs. zext doesn't matter.
5851     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5852   }
5853   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5854                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5855 }
5856 
isAddSubSExt(SDNode * N,SelectionDAG & DAG)5857 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5858   unsigned Opcode = N->getOpcode();
5859   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5860     SDNode *N0 = N->getOperand(0).getNode();
5861     SDNode *N1 = N->getOperand(1).getNode();
5862     return N0->hasOneUse() && N1->hasOneUse() &&
5863       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5864   }
5865   return false;
5866 }
5867 
isAddSubZExt(SDNode * N,SelectionDAG & DAG)5868 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5869   unsigned Opcode = N->getOpcode();
5870   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5871     SDNode *N0 = N->getOperand(0).getNode();
5872     SDNode *N1 = N->getOperand(1).getNode();
5873     return N0->hasOneUse() && N1->hasOneUse() &&
5874       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5875   }
5876   return false;
5877 }
5878 
LowerMUL(SDValue Op,SelectionDAG & DAG)5879 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5880   // Multiplications are only custom-lowered for 128-bit vectors so that
5881   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5882   EVT VT = Op.getValueType();
5883   assert(VT.is128BitVector() && VT.isInteger() &&
5884          "unexpected type for custom-lowering ISD::MUL");
5885   SDNode *N0 = Op.getOperand(0).getNode();
5886   SDNode *N1 = Op.getOperand(1).getNode();
5887   unsigned NewOpc = 0;
5888   bool isMLA = false;
5889   bool isN0SExt = isSignExtended(N0, DAG);
5890   bool isN1SExt = isSignExtended(N1, DAG);
5891   if (isN0SExt && isN1SExt)
5892     NewOpc = ARMISD::VMULLs;
5893   else {
5894     bool isN0ZExt = isZeroExtended(N0, DAG);
5895     bool isN1ZExt = isZeroExtended(N1, DAG);
5896     if (isN0ZExt && isN1ZExt)
5897       NewOpc = ARMISD::VMULLu;
5898     else if (isN1SExt || isN1ZExt) {
5899       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5900       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5901       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5902         NewOpc = ARMISD::VMULLs;
5903         isMLA = true;
5904       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5905         NewOpc = ARMISD::VMULLu;
5906         isMLA = true;
5907       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5908         std::swap(N0, N1);
5909         NewOpc = ARMISD::VMULLu;
5910         isMLA = true;
5911       }
5912     }
5913 
5914     if (!NewOpc) {
5915       if (VT == MVT::v2i64)
5916         // Fall through to expand this.  It is not legal.
5917         return SDValue();
5918       else
5919         // Other vector multiplications are legal.
5920         return Op;
5921     }
5922   }
5923 
5924   // Legalize to a VMULL instruction.
5925   SDLoc DL(Op);
5926   SDValue Op0;
5927   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5928   if (!isMLA) {
5929     Op0 = SkipExtensionForVMULL(N0, DAG);
5930     assert(Op0.getValueType().is64BitVector() &&
5931            Op1.getValueType().is64BitVector() &&
5932            "unexpected types for extended operands to VMULL");
5933     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5934   }
5935 
5936   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5937   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5938   //   vmull q0, d4, d6
5939   //   vmlal q0, d5, d6
5940   // is faster than
5941   //   vaddl q0, d4, d5
5942   //   vmovl q1, d6
5943   //   vmul  q0, q0, q1
5944   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5945   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5946   EVT Op1VT = Op1.getValueType();
5947   return DAG.getNode(N0->getOpcode(), DL, VT,
5948                      DAG.getNode(NewOpc, DL, VT,
5949                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5950                      DAG.getNode(NewOpc, DL, VT,
5951                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5952 }
5953 
5954 static SDValue
LowerSDIV_v4i8(SDValue X,SDValue Y,SDLoc dl,SelectionDAG & DAG)5955 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5956   // Convert to float
5957   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5958   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5959   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5960   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5961   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5962   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5963   // Get reciprocal estimate.
5964   // float4 recip = vrecpeq_f32(yf);
5965   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5966                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5967   // Because char has a smaller range than uchar, we can actually get away
5968   // without any newton steps.  This requires that we use a weird bias
5969   // of 0xb000, however (again, this has been exhaustively tested).
5970   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5971   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5972   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5973   Y = DAG.getConstant(0xb000, MVT::i32);
5974   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5975   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5976   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5977   // Convert back to short.
5978   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5979   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5980   return X;
5981 }
5982 
5983 static SDValue
LowerSDIV_v4i16(SDValue N0,SDValue N1,SDLoc dl,SelectionDAG & DAG)5984 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5985   SDValue N2;
5986   // Convert to float.
5987   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5988   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5989   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5990   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5991   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5992   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5993 
5994   // Use reciprocal estimate and one refinement step.
5995   // float4 recip = vrecpeq_f32(yf);
5996   // recip *= vrecpsq_f32(yf, recip);
5997   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5998                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5999   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6000                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6001                    N1, N2);
6002   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6003   // Because short has a smaller range than ushort, we can actually get away
6004   // with only a single newton step.  This requires that we use a weird bias
6005   // of 89, however (again, this has been exhaustively tested).
6006   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6007   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6008   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6009   N1 = DAG.getConstant(0x89, MVT::i32);
6010   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6011   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6012   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6013   // Convert back to integer and return.
6014   // return vmovn_s32(vcvt_s32_f32(result));
6015   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6016   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6017   return N0;
6018 }
6019 
LowerSDIV(SDValue Op,SelectionDAG & DAG)6020 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6021   EVT VT = Op.getValueType();
6022   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6023          "unexpected type for custom-lowering ISD::SDIV");
6024 
6025   SDLoc dl(Op);
6026   SDValue N0 = Op.getOperand(0);
6027   SDValue N1 = Op.getOperand(1);
6028   SDValue N2, N3;
6029 
6030   if (VT == MVT::v8i8) {
6031     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6032     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6033 
6034     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6035                      DAG.getIntPtrConstant(4));
6036     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6037                      DAG.getIntPtrConstant(4));
6038     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6039                      DAG.getIntPtrConstant(0));
6040     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6041                      DAG.getIntPtrConstant(0));
6042 
6043     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6044     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6045 
6046     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6047     N0 = LowerCONCAT_VECTORS(N0, DAG);
6048 
6049     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6050     return N0;
6051   }
6052   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6053 }
6054 
LowerUDIV(SDValue Op,SelectionDAG & DAG)6055 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6056   EVT VT = Op.getValueType();
6057   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6058          "unexpected type for custom-lowering ISD::UDIV");
6059 
6060   SDLoc dl(Op);
6061   SDValue N0 = Op.getOperand(0);
6062   SDValue N1 = Op.getOperand(1);
6063   SDValue N2, N3;
6064 
6065   if (VT == MVT::v8i8) {
6066     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6067     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6068 
6069     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6070                      DAG.getIntPtrConstant(4));
6071     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6072                      DAG.getIntPtrConstant(4));
6073     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6074                      DAG.getIntPtrConstant(0));
6075     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6076                      DAG.getIntPtrConstant(0));
6077 
6078     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6079     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6080 
6081     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6082     N0 = LowerCONCAT_VECTORS(N0, DAG);
6083 
6084     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6085                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6086                      N0);
6087     return N0;
6088   }
6089 
6090   // v4i16 sdiv ... Convert to float.
6091   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6092   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6093   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6094   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6095   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6096   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6097 
6098   // Use reciprocal estimate and two refinement steps.
6099   // float4 recip = vrecpeq_f32(yf);
6100   // recip *= vrecpsq_f32(yf, recip);
6101   // recip *= vrecpsq_f32(yf, recip);
6102   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6103                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6104   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6105                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6106                    BN1, N2);
6107   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6108   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6109                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6110                    BN1, N2);
6111   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6112   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6113   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6114   // and that it will never cause us to return an answer too large).
6115   // float4 result = as_float4(as_int4(xf*recip) + 2);
6116   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6117   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6118   N1 = DAG.getConstant(2, MVT::i32);
6119   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6120   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6121   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6122   // Convert back to integer and return.
6123   // return vmovn_u32(vcvt_s32_f32(result));
6124   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6125   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6126   return N0;
6127 }
6128 
LowerADDC_ADDE_SUBC_SUBE(SDValue Op,SelectionDAG & DAG)6129 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6130   EVT VT = Op.getNode()->getValueType(0);
6131   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6132 
6133   unsigned Opc;
6134   bool ExtraOp = false;
6135   switch (Op.getOpcode()) {
6136   default: llvm_unreachable("Invalid code");
6137   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6138   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6139   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6140   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6141   }
6142 
6143   if (!ExtraOp)
6144     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6145                        Op.getOperand(1));
6146   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6147                      Op.getOperand(1), Op.getOperand(2));
6148 }
6149 
LowerFSINCOS(SDValue Op,SelectionDAG & DAG) const6150 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6151   assert(Subtarget->isTargetDarwin());
6152 
6153   // For iOS, we want to call an alternative entry point: __sincos_stret,
6154   // return values are passed via sret.
6155   SDLoc dl(Op);
6156   SDValue Arg = Op.getOperand(0);
6157   EVT ArgVT = Arg.getValueType();
6158   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6159 
6160   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6162 
6163   // Pair of floats / doubles used to pass the result.
6164   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6165 
6166   // Create stack object for sret.
6167   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6168   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6169   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6170   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6171 
6172   ArgListTy Args;
6173   ArgListEntry Entry;
6174 
6175   Entry.Node = SRet;
6176   Entry.Ty = RetTy->getPointerTo();
6177   Entry.isSExt = false;
6178   Entry.isZExt = false;
6179   Entry.isSRet = true;
6180   Args.push_back(Entry);
6181 
6182   Entry.Node = Arg;
6183   Entry.Ty = ArgTy;
6184   Entry.isSExt = false;
6185   Entry.isZExt = false;
6186   Args.push_back(Entry);
6187 
6188   const char *LibcallName  = (ArgVT == MVT::f64)
6189   ? "__sincos_stret" : "__sincosf_stret";
6190   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6191 
6192   TargetLowering::CallLoweringInfo CLI(DAG);
6193   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6194     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6195                std::move(Args), 0)
6196     .setDiscardResult();
6197 
6198   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6199 
6200   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6201                                 MachinePointerInfo(), false, false, false, 0);
6202 
6203   // Address of cos field.
6204   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6205                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6206   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6207                                 MachinePointerInfo(), false, false, false, 0);
6208 
6209   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6210   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6211                      LoadSin.getValue(0), LoadCos.getValue(0));
6212 }
6213 
LowerAtomicLoadStore(SDValue Op,SelectionDAG & DAG)6214 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6215   // Monotonic load/store is legal for all targets
6216   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6217     return Op;
6218 
6219   // Acquire/Release load/store is not legal for targets without a
6220   // dmb or equivalent available.
6221   return SDValue();
6222 }
6223 
ReplaceREADCYCLECOUNTER(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,const ARMSubtarget * Subtarget)6224 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6225                                     SmallVectorImpl<SDValue> &Results,
6226                                     SelectionDAG &DAG,
6227                                     const ARMSubtarget *Subtarget) {
6228   SDLoc DL(N);
6229   SDValue Cycles32, OutChain;
6230 
6231   if (Subtarget->hasPerfMon()) {
6232     // Under Power Management extensions, the cycle-count is:
6233     //    mrc p15, #0, <Rt>, c9, c13, #0
6234     SDValue Ops[] = { N->getOperand(0), // Chain
6235                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6236                       DAG.getConstant(15, MVT::i32),
6237                       DAG.getConstant(0, MVT::i32),
6238                       DAG.getConstant(9, MVT::i32),
6239                       DAG.getConstant(13, MVT::i32),
6240                       DAG.getConstant(0, MVT::i32)
6241     };
6242 
6243     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6244                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6245     OutChain = Cycles32.getValue(1);
6246   } else {
6247     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6248     // there are older ARM CPUs that have implementation-specific ways of
6249     // obtaining this information (FIXME!).
6250     Cycles32 = DAG.getConstant(0, MVT::i32);
6251     OutChain = DAG.getEntryNode();
6252   }
6253 
6254 
6255   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6256                                  Cycles32, DAG.getConstant(0, MVT::i32));
6257   Results.push_back(Cycles64);
6258   Results.push_back(OutChain);
6259 }
6260 
LowerOperation(SDValue Op,SelectionDAG & DAG) const6261 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6262   switch (Op.getOpcode()) {
6263   default: llvm_unreachable("Don't know how to custom lower this!");
6264   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6265   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6266   case ISD::GlobalAddress:
6267     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6268     default: llvm_unreachable("unknown object format");
6269     case Triple::COFF:
6270       return LowerGlobalAddressWindows(Op, DAG);
6271     case Triple::ELF:
6272       return LowerGlobalAddressELF(Op, DAG);
6273     case Triple::MachO:
6274       return LowerGlobalAddressDarwin(Op, DAG);
6275     }
6276   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6277   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6278   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6279   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6280   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6281   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6282   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6283   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6284   case ISD::SINT_TO_FP:
6285   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6286   case ISD::FP_TO_SINT:
6287   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6288   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6289   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6290   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6291   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6292   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6293   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6294   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6295                                                                Subtarget);
6296   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6297   case ISD::SHL:
6298   case ISD::SRL:
6299   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6300   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6301   case ISD::SRL_PARTS:
6302   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6303   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6304   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6305   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6306   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6307   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6308   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6309   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6310   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6311   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6312   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6313   case ISD::MUL:           return LowerMUL(Op, DAG);
6314   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6315   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6316   case ISD::ADDC:
6317   case ISD::ADDE:
6318   case ISD::SUBC:
6319   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6320   case ISD::SADDO:
6321   case ISD::UADDO:
6322   case ISD::SSUBO:
6323   case ISD::USUBO:
6324     return LowerXALUO(Op, DAG);
6325   case ISD::ATOMIC_LOAD:
6326   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6327   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6328   case ISD::SDIVREM:
6329   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6330   case ISD::DYNAMIC_STACKALLOC:
6331     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6332       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6333     llvm_unreachable("Don't know how to custom lower this!");
6334   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6335   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6336   }
6337 }
6338 
6339 /// ReplaceNodeResults - Replace the results of node with an illegal result
6340 /// type with new values built out of custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const6341 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6342                                            SmallVectorImpl<SDValue>&Results,
6343                                            SelectionDAG &DAG) const {
6344   SDValue Res;
6345   switch (N->getOpcode()) {
6346   default:
6347     llvm_unreachable("Don't know how to custom expand this!");
6348   case ISD::BITCAST:
6349     Res = ExpandBITCAST(N, DAG);
6350     break;
6351   case ISD::SRL:
6352   case ISD::SRA:
6353     Res = Expand64BitShift(N, DAG, Subtarget);
6354     break;
6355   case ISD::READCYCLECOUNTER:
6356     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6357     return;
6358   }
6359   if (Res.getNode())
6360     Results.push_back(Res);
6361 }
6362 
6363 //===----------------------------------------------------------------------===//
6364 //                           ARM Scheduler Hooks
6365 //===----------------------------------------------------------------------===//
6366 
6367 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6368 /// registers the function context.
6369 void ARMTargetLowering::
SetupEntryBlockForSjLj(MachineInstr * MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const6370 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6371                        MachineBasicBlock *DispatchBB, int FI) const {
6372   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6373   DebugLoc dl = MI->getDebugLoc();
6374   MachineFunction *MF = MBB->getParent();
6375   MachineRegisterInfo *MRI = &MF->getRegInfo();
6376   MachineConstantPool *MCP = MF->getConstantPool();
6377   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6378   const Function *F = MF->getFunction();
6379 
6380   bool isThumb = Subtarget->isThumb();
6381   bool isThumb2 = Subtarget->isThumb2();
6382 
6383   unsigned PCLabelId = AFI->createPICLabelUId();
6384   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6385   ARMConstantPoolValue *CPV =
6386     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6387   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6388 
6389   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6390                                            : &ARM::GPRRegClass;
6391 
6392   // Grab constant pool and fixed stack memory operands.
6393   MachineMemOperand *CPMMO =
6394     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6395                              MachineMemOperand::MOLoad, 4, 4);
6396 
6397   MachineMemOperand *FIMMOSt =
6398     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6399                              MachineMemOperand::MOStore, 4, 4);
6400 
6401   // Load the address of the dispatch MBB into the jump buffer.
6402   if (isThumb2) {
6403     // Incoming value: jbuf
6404     //   ldr.n  r5, LCPI1_1
6405     //   orr    r5, r5, #1
6406     //   add    r5, pc
6407     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6408     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6409     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6410                    .addConstantPoolIndex(CPI)
6411                    .addMemOperand(CPMMO));
6412     // Set the low bit because of thumb mode.
6413     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6414     AddDefaultCC(
6415       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6416                      .addReg(NewVReg1, RegState::Kill)
6417                      .addImm(0x01)));
6418     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6419     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6420       .addReg(NewVReg2, RegState::Kill)
6421       .addImm(PCLabelId);
6422     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6423                    .addReg(NewVReg3, RegState::Kill)
6424                    .addFrameIndex(FI)
6425                    .addImm(36)  // &jbuf[1] :: pc
6426                    .addMemOperand(FIMMOSt));
6427   } else if (isThumb) {
6428     // Incoming value: jbuf
6429     //   ldr.n  r1, LCPI1_4
6430     //   add    r1, pc
6431     //   mov    r2, #1
6432     //   orrs   r1, r2
6433     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6434     //   str    r1, [r2]
6435     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6436     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6437                    .addConstantPoolIndex(CPI)
6438                    .addMemOperand(CPMMO));
6439     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6440     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6441       .addReg(NewVReg1, RegState::Kill)
6442       .addImm(PCLabelId);
6443     // Set the low bit because of thumb mode.
6444     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6445     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6446                    .addReg(ARM::CPSR, RegState::Define)
6447                    .addImm(1));
6448     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6449     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6450                    .addReg(ARM::CPSR, RegState::Define)
6451                    .addReg(NewVReg2, RegState::Kill)
6452                    .addReg(NewVReg3, RegState::Kill));
6453     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6454     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6455             .addFrameIndex(FI)
6456             .addImm(36); // &jbuf[1] :: pc
6457     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6458                    .addReg(NewVReg4, RegState::Kill)
6459                    .addReg(NewVReg5, RegState::Kill)
6460                    .addImm(0)
6461                    .addMemOperand(FIMMOSt));
6462   } else {
6463     // Incoming value: jbuf
6464     //   ldr  r1, LCPI1_1
6465     //   add  r1, pc, r1
6466     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6467     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6468     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6469                    .addConstantPoolIndex(CPI)
6470                    .addImm(0)
6471                    .addMemOperand(CPMMO));
6472     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6473     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6474                    .addReg(NewVReg1, RegState::Kill)
6475                    .addImm(PCLabelId));
6476     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6477                    .addReg(NewVReg2, RegState::Kill)
6478                    .addFrameIndex(FI)
6479                    .addImm(36)  // &jbuf[1] :: pc
6480                    .addMemOperand(FIMMOSt));
6481   }
6482 }
6483 
6484 MachineBasicBlock *ARMTargetLowering::
EmitSjLjDispatchBlock(MachineInstr * MI,MachineBasicBlock * MBB) const6485 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6486   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6487   DebugLoc dl = MI->getDebugLoc();
6488   MachineFunction *MF = MBB->getParent();
6489   MachineRegisterInfo *MRI = &MF->getRegInfo();
6490   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6491   MachineFrameInfo *MFI = MF->getFrameInfo();
6492   int FI = MFI->getFunctionContextIndex();
6493 
6494   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6495                                                         : &ARM::GPRnopcRegClass;
6496 
6497   // Get a mapping of the call site numbers to all of the landing pads they're
6498   // associated with.
6499   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6500   unsigned MaxCSNum = 0;
6501   MachineModuleInfo &MMI = MF->getMMI();
6502   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6503        ++BB) {
6504     if (!BB->isLandingPad()) continue;
6505 
6506     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6507     // pad.
6508     for (MachineBasicBlock::iterator
6509            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6510       if (!II->isEHLabel()) continue;
6511 
6512       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6513       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6514 
6515       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6516       for (SmallVectorImpl<unsigned>::iterator
6517              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6518            CSI != CSE; ++CSI) {
6519         CallSiteNumToLPad[*CSI].push_back(BB);
6520         MaxCSNum = std::max(MaxCSNum, *CSI);
6521       }
6522       break;
6523     }
6524   }
6525 
6526   // Get an ordered list of the machine basic blocks for the jump table.
6527   std::vector<MachineBasicBlock*> LPadList;
6528   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6529   LPadList.reserve(CallSiteNumToLPad.size());
6530   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6531     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6532     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6533            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6534       LPadList.push_back(*II);
6535       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6536     }
6537   }
6538 
6539   assert(!LPadList.empty() &&
6540          "No landing pad destinations for the dispatch jump table!");
6541 
6542   // Create the jump table and associated information.
6543   MachineJumpTableInfo *JTI =
6544     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6545   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6546   unsigned UId = AFI->createJumpTableUId();
6547   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6548 
6549   // Create the MBBs for the dispatch code.
6550 
6551   // Shove the dispatch's address into the return slot in the function context.
6552   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6553   DispatchBB->setIsLandingPad();
6554 
6555   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6556   unsigned trap_opcode;
6557   if (Subtarget->isThumb())
6558     trap_opcode = ARM::tTRAP;
6559   else
6560     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6561 
6562   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6563   DispatchBB->addSuccessor(TrapBB);
6564 
6565   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6566   DispatchBB->addSuccessor(DispContBB);
6567 
6568   // Insert and MBBs.
6569   MF->insert(MF->end(), DispatchBB);
6570   MF->insert(MF->end(), DispContBB);
6571   MF->insert(MF->end(), TrapBB);
6572 
6573   // Insert code into the entry block that creates and registers the function
6574   // context.
6575   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6576 
6577   MachineMemOperand *FIMMOLd =
6578     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6579                              MachineMemOperand::MOLoad |
6580                              MachineMemOperand::MOVolatile, 4, 4);
6581 
6582   MachineInstrBuilder MIB;
6583   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6584 
6585   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6586   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6587 
6588   // Add a register mask with no preserved registers.  This results in all
6589   // registers being marked as clobbered.
6590   MIB.addRegMask(RI.getNoPreservedMask());
6591 
6592   unsigned NumLPads = LPadList.size();
6593   if (Subtarget->isThumb2()) {
6594     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6595     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6596                    .addFrameIndex(FI)
6597                    .addImm(4)
6598                    .addMemOperand(FIMMOLd));
6599 
6600     if (NumLPads < 256) {
6601       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6602                      .addReg(NewVReg1)
6603                      .addImm(LPadList.size()));
6604     } else {
6605       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6606       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6607                      .addImm(NumLPads & 0xFFFF));
6608 
6609       unsigned VReg2 = VReg1;
6610       if ((NumLPads & 0xFFFF0000) != 0) {
6611         VReg2 = MRI->createVirtualRegister(TRC);
6612         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6613                        .addReg(VReg1)
6614                        .addImm(NumLPads >> 16));
6615       }
6616 
6617       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6618                      .addReg(NewVReg1)
6619                      .addReg(VReg2));
6620     }
6621 
6622     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6623       .addMBB(TrapBB)
6624       .addImm(ARMCC::HI)
6625       .addReg(ARM::CPSR);
6626 
6627     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6628     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6629                    .addJumpTableIndex(MJTI)
6630                    .addImm(UId));
6631 
6632     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6633     AddDefaultCC(
6634       AddDefaultPred(
6635         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6636         .addReg(NewVReg3, RegState::Kill)
6637         .addReg(NewVReg1)
6638         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6639 
6640     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6641       .addReg(NewVReg4, RegState::Kill)
6642       .addReg(NewVReg1)
6643       .addJumpTableIndex(MJTI)
6644       .addImm(UId);
6645   } else if (Subtarget->isThumb()) {
6646     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6647     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6648                    .addFrameIndex(FI)
6649                    .addImm(1)
6650                    .addMemOperand(FIMMOLd));
6651 
6652     if (NumLPads < 256) {
6653       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6654                      .addReg(NewVReg1)
6655                      .addImm(NumLPads));
6656     } else {
6657       MachineConstantPool *ConstantPool = MF->getConstantPool();
6658       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6659       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6660 
6661       // MachineConstantPool wants an explicit alignment.
6662       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6663       if (Align == 0)
6664         Align = getDataLayout()->getTypeAllocSize(C->getType());
6665       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6666 
6667       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6668       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6669                      .addReg(VReg1, RegState::Define)
6670                      .addConstantPoolIndex(Idx));
6671       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6672                      .addReg(NewVReg1)
6673                      .addReg(VReg1));
6674     }
6675 
6676     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6677       .addMBB(TrapBB)
6678       .addImm(ARMCC::HI)
6679       .addReg(ARM::CPSR);
6680 
6681     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6682     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6683                    .addReg(ARM::CPSR, RegState::Define)
6684                    .addReg(NewVReg1)
6685                    .addImm(2));
6686 
6687     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6688     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6689                    .addJumpTableIndex(MJTI)
6690                    .addImm(UId));
6691 
6692     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6693     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6694                    .addReg(ARM::CPSR, RegState::Define)
6695                    .addReg(NewVReg2, RegState::Kill)
6696                    .addReg(NewVReg3));
6697 
6698     MachineMemOperand *JTMMOLd =
6699       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6700                                MachineMemOperand::MOLoad, 4, 4);
6701 
6702     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6703     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6704                    .addReg(NewVReg4, RegState::Kill)
6705                    .addImm(0)
6706                    .addMemOperand(JTMMOLd));
6707 
6708     unsigned NewVReg6 = NewVReg5;
6709     if (RelocM == Reloc::PIC_) {
6710       NewVReg6 = MRI->createVirtualRegister(TRC);
6711       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6712                      .addReg(ARM::CPSR, RegState::Define)
6713                      .addReg(NewVReg5, RegState::Kill)
6714                      .addReg(NewVReg3));
6715     }
6716 
6717     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6718       .addReg(NewVReg6, RegState::Kill)
6719       .addJumpTableIndex(MJTI)
6720       .addImm(UId);
6721   } else {
6722     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6723     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6724                    .addFrameIndex(FI)
6725                    .addImm(4)
6726                    .addMemOperand(FIMMOLd));
6727 
6728     if (NumLPads < 256) {
6729       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6730                      .addReg(NewVReg1)
6731                      .addImm(NumLPads));
6732     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6733       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6734       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6735                      .addImm(NumLPads & 0xFFFF));
6736 
6737       unsigned VReg2 = VReg1;
6738       if ((NumLPads & 0xFFFF0000) != 0) {
6739         VReg2 = MRI->createVirtualRegister(TRC);
6740         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6741                        .addReg(VReg1)
6742                        .addImm(NumLPads >> 16));
6743       }
6744 
6745       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6746                      .addReg(NewVReg1)
6747                      .addReg(VReg2));
6748     } else {
6749       MachineConstantPool *ConstantPool = MF->getConstantPool();
6750       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6751       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6752 
6753       // MachineConstantPool wants an explicit alignment.
6754       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6755       if (Align == 0)
6756         Align = getDataLayout()->getTypeAllocSize(C->getType());
6757       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6758 
6759       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6760       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6761                      .addReg(VReg1, RegState::Define)
6762                      .addConstantPoolIndex(Idx)
6763                      .addImm(0));
6764       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6765                      .addReg(NewVReg1)
6766                      .addReg(VReg1, RegState::Kill));
6767     }
6768 
6769     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6770       .addMBB(TrapBB)
6771       .addImm(ARMCC::HI)
6772       .addReg(ARM::CPSR);
6773 
6774     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6775     AddDefaultCC(
6776       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6777                      .addReg(NewVReg1)
6778                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6779     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6780     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6781                    .addJumpTableIndex(MJTI)
6782                    .addImm(UId));
6783 
6784     MachineMemOperand *JTMMOLd =
6785       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6786                                MachineMemOperand::MOLoad, 4, 4);
6787     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6788     AddDefaultPred(
6789       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6790       .addReg(NewVReg3, RegState::Kill)
6791       .addReg(NewVReg4)
6792       .addImm(0)
6793       .addMemOperand(JTMMOLd));
6794 
6795     if (RelocM == Reloc::PIC_) {
6796       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6797         .addReg(NewVReg5, RegState::Kill)
6798         .addReg(NewVReg4)
6799         .addJumpTableIndex(MJTI)
6800         .addImm(UId);
6801     } else {
6802       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6803         .addReg(NewVReg5, RegState::Kill)
6804         .addJumpTableIndex(MJTI)
6805         .addImm(UId);
6806     }
6807   }
6808 
6809   // Add the jump table entries as successors to the MBB.
6810   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6811   for (std::vector<MachineBasicBlock*>::iterator
6812          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6813     MachineBasicBlock *CurMBB = *I;
6814     if (SeenMBBs.insert(CurMBB).second)
6815       DispContBB->addSuccessor(CurMBB);
6816   }
6817 
6818   // N.B. the order the invoke BBs are processed in doesn't matter here.
6819   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6820   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6821   for (MachineBasicBlock *BB : InvokeBBs) {
6822 
6823     // Remove the landing pad successor from the invoke block and replace it
6824     // with the new dispatch block.
6825     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6826                                                   BB->succ_end());
6827     while (!Successors.empty()) {
6828       MachineBasicBlock *SMBB = Successors.pop_back_val();
6829       if (SMBB->isLandingPad()) {
6830         BB->removeSuccessor(SMBB);
6831         MBBLPads.push_back(SMBB);
6832       }
6833     }
6834 
6835     BB->addSuccessor(DispatchBB);
6836 
6837     // Find the invoke call and mark all of the callee-saved registers as
6838     // 'implicit defined' so that they're spilled. This prevents code from
6839     // moving instructions to before the EH block, where they will never be
6840     // executed.
6841     for (MachineBasicBlock::reverse_iterator
6842            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6843       if (!II->isCall()) continue;
6844 
6845       DenseMap<unsigned, bool> DefRegs;
6846       for (MachineInstr::mop_iterator
6847              OI = II->operands_begin(), OE = II->operands_end();
6848            OI != OE; ++OI) {
6849         if (!OI->isReg()) continue;
6850         DefRegs[OI->getReg()] = true;
6851       }
6852 
6853       MachineInstrBuilder MIB(*MF, &*II);
6854 
6855       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6856         unsigned Reg = SavedRegs[i];
6857         if (Subtarget->isThumb2() &&
6858             !ARM::tGPRRegClass.contains(Reg) &&
6859             !ARM::hGPRRegClass.contains(Reg))
6860           continue;
6861         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6862           continue;
6863         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6864           continue;
6865         if (!DefRegs[Reg])
6866           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6867       }
6868 
6869       break;
6870     }
6871   }
6872 
6873   // Mark all former landing pads as non-landing pads. The dispatch is the only
6874   // landing pad now.
6875   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6876          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6877     (*I)->setIsLandingPad(false);
6878 
6879   // The instruction is gone now.
6880   MI->eraseFromParent();
6881 
6882   return MBB;
6883 }
6884 
6885 static
OtherSucc(MachineBasicBlock * MBB,MachineBasicBlock * Succ)6886 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6887   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6888        E = MBB->succ_end(); I != E; ++I)
6889     if (*I != Succ)
6890       return *I;
6891   llvm_unreachable("Expecting a BB with two successors!");
6892 }
6893 
6894 /// Return the load opcode for a given load size. If load size >= 8,
6895 /// neon opcode will be returned.
getLdOpcode(unsigned LdSize,bool IsThumb1,bool IsThumb2)6896 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6897   if (LdSize >= 8)
6898     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6899                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6900   if (IsThumb1)
6901     return LdSize == 4 ? ARM::tLDRi
6902                        : LdSize == 2 ? ARM::tLDRHi
6903                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6904   if (IsThumb2)
6905     return LdSize == 4 ? ARM::t2LDR_POST
6906                        : LdSize == 2 ? ARM::t2LDRH_POST
6907                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6908   return LdSize == 4 ? ARM::LDR_POST_IMM
6909                      : LdSize == 2 ? ARM::LDRH_POST
6910                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6911 }
6912 
6913 /// Return the store opcode for a given store size. If store size >= 8,
6914 /// neon opcode will be returned.
getStOpcode(unsigned StSize,bool IsThumb1,bool IsThumb2)6915 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6916   if (StSize >= 8)
6917     return StSize == 16 ? ARM::VST1q32wb_fixed
6918                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6919   if (IsThumb1)
6920     return StSize == 4 ? ARM::tSTRi
6921                        : StSize == 2 ? ARM::tSTRHi
6922                                      : StSize == 1 ? ARM::tSTRBi : 0;
6923   if (IsThumb2)
6924     return StSize == 4 ? ARM::t2STR_POST
6925                        : StSize == 2 ? ARM::t2STRH_POST
6926                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6927   return StSize == 4 ? ARM::STR_POST_IMM
6928                      : StSize == 2 ? ARM::STRH_POST
6929                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6930 }
6931 
6932 /// Emit a post-increment load operation with given size. The instructions
6933 /// will be added to BB at Pos.
emitPostLd(MachineBasicBlock * BB,MachineInstr * Pos,const TargetInstrInfo * TII,DebugLoc dl,unsigned LdSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)6934 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6935                        const TargetInstrInfo *TII, DebugLoc dl,
6936                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6937                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6938   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6939   assert(LdOpc != 0 && "Should have a load opcode");
6940   if (LdSize >= 8) {
6941     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6942                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6943                        .addImm(0));
6944   } else if (IsThumb1) {
6945     // load + update AddrIn
6946     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6947                        .addReg(AddrIn).addImm(0));
6948     MachineInstrBuilder MIB =
6949         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6950     MIB = AddDefaultT1CC(MIB);
6951     MIB.addReg(AddrIn).addImm(LdSize);
6952     AddDefaultPred(MIB);
6953   } else if (IsThumb2) {
6954     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6955                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6956                        .addImm(LdSize));
6957   } else { // arm
6958     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6959                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6960                        .addReg(0).addImm(LdSize));
6961   }
6962 }
6963 
6964 /// Emit a post-increment store operation with given size. The instructions
6965 /// will be added to BB at Pos.
emitPostSt(MachineBasicBlock * BB,MachineInstr * Pos,const TargetInstrInfo * TII,DebugLoc dl,unsigned StSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)6966 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6967                        const TargetInstrInfo *TII, DebugLoc dl,
6968                        unsigned StSize, unsigned Data, unsigned AddrIn,
6969                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6970   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6971   assert(StOpc != 0 && "Should have a store opcode");
6972   if (StSize >= 8) {
6973     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6974                        .addReg(AddrIn).addImm(0).addReg(Data));
6975   } else if (IsThumb1) {
6976     // store + update AddrIn
6977     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6978                        .addReg(AddrIn).addImm(0));
6979     MachineInstrBuilder MIB =
6980         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6981     MIB = AddDefaultT1CC(MIB);
6982     MIB.addReg(AddrIn).addImm(StSize);
6983     AddDefaultPred(MIB);
6984   } else if (IsThumb2) {
6985     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6986                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6987   } else { // arm
6988     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6989                        .addReg(Data).addReg(AddrIn).addReg(0)
6990                        .addImm(StSize));
6991   }
6992 }
6993 
6994 MachineBasicBlock *
EmitStructByval(MachineInstr * MI,MachineBasicBlock * BB) const6995 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6996                                    MachineBasicBlock *BB) const {
6997   // This pseudo instruction has 3 operands: dst, src, size
6998   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6999   // Otherwise, we will generate unrolled scalar copies.
7000   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7001   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7002   MachineFunction::iterator It = BB;
7003   ++It;
7004 
7005   unsigned dest = MI->getOperand(0).getReg();
7006   unsigned src = MI->getOperand(1).getReg();
7007   unsigned SizeVal = MI->getOperand(2).getImm();
7008   unsigned Align = MI->getOperand(3).getImm();
7009   DebugLoc dl = MI->getDebugLoc();
7010 
7011   MachineFunction *MF = BB->getParent();
7012   MachineRegisterInfo &MRI = MF->getRegInfo();
7013   unsigned UnitSize = 0;
7014   const TargetRegisterClass *TRC = nullptr;
7015   const TargetRegisterClass *VecTRC = nullptr;
7016 
7017   bool IsThumb1 = Subtarget->isThumb1Only();
7018   bool IsThumb2 = Subtarget->isThumb2();
7019 
7020   if (Align & 1) {
7021     UnitSize = 1;
7022   } else if (Align & 2) {
7023     UnitSize = 2;
7024   } else {
7025     // Check whether we can use NEON instructions.
7026     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7027         Subtarget->hasNEON()) {
7028       if ((Align % 16 == 0) && SizeVal >= 16)
7029         UnitSize = 16;
7030       else if ((Align % 8 == 0) && SizeVal >= 8)
7031         UnitSize = 8;
7032     }
7033     // Can't use NEON instructions.
7034     if (UnitSize == 0)
7035       UnitSize = 4;
7036   }
7037 
7038   // Select the correct opcode and register class for unit size load/store
7039   bool IsNeon = UnitSize >= 8;
7040   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7041   if (IsNeon)
7042     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7043                             : UnitSize == 8 ? &ARM::DPRRegClass
7044                                             : nullptr;
7045 
7046   unsigned BytesLeft = SizeVal % UnitSize;
7047   unsigned LoopSize = SizeVal - BytesLeft;
7048 
7049   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7050     // Use LDR and STR to copy.
7051     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7052     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7053     unsigned srcIn = src;
7054     unsigned destIn = dest;
7055     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7056       unsigned srcOut = MRI.createVirtualRegister(TRC);
7057       unsigned destOut = MRI.createVirtualRegister(TRC);
7058       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7059       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7060                  IsThumb1, IsThumb2);
7061       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7062                  IsThumb1, IsThumb2);
7063       srcIn = srcOut;
7064       destIn = destOut;
7065     }
7066 
7067     // Handle the leftover bytes with LDRB and STRB.
7068     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7069     // [destOut] = STRB_POST(scratch, destIn, 1)
7070     for (unsigned i = 0; i < BytesLeft; i++) {
7071       unsigned srcOut = MRI.createVirtualRegister(TRC);
7072       unsigned destOut = MRI.createVirtualRegister(TRC);
7073       unsigned scratch = MRI.createVirtualRegister(TRC);
7074       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7075                  IsThumb1, IsThumb2);
7076       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7077                  IsThumb1, IsThumb2);
7078       srcIn = srcOut;
7079       destIn = destOut;
7080     }
7081     MI->eraseFromParent();   // The instruction is gone now.
7082     return BB;
7083   }
7084 
7085   // Expand the pseudo op to a loop.
7086   // thisMBB:
7087   //   ...
7088   //   movw varEnd, # --> with thumb2
7089   //   movt varEnd, #
7090   //   ldrcp varEnd, idx --> without thumb2
7091   //   fallthrough --> loopMBB
7092   // loopMBB:
7093   //   PHI varPhi, varEnd, varLoop
7094   //   PHI srcPhi, src, srcLoop
7095   //   PHI destPhi, dst, destLoop
7096   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7097   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7098   //   subs varLoop, varPhi, #UnitSize
7099   //   bne loopMBB
7100   //   fallthrough --> exitMBB
7101   // exitMBB:
7102   //   epilogue to handle left-over bytes
7103   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7104   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7105   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7106   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7107   MF->insert(It, loopMBB);
7108   MF->insert(It, exitMBB);
7109 
7110   // Transfer the remainder of BB and its successor edges to exitMBB.
7111   exitMBB->splice(exitMBB->begin(), BB,
7112                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7113   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7114 
7115   // Load an immediate to varEnd.
7116   unsigned varEnd = MRI.createVirtualRegister(TRC);
7117   if (Subtarget->useMovt(*MF)) {
7118     unsigned Vtmp = varEnd;
7119     if ((LoopSize & 0xFFFF0000) != 0)
7120       Vtmp = MRI.createVirtualRegister(TRC);
7121     AddDefaultPred(BuildMI(BB, dl,
7122                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7123                            Vtmp).addImm(LoopSize & 0xFFFF));
7124 
7125     if ((LoopSize & 0xFFFF0000) != 0)
7126       AddDefaultPred(BuildMI(BB, dl,
7127                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7128                              varEnd)
7129                          .addReg(Vtmp)
7130                          .addImm(LoopSize >> 16));
7131   } else {
7132     MachineConstantPool *ConstantPool = MF->getConstantPool();
7133     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7134     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7135 
7136     // MachineConstantPool wants an explicit alignment.
7137     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7138     if (Align == 0)
7139       Align = getDataLayout()->getTypeAllocSize(C->getType());
7140     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7141 
7142     if (IsThumb1)
7143       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7144           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7145     else
7146       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7147           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7148   }
7149   BB->addSuccessor(loopMBB);
7150 
7151   // Generate the loop body:
7152   //   varPhi = PHI(varLoop, varEnd)
7153   //   srcPhi = PHI(srcLoop, src)
7154   //   destPhi = PHI(destLoop, dst)
7155   MachineBasicBlock *entryBB = BB;
7156   BB = loopMBB;
7157   unsigned varLoop = MRI.createVirtualRegister(TRC);
7158   unsigned varPhi = MRI.createVirtualRegister(TRC);
7159   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7160   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7161   unsigned destLoop = MRI.createVirtualRegister(TRC);
7162   unsigned destPhi = MRI.createVirtualRegister(TRC);
7163 
7164   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7165     .addReg(varLoop).addMBB(loopMBB)
7166     .addReg(varEnd).addMBB(entryBB);
7167   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7168     .addReg(srcLoop).addMBB(loopMBB)
7169     .addReg(src).addMBB(entryBB);
7170   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7171     .addReg(destLoop).addMBB(loopMBB)
7172     .addReg(dest).addMBB(entryBB);
7173 
7174   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7175   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7176   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7177   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7178              IsThumb1, IsThumb2);
7179   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7180              IsThumb1, IsThumb2);
7181 
7182   // Decrement loop variable by UnitSize.
7183   if (IsThumb1) {
7184     MachineInstrBuilder MIB =
7185         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7186     MIB = AddDefaultT1CC(MIB);
7187     MIB.addReg(varPhi).addImm(UnitSize);
7188     AddDefaultPred(MIB);
7189   } else {
7190     MachineInstrBuilder MIB =
7191         BuildMI(*BB, BB->end(), dl,
7192                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7193     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7194     MIB->getOperand(5).setReg(ARM::CPSR);
7195     MIB->getOperand(5).setIsDef(true);
7196   }
7197   BuildMI(*BB, BB->end(), dl,
7198           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7199       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7200 
7201   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7202   BB->addSuccessor(loopMBB);
7203   BB->addSuccessor(exitMBB);
7204 
7205   // Add epilogue to handle BytesLeft.
7206   BB = exitMBB;
7207   MachineInstr *StartOfExit = exitMBB->begin();
7208 
7209   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7210   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7211   unsigned srcIn = srcLoop;
7212   unsigned destIn = destLoop;
7213   for (unsigned i = 0; i < BytesLeft; i++) {
7214     unsigned srcOut = MRI.createVirtualRegister(TRC);
7215     unsigned destOut = MRI.createVirtualRegister(TRC);
7216     unsigned scratch = MRI.createVirtualRegister(TRC);
7217     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7218                IsThumb1, IsThumb2);
7219     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7220                IsThumb1, IsThumb2);
7221     srcIn = srcOut;
7222     destIn = destOut;
7223   }
7224 
7225   MI->eraseFromParent();   // The instruction is gone now.
7226   return BB;
7227 }
7228 
7229 MachineBasicBlock *
EmitLowered__chkstk(MachineInstr * MI,MachineBasicBlock * MBB) const7230 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7231                                        MachineBasicBlock *MBB) const {
7232   const TargetMachine &TM = getTargetMachine();
7233   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7234   DebugLoc DL = MI->getDebugLoc();
7235 
7236   assert(Subtarget->isTargetWindows() &&
7237          "__chkstk is only supported on Windows");
7238   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7239 
7240   // __chkstk takes the number of words to allocate on the stack in R4, and
7241   // returns the stack adjustment in number of bytes in R4.  This will not
7242   // clober any other registers (other than the obvious lr).
7243   //
7244   // Although, technically, IP should be considered a register which may be
7245   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7246   // thumb-2 environment, so there is no interworking required.  As a result, we
7247   // do not expect a veneer to be emitted by the linker, clobbering IP.
7248   //
7249   // Each module receives its own copy of __chkstk, so no import thunk is
7250   // required, again, ensuring that IP is not clobbered.
7251   //
7252   // Finally, although some linkers may theoretically provide a trampoline for
7253   // out of range calls (which is quite common due to a 32M range limitation of
7254   // branches for Thumb), we can generate the long-call version via
7255   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7256   // IP.
7257 
7258   switch (TM.getCodeModel()) {
7259   case CodeModel::Small:
7260   case CodeModel::Medium:
7261   case CodeModel::Default:
7262   case CodeModel::Kernel:
7263     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7264       .addImm((unsigned)ARMCC::AL).addReg(0)
7265       .addExternalSymbol("__chkstk")
7266       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7267       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7268       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7269     break;
7270   case CodeModel::Large:
7271   case CodeModel::JITDefault: {
7272     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7273     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7274 
7275     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7276       .addExternalSymbol("__chkstk");
7277     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7278       .addImm((unsigned)ARMCC::AL).addReg(0)
7279       .addReg(Reg, RegState::Kill)
7280       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7281       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7282       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7283     break;
7284   }
7285   }
7286 
7287   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7288                                       ARM::SP)
7289                               .addReg(ARM::SP).addReg(ARM::R4)));
7290 
7291   MI->eraseFromParent();
7292   return MBB;
7293 }
7294 
7295 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr * MI,MachineBasicBlock * BB) const7296 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7297                                                MachineBasicBlock *BB) const {
7298   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7299   DebugLoc dl = MI->getDebugLoc();
7300   bool isThumb2 = Subtarget->isThumb2();
7301   switch (MI->getOpcode()) {
7302   default: {
7303     MI->dump();
7304     llvm_unreachable("Unexpected instr type to insert");
7305   }
7306   // The Thumb2 pre-indexed stores have the same MI operands, they just
7307   // define them differently in the .td files from the isel patterns, so
7308   // they need pseudos.
7309   case ARM::t2STR_preidx:
7310     MI->setDesc(TII->get(ARM::t2STR_PRE));
7311     return BB;
7312   case ARM::t2STRB_preidx:
7313     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7314     return BB;
7315   case ARM::t2STRH_preidx:
7316     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7317     return BB;
7318 
7319   case ARM::STRi_preidx:
7320   case ARM::STRBi_preidx: {
7321     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7322       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7323     // Decode the offset.
7324     unsigned Offset = MI->getOperand(4).getImm();
7325     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7326     Offset = ARM_AM::getAM2Offset(Offset);
7327     if (isSub)
7328       Offset = -Offset;
7329 
7330     MachineMemOperand *MMO = *MI->memoperands_begin();
7331     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7332       .addOperand(MI->getOperand(0))  // Rn_wb
7333       .addOperand(MI->getOperand(1))  // Rt
7334       .addOperand(MI->getOperand(2))  // Rn
7335       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7336       .addOperand(MI->getOperand(5))  // pred
7337       .addOperand(MI->getOperand(6))
7338       .addMemOperand(MMO);
7339     MI->eraseFromParent();
7340     return BB;
7341   }
7342   case ARM::STRr_preidx:
7343   case ARM::STRBr_preidx:
7344   case ARM::STRH_preidx: {
7345     unsigned NewOpc;
7346     switch (MI->getOpcode()) {
7347     default: llvm_unreachable("unexpected opcode!");
7348     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7349     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7350     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7351     }
7352     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7353     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7354       MIB.addOperand(MI->getOperand(i));
7355     MI->eraseFromParent();
7356     return BB;
7357   }
7358 
7359   case ARM::tMOVCCr_pseudo: {
7360     // To "insert" a SELECT_CC instruction, we actually have to insert the
7361     // diamond control-flow pattern.  The incoming instruction knows the
7362     // destination vreg to set, the condition code register to branch on, the
7363     // true/false values to select between, and a branch opcode to use.
7364     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7365     MachineFunction::iterator It = BB;
7366     ++It;
7367 
7368     //  thisMBB:
7369     //  ...
7370     //   TrueVal = ...
7371     //   cmpTY ccX, r1, r2
7372     //   bCC copy1MBB
7373     //   fallthrough --> copy0MBB
7374     MachineBasicBlock *thisMBB  = BB;
7375     MachineFunction *F = BB->getParent();
7376     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7377     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7378     F->insert(It, copy0MBB);
7379     F->insert(It, sinkMBB);
7380 
7381     // Transfer the remainder of BB and its successor edges to sinkMBB.
7382     sinkMBB->splice(sinkMBB->begin(), BB,
7383                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7384     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7385 
7386     BB->addSuccessor(copy0MBB);
7387     BB->addSuccessor(sinkMBB);
7388 
7389     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7390       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7391 
7392     //  copy0MBB:
7393     //   %FalseValue = ...
7394     //   # fallthrough to sinkMBB
7395     BB = copy0MBB;
7396 
7397     // Update machine-CFG edges
7398     BB->addSuccessor(sinkMBB);
7399 
7400     //  sinkMBB:
7401     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7402     //  ...
7403     BB = sinkMBB;
7404     BuildMI(*BB, BB->begin(), dl,
7405             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7406       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7407       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7408 
7409     MI->eraseFromParent();   // The pseudo instruction is gone now.
7410     return BB;
7411   }
7412 
7413   case ARM::BCCi64:
7414   case ARM::BCCZi64: {
7415     // If there is an unconditional branch to the other successor, remove it.
7416     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7417 
7418     // Compare both parts that make up the double comparison separately for
7419     // equality.
7420     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7421 
7422     unsigned LHS1 = MI->getOperand(1).getReg();
7423     unsigned LHS2 = MI->getOperand(2).getReg();
7424     if (RHSisZero) {
7425       AddDefaultPred(BuildMI(BB, dl,
7426                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7427                      .addReg(LHS1).addImm(0));
7428       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7429         .addReg(LHS2).addImm(0)
7430         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7431     } else {
7432       unsigned RHS1 = MI->getOperand(3).getReg();
7433       unsigned RHS2 = MI->getOperand(4).getReg();
7434       AddDefaultPred(BuildMI(BB, dl,
7435                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7436                      .addReg(LHS1).addReg(RHS1));
7437       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7438         .addReg(LHS2).addReg(RHS2)
7439         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7440     }
7441 
7442     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7443     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7444     if (MI->getOperand(0).getImm() == ARMCC::NE)
7445       std::swap(destMBB, exitMBB);
7446 
7447     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7448       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7449     if (isThumb2)
7450       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7451     else
7452       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7453 
7454     MI->eraseFromParent();   // The pseudo instruction is gone now.
7455     return BB;
7456   }
7457 
7458   case ARM::Int_eh_sjlj_setjmp:
7459   case ARM::Int_eh_sjlj_setjmp_nofp:
7460   case ARM::tInt_eh_sjlj_setjmp:
7461   case ARM::t2Int_eh_sjlj_setjmp:
7462   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7463     EmitSjLjDispatchBlock(MI, BB);
7464     return BB;
7465 
7466   case ARM::ABS:
7467   case ARM::t2ABS: {
7468     // To insert an ABS instruction, we have to insert the
7469     // diamond control-flow pattern.  The incoming instruction knows the
7470     // source vreg to test against 0, the destination vreg to set,
7471     // the condition code register to branch on, the
7472     // true/false values to select between, and a branch opcode to use.
7473     // It transforms
7474     //     V1 = ABS V0
7475     // into
7476     //     V2 = MOVS V0
7477     //     BCC                      (branch to SinkBB if V0 >= 0)
7478     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7479     //     SinkBB: V1 = PHI(V2, V3)
7480     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7481     MachineFunction::iterator BBI = BB;
7482     ++BBI;
7483     MachineFunction *Fn = BB->getParent();
7484     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7485     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7486     Fn->insert(BBI, RSBBB);
7487     Fn->insert(BBI, SinkBB);
7488 
7489     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7490     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7491     bool isThumb2 = Subtarget->isThumb2();
7492     MachineRegisterInfo &MRI = Fn->getRegInfo();
7493     // In Thumb mode S must not be specified if source register is the SP or
7494     // PC and if destination register is the SP, so restrict register class
7495     unsigned NewRsbDstReg =
7496       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7497 
7498     // Transfer the remainder of BB and its successor edges to sinkMBB.
7499     SinkBB->splice(SinkBB->begin(), BB,
7500                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7501     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7502 
7503     BB->addSuccessor(RSBBB);
7504     BB->addSuccessor(SinkBB);
7505 
7506     // fall through to SinkMBB
7507     RSBBB->addSuccessor(SinkBB);
7508 
7509     // insert a cmp at the end of BB
7510     AddDefaultPred(BuildMI(BB, dl,
7511                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7512                    .addReg(ABSSrcReg).addImm(0));
7513 
7514     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7515     BuildMI(BB, dl,
7516       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7517       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7518 
7519     // insert rsbri in RSBBB
7520     // Note: BCC and rsbri will be converted into predicated rsbmi
7521     // by if-conversion pass
7522     BuildMI(*RSBBB, RSBBB->begin(), dl,
7523       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7524       .addReg(ABSSrcReg, RegState::Kill)
7525       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7526 
7527     // insert PHI in SinkBB,
7528     // reuse ABSDstReg to not change uses of ABS instruction
7529     BuildMI(*SinkBB, SinkBB->begin(), dl,
7530       TII->get(ARM::PHI), ABSDstReg)
7531       .addReg(NewRsbDstReg).addMBB(RSBBB)
7532       .addReg(ABSSrcReg).addMBB(BB);
7533 
7534     // remove ABS instruction
7535     MI->eraseFromParent();
7536 
7537     // return last added BB
7538     return SinkBB;
7539   }
7540   case ARM::COPY_STRUCT_BYVAL_I32:
7541     ++NumLoopByVals;
7542     return EmitStructByval(MI, BB);
7543   case ARM::WIN__CHKSTK:
7544     return EmitLowered__chkstk(MI, BB);
7545   }
7546 }
7547 
AdjustInstrPostInstrSelection(MachineInstr * MI,SDNode * Node) const7548 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7549                                                       SDNode *Node) const {
7550   const MCInstrDesc *MCID = &MI->getDesc();
7551   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7552   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7553   // operand is still set to noreg. If needed, set the optional operand's
7554   // register to CPSR, and remove the redundant implicit def.
7555   //
7556   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7557 
7558   // Rename pseudo opcodes.
7559   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7560   if (NewOpc) {
7561     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7562     MCID = &TII->get(NewOpc);
7563 
7564     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7565            "converted opcode should be the same except for cc_out");
7566 
7567     MI->setDesc(*MCID);
7568 
7569     // Add the optional cc_out operand
7570     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7571   }
7572   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7573 
7574   // Any ARM instruction that sets the 's' bit should specify an optional
7575   // "cc_out" operand in the last operand position.
7576   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7577     assert(!NewOpc && "Optional cc_out operand required");
7578     return;
7579   }
7580   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7581   // since we already have an optional CPSR def.
7582   bool definesCPSR = false;
7583   bool deadCPSR = false;
7584   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7585        i != e; ++i) {
7586     const MachineOperand &MO = MI->getOperand(i);
7587     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7588       definesCPSR = true;
7589       if (MO.isDead())
7590         deadCPSR = true;
7591       MI->RemoveOperand(i);
7592       break;
7593     }
7594   }
7595   if (!definesCPSR) {
7596     assert(!NewOpc && "Optional cc_out operand required");
7597     return;
7598   }
7599   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7600   if (deadCPSR) {
7601     assert(!MI->getOperand(ccOutIdx).getReg() &&
7602            "expect uninitialized optional cc_out operand");
7603     return;
7604   }
7605 
7606   // If this instruction was defined with an optional CPSR def and its dag node
7607   // had a live implicit CPSR def, then activate the optional CPSR def.
7608   MachineOperand &MO = MI->getOperand(ccOutIdx);
7609   MO.setReg(ARM::CPSR);
7610   MO.setIsDef(true);
7611 }
7612 
7613 //===----------------------------------------------------------------------===//
7614 //                           ARM Optimization Hooks
7615 //===----------------------------------------------------------------------===//
7616 
7617 // Helper function that checks if N is a null or all ones constant.
isZeroOrAllOnes(SDValue N,bool AllOnes)7618 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7619   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7620   if (!C)
7621     return false;
7622   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7623 }
7624 
7625 // Return true if N is conditionally 0 or all ones.
7626 // Detects these expressions where cc is an i1 value:
7627 //
7628 //   (select cc 0, y)   [AllOnes=0]
7629 //   (select cc y, 0)   [AllOnes=0]
7630 //   (zext cc)          [AllOnes=0]
7631 //   (sext cc)          [AllOnes=0/1]
7632 //   (select cc -1, y)  [AllOnes=1]
7633 //   (select cc y, -1)  [AllOnes=1]
7634 //
7635 // Invert is set when N is the null/all ones constant when CC is false.
7636 // OtherOp is set to the alternative value of N.
isConditionalZeroOrAllOnes(SDNode * N,bool AllOnes,SDValue & CC,bool & Invert,SDValue & OtherOp,SelectionDAG & DAG)7637 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7638                                        SDValue &CC, bool &Invert,
7639                                        SDValue &OtherOp,
7640                                        SelectionDAG &DAG) {
7641   switch (N->getOpcode()) {
7642   default: return false;
7643   case ISD::SELECT: {
7644     CC = N->getOperand(0);
7645     SDValue N1 = N->getOperand(1);
7646     SDValue N2 = N->getOperand(2);
7647     if (isZeroOrAllOnes(N1, AllOnes)) {
7648       Invert = false;
7649       OtherOp = N2;
7650       return true;
7651     }
7652     if (isZeroOrAllOnes(N2, AllOnes)) {
7653       Invert = true;
7654       OtherOp = N1;
7655       return true;
7656     }
7657     return false;
7658   }
7659   case ISD::ZERO_EXTEND:
7660     // (zext cc) can never be the all ones value.
7661     if (AllOnes)
7662       return false;
7663     // Fall through.
7664   case ISD::SIGN_EXTEND: {
7665     EVT VT = N->getValueType(0);
7666     CC = N->getOperand(0);
7667     if (CC.getValueType() != MVT::i1)
7668       return false;
7669     Invert = !AllOnes;
7670     if (AllOnes)
7671       // When looking for an AllOnes constant, N is an sext, and the 'other'
7672       // value is 0.
7673       OtherOp = DAG.getConstant(0, VT);
7674     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7675       // When looking for a 0 constant, N can be zext or sext.
7676       OtherOp = DAG.getConstant(1, VT);
7677     else
7678       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7679     return true;
7680   }
7681   }
7682 }
7683 
7684 // Combine a constant select operand into its use:
7685 //
7686 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7687 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7688 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7689 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7690 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7691 //
7692 // The transform is rejected if the select doesn't have a constant operand that
7693 // is null, or all ones when AllOnes is set.
7694 //
7695 // Also recognize sext/zext from i1:
7696 //
7697 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7698 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7699 //
7700 // These transformations eventually create predicated instructions.
7701 //
7702 // @param N       The node to transform.
7703 // @param Slct    The N operand that is a select.
7704 // @param OtherOp The other N operand (x above).
7705 // @param DCI     Context.
7706 // @param AllOnes Require the select constant to be all ones instead of null.
7707 // @returns The new node, or SDValue() on failure.
7708 static
combineSelectAndUse(SDNode * N,SDValue Slct,SDValue OtherOp,TargetLowering::DAGCombinerInfo & DCI,bool AllOnes=false)7709 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7710                             TargetLowering::DAGCombinerInfo &DCI,
7711                             bool AllOnes = false) {
7712   SelectionDAG &DAG = DCI.DAG;
7713   EVT VT = N->getValueType(0);
7714   SDValue NonConstantVal;
7715   SDValue CCOp;
7716   bool SwapSelectOps;
7717   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7718                                   NonConstantVal, DAG))
7719     return SDValue();
7720 
7721   // Slct is now know to be the desired identity constant when CC is true.
7722   SDValue TrueVal = OtherOp;
7723   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7724                                  OtherOp, NonConstantVal);
7725   // Unless SwapSelectOps says CC should be false.
7726   if (SwapSelectOps)
7727     std::swap(TrueVal, FalseVal);
7728 
7729   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7730                      CCOp, TrueVal, FalseVal);
7731 }
7732 
7733 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7734 static
combineSelectAndUseCommutative(SDNode * N,bool AllOnes,TargetLowering::DAGCombinerInfo & DCI)7735 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7736                                        TargetLowering::DAGCombinerInfo &DCI) {
7737   SDValue N0 = N->getOperand(0);
7738   SDValue N1 = N->getOperand(1);
7739   if (N0.getNode()->hasOneUse()) {
7740     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7741     if (Result.getNode())
7742       return Result;
7743   }
7744   if (N1.getNode()->hasOneUse()) {
7745     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7746     if (Result.getNode())
7747       return Result;
7748   }
7749   return SDValue();
7750 }
7751 
7752 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7753 // (only after legalization).
AddCombineToVPADDL(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)7754 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7755                                  TargetLowering::DAGCombinerInfo &DCI,
7756                                  const ARMSubtarget *Subtarget) {
7757 
7758   // Only perform optimization if after legalize, and if NEON is available. We
7759   // also expected both operands to be BUILD_VECTORs.
7760   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7761       || N0.getOpcode() != ISD::BUILD_VECTOR
7762       || N1.getOpcode() != ISD::BUILD_VECTOR)
7763     return SDValue();
7764 
7765   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7766   EVT VT = N->getValueType(0);
7767   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7768     return SDValue();
7769 
7770   // Check that the vector operands are of the right form.
7771   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7772   // operands, where N is the size of the formed vector.
7773   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7774   // index such that we have a pair wise add pattern.
7775 
7776   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7777   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7778     return SDValue();
7779   SDValue Vec = N0->getOperand(0)->getOperand(0);
7780   SDNode *V = Vec.getNode();
7781   unsigned nextIndex = 0;
7782 
7783   // For each operands to the ADD which are BUILD_VECTORs,
7784   // check to see if each of their operands are an EXTRACT_VECTOR with
7785   // the same vector and appropriate index.
7786   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7787     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7788         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7789 
7790       SDValue ExtVec0 = N0->getOperand(i);
7791       SDValue ExtVec1 = N1->getOperand(i);
7792 
7793       // First operand is the vector, verify its the same.
7794       if (V != ExtVec0->getOperand(0).getNode() ||
7795           V != ExtVec1->getOperand(0).getNode())
7796         return SDValue();
7797 
7798       // Second is the constant, verify its correct.
7799       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7800       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7801 
7802       // For the constant, we want to see all the even or all the odd.
7803       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7804           || C1->getZExtValue() != nextIndex+1)
7805         return SDValue();
7806 
7807       // Increment index.
7808       nextIndex+=2;
7809     } else
7810       return SDValue();
7811   }
7812 
7813   // Create VPADDL node.
7814   SelectionDAG &DAG = DCI.DAG;
7815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7816 
7817   // Build operand list.
7818   SmallVector<SDValue, 8> Ops;
7819   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7820                                 TLI.getPointerTy()));
7821 
7822   // Input is the vector.
7823   Ops.push_back(Vec);
7824 
7825   // Get widened type and narrowed type.
7826   MVT widenType;
7827   unsigned numElem = VT.getVectorNumElements();
7828 
7829   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7830   switch (inputLaneType.getSimpleVT().SimpleTy) {
7831     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7832     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7833     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7834     default:
7835       llvm_unreachable("Invalid vector element type for padd optimization.");
7836   }
7837 
7838   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7839   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7840   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7841 }
7842 
findMUL_LOHI(SDValue V)7843 static SDValue findMUL_LOHI(SDValue V) {
7844   if (V->getOpcode() == ISD::UMUL_LOHI ||
7845       V->getOpcode() == ISD::SMUL_LOHI)
7846     return V;
7847   return SDValue();
7848 }
7849 
AddCombineTo64bitMLAL(SDNode * AddcNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)7850 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7851                                      TargetLowering::DAGCombinerInfo &DCI,
7852                                      const ARMSubtarget *Subtarget) {
7853 
7854   if (Subtarget->isThumb1Only()) return SDValue();
7855 
7856   // Only perform the checks after legalize when the pattern is available.
7857   if (DCI.isBeforeLegalize()) return SDValue();
7858 
7859   // Look for multiply add opportunities.
7860   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7861   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7862   // a glue link from the first add to the second add.
7863   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7864   // a S/UMLAL instruction.
7865   //          loAdd   UMUL_LOHI
7866   //            \    / :lo    \ :hi
7867   //             \  /          \          [no multiline comment]
7868   //              ADDC         |  hiAdd
7869   //                 \ :glue  /  /
7870   //                  \      /  /
7871   //                    ADDE
7872   //
7873   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7874   SDValue AddcOp0 = AddcNode->getOperand(0);
7875   SDValue AddcOp1 = AddcNode->getOperand(1);
7876 
7877   // Check if the two operands are from the same mul_lohi node.
7878   if (AddcOp0.getNode() == AddcOp1.getNode())
7879     return SDValue();
7880 
7881   assert(AddcNode->getNumValues() == 2 &&
7882          AddcNode->getValueType(0) == MVT::i32 &&
7883          "Expect ADDC with two result values. First: i32");
7884 
7885   // Check that we have a glued ADDC node.
7886   if (AddcNode->getValueType(1) != MVT::Glue)
7887     return SDValue();
7888 
7889   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7890   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7891       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7892       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7893       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7894     return SDValue();
7895 
7896   // Look for the glued ADDE.
7897   SDNode* AddeNode = AddcNode->getGluedUser();
7898   if (!AddeNode)
7899     return SDValue();
7900 
7901   // Make sure it is really an ADDE.
7902   if (AddeNode->getOpcode() != ISD::ADDE)
7903     return SDValue();
7904 
7905   assert(AddeNode->getNumOperands() == 3 &&
7906          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7907          "ADDE node has the wrong inputs");
7908 
7909   // Check for the triangle shape.
7910   SDValue AddeOp0 = AddeNode->getOperand(0);
7911   SDValue AddeOp1 = AddeNode->getOperand(1);
7912 
7913   // Make sure that the ADDE operands are not coming from the same node.
7914   if (AddeOp0.getNode() == AddeOp1.getNode())
7915     return SDValue();
7916 
7917   // Find the MUL_LOHI node walking up ADDE's operands.
7918   bool IsLeftOperandMUL = false;
7919   SDValue MULOp = findMUL_LOHI(AddeOp0);
7920   if (MULOp == SDValue())
7921    MULOp = findMUL_LOHI(AddeOp1);
7922   else
7923     IsLeftOperandMUL = true;
7924   if (MULOp == SDValue())
7925     return SDValue();
7926 
7927   // Figure out the right opcode.
7928   unsigned Opc = MULOp->getOpcode();
7929   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7930 
7931   // Figure out the high and low input values to the MLAL node.
7932   SDValue* HiAdd = nullptr;
7933   SDValue* LoMul = nullptr;
7934   SDValue* LowAdd = nullptr;
7935 
7936   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7937   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7938     return SDValue();
7939 
7940   if (IsLeftOperandMUL)
7941     HiAdd = &AddeOp1;
7942   else
7943     HiAdd = &AddeOp0;
7944 
7945 
7946   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7947   // whose low result is fed to the ADDC we are checking.
7948 
7949   if (AddcOp0 == MULOp.getValue(0)) {
7950     LoMul = &AddcOp0;
7951     LowAdd = &AddcOp1;
7952   }
7953   if (AddcOp1 == MULOp.getValue(0)) {
7954     LoMul = &AddcOp1;
7955     LowAdd = &AddcOp0;
7956   }
7957 
7958   if (!LoMul)
7959     return SDValue();
7960 
7961   // Create the merged node.
7962   SelectionDAG &DAG = DCI.DAG;
7963 
7964   // Build operand list.
7965   SmallVector<SDValue, 8> Ops;
7966   Ops.push_back(LoMul->getOperand(0));
7967   Ops.push_back(LoMul->getOperand(1));
7968   Ops.push_back(*LowAdd);
7969   Ops.push_back(*HiAdd);
7970 
7971   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7972                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7973 
7974   // Replace the ADDs' nodes uses by the MLA node's values.
7975   SDValue HiMLALResult(MLALNode.getNode(), 1);
7976   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7977 
7978   SDValue LoMLALResult(MLALNode.getNode(), 0);
7979   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7980 
7981   // Return original node to notify the driver to stop replacing.
7982   SDValue resNode(AddcNode, 0);
7983   return resNode;
7984 }
7985 
7986 /// PerformADDCCombine - Target-specific dag combine transform from
7987 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
PerformADDCCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)7988 static SDValue PerformADDCCombine(SDNode *N,
7989                                  TargetLowering::DAGCombinerInfo &DCI,
7990                                  const ARMSubtarget *Subtarget) {
7991 
7992   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7993 
7994 }
7995 
7996 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7997 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7998 /// called with the default operands, and if that fails, with commuted
7999 /// operands.
PerformADDCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8000 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8001                                           TargetLowering::DAGCombinerInfo &DCI,
8002                                           const ARMSubtarget *Subtarget){
8003 
8004   // Attempt to create vpaddl for this add.
8005   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8006   if (Result.getNode())
8007     return Result;
8008 
8009   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8010   if (N0.getNode()->hasOneUse()) {
8011     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8012     if (Result.getNode()) return Result;
8013   }
8014   return SDValue();
8015 }
8016 
8017 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8018 ///
PerformADDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8019 static SDValue PerformADDCombine(SDNode *N,
8020                                  TargetLowering::DAGCombinerInfo &DCI,
8021                                  const ARMSubtarget *Subtarget) {
8022   SDValue N0 = N->getOperand(0);
8023   SDValue N1 = N->getOperand(1);
8024 
8025   // First try with the default operand order.
8026   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8027   if (Result.getNode())
8028     return Result;
8029 
8030   // If that didn't work, try again with the operands commuted.
8031   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8032 }
8033 
8034 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8035 ///
PerformSUBCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8036 static SDValue PerformSUBCombine(SDNode *N,
8037                                  TargetLowering::DAGCombinerInfo &DCI) {
8038   SDValue N0 = N->getOperand(0);
8039   SDValue N1 = N->getOperand(1);
8040 
8041   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8042   if (N1.getNode()->hasOneUse()) {
8043     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8044     if (Result.getNode()) return Result;
8045   }
8046 
8047   return SDValue();
8048 }
8049 
8050 /// PerformVMULCombine
8051 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8052 /// special multiplier accumulator forwarding.
8053 ///   vmul d3, d0, d2
8054 ///   vmla d3, d1, d2
8055 /// is faster than
8056 ///   vadd d3, d0, d1
8057 ///   vmul d3, d3, d2
8058 //  However, for (A + B) * (A + B),
8059 //    vadd d2, d0, d1
8060 //    vmul d3, d0, d2
8061 //    vmla d3, d1, d2
8062 //  is slower than
8063 //    vadd d2, d0, d1
8064 //    vmul d3, d2, d2
PerformVMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8065 static SDValue PerformVMULCombine(SDNode *N,
8066                                   TargetLowering::DAGCombinerInfo &DCI,
8067                                   const ARMSubtarget *Subtarget) {
8068   if (!Subtarget->hasVMLxForwarding())
8069     return SDValue();
8070 
8071   SelectionDAG &DAG = DCI.DAG;
8072   SDValue N0 = N->getOperand(0);
8073   SDValue N1 = N->getOperand(1);
8074   unsigned Opcode = N0.getOpcode();
8075   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8076       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8077     Opcode = N1.getOpcode();
8078     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8079         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8080       return SDValue();
8081     std::swap(N0, N1);
8082   }
8083 
8084   if (N0 == N1)
8085     return SDValue();
8086 
8087   EVT VT = N->getValueType(0);
8088   SDLoc DL(N);
8089   SDValue N00 = N0->getOperand(0);
8090   SDValue N01 = N0->getOperand(1);
8091   return DAG.getNode(Opcode, DL, VT,
8092                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8093                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8094 }
8095 
PerformMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8096 static SDValue PerformMULCombine(SDNode *N,
8097                                  TargetLowering::DAGCombinerInfo &DCI,
8098                                  const ARMSubtarget *Subtarget) {
8099   SelectionDAG &DAG = DCI.DAG;
8100 
8101   if (Subtarget->isThumb1Only())
8102     return SDValue();
8103 
8104   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8105     return SDValue();
8106 
8107   EVT VT = N->getValueType(0);
8108   if (VT.is64BitVector() || VT.is128BitVector())
8109     return PerformVMULCombine(N, DCI, Subtarget);
8110   if (VT != MVT::i32)
8111     return SDValue();
8112 
8113   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8114   if (!C)
8115     return SDValue();
8116 
8117   int64_t MulAmt = C->getSExtValue();
8118   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8119 
8120   ShiftAmt = ShiftAmt & (32 - 1);
8121   SDValue V = N->getOperand(0);
8122   SDLoc DL(N);
8123 
8124   SDValue Res;
8125   MulAmt >>= ShiftAmt;
8126 
8127   if (MulAmt >= 0) {
8128     if (isPowerOf2_32(MulAmt - 1)) {
8129       // (mul x, 2^N + 1) => (add (shl x, N), x)
8130       Res = DAG.getNode(ISD::ADD, DL, VT,
8131                         V,
8132                         DAG.getNode(ISD::SHL, DL, VT,
8133                                     V,
8134                                     DAG.getConstant(Log2_32(MulAmt - 1),
8135                                                     MVT::i32)));
8136     } else if (isPowerOf2_32(MulAmt + 1)) {
8137       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8138       Res = DAG.getNode(ISD::SUB, DL, VT,
8139                         DAG.getNode(ISD::SHL, DL, VT,
8140                                     V,
8141                                     DAG.getConstant(Log2_32(MulAmt + 1),
8142                                                     MVT::i32)),
8143                         V);
8144     } else
8145       return SDValue();
8146   } else {
8147     uint64_t MulAmtAbs = -MulAmt;
8148     if (isPowerOf2_32(MulAmtAbs + 1)) {
8149       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8150       Res = DAG.getNode(ISD::SUB, DL, VT,
8151                         V,
8152                         DAG.getNode(ISD::SHL, DL, VT,
8153                                     V,
8154                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8155                                                     MVT::i32)));
8156     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8157       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8158       Res = DAG.getNode(ISD::ADD, DL, VT,
8159                         V,
8160                         DAG.getNode(ISD::SHL, DL, VT,
8161                                     V,
8162                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8163                                                     MVT::i32)));
8164       Res = DAG.getNode(ISD::SUB, DL, VT,
8165                         DAG.getConstant(0, MVT::i32),Res);
8166 
8167     } else
8168       return SDValue();
8169   }
8170 
8171   if (ShiftAmt != 0)
8172     Res = DAG.getNode(ISD::SHL, DL, VT,
8173                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8174 
8175   // Do not add new nodes to DAG combiner worklist.
8176   DCI.CombineTo(N, Res, false);
8177   return SDValue();
8178 }
8179 
PerformANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8180 static SDValue PerformANDCombine(SDNode *N,
8181                                  TargetLowering::DAGCombinerInfo &DCI,
8182                                  const ARMSubtarget *Subtarget) {
8183 
8184   // Attempt to use immediate-form VBIC
8185   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8186   SDLoc dl(N);
8187   EVT VT = N->getValueType(0);
8188   SelectionDAG &DAG = DCI.DAG;
8189 
8190   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8191     return SDValue();
8192 
8193   APInt SplatBits, SplatUndef;
8194   unsigned SplatBitSize;
8195   bool HasAnyUndefs;
8196   if (BVN &&
8197       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8198     if (SplatBitSize <= 64) {
8199       EVT VbicVT;
8200       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8201                                       SplatUndef.getZExtValue(), SplatBitSize,
8202                                       DAG, VbicVT, VT.is128BitVector(),
8203                                       OtherModImm);
8204       if (Val.getNode()) {
8205         SDValue Input =
8206           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8207         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8208         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8209       }
8210     }
8211   }
8212 
8213   if (!Subtarget->isThumb1Only()) {
8214     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8215     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8216     if (Result.getNode())
8217       return Result;
8218   }
8219 
8220   return SDValue();
8221 }
8222 
8223 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
PerformORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8224 static SDValue PerformORCombine(SDNode *N,
8225                                 TargetLowering::DAGCombinerInfo &DCI,
8226                                 const ARMSubtarget *Subtarget) {
8227   // Attempt to use immediate-form VORR
8228   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8229   SDLoc dl(N);
8230   EVT VT = N->getValueType(0);
8231   SelectionDAG &DAG = DCI.DAG;
8232 
8233   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8234     return SDValue();
8235 
8236   APInt SplatBits, SplatUndef;
8237   unsigned SplatBitSize;
8238   bool HasAnyUndefs;
8239   if (BVN && Subtarget->hasNEON() &&
8240       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8241     if (SplatBitSize <= 64) {
8242       EVT VorrVT;
8243       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8244                                       SplatUndef.getZExtValue(), SplatBitSize,
8245                                       DAG, VorrVT, VT.is128BitVector(),
8246                                       OtherModImm);
8247       if (Val.getNode()) {
8248         SDValue Input =
8249           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8250         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8251         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8252       }
8253     }
8254   }
8255 
8256   if (!Subtarget->isThumb1Only()) {
8257     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8258     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8259     if (Result.getNode())
8260       return Result;
8261   }
8262 
8263   // The code below optimizes (or (and X, Y), Z).
8264   // The AND operand needs to have a single user to make these optimizations
8265   // profitable.
8266   SDValue N0 = N->getOperand(0);
8267   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8268     return SDValue();
8269   SDValue N1 = N->getOperand(1);
8270 
8271   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8272   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8273       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8274     APInt SplatUndef;
8275     unsigned SplatBitSize;
8276     bool HasAnyUndefs;
8277 
8278     APInt SplatBits0, SplatBits1;
8279     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8280     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8281     // Ensure that the second operand of both ands are constants
8282     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8283                                       HasAnyUndefs) && !HasAnyUndefs) {
8284         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8285                                           HasAnyUndefs) && !HasAnyUndefs) {
8286             // Ensure that the bit width of the constants are the same and that
8287             // the splat arguments are logical inverses as per the pattern we
8288             // are trying to simplify.
8289             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8290                 SplatBits0 == ~SplatBits1) {
8291                 // Canonicalize the vector type to make instruction selection
8292                 // simpler.
8293                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8294                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8295                                              N0->getOperand(1),
8296                                              N0->getOperand(0),
8297                                              N1->getOperand(0));
8298                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8299             }
8300         }
8301     }
8302   }
8303 
8304   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8305   // reasonable.
8306 
8307   // BFI is only available on V6T2+
8308   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8309     return SDValue();
8310 
8311   SDLoc DL(N);
8312   // 1) or (and A, mask), val => ARMbfi A, val, mask
8313   //      iff (val & mask) == val
8314   //
8315   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8316   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8317   //          && mask == ~mask2
8318   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8319   //          && ~mask == mask2
8320   //  (i.e., copy a bitfield value into another bitfield of the same width)
8321 
8322   if (VT != MVT::i32)
8323     return SDValue();
8324 
8325   SDValue N00 = N0.getOperand(0);
8326 
8327   // The value and the mask need to be constants so we can verify this is
8328   // actually a bitfield set. If the mask is 0xffff, we can do better
8329   // via a movt instruction, so don't use BFI in that case.
8330   SDValue MaskOp = N0.getOperand(1);
8331   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8332   if (!MaskC)
8333     return SDValue();
8334   unsigned Mask = MaskC->getZExtValue();
8335   if (Mask == 0xffff)
8336     return SDValue();
8337   SDValue Res;
8338   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8339   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8340   if (N1C) {
8341     unsigned Val = N1C->getZExtValue();
8342     if ((Val & ~Mask) != Val)
8343       return SDValue();
8344 
8345     if (ARM::isBitFieldInvertedMask(Mask)) {
8346       Val >>= countTrailingZeros(~Mask);
8347 
8348       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8349                         DAG.getConstant(Val, MVT::i32),
8350                         DAG.getConstant(Mask, MVT::i32));
8351 
8352       // Do not add new nodes to DAG combiner worklist.
8353       DCI.CombineTo(N, Res, false);
8354       return SDValue();
8355     }
8356   } else if (N1.getOpcode() == ISD::AND) {
8357     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8358     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8359     if (!N11C)
8360       return SDValue();
8361     unsigned Mask2 = N11C->getZExtValue();
8362 
8363     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8364     // as is to match.
8365     if (ARM::isBitFieldInvertedMask(Mask) &&
8366         (Mask == ~Mask2)) {
8367       // The pack halfword instruction works better for masks that fit it,
8368       // so use that when it's available.
8369       if (Subtarget->hasT2ExtractPack() &&
8370           (Mask == 0xffff || Mask == 0xffff0000))
8371         return SDValue();
8372       // 2a
8373       unsigned amt = countTrailingZeros(Mask2);
8374       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8375                         DAG.getConstant(amt, MVT::i32));
8376       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8377                         DAG.getConstant(Mask, MVT::i32));
8378       // Do not add new nodes to DAG combiner worklist.
8379       DCI.CombineTo(N, Res, false);
8380       return SDValue();
8381     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8382                (~Mask == Mask2)) {
8383       // The pack halfword instruction works better for masks that fit it,
8384       // so use that when it's available.
8385       if (Subtarget->hasT2ExtractPack() &&
8386           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8387         return SDValue();
8388       // 2b
8389       unsigned lsb = countTrailingZeros(Mask);
8390       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8391                         DAG.getConstant(lsb, MVT::i32));
8392       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8393                         DAG.getConstant(Mask2, MVT::i32));
8394       // Do not add new nodes to DAG combiner worklist.
8395       DCI.CombineTo(N, Res, false);
8396       return SDValue();
8397     }
8398   }
8399 
8400   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8401       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8402       ARM::isBitFieldInvertedMask(~Mask)) {
8403     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8404     // where lsb(mask) == #shamt and masked bits of B are known zero.
8405     SDValue ShAmt = N00.getOperand(1);
8406     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8407     unsigned LSB = countTrailingZeros(Mask);
8408     if (ShAmtC != LSB)
8409       return SDValue();
8410 
8411     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8412                       DAG.getConstant(~Mask, MVT::i32));
8413 
8414     // Do not add new nodes to DAG combiner worklist.
8415     DCI.CombineTo(N, Res, false);
8416   }
8417 
8418   return SDValue();
8419 }
8420 
PerformXORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8421 static SDValue PerformXORCombine(SDNode *N,
8422                                  TargetLowering::DAGCombinerInfo &DCI,
8423                                  const ARMSubtarget *Subtarget) {
8424   EVT VT = N->getValueType(0);
8425   SelectionDAG &DAG = DCI.DAG;
8426 
8427   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8428     return SDValue();
8429 
8430   if (!Subtarget->isThumb1Only()) {
8431     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8432     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8433     if (Result.getNode())
8434       return Result;
8435   }
8436 
8437   return SDValue();
8438 }
8439 
8440 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8441 /// the bits being cleared by the AND are not demanded by the BFI.
PerformBFICombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8442 static SDValue PerformBFICombine(SDNode *N,
8443                                  TargetLowering::DAGCombinerInfo &DCI) {
8444   SDValue N1 = N->getOperand(1);
8445   if (N1.getOpcode() == ISD::AND) {
8446     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8447     if (!N11C)
8448       return SDValue();
8449     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8450     unsigned LSB = countTrailingZeros(~InvMask);
8451     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8452     assert(Width <
8453                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8454            "undefined behavior");
8455     unsigned Mask = (1u << Width) - 1;
8456     unsigned Mask2 = N11C->getZExtValue();
8457     if ((Mask & (~Mask2)) == 0)
8458       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8459                              N->getOperand(0), N1.getOperand(0),
8460                              N->getOperand(2));
8461   }
8462   return SDValue();
8463 }
8464 
8465 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8466 /// ARMISD::VMOVRRD.
PerformVMOVRRDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8467 static SDValue PerformVMOVRRDCombine(SDNode *N,
8468                                      TargetLowering::DAGCombinerInfo &DCI,
8469                                      const ARMSubtarget *Subtarget) {
8470   // vmovrrd(vmovdrr x, y) -> x,y
8471   SDValue InDouble = N->getOperand(0);
8472   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8473     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8474 
8475   // vmovrrd(load f64) -> (load i32), (load i32)
8476   SDNode *InNode = InDouble.getNode();
8477   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8478       InNode->getValueType(0) == MVT::f64 &&
8479       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8480       !cast<LoadSDNode>(InNode)->isVolatile()) {
8481     // TODO: Should this be done for non-FrameIndex operands?
8482     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8483 
8484     SelectionDAG &DAG = DCI.DAG;
8485     SDLoc DL(LD);
8486     SDValue BasePtr = LD->getBasePtr();
8487     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8488                                  LD->getPointerInfo(), LD->isVolatile(),
8489                                  LD->isNonTemporal(), LD->isInvariant(),
8490                                  LD->getAlignment());
8491 
8492     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8493                                     DAG.getConstant(4, MVT::i32));
8494     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8495                                  LD->getPointerInfo(), LD->isVolatile(),
8496                                  LD->isNonTemporal(), LD->isInvariant(),
8497                                  std::min(4U, LD->getAlignment() / 2));
8498 
8499     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8500     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8501       std::swap (NewLD1, NewLD2);
8502     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8503     return Result;
8504   }
8505 
8506   return SDValue();
8507 }
8508 
8509 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8510 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
PerformVMOVDRRCombine(SDNode * N,SelectionDAG & DAG)8511 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8512   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8513   SDValue Op0 = N->getOperand(0);
8514   SDValue Op1 = N->getOperand(1);
8515   if (Op0.getOpcode() == ISD::BITCAST)
8516     Op0 = Op0.getOperand(0);
8517   if (Op1.getOpcode() == ISD::BITCAST)
8518     Op1 = Op1.getOperand(0);
8519   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8520       Op0.getNode() == Op1.getNode() &&
8521       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8522     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8523                        N->getValueType(0), Op0.getOperand(0));
8524   return SDValue();
8525 }
8526 
8527 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8528 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8529 /// i64 vector to have f64 elements, since the value can then be loaded
8530 /// directly into a VFP register.
hasNormalLoadOperand(SDNode * N)8531 static bool hasNormalLoadOperand(SDNode *N) {
8532   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8533   for (unsigned i = 0; i < NumElts; ++i) {
8534     SDNode *Elt = N->getOperand(i).getNode();
8535     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8536       return true;
8537   }
8538   return false;
8539 }
8540 
8541 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8542 /// ISD::BUILD_VECTOR.
PerformBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8543 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8544                                           TargetLowering::DAGCombinerInfo &DCI,
8545                                           const ARMSubtarget *Subtarget) {
8546   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8547   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8548   // into a pair of GPRs, which is fine when the value is used as a scalar,
8549   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8550   SelectionDAG &DAG = DCI.DAG;
8551   if (N->getNumOperands() == 2) {
8552     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8553     if (RV.getNode())
8554       return RV;
8555   }
8556 
8557   // Load i64 elements as f64 values so that type legalization does not split
8558   // them up into i32 values.
8559   EVT VT = N->getValueType(0);
8560   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8561     return SDValue();
8562   SDLoc dl(N);
8563   SmallVector<SDValue, 8> Ops;
8564   unsigned NumElts = VT.getVectorNumElements();
8565   for (unsigned i = 0; i < NumElts; ++i) {
8566     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8567     Ops.push_back(V);
8568     // Make the DAGCombiner fold the bitcast.
8569     DCI.AddToWorklist(V.getNode());
8570   }
8571   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8572   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8573   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8574 }
8575 
8576 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8577 static SDValue
PerformARMBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8578 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8579   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8580   // At that time, we may have inserted bitcasts from integer to float.
8581   // If these bitcasts have survived DAGCombine, change the lowering of this
8582   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8583   // force to use floating point types.
8584 
8585   // Make sure we can change the type of the vector.
8586   // This is possible iff:
8587   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8588   //    1.1. Vector is used only once.
8589   //    1.2. Use is a bit convert to an integer type.
8590   // 2. The size of its operands are 32-bits (64-bits are not legal).
8591   EVT VT = N->getValueType(0);
8592   EVT EltVT = VT.getVectorElementType();
8593 
8594   // Check 1.1. and 2.
8595   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8596     return SDValue();
8597 
8598   // By construction, the input type must be float.
8599   assert(EltVT == MVT::f32 && "Unexpected type!");
8600 
8601   // Check 1.2.
8602   SDNode *Use = *N->use_begin();
8603   if (Use->getOpcode() != ISD::BITCAST ||
8604       Use->getValueType(0).isFloatingPoint())
8605     return SDValue();
8606 
8607   // Check profitability.
8608   // Model is, if more than half of the relevant operands are bitcast from
8609   // i32, turn the build_vector into a sequence of insert_vector_elt.
8610   // Relevant operands are everything that is not statically
8611   // (i.e., at compile time) bitcasted.
8612   unsigned NumOfBitCastedElts = 0;
8613   unsigned NumElts = VT.getVectorNumElements();
8614   unsigned NumOfRelevantElts = NumElts;
8615   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8616     SDValue Elt = N->getOperand(Idx);
8617     if (Elt->getOpcode() == ISD::BITCAST) {
8618       // Assume only bit cast to i32 will go away.
8619       if (Elt->getOperand(0).getValueType() == MVT::i32)
8620         ++NumOfBitCastedElts;
8621     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8622       // Constants are statically casted, thus do not count them as
8623       // relevant operands.
8624       --NumOfRelevantElts;
8625   }
8626 
8627   // Check if more than half of the elements require a non-free bitcast.
8628   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8629     return SDValue();
8630 
8631   SelectionDAG &DAG = DCI.DAG;
8632   // Create the new vector type.
8633   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8634   // Check if the type is legal.
8635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8636   if (!TLI.isTypeLegal(VecVT))
8637     return SDValue();
8638 
8639   // Combine:
8640   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8641   // => BITCAST INSERT_VECTOR_ELT
8642   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8643   //                      (BITCAST EN), N.
8644   SDValue Vec = DAG.getUNDEF(VecVT);
8645   SDLoc dl(N);
8646   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8647     SDValue V = N->getOperand(Idx);
8648     if (V.getOpcode() == ISD::UNDEF)
8649       continue;
8650     if (V.getOpcode() == ISD::BITCAST &&
8651         V->getOperand(0).getValueType() == MVT::i32)
8652       // Fold obvious case.
8653       V = V.getOperand(0);
8654     else {
8655       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8656       // Make the DAGCombiner fold the bitcasts.
8657       DCI.AddToWorklist(V.getNode());
8658     }
8659     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8660     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8661   }
8662   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8663   // Make the DAGCombiner fold the bitcasts.
8664   DCI.AddToWorklist(Vec.getNode());
8665   return Vec;
8666 }
8667 
8668 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8669 /// ISD::INSERT_VECTOR_ELT.
PerformInsertEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8670 static SDValue PerformInsertEltCombine(SDNode *N,
8671                                        TargetLowering::DAGCombinerInfo &DCI) {
8672   // Bitcast an i64 load inserted into a vector to f64.
8673   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8674   EVT VT = N->getValueType(0);
8675   SDNode *Elt = N->getOperand(1).getNode();
8676   if (VT.getVectorElementType() != MVT::i64 ||
8677       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8678     return SDValue();
8679 
8680   SelectionDAG &DAG = DCI.DAG;
8681   SDLoc dl(N);
8682   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8683                                  VT.getVectorNumElements());
8684   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8685   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8686   // Make the DAGCombiner fold the bitcasts.
8687   DCI.AddToWorklist(Vec.getNode());
8688   DCI.AddToWorklist(V.getNode());
8689   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8690                                Vec, V, N->getOperand(2));
8691   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8692 }
8693 
8694 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8695 /// ISD::VECTOR_SHUFFLE.
PerformVECTOR_SHUFFLECombine(SDNode * N,SelectionDAG & DAG)8696 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8697   // The LLVM shufflevector instruction does not require the shuffle mask
8698   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8699   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8700   // operands do not match the mask length, they are extended by concatenating
8701   // them with undef vectors.  That is probably the right thing for other
8702   // targets, but for NEON it is better to concatenate two double-register
8703   // size vector operands into a single quad-register size vector.  Do that
8704   // transformation here:
8705   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8706   //   shuffle(concat(v1, v2), undef)
8707   SDValue Op0 = N->getOperand(0);
8708   SDValue Op1 = N->getOperand(1);
8709   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8710       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8711       Op0.getNumOperands() != 2 ||
8712       Op1.getNumOperands() != 2)
8713     return SDValue();
8714   SDValue Concat0Op1 = Op0.getOperand(1);
8715   SDValue Concat1Op1 = Op1.getOperand(1);
8716   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8717       Concat1Op1.getOpcode() != ISD::UNDEF)
8718     return SDValue();
8719   // Skip the transformation if any of the types are illegal.
8720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8721   EVT VT = N->getValueType(0);
8722   if (!TLI.isTypeLegal(VT) ||
8723       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8724       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8725     return SDValue();
8726 
8727   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8728                                   Op0.getOperand(0), Op1.getOperand(0));
8729   // Translate the shuffle mask.
8730   SmallVector<int, 16> NewMask;
8731   unsigned NumElts = VT.getVectorNumElements();
8732   unsigned HalfElts = NumElts/2;
8733   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8734   for (unsigned n = 0; n < NumElts; ++n) {
8735     int MaskElt = SVN->getMaskElt(n);
8736     int NewElt = -1;
8737     if (MaskElt < (int)HalfElts)
8738       NewElt = MaskElt;
8739     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8740       NewElt = HalfElts + MaskElt - NumElts;
8741     NewMask.push_back(NewElt);
8742   }
8743   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8744                               DAG.getUNDEF(VT), NewMask.data());
8745 }
8746 
8747 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8748 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8749 /// base address updates.
8750 /// For generic load/stores, the memory type is assumed to be a vector.
8751 /// The caller is assumed to have checked legality.
CombineBaseUpdate(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8752 static SDValue CombineBaseUpdate(SDNode *N,
8753                                  TargetLowering::DAGCombinerInfo &DCI) {
8754   SelectionDAG &DAG = DCI.DAG;
8755   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8756                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8757   const bool isStore = N->getOpcode() == ISD::STORE;
8758   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8759   SDValue Addr = N->getOperand(AddrOpIdx);
8760   MemSDNode *MemN = cast<MemSDNode>(N);
8761 
8762   // Search for a use of the address operand that is an increment.
8763   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8764          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8765     SDNode *User = *UI;
8766     if (User->getOpcode() != ISD::ADD ||
8767         UI.getUse().getResNo() != Addr.getResNo())
8768       continue;
8769 
8770     // Check that the add is independent of the load/store.  Otherwise, folding
8771     // it would create a cycle.
8772     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8773       continue;
8774 
8775     // Find the new opcode for the updating load/store.
8776     bool isLoadOp = true;
8777     bool isLaneOp = false;
8778     unsigned NewOpc = 0;
8779     unsigned NumVecs = 0;
8780     if (isIntrinsic) {
8781       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8782       switch (IntNo) {
8783       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8784       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8785         NumVecs = 1; break;
8786       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8787         NumVecs = 2; break;
8788       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8789         NumVecs = 3; break;
8790       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8791         NumVecs = 4; break;
8792       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8793         NumVecs = 2; isLaneOp = true; break;
8794       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8795         NumVecs = 3; isLaneOp = true; break;
8796       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8797         NumVecs = 4; isLaneOp = true; break;
8798       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8799         NumVecs = 1; isLoadOp = false; break;
8800       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8801         NumVecs = 2; isLoadOp = false; break;
8802       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8803         NumVecs = 3; isLoadOp = false; break;
8804       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8805         NumVecs = 4; isLoadOp = false; break;
8806       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8807         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8808       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8809         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8810       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8811         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8812       }
8813     } else {
8814       isLaneOp = true;
8815       switch (N->getOpcode()) {
8816       default: llvm_unreachable("unexpected opcode for Neon base update");
8817       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8818       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8819       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8820       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8821         NumVecs = 1; isLaneOp = false; break;
8822       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8823         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8824       }
8825     }
8826 
8827     // Find the size of memory referenced by the load/store.
8828     EVT VecTy;
8829     if (isLoadOp) {
8830       VecTy = N->getValueType(0);
8831     } else if (isIntrinsic) {
8832       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8833     } else {
8834       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8835       VecTy = N->getOperand(1).getValueType();
8836     }
8837 
8838     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8839     if (isLaneOp)
8840       NumBytes /= VecTy.getVectorNumElements();
8841 
8842     // If the increment is a constant, it must match the memory ref size.
8843     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8844     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8845       uint64_t IncVal = CInc->getZExtValue();
8846       if (IncVal != NumBytes)
8847         continue;
8848     } else if (NumBytes >= 3 * 16) {
8849       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8850       // separate instructions that make it harder to use a non-constant update.
8851       continue;
8852     }
8853 
8854     // OK, we found an ADD we can fold into the base update.
8855     // Now, create a _UPD node, taking care of not breaking alignment.
8856 
8857     EVT AlignedVecTy = VecTy;
8858     unsigned Alignment = MemN->getAlignment();
8859 
8860     // If this is a less-than-standard-aligned load/store, change the type to
8861     // match the standard alignment.
8862     // The alignment is overlooked when selecting _UPD variants; and it's
8863     // easier to introduce bitcasts here than fix that.
8864     // There are 3 ways to get to this base-update combine:
8865     // - intrinsics: they are assumed to be properly aligned (to the standard
8866     //   alignment of the memory type), so we don't need to do anything.
8867     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8868     //   intrinsics, so, likewise, there's nothing to do.
8869     // - generic load/store instructions: the alignment is specified as an
8870     //   explicit operand, rather than implicitly as the standard alignment
8871     //   of the memory type (like the intrisics).  We need to change the
8872     //   memory type to match the explicit alignment.  That way, we don't
8873     //   generate non-standard-aligned ARMISD::VLDx nodes.
8874     if (isa<LSBaseSDNode>(N)) {
8875       if (Alignment == 0)
8876         Alignment = 1;
8877       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8878         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8879         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8880         assert(!isLaneOp && "Unexpected generic load/store lane.");
8881         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8882         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8883       }
8884       // Don't set an explicit alignment on regular load/stores that we want
8885       // to transform to VLD/VST 1_UPD nodes.
8886       // This matches the behavior of regular load/stores, which only get an
8887       // explicit alignment if the MMO alignment is larger than the standard
8888       // alignment of the memory type.
8889       // Intrinsics, however, always get an explicit alignment, set to the
8890       // alignment of the MMO.
8891       Alignment = 1;
8892     }
8893 
8894     // Create the new updating load/store node.
8895     // First, create an SDVTList for the new updating node's results.
8896     EVT Tys[6];
8897     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8898     unsigned n;
8899     for (n = 0; n < NumResultVecs; ++n)
8900       Tys[n] = AlignedVecTy;
8901     Tys[n++] = MVT::i32;
8902     Tys[n] = MVT::Other;
8903     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8904 
8905     // Then, gather the new node's operands.
8906     SmallVector<SDValue, 8> Ops;
8907     Ops.push_back(N->getOperand(0)); // incoming chain
8908     Ops.push_back(N->getOperand(AddrOpIdx));
8909     Ops.push_back(Inc);
8910 
8911     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8912       // Try to match the intrinsic's signature
8913       Ops.push_back(StN->getValue());
8914     } else {
8915       // Loads (and of course intrinsics) match the intrinsics' signature,
8916       // so just add all but the alignment operand.
8917       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8918         Ops.push_back(N->getOperand(i));
8919     }
8920 
8921     // For all node types, the alignment operand is always the last one.
8922     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8923 
8924     // If this is a non-standard-aligned STORE, the penultimate operand is the
8925     // stored value.  Bitcast it to the aligned type.
8926     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8927       SDValue &StVal = Ops[Ops.size()-2];
8928       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8929     }
8930 
8931     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8932                                            Ops, AlignedVecTy,
8933                                            MemN->getMemOperand());
8934 
8935     // Update the uses.
8936     SmallVector<SDValue, 5> NewResults;
8937     for (unsigned i = 0; i < NumResultVecs; ++i)
8938       NewResults.push_back(SDValue(UpdN.getNode(), i));
8939 
8940     // If this is an non-standard-aligned LOAD, the first result is the loaded
8941     // value.  Bitcast it to the expected result type.
8942     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8943       SDValue &LdVal = NewResults[0];
8944       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8945     }
8946 
8947     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8948     DCI.CombineTo(N, NewResults);
8949     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8950 
8951     break;
8952   }
8953   return SDValue();
8954 }
8955 
PerformVLDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8956 static SDValue PerformVLDCombine(SDNode *N,
8957                                  TargetLowering::DAGCombinerInfo &DCI) {
8958   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8959     return SDValue();
8960 
8961   return CombineBaseUpdate(N, DCI);
8962 }
8963 
8964 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8965 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8966 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8967 /// return true.
CombineVLDDUP(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8968 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8969   SelectionDAG &DAG = DCI.DAG;
8970   EVT VT = N->getValueType(0);
8971   // vldN-dup instructions only support 64-bit vectors for N > 1.
8972   if (!VT.is64BitVector())
8973     return false;
8974 
8975   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8976   SDNode *VLD = N->getOperand(0).getNode();
8977   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8978     return false;
8979   unsigned NumVecs = 0;
8980   unsigned NewOpc = 0;
8981   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8982   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8983     NumVecs = 2;
8984     NewOpc = ARMISD::VLD2DUP;
8985   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8986     NumVecs = 3;
8987     NewOpc = ARMISD::VLD3DUP;
8988   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8989     NumVecs = 4;
8990     NewOpc = ARMISD::VLD4DUP;
8991   } else {
8992     return false;
8993   }
8994 
8995   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8996   // numbers match the load.
8997   unsigned VLDLaneNo =
8998     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8999   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9000        UI != UE; ++UI) {
9001     // Ignore uses of the chain result.
9002     if (UI.getUse().getResNo() == NumVecs)
9003       continue;
9004     SDNode *User = *UI;
9005     if (User->getOpcode() != ARMISD::VDUPLANE ||
9006         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9007       return false;
9008   }
9009 
9010   // Create the vldN-dup node.
9011   EVT Tys[5];
9012   unsigned n;
9013   for (n = 0; n < NumVecs; ++n)
9014     Tys[n] = VT;
9015   Tys[n] = MVT::Other;
9016   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9017   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9018   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9019   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9020                                            Ops, VLDMemInt->getMemoryVT(),
9021                                            VLDMemInt->getMemOperand());
9022 
9023   // Update the uses.
9024   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9025        UI != UE; ++UI) {
9026     unsigned ResNo = UI.getUse().getResNo();
9027     // Ignore uses of the chain result.
9028     if (ResNo == NumVecs)
9029       continue;
9030     SDNode *User = *UI;
9031     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9032   }
9033 
9034   // Now the vldN-lane intrinsic is dead except for its chain result.
9035   // Update uses of the chain.
9036   std::vector<SDValue> VLDDupResults;
9037   for (unsigned n = 0; n < NumVecs; ++n)
9038     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9039   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9040   DCI.CombineTo(VLD, VLDDupResults);
9041 
9042   return true;
9043 }
9044 
9045 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9046 /// ARMISD::VDUPLANE.
PerformVDUPLANECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9047 static SDValue PerformVDUPLANECombine(SDNode *N,
9048                                       TargetLowering::DAGCombinerInfo &DCI) {
9049   SDValue Op = N->getOperand(0);
9050 
9051   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9052   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9053   if (CombineVLDDUP(N, DCI))
9054     return SDValue(N, 0);
9055 
9056   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9057   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9058   while (Op.getOpcode() == ISD::BITCAST)
9059     Op = Op.getOperand(0);
9060   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9061     return SDValue();
9062 
9063   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9064   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9065   // The canonical VMOV for a zero vector uses a 32-bit element size.
9066   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9067   unsigned EltBits;
9068   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9069     EltSize = 8;
9070   EVT VT = N->getValueType(0);
9071   if (EltSize > VT.getVectorElementType().getSizeInBits())
9072     return SDValue();
9073 
9074   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9075 }
9076 
PerformLOADCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9077 static SDValue PerformLOADCombine(SDNode *N,
9078                                   TargetLowering::DAGCombinerInfo &DCI) {
9079   EVT VT = N->getValueType(0);
9080 
9081   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9082   if (ISD::isNormalLoad(N) && VT.isVector() &&
9083       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9084     return CombineBaseUpdate(N, DCI);
9085 
9086   return SDValue();
9087 }
9088 
9089 /// PerformSTORECombine - Target-specific dag combine xforms for
9090 /// ISD::STORE.
PerformSTORECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9091 static SDValue PerformSTORECombine(SDNode *N,
9092                                    TargetLowering::DAGCombinerInfo &DCI) {
9093   StoreSDNode *St = cast<StoreSDNode>(N);
9094   if (St->isVolatile())
9095     return SDValue();
9096 
9097   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9098   // pack all of the elements in one place.  Next, store to memory in fewer
9099   // chunks.
9100   SDValue StVal = St->getValue();
9101   EVT VT = StVal.getValueType();
9102   if (St->isTruncatingStore() && VT.isVector()) {
9103     SelectionDAG &DAG = DCI.DAG;
9104     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9105     EVT StVT = St->getMemoryVT();
9106     unsigned NumElems = VT.getVectorNumElements();
9107     assert(StVT != VT && "Cannot truncate to the same type");
9108     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9109     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9110 
9111     // From, To sizes and ElemCount must be pow of two
9112     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9113 
9114     // We are going to use the original vector elt for storing.
9115     // Accumulated smaller vector elements must be a multiple of the store size.
9116     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9117 
9118     unsigned SizeRatio  = FromEltSz / ToEltSz;
9119     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9120 
9121     // Create a type on which we perform the shuffle.
9122     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9123                                      NumElems*SizeRatio);
9124     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9125 
9126     SDLoc DL(St);
9127     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9128     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9129     for (unsigned i = 0; i < NumElems; ++i)
9130       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9131 
9132     // Can't shuffle using an illegal type.
9133     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9134 
9135     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9136                                 DAG.getUNDEF(WideVec.getValueType()),
9137                                 ShuffleVec.data());
9138     // At this point all of the data is stored at the bottom of the
9139     // register. We now need to save it to mem.
9140 
9141     // Find the largest store unit
9142     MVT StoreType = MVT::i8;
9143     for (MVT Tp : MVT::integer_valuetypes()) {
9144       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9145         StoreType = Tp;
9146     }
9147     // Didn't find a legal store type.
9148     if (!TLI.isTypeLegal(StoreType))
9149       return SDValue();
9150 
9151     // Bitcast the original vector into a vector of store-size units
9152     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9153             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9154     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9155     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9156     SmallVector<SDValue, 8> Chains;
9157     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9158                                         TLI.getPointerTy());
9159     SDValue BasePtr = St->getBasePtr();
9160 
9161     // Perform one or more big stores into memory.
9162     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9163     for (unsigned I = 0; I < E; I++) {
9164       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9165                                    StoreType, ShuffWide,
9166                                    DAG.getIntPtrConstant(I));
9167       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9168                                 St->getPointerInfo(), St->isVolatile(),
9169                                 St->isNonTemporal(), St->getAlignment());
9170       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9171                             Increment);
9172       Chains.push_back(Ch);
9173     }
9174     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9175   }
9176 
9177   if (!ISD::isNormalStore(St))
9178     return SDValue();
9179 
9180   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9181   // ARM stores of arguments in the same cache line.
9182   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9183       StVal.getNode()->hasOneUse()) {
9184     SelectionDAG  &DAG = DCI.DAG;
9185     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9186     SDLoc DL(St);
9187     SDValue BasePtr = St->getBasePtr();
9188     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9189                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9190                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9191                                   St->isNonTemporal(), St->getAlignment());
9192 
9193     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9194                                     DAG.getConstant(4, MVT::i32));
9195     return DAG.getStore(NewST1.getValue(0), DL,
9196                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9197                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9198                         St->isNonTemporal(),
9199                         std::min(4U, St->getAlignment() / 2));
9200   }
9201 
9202   if (StVal.getValueType() == MVT::i64 &&
9203       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9204 
9205     // Bitcast an i64 store extracted from a vector to f64.
9206     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9207     SelectionDAG &DAG = DCI.DAG;
9208     SDLoc dl(StVal);
9209     SDValue IntVec = StVal.getOperand(0);
9210     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9211                                    IntVec.getValueType().getVectorNumElements());
9212     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9213     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9214                                  Vec, StVal.getOperand(1));
9215     dl = SDLoc(N);
9216     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9217     // Make the DAGCombiner fold the bitcasts.
9218     DCI.AddToWorklist(Vec.getNode());
9219     DCI.AddToWorklist(ExtElt.getNode());
9220     DCI.AddToWorklist(V.getNode());
9221     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9222                         St->getPointerInfo(), St->isVolatile(),
9223                         St->isNonTemporal(), St->getAlignment(),
9224                         St->getAAInfo());
9225   }
9226 
9227   // If this is a legal vector store, try to combine it into a VST1_UPD.
9228   if (ISD::isNormalStore(N) && VT.isVector() &&
9229       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9230     return CombineBaseUpdate(N, DCI);
9231 
9232   return SDValue();
9233 }
9234 
9235 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9236 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
isConstVecPow2(SDValue ConstVec,bool isSigned,uint64_t & C)9237 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9238 {
9239   integerPart cN;
9240   integerPart c0 = 0;
9241   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9242        I != E; I++) {
9243     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9244     if (!C)
9245       return false;
9246 
9247     bool isExact;
9248     APFloat APF = C->getValueAPF();
9249     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9250         != APFloat::opOK || !isExact)
9251       return false;
9252 
9253     c0 = (I == 0) ? cN : c0;
9254     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9255       return false;
9256   }
9257   C = c0;
9258   return true;
9259 }
9260 
9261 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9262 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9263 /// when the VMUL has a constant operand that is a power of 2.
9264 ///
9265 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9266 ///  vmul.f32        d16, d17, d16
9267 ///  vcvt.s32.f32    d16, d16
9268 /// becomes:
9269 ///  vcvt.s32.f32    d16, d16, #3
PerformVCVTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)9270 static SDValue PerformVCVTCombine(SDNode *N,
9271                                   TargetLowering::DAGCombinerInfo &DCI,
9272                                   const ARMSubtarget *Subtarget) {
9273   SelectionDAG &DAG = DCI.DAG;
9274   SDValue Op = N->getOperand(0);
9275 
9276   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9277       Op.getOpcode() != ISD::FMUL)
9278     return SDValue();
9279 
9280   uint64_t C;
9281   SDValue N0 = Op->getOperand(0);
9282   SDValue ConstVec = Op->getOperand(1);
9283   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9284 
9285   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9286       !isConstVecPow2(ConstVec, isSigned, C))
9287     return SDValue();
9288 
9289   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9290   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9291   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9292   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9293       NumLanes > 4) {
9294     // These instructions only exist converting from f32 to i32. We can handle
9295     // smaller integers by generating an extra truncate, but larger ones would
9296     // be lossy. We also can't handle more then 4 lanes, since these intructions
9297     // only support v2i32/v4i32 types.
9298     return SDValue();
9299   }
9300 
9301   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9302     Intrinsic::arm_neon_vcvtfp2fxu;
9303   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9304                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9305                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9306                                  DAG.getConstant(Log2_64(C), MVT::i32));
9307 
9308   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9309     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9310 
9311   return FixConv;
9312 }
9313 
9314 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9315 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9316 /// when the VDIV has a constant operand that is a power of 2.
9317 ///
9318 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9319 ///  vcvt.f32.s32    d16, d16
9320 ///  vdiv.f32        d16, d17, d16
9321 /// becomes:
9322 ///  vcvt.f32.s32    d16, d16, #3
PerformVDIVCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)9323 static SDValue PerformVDIVCombine(SDNode *N,
9324                                   TargetLowering::DAGCombinerInfo &DCI,
9325                                   const ARMSubtarget *Subtarget) {
9326   SelectionDAG &DAG = DCI.DAG;
9327   SDValue Op = N->getOperand(0);
9328   unsigned OpOpcode = Op.getNode()->getOpcode();
9329 
9330   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9331       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9332     return SDValue();
9333 
9334   uint64_t C;
9335   SDValue ConstVec = N->getOperand(1);
9336   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9337 
9338   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9339       !isConstVecPow2(ConstVec, isSigned, C))
9340     return SDValue();
9341 
9342   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9343   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9344   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9345     // These instructions only exist converting from i32 to f32. We can handle
9346     // smaller integers by generating an extra extend, but larger ones would
9347     // be lossy.
9348     return SDValue();
9349   }
9350 
9351   SDValue ConvInput = Op.getOperand(0);
9352   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9353   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9354     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9355                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9356                             ConvInput);
9357 
9358   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9359     Intrinsic::arm_neon_vcvtfxu2fp;
9360   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9361                      Op.getValueType(),
9362                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9363                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9364 }
9365 
9366 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9367 /// operand of a vector shift operation, where all the elements of the
9368 /// build_vector must have the same constant integer value.
getVShiftImm(SDValue Op,unsigned ElementBits,int64_t & Cnt)9369 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9370   // Ignore bit_converts.
9371   while (Op.getOpcode() == ISD::BITCAST)
9372     Op = Op.getOperand(0);
9373   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9374   APInt SplatBits, SplatUndef;
9375   unsigned SplatBitSize;
9376   bool HasAnyUndefs;
9377   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9378                                       HasAnyUndefs, ElementBits) ||
9379       SplatBitSize > ElementBits)
9380     return false;
9381   Cnt = SplatBits.getSExtValue();
9382   return true;
9383 }
9384 
9385 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9386 /// operand of a vector shift left operation.  That value must be in the range:
9387 ///   0 <= Value < ElementBits for a left shift; or
9388 ///   0 <= Value <= ElementBits for a long left shift.
isVShiftLImm(SDValue Op,EVT VT,bool isLong,int64_t & Cnt)9389 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9390   assert(VT.isVector() && "vector shift count is not a vector type");
9391   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9392   if (! getVShiftImm(Op, ElementBits, Cnt))
9393     return false;
9394   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9395 }
9396 
9397 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9398 /// operand of a vector shift right operation.  For a shift opcode, the value
9399 /// is positive, but for an intrinsic the value count must be negative. The
9400 /// absolute value must be in the range:
9401 ///   1 <= |Value| <= ElementBits for a right shift; or
9402 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
isVShiftRImm(SDValue Op,EVT VT,bool isNarrow,bool isIntrinsic,int64_t & Cnt)9403 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9404                          int64_t &Cnt) {
9405   assert(VT.isVector() && "vector shift count is not a vector type");
9406   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9407   if (! getVShiftImm(Op, ElementBits, Cnt))
9408     return false;
9409   if (isIntrinsic)
9410     Cnt = -Cnt;
9411   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9412 }
9413 
9414 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
PerformIntrinsicCombine(SDNode * N,SelectionDAG & DAG)9415 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9416   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9417   switch (IntNo) {
9418   default:
9419     // Don't do anything for most intrinsics.
9420     break;
9421 
9422   // Vector shifts: check for immediate versions and lower them.
9423   // Note: This is done during DAG combining instead of DAG legalizing because
9424   // the build_vectors for 64-bit vector element shift counts are generally
9425   // not legal, and it is hard to see their values after they get legalized to
9426   // loads from a constant pool.
9427   case Intrinsic::arm_neon_vshifts:
9428   case Intrinsic::arm_neon_vshiftu:
9429   case Intrinsic::arm_neon_vrshifts:
9430   case Intrinsic::arm_neon_vrshiftu:
9431   case Intrinsic::arm_neon_vrshiftn:
9432   case Intrinsic::arm_neon_vqshifts:
9433   case Intrinsic::arm_neon_vqshiftu:
9434   case Intrinsic::arm_neon_vqshiftsu:
9435   case Intrinsic::arm_neon_vqshiftns:
9436   case Intrinsic::arm_neon_vqshiftnu:
9437   case Intrinsic::arm_neon_vqshiftnsu:
9438   case Intrinsic::arm_neon_vqrshiftns:
9439   case Intrinsic::arm_neon_vqrshiftnu:
9440   case Intrinsic::arm_neon_vqrshiftnsu: {
9441     EVT VT = N->getOperand(1).getValueType();
9442     int64_t Cnt;
9443     unsigned VShiftOpc = 0;
9444 
9445     switch (IntNo) {
9446     case Intrinsic::arm_neon_vshifts:
9447     case Intrinsic::arm_neon_vshiftu:
9448       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9449         VShiftOpc = ARMISD::VSHL;
9450         break;
9451       }
9452       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9453         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9454                      ARMISD::VSHRs : ARMISD::VSHRu);
9455         break;
9456       }
9457       return SDValue();
9458 
9459     case Intrinsic::arm_neon_vrshifts:
9460     case Intrinsic::arm_neon_vrshiftu:
9461       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9462         break;
9463       return SDValue();
9464 
9465     case Intrinsic::arm_neon_vqshifts:
9466     case Intrinsic::arm_neon_vqshiftu:
9467       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9468         break;
9469       return SDValue();
9470 
9471     case Intrinsic::arm_neon_vqshiftsu:
9472       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9473         break;
9474       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9475 
9476     case Intrinsic::arm_neon_vrshiftn:
9477     case Intrinsic::arm_neon_vqshiftns:
9478     case Intrinsic::arm_neon_vqshiftnu:
9479     case Intrinsic::arm_neon_vqshiftnsu:
9480     case Intrinsic::arm_neon_vqrshiftns:
9481     case Intrinsic::arm_neon_vqrshiftnu:
9482     case Intrinsic::arm_neon_vqrshiftnsu:
9483       // Narrowing shifts require an immediate right shift.
9484       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9485         break;
9486       llvm_unreachable("invalid shift count for narrowing vector shift "
9487                        "intrinsic");
9488 
9489     default:
9490       llvm_unreachable("unhandled vector shift");
9491     }
9492 
9493     switch (IntNo) {
9494     case Intrinsic::arm_neon_vshifts:
9495     case Intrinsic::arm_neon_vshiftu:
9496       // Opcode already set above.
9497       break;
9498     case Intrinsic::arm_neon_vrshifts:
9499       VShiftOpc = ARMISD::VRSHRs; break;
9500     case Intrinsic::arm_neon_vrshiftu:
9501       VShiftOpc = ARMISD::VRSHRu; break;
9502     case Intrinsic::arm_neon_vrshiftn:
9503       VShiftOpc = ARMISD::VRSHRN; break;
9504     case Intrinsic::arm_neon_vqshifts:
9505       VShiftOpc = ARMISD::VQSHLs; break;
9506     case Intrinsic::arm_neon_vqshiftu:
9507       VShiftOpc = ARMISD::VQSHLu; break;
9508     case Intrinsic::arm_neon_vqshiftsu:
9509       VShiftOpc = ARMISD::VQSHLsu; break;
9510     case Intrinsic::arm_neon_vqshiftns:
9511       VShiftOpc = ARMISD::VQSHRNs; break;
9512     case Intrinsic::arm_neon_vqshiftnu:
9513       VShiftOpc = ARMISD::VQSHRNu; break;
9514     case Intrinsic::arm_neon_vqshiftnsu:
9515       VShiftOpc = ARMISD::VQSHRNsu; break;
9516     case Intrinsic::arm_neon_vqrshiftns:
9517       VShiftOpc = ARMISD::VQRSHRNs; break;
9518     case Intrinsic::arm_neon_vqrshiftnu:
9519       VShiftOpc = ARMISD::VQRSHRNu; break;
9520     case Intrinsic::arm_neon_vqrshiftnsu:
9521       VShiftOpc = ARMISD::VQRSHRNsu; break;
9522     }
9523 
9524     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9525                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9526   }
9527 
9528   case Intrinsic::arm_neon_vshiftins: {
9529     EVT VT = N->getOperand(1).getValueType();
9530     int64_t Cnt;
9531     unsigned VShiftOpc = 0;
9532 
9533     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9534       VShiftOpc = ARMISD::VSLI;
9535     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9536       VShiftOpc = ARMISD::VSRI;
9537     else {
9538       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9539     }
9540 
9541     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9542                        N->getOperand(1), N->getOperand(2),
9543                        DAG.getConstant(Cnt, MVT::i32));
9544   }
9545 
9546   case Intrinsic::arm_neon_vqrshifts:
9547   case Intrinsic::arm_neon_vqrshiftu:
9548     // No immediate versions of these to check for.
9549     break;
9550   }
9551 
9552   return SDValue();
9553 }
9554 
9555 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9556 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9557 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9558 /// vector element shift counts are generally not legal, and it is hard to see
9559 /// their values after they get legalized to loads from a constant pool.
PerformShiftCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)9560 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9561                                    const ARMSubtarget *ST) {
9562   EVT VT = N->getValueType(0);
9563   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9564     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9565     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9566     SDValue N1 = N->getOperand(1);
9567     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9568       SDValue N0 = N->getOperand(0);
9569       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9570           DAG.MaskedValueIsZero(N0.getOperand(0),
9571                                 APInt::getHighBitsSet(32, 16)))
9572         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9573     }
9574   }
9575 
9576   // Nothing to be done for scalar shifts.
9577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9578   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9579     return SDValue();
9580 
9581   assert(ST->hasNEON() && "unexpected vector shift");
9582   int64_t Cnt;
9583 
9584   switch (N->getOpcode()) {
9585   default: llvm_unreachable("unexpected shift opcode");
9586 
9587   case ISD::SHL:
9588     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9589       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9590                          DAG.getConstant(Cnt, MVT::i32));
9591     break;
9592 
9593   case ISD::SRA:
9594   case ISD::SRL:
9595     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9596       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9597                             ARMISD::VSHRs : ARMISD::VSHRu);
9598       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9599                          DAG.getConstant(Cnt, MVT::i32));
9600     }
9601   }
9602   return SDValue();
9603 }
9604 
9605 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9606 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
PerformExtendCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)9607 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9608                                     const ARMSubtarget *ST) {
9609   SDValue N0 = N->getOperand(0);
9610 
9611   // Check for sign- and zero-extensions of vector extract operations of 8-
9612   // and 16-bit vector elements.  NEON supports these directly.  They are
9613   // handled during DAG combining because type legalization will promote them
9614   // to 32-bit types and it is messy to recognize the operations after that.
9615   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9616     SDValue Vec = N0.getOperand(0);
9617     SDValue Lane = N0.getOperand(1);
9618     EVT VT = N->getValueType(0);
9619     EVT EltVT = N0.getValueType();
9620     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9621 
9622     if (VT == MVT::i32 &&
9623         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9624         TLI.isTypeLegal(Vec.getValueType()) &&
9625         isa<ConstantSDNode>(Lane)) {
9626 
9627       unsigned Opc = 0;
9628       switch (N->getOpcode()) {
9629       default: llvm_unreachable("unexpected opcode");
9630       case ISD::SIGN_EXTEND:
9631         Opc = ARMISD::VGETLANEs;
9632         break;
9633       case ISD::ZERO_EXTEND:
9634       case ISD::ANY_EXTEND:
9635         Opc = ARMISD::VGETLANEu;
9636         break;
9637       }
9638       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9639     }
9640   }
9641 
9642   return SDValue();
9643 }
9644 
9645 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9646 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
PerformSELECT_CCCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)9647 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9648                                        const ARMSubtarget *ST) {
9649   // If the target supports NEON, try to use vmax/vmin instructions for f32
9650   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9651   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9652   // a NaN; only do the transformation when it matches that behavior.
9653 
9654   // For now only do this when using NEON for FP operations; if using VFP, it
9655   // is not obvious that the benefit outweighs the cost of switching to the
9656   // NEON pipeline.
9657   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9658       N->getValueType(0) != MVT::f32)
9659     return SDValue();
9660 
9661   SDValue CondLHS = N->getOperand(0);
9662   SDValue CondRHS = N->getOperand(1);
9663   SDValue LHS = N->getOperand(2);
9664   SDValue RHS = N->getOperand(3);
9665   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9666 
9667   unsigned Opcode = 0;
9668   bool IsReversed;
9669   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9670     IsReversed = false; // x CC y ? x : y
9671   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9672     IsReversed = true ; // x CC y ? y : x
9673   } else {
9674     return SDValue();
9675   }
9676 
9677   bool IsUnordered;
9678   switch (CC) {
9679   default: break;
9680   case ISD::SETOLT:
9681   case ISD::SETOLE:
9682   case ISD::SETLT:
9683   case ISD::SETLE:
9684   case ISD::SETULT:
9685   case ISD::SETULE:
9686     // If LHS is NaN, an ordered comparison will be false and the result will
9687     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9688     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9689     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9690     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9691       break;
9692     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9693     // will return -0, so vmin can only be used for unsafe math or if one of
9694     // the operands is known to be nonzero.
9695     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9696         !DAG.getTarget().Options.UnsafeFPMath &&
9697         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9698       break;
9699     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9700     break;
9701 
9702   case ISD::SETOGT:
9703   case ISD::SETOGE:
9704   case ISD::SETGT:
9705   case ISD::SETGE:
9706   case ISD::SETUGT:
9707   case ISD::SETUGE:
9708     // If LHS is NaN, an ordered comparison will be false and the result will
9709     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9710     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9711     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9712     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9713       break;
9714     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9715     // will return +0, so vmax can only be used for unsafe math or if one of
9716     // the operands is known to be nonzero.
9717     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9718         !DAG.getTarget().Options.UnsafeFPMath &&
9719         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9720       break;
9721     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9722     break;
9723   }
9724 
9725   if (!Opcode)
9726     return SDValue();
9727   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9728 }
9729 
9730 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9731 SDValue
PerformCMOVCombine(SDNode * N,SelectionDAG & DAG) const9732 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9733   SDValue Cmp = N->getOperand(4);
9734   if (Cmp.getOpcode() != ARMISD::CMPZ)
9735     // Only looking at EQ and NE cases.
9736     return SDValue();
9737 
9738   EVT VT = N->getValueType(0);
9739   SDLoc dl(N);
9740   SDValue LHS = Cmp.getOperand(0);
9741   SDValue RHS = Cmp.getOperand(1);
9742   SDValue FalseVal = N->getOperand(0);
9743   SDValue TrueVal = N->getOperand(1);
9744   SDValue ARMcc = N->getOperand(2);
9745   ARMCC::CondCodes CC =
9746     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9747 
9748   // Simplify
9749   //   mov     r1, r0
9750   //   cmp     r1, x
9751   //   mov     r0, y
9752   //   moveq   r0, x
9753   // to
9754   //   cmp     r0, x
9755   //   movne   r0, y
9756   //
9757   //   mov     r1, r0
9758   //   cmp     r1, x
9759   //   mov     r0, x
9760   //   movne   r0, y
9761   // to
9762   //   cmp     r0, x
9763   //   movne   r0, y
9764   /// FIXME: Turn this into a target neutral optimization?
9765   SDValue Res;
9766   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9767     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9768                       N->getOperand(3), Cmp);
9769   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9770     SDValue ARMcc;
9771     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9772     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9773                       N->getOperand(3), NewCmp);
9774   }
9775 
9776   if (Res.getNode()) {
9777     APInt KnownZero, KnownOne;
9778     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9779     // Capture demanded bits information that would be otherwise lost.
9780     if (KnownZero == 0xfffffffe)
9781       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9782                         DAG.getValueType(MVT::i1));
9783     else if (KnownZero == 0xffffff00)
9784       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9785                         DAG.getValueType(MVT::i8));
9786     else if (KnownZero == 0xffff0000)
9787       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9788                         DAG.getValueType(MVT::i16));
9789   }
9790 
9791   return Res;
9792 }
9793 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const9794 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9795                                              DAGCombinerInfo &DCI) const {
9796   switch (N->getOpcode()) {
9797   default: break;
9798   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9799   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9800   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9801   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9802   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9803   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9804   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9805   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9806   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9807   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9808   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9809   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9810   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9811   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9812   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9813   case ISD::FP_TO_SINT:
9814   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9815   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9816   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9817   case ISD::SHL:
9818   case ISD::SRA:
9819   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9820   case ISD::SIGN_EXTEND:
9821   case ISD::ZERO_EXTEND:
9822   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9823   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9824   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9825   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9826   case ARMISD::VLD2DUP:
9827   case ARMISD::VLD3DUP:
9828   case ARMISD::VLD4DUP:
9829     return PerformVLDCombine(N, DCI);
9830   case ARMISD::BUILD_VECTOR:
9831     return PerformARMBUILD_VECTORCombine(N, DCI);
9832   case ISD::INTRINSIC_VOID:
9833   case ISD::INTRINSIC_W_CHAIN:
9834     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9835     case Intrinsic::arm_neon_vld1:
9836     case Intrinsic::arm_neon_vld2:
9837     case Intrinsic::arm_neon_vld3:
9838     case Intrinsic::arm_neon_vld4:
9839     case Intrinsic::arm_neon_vld2lane:
9840     case Intrinsic::arm_neon_vld3lane:
9841     case Intrinsic::arm_neon_vld4lane:
9842     case Intrinsic::arm_neon_vst1:
9843     case Intrinsic::arm_neon_vst2:
9844     case Intrinsic::arm_neon_vst3:
9845     case Intrinsic::arm_neon_vst4:
9846     case Intrinsic::arm_neon_vst2lane:
9847     case Intrinsic::arm_neon_vst3lane:
9848     case Intrinsic::arm_neon_vst4lane:
9849       return PerformVLDCombine(N, DCI);
9850     default: break;
9851     }
9852     break;
9853   }
9854   return SDValue();
9855 }
9856 
isDesirableToTransformToIntegerOp(unsigned Opc,EVT VT) const9857 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9858                                                           EVT VT) const {
9859   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9860 }
9861 
allowsMisalignedMemoryAccesses(EVT VT,unsigned,unsigned,bool * Fast) const9862 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9863                                                        unsigned,
9864                                                        unsigned,
9865                                                        bool *Fast) const {
9866   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9867   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9868 
9869   switch (VT.getSimpleVT().SimpleTy) {
9870   default:
9871     return false;
9872   case MVT::i8:
9873   case MVT::i16:
9874   case MVT::i32: {
9875     // Unaligned access can use (for example) LRDB, LRDH, LDR
9876     if (AllowsUnaligned) {
9877       if (Fast)
9878         *Fast = Subtarget->hasV7Ops();
9879       return true;
9880     }
9881     return false;
9882   }
9883   case MVT::f64:
9884   case MVT::v2f64: {
9885     // For any little-endian targets with neon, we can support unaligned ld/st
9886     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9887     // A big-endian target may also explicitly support unaligned accesses
9888     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9889       if (Fast)
9890         *Fast = true;
9891       return true;
9892     }
9893     return false;
9894   }
9895   }
9896 }
9897 
memOpAlign(unsigned DstAlign,unsigned SrcAlign,unsigned AlignCheck)9898 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9899                        unsigned AlignCheck) {
9900   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9901           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9902 }
9903 
getOptimalMemOpType(uint64_t Size,unsigned DstAlign,unsigned SrcAlign,bool IsMemset,bool ZeroMemset,bool MemcpyStrSrc,MachineFunction & MF) const9904 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9905                                            unsigned DstAlign, unsigned SrcAlign,
9906                                            bool IsMemset, bool ZeroMemset,
9907                                            bool MemcpyStrSrc,
9908                                            MachineFunction &MF) const {
9909   const Function *F = MF.getFunction();
9910 
9911   // See if we can use NEON instructions for this...
9912   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9913       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9914     bool Fast;
9915     if (Size >= 16 &&
9916         (memOpAlign(SrcAlign, DstAlign, 16) ||
9917          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9918       return MVT::v2f64;
9919     } else if (Size >= 8 &&
9920                (memOpAlign(SrcAlign, DstAlign, 8) ||
9921                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9922                  Fast))) {
9923       return MVT::f64;
9924     }
9925   }
9926 
9927   // Lowering to i32/i16 if the size permits.
9928   if (Size >= 4)
9929     return MVT::i32;
9930   else if (Size >= 2)
9931     return MVT::i16;
9932 
9933   // Let the target-independent logic figure it out.
9934   return MVT::Other;
9935 }
9936 
isZExtFree(SDValue Val,EVT VT2) const9937 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9938   if (Val.getOpcode() != ISD::LOAD)
9939     return false;
9940 
9941   EVT VT1 = Val.getValueType();
9942   if (!VT1.isSimple() || !VT1.isInteger() ||
9943       !VT2.isSimple() || !VT2.isInteger())
9944     return false;
9945 
9946   switch (VT1.getSimpleVT().SimpleTy) {
9947   default: break;
9948   case MVT::i1:
9949   case MVT::i8:
9950   case MVT::i16:
9951     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9952     return true;
9953   }
9954 
9955   return false;
9956 }
9957 
isVectorLoadExtDesirable(SDValue ExtVal) const9958 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9959   EVT VT = ExtVal.getValueType();
9960 
9961   if (!isTypeLegal(VT))
9962     return false;
9963 
9964   // Don't create a loadext if we can fold the extension into a wide/long
9965   // instruction.
9966   // If there's more than one user instruction, the loadext is desirable no
9967   // matter what.  There can be two uses by the same instruction.
9968   if (ExtVal->use_empty() ||
9969       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9970     return true;
9971 
9972   SDNode *U = *ExtVal->use_begin();
9973   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9974        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9975     return false;
9976 
9977   return true;
9978 }
9979 
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const9980 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9981   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9982     return false;
9983 
9984   if (!isTypeLegal(EVT::getEVT(Ty1)))
9985     return false;
9986 
9987   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9988 
9989   // Assuming the caller doesn't have a zeroext or signext return parameter,
9990   // truncation all the way down to i1 is valid.
9991   return true;
9992 }
9993 
9994 
isLegalT1AddressImmediate(int64_t V,EVT VT)9995 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9996   if (V < 0)
9997     return false;
9998 
9999   unsigned Scale = 1;
10000   switch (VT.getSimpleVT().SimpleTy) {
10001   default: return false;
10002   case MVT::i1:
10003   case MVT::i8:
10004     // Scale == 1;
10005     break;
10006   case MVT::i16:
10007     // Scale == 2;
10008     Scale = 2;
10009     break;
10010   case MVT::i32:
10011     // Scale == 4;
10012     Scale = 4;
10013     break;
10014   }
10015 
10016   if ((V & (Scale - 1)) != 0)
10017     return false;
10018   V /= Scale;
10019   return V == (V & ((1LL << 5) - 1));
10020 }
10021 
isLegalT2AddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)10022 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10023                                       const ARMSubtarget *Subtarget) {
10024   bool isNeg = false;
10025   if (V < 0) {
10026     isNeg = true;
10027     V = - V;
10028   }
10029 
10030   switch (VT.getSimpleVT().SimpleTy) {
10031   default: return false;
10032   case MVT::i1:
10033   case MVT::i8:
10034   case MVT::i16:
10035   case MVT::i32:
10036     // + imm12 or - imm8
10037     if (isNeg)
10038       return V == (V & ((1LL << 8) - 1));
10039     return V == (V & ((1LL << 12) - 1));
10040   case MVT::f32:
10041   case MVT::f64:
10042     // Same as ARM mode. FIXME: NEON?
10043     if (!Subtarget->hasVFP2())
10044       return false;
10045     if ((V & 3) != 0)
10046       return false;
10047     V >>= 2;
10048     return V == (V & ((1LL << 8) - 1));
10049   }
10050 }
10051 
10052 /// isLegalAddressImmediate - Return true if the integer value can be used
10053 /// as the offset of the target addressing mode for load / store of the
10054 /// given type.
isLegalAddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)10055 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10056                                     const ARMSubtarget *Subtarget) {
10057   if (V == 0)
10058     return true;
10059 
10060   if (!VT.isSimple())
10061     return false;
10062 
10063   if (Subtarget->isThumb1Only())
10064     return isLegalT1AddressImmediate(V, VT);
10065   else if (Subtarget->isThumb2())
10066     return isLegalT2AddressImmediate(V, VT, Subtarget);
10067 
10068   // ARM mode.
10069   if (V < 0)
10070     V = - V;
10071   switch (VT.getSimpleVT().SimpleTy) {
10072   default: return false;
10073   case MVT::i1:
10074   case MVT::i8:
10075   case MVT::i32:
10076     // +- imm12
10077     return V == (V & ((1LL << 12) - 1));
10078   case MVT::i16:
10079     // +- imm8
10080     return V == (V & ((1LL << 8) - 1));
10081   case MVT::f32:
10082   case MVT::f64:
10083     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10084       return false;
10085     if ((V & 3) != 0)
10086       return false;
10087     V >>= 2;
10088     return V == (V & ((1LL << 8) - 1));
10089   }
10090 }
10091 
isLegalT2ScaledAddressingMode(const AddrMode & AM,EVT VT) const10092 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10093                                                       EVT VT) const {
10094   int Scale = AM.Scale;
10095   if (Scale < 0)
10096     return false;
10097 
10098   switch (VT.getSimpleVT().SimpleTy) {
10099   default: return false;
10100   case MVT::i1:
10101   case MVT::i8:
10102   case MVT::i16:
10103   case MVT::i32:
10104     if (Scale == 1)
10105       return true;
10106     // r + r << imm
10107     Scale = Scale & ~1;
10108     return Scale == 2 || Scale == 4 || Scale == 8;
10109   case MVT::i64:
10110     // r + r
10111     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10112       return true;
10113     return false;
10114   case MVT::isVoid:
10115     // Note, we allow "void" uses (basically, uses that aren't loads or
10116     // stores), because arm allows folding a scale into many arithmetic
10117     // operations.  This should be made more precise and revisited later.
10118 
10119     // Allow r << imm, but the imm has to be a multiple of two.
10120     if (Scale & 1) return false;
10121     return isPowerOf2_32(Scale);
10122   }
10123 }
10124 
10125 /// isLegalAddressingMode - Return true if the addressing mode represented
10126 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const AddrMode & AM,Type * Ty) const10127 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10128                                               Type *Ty) const {
10129   EVT VT = getValueType(Ty, true);
10130   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10131     return false;
10132 
10133   // Can never fold addr of global into load/store.
10134   if (AM.BaseGV)
10135     return false;
10136 
10137   switch (AM.Scale) {
10138   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10139     break;
10140   case 1:
10141     if (Subtarget->isThumb1Only())
10142       return false;
10143     // FALL THROUGH.
10144   default:
10145     // ARM doesn't support any R+R*scale+imm addr modes.
10146     if (AM.BaseOffs)
10147       return false;
10148 
10149     if (!VT.isSimple())
10150       return false;
10151 
10152     if (Subtarget->isThumb2())
10153       return isLegalT2ScaledAddressingMode(AM, VT);
10154 
10155     int Scale = AM.Scale;
10156     switch (VT.getSimpleVT().SimpleTy) {
10157     default: return false;
10158     case MVT::i1:
10159     case MVT::i8:
10160     case MVT::i32:
10161       if (Scale < 0) Scale = -Scale;
10162       if (Scale == 1)
10163         return true;
10164       // r + r << imm
10165       return isPowerOf2_32(Scale & ~1);
10166     case MVT::i16:
10167     case MVT::i64:
10168       // r + r
10169       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10170         return true;
10171       return false;
10172 
10173     case MVT::isVoid:
10174       // Note, we allow "void" uses (basically, uses that aren't loads or
10175       // stores), because arm allows folding a scale into many arithmetic
10176       // operations.  This should be made more precise and revisited later.
10177 
10178       // Allow r << imm, but the imm has to be a multiple of two.
10179       if (Scale & 1) return false;
10180       return isPowerOf2_32(Scale);
10181     }
10182   }
10183   return true;
10184 }
10185 
10186 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10187 /// icmp immediate, that is the target has icmp instructions which can compare
10188 /// a register against the immediate without having to materialize the
10189 /// immediate into a register.
isLegalICmpImmediate(int64_t Imm) const10190 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10191   // Thumb2 and ARM modes can use cmn for negative immediates.
10192   if (!Subtarget->isThumb())
10193     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10194   if (Subtarget->isThumb2())
10195     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10196   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10197   return Imm >= 0 && Imm <= 255;
10198 }
10199 
10200 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10201 /// *or sub* immediate, that is the target has add or sub instructions which can
10202 /// add a register with the immediate without having to materialize the
10203 /// immediate into a register.
isLegalAddImmediate(int64_t Imm) const10204 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10205   // Same encoding for add/sub, just flip the sign.
10206   int64_t AbsImm = std::abs(Imm);
10207   if (!Subtarget->isThumb())
10208     return ARM_AM::getSOImmVal(AbsImm) != -1;
10209   if (Subtarget->isThumb2())
10210     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10211   // Thumb1 only has 8-bit unsigned immediate.
10212   return AbsImm >= 0 && AbsImm <= 255;
10213 }
10214 
getARMIndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)10215 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10216                                       bool isSEXTLoad, SDValue &Base,
10217                                       SDValue &Offset, bool &isInc,
10218                                       SelectionDAG &DAG) {
10219   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10220     return false;
10221 
10222   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10223     // AddressingMode 3
10224     Base = Ptr->getOperand(0);
10225     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10226       int RHSC = (int)RHS->getZExtValue();
10227       if (RHSC < 0 && RHSC > -256) {
10228         assert(Ptr->getOpcode() == ISD::ADD);
10229         isInc = false;
10230         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10231         return true;
10232       }
10233     }
10234     isInc = (Ptr->getOpcode() == ISD::ADD);
10235     Offset = Ptr->getOperand(1);
10236     return true;
10237   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10238     // AddressingMode 2
10239     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10240       int RHSC = (int)RHS->getZExtValue();
10241       if (RHSC < 0 && RHSC > -0x1000) {
10242         assert(Ptr->getOpcode() == ISD::ADD);
10243         isInc = false;
10244         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10245         Base = Ptr->getOperand(0);
10246         return true;
10247       }
10248     }
10249 
10250     if (Ptr->getOpcode() == ISD::ADD) {
10251       isInc = true;
10252       ARM_AM::ShiftOpc ShOpcVal=
10253         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10254       if (ShOpcVal != ARM_AM::no_shift) {
10255         Base = Ptr->getOperand(1);
10256         Offset = Ptr->getOperand(0);
10257       } else {
10258         Base = Ptr->getOperand(0);
10259         Offset = Ptr->getOperand(1);
10260       }
10261       return true;
10262     }
10263 
10264     isInc = (Ptr->getOpcode() == ISD::ADD);
10265     Base = Ptr->getOperand(0);
10266     Offset = Ptr->getOperand(1);
10267     return true;
10268   }
10269 
10270   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10271   return false;
10272 }
10273 
getT2IndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)10274 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10275                                      bool isSEXTLoad, SDValue &Base,
10276                                      SDValue &Offset, bool &isInc,
10277                                      SelectionDAG &DAG) {
10278   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10279     return false;
10280 
10281   Base = Ptr->getOperand(0);
10282   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10283     int RHSC = (int)RHS->getZExtValue();
10284     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10285       assert(Ptr->getOpcode() == ISD::ADD);
10286       isInc = false;
10287       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10288       return true;
10289     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10290       isInc = Ptr->getOpcode() == ISD::ADD;
10291       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10292       return true;
10293     }
10294   }
10295 
10296   return false;
10297 }
10298 
10299 /// getPreIndexedAddressParts - returns true by value, base pointer and
10300 /// offset pointer and addressing mode by reference if the node's address
10301 /// can be legally represented as pre-indexed load / store address.
10302 bool
getPreIndexedAddressParts(SDNode * N,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const10303 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10304                                              SDValue &Offset,
10305                                              ISD::MemIndexedMode &AM,
10306                                              SelectionDAG &DAG) const {
10307   if (Subtarget->isThumb1Only())
10308     return false;
10309 
10310   EVT VT;
10311   SDValue Ptr;
10312   bool isSEXTLoad = false;
10313   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10314     Ptr = LD->getBasePtr();
10315     VT  = LD->getMemoryVT();
10316     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10317   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10318     Ptr = ST->getBasePtr();
10319     VT  = ST->getMemoryVT();
10320   } else
10321     return false;
10322 
10323   bool isInc;
10324   bool isLegal = false;
10325   if (Subtarget->isThumb2())
10326     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10327                                        Offset, isInc, DAG);
10328   else
10329     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10330                                         Offset, isInc, DAG);
10331   if (!isLegal)
10332     return false;
10333 
10334   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10335   return true;
10336 }
10337 
10338 /// getPostIndexedAddressParts - returns true by value, base pointer and
10339 /// offset pointer and addressing mode by reference if this node can be
10340 /// combined with a load / store to form a post-indexed load / store.
getPostIndexedAddressParts(SDNode * N,SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const10341 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10342                                                    SDValue &Base,
10343                                                    SDValue &Offset,
10344                                                    ISD::MemIndexedMode &AM,
10345                                                    SelectionDAG &DAG) const {
10346   if (Subtarget->isThumb1Only())
10347     return false;
10348 
10349   EVT VT;
10350   SDValue Ptr;
10351   bool isSEXTLoad = false;
10352   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10353     VT  = LD->getMemoryVT();
10354     Ptr = LD->getBasePtr();
10355     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10356   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10357     VT  = ST->getMemoryVT();
10358     Ptr = ST->getBasePtr();
10359   } else
10360     return false;
10361 
10362   bool isInc;
10363   bool isLegal = false;
10364   if (Subtarget->isThumb2())
10365     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10366                                        isInc, DAG);
10367   else
10368     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10369                                         isInc, DAG);
10370   if (!isLegal)
10371     return false;
10372 
10373   if (Ptr != Base) {
10374     // Swap base ptr and offset to catch more post-index load / store when
10375     // it's legal. In Thumb2 mode, offset must be an immediate.
10376     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10377         !Subtarget->isThumb2())
10378       std::swap(Base, Offset);
10379 
10380     // Post-indexed load / store update the base pointer.
10381     if (Ptr != Base)
10382       return false;
10383   }
10384 
10385   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10386   return true;
10387 }
10388 
computeKnownBitsForTargetNode(const SDValue Op,APInt & KnownZero,APInt & KnownOne,const SelectionDAG & DAG,unsigned Depth) const10389 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10390                                                       APInt &KnownZero,
10391                                                       APInt &KnownOne,
10392                                                       const SelectionDAG &DAG,
10393                                                       unsigned Depth) const {
10394   unsigned BitWidth = KnownOne.getBitWidth();
10395   KnownZero = KnownOne = APInt(BitWidth, 0);
10396   switch (Op.getOpcode()) {
10397   default: break;
10398   case ARMISD::ADDC:
10399   case ARMISD::ADDE:
10400   case ARMISD::SUBC:
10401   case ARMISD::SUBE:
10402     // These nodes' second result is a boolean
10403     if (Op.getResNo() == 0)
10404       break;
10405     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10406     break;
10407   case ARMISD::CMOV: {
10408     // Bits are known zero/one if known on the LHS and RHS.
10409     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10410     if (KnownZero == 0 && KnownOne == 0) return;
10411 
10412     APInt KnownZeroRHS, KnownOneRHS;
10413     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10414     KnownZero &= KnownZeroRHS;
10415     KnownOne  &= KnownOneRHS;
10416     return;
10417   }
10418   case ISD::INTRINSIC_W_CHAIN: {
10419     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10420     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10421     switch (IntID) {
10422     default: return;
10423     case Intrinsic::arm_ldaex:
10424     case Intrinsic::arm_ldrex: {
10425       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10426       unsigned MemBits = VT.getScalarType().getSizeInBits();
10427       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10428       return;
10429     }
10430     }
10431   }
10432   }
10433 }
10434 
10435 //===----------------------------------------------------------------------===//
10436 //                           ARM Inline Assembly Support
10437 //===----------------------------------------------------------------------===//
10438 
ExpandInlineAsm(CallInst * CI) const10439 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10440   // Looking for "rev" which is V6+.
10441   if (!Subtarget->hasV6Ops())
10442     return false;
10443 
10444   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10445   std::string AsmStr = IA->getAsmString();
10446   SmallVector<StringRef, 4> AsmPieces;
10447   SplitString(AsmStr, AsmPieces, ";\n");
10448 
10449   switch (AsmPieces.size()) {
10450   default: return false;
10451   case 1:
10452     AsmStr = AsmPieces[0];
10453     AsmPieces.clear();
10454     SplitString(AsmStr, AsmPieces, " \t,");
10455 
10456     // rev $0, $1
10457     if (AsmPieces.size() == 3 &&
10458         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10459         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10460       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10461       if (Ty && Ty->getBitWidth() == 32)
10462         return IntrinsicLowering::LowerToByteSwap(CI);
10463     }
10464     break;
10465   }
10466 
10467   return false;
10468 }
10469 
10470 /// getConstraintType - Given a constraint letter, return the type of
10471 /// constraint it is for this target.
10472 ARMTargetLowering::ConstraintType
getConstraintType(const std::string & Constraint) const10473 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10474   if (Constraint.size() == 1) {
10475     switch (Constraint[0]) {
10476     default:  break;
10477     case 'l': return C_RegisterClass;
10478     case 'w': return C_RegisterClass;
10479     case 'h': return C_RegisterClass;
10480     case 'x': return C_RegisterClass;
10481     case 't': return C_RegisterClass;
10482     case 'j': return C_Other; // Constant for movw.
10483       // An address with a single base register. Due to the way we
10484       // currently handle addresses it is the same as an 'r' memory constraint.
10485     case 'Q': return C_Memory;
10486     }
10487   } else if (Constraint.size() == 2) {
10488     switch (Constraint[0]) {
10489     default: break;
10490     // All 'U+' constraints are addresses.
10491     case 'U': return C_Memory;
10492     }
10493   }
10494   return TargetLowering::getConstraintType(Constraint);
10495 }
10496 
10497 /// Examine constraint type and operand type and determine a weight value.
10498 /// This object must already have been set up with the operand type
10499 /// and the current alternative constraint selected.
10500 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const10501 ARMTargetLowering::getSingleConstraintMatchWeight(
10502     AsmOperandInfo &info, const char *constraint) const {
10503   ConstraintWeight weight = CW_Invalid;
10504   Value *CallOperandVal = info.CallOperandVal;
10505     // If we don't have a value, we can't do a match,
10506     // but allow it at the lowest weight.
10507   if (!CallOperandVal)
10508     return CW_Default;
10509   Type *type = CallOperandVal->getType();
10510   // Look at the constraint type.
10511   switch (*constraint) {
10512   default:
10513     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10514     break;
10515   case 'l':
10516     if (type->isIntegerTy()) {
10517       if (Subtarget->isThumb())
10518         weight = CW_SpecificReg;
10519       else
10520         weight = CW_Register;
10521     }
10522     break;
10523   case 'w':
10524     if (type->isFloatingPointTy())
10525       weight = CW_Register;
10526     break;
10527   }
10528   return weight;
10529 }
10530 
10531 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10532 RCPair
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,const std::string & Constraint,MVT VT) const10533 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10534                                                 const std::string &Constraint,
10535                                                 MVT VT) const {
10536   if (Constraint.size() == 1) {
10537     // GCC ARM Constraint Letters
10538     switch (Constraint[0]) {
10539     case 'l': // Low regs or general regs.
10540       if (Subtarget->isThumb())
10541         return RCPair(0U, &ARM::tGPRRegClass);
10542       return RCPair(0U, &ARM::GPRRegClass);
10543     case 'h': // High regs or no regs.
10544       if (Subtarget->isThumb())
10545         return RCPair(0U, &ARM::hGPRRegClass);
10546       break;
10547     case 'r':
10548       if (Subtarget->isThumb1Only())
10549         return RCPair(0U, &ARM::tGPRRegClass);
10550       return RCPair(0U, &ARM::GPRRegClass);
10551     case 'w':
10552       if (VT == MVT::Other)
10553         break;
10554       if (VT == MVT::f32)
10555         return RCPair(0U, &ARM::SPRRegClass);
10556       if (VT.getSizeInBits() == 64)
10557         return RCPair(0U, &ARM::DPRRegClass);
10558       if (VT.getSizeInBits() == 128)
10559         return RCPair(0U, &ARM::QPRRegClass);
10560       break;
10561     case 'x':
10562       if (VT == MVT::Other)
10563         break;
10564       if (VT == MVT::f32)
10565         return RCPair(0U, &ARM::SPR_8RegClass);
10566       if (VT.getSizeInBits() == 64)
10567         return RCPair(0U, &ARM::DPR_8RegClass);
10568       if (VT.getSizeInBits() == 128)
10569         return RCPair(0U, &ARM::QPR_8RegClass);
10570       break;
10571     case 't':
10572       if (VT == MVT::f32)
10573         return RCPair(0U, &ARM::SPRRegClass);
10574       break;
10575     }
10576   }
10577   if (StringRef("{cc}").equals_lower(Constraint))
10578     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10579 
10580   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10581 }
10582 
10583 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10584 /// vector.  If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const10585 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10586                                                      std::string &Constraint,
10587                                                      std::vector<SDValue>&Ops,
10588                                                      SelectionDAG &DAG) const {
10589   SDValue Result;
10590 
10591   // Currently only support length 1 constraints.
10592   if (Constraint.length() != 1) return;
10593 
10594   char ConstraintLetter = Constraint[0];
10595   switch (ConstraintLetter) {
10596   default: break;
10597   case 'j':
10598   case 'I': case 'J': case 'K': case 'L':
10599   case 'M': case 'N': case 'O':
10600     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10601     if (!C)
10602       return;
10603 
10604     int64_t CVal64 = C->getSExtValue();
10605     int CVal = (int) CVal64;
10606     // None of these constraints allow values larger than 32 bits.  Check
10607     // that the value fits in an int.
10608     if (CVal != CVal64)
10609       return;
10610 
10611     switch (ConstraintLetter) {
10612       case 'j':
10613         // Constant suitable for movw, must be between 0 and
10614         // 65535.
10615         if (Subtarget->hasV6T2Ops())
10616           if (CVal >= 0 && CVal <= 65535)
10617             break;
10618         return;
10619       case 'I':
10620         if (Subtarget->isThumb1Only()) {
10621           // This must be a constant between 0 and 255, for ADD
10622           // immediates.
10623           if (CVal >= 0 && CVal <= 255)
10624             break;
10625         } else if (Subtarget->isThumb2()) {
10626           // A constant that can be used as an immediate value in a
10627           // data-processing instruction.
10628           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10629             break;
10630         } else {
10631           // A constant that can be used as an immediate value in a
10632           // data-processing instruction.
10633           if (ARM_AM::getSOImmVal(CVal) != -1)
10634             break;
10635         }
10636         return;
10637 
10638       case 'J':
10639         if (Subtarget->isThumb()) {  // FIXME thumb2
10640           // This must be a constant between -255 and -1, for negated ADD
10641           // immediates. This can be used in GCC with an "n" modifier that
10642           // prints the negated value, for use with SUB instructions. It is
10643           // not useful otherwise but is implemented for compatibility.
10644           if (CVal >= -255 && CVal <= -1)
10645             break;
10646         } else {
10647           // This must be a constant between -4095 and 4095. It is not clear
10648           // what this constraint is intended for. Implemented for
10649           // compatibility with GCC.
10650           if (CVal >= -4095 && CVal <= 4095)
10651             break;
10652         }
10653         return;
10654 
10655       case 'K':
10656         if (Subtarget->isThumb1Only()) {
10657           // A 32-bit value where only one byte has a nonzero value. Exclude
10658           // zero to match GCC. This constraint is used by GCC internally for
10659           // constants that can be loaded with a move/shift combination.
10660           // It is not useful otherwise but is implemented for compatibility.
10661           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10662             break;
10663         } else if (Subtarget->isThumb2()) {
10664           // A constant whose bitwise inverse can be used as an immediate
10665           // value in a data-processing instruction. This can be used in GCC
10666           // with a "B" modifier that prints the inverted value, for use with
10667           // BIC and MVN instructions. It is not useful otherwise but is
10668           // implemented for compatibility.
10669           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10670             break;
10671         } else {
10672           // A constant whose bitwise inverse can be used as an immediate
10673           // value in a data-processing instruction. This can be used in GCC
10674           // with a "B" modifier that prints the inverted value, for use with
10675           // BIC and MVN instructions. It is not useful otherwise but is
10676           // implemented for compatibility.
10677           if (ARM_AM::getSOImmVal(~CVal) != -1)
10678             break;
10679         }
10680         return;
10681 
10682       case 'L':
10683         if (Subtarget->isThumb1Only()) {
10684           // This must be a constant between -7 and 7,
10685           // for 3-operand ADD/SUB immediate instructions.
10686           if (CVal >= -7 && CVal < 7)
10687             break;
10688         } else if (Subtarget->isThumb2()) {
10689           // A constant whose negation can be used as an immediate value in a
10690           // data-processing instruction. This can be used in GCC with an "n"
10691           // modifier that prints the negated value, for use with SUB
10692           // instructions. It is not useful otherwise but is implemented for
10693           // compatibility.
10694           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10695             break;
10696         } else {
10697           // A constant whose negation can be used as an immediate value in a
10698           // data-processing instruction. This can be used in GCC with an "n"
10699           // modifier that prints the negated value, for use with SUB
10700           // instructions. It is not useful otherwise but is implemented for
10701           // compatibility.
10702           if (ARM_AM::getSOImmVal(-CVal) != -1)
10703             break;
10704         }
10705         return;
10706 
10707       case 'M':
10708         if (Subtarget->isThumb()) { // FIXME thumb2
10709           // This must be a multiple of 4 between 0 and 1020, for
10710           // ADD sp + immediate.
10711           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10712             break;
10713         } else {
10714           // A power of two or a constant between 0 and 32.  This is used in
10715           // GCC for the shift amount on shifted register operands, but it is
10716           // useful in general for any shift amounts.
10717           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10718             break;
10719         }
10720         return;
10721 
10722       case 'N':
10723         if (Subtarget->isThumb()) {  // FIXME thumb2
10724           // This must be a constant between 0 and 31, for shift amounts.
10725           if (CVal >= 0 && CVal <= 31)
10726             break;
10727         }
10728         return;
10729 
10730       case 'O':
10731         if (Subtarget->isThumb()) {  // FIXME thumb2
10732           // This must be a multiple of 4 between -508 and 508, for
10733           // ADD/SUB sp = sp + immediate.
10734           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10735             break;
10736         }
10737         return;
10738     }
10739     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10740     break;
10741   }
10742 
10743   if (Result.getNode()) {
10744     Ops.push_back(Result);
10745     return;
10746   }
10747   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10748 }
10749 
LowerDivRem(SDValue Op,SelectionDAG & DAG) const10750 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10751   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10752   unsigned Opcode = Op->getOpcode();
10753   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10754          "Invalid opcode for Div/Rem lowering");
10755   bool isSigned = (Opcode == ISD::SDIVREM);
10756   EVT VT = Op->getValueType(0);
10757   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10758 
10759   RTLIB::Libcall LC;
10760   switch (VT.getSimpleVT().SimpleTy) {
10761   default: llvm_unreachable("Unexpected request for libcall!");
10762   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10763   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10764   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10765   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10766   }
10767 
10768   SDValue InChain = DAG.getEntryNode();
10769 
10770   TargetLowering::ArgListTy Args;
10771   TargetLowering::ArgListEntry Entry;
10772   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10773     EVT ArgVT = Op->getOperand(i).getValueType();
10774     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10775     Entry.Node = Op->getOperand(i);
10776     Entry.Ty = ArgTy;
10777     Entry.isSExt = isSigned;
10778     Entry.isZExt = !isSigned;
10779     Args.push_back(Entry);
10780   }
10781 
10782   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10783                                          getPointerTy());
10784 
10785   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10786 
10787   SDLoc dl(Op);
10788   TargetLowering::CallLoweringInfo CLI(DAG);
10789   CLI.setDebugLoc(dl).setChain(InChain)
10790     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10791     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10792 
10793   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10794   return CallInfo.first;
10795 }
10796 
10797 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const10798 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10799   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10800   SDLoc DL(Op);
10801 
10802   // Get the inputs.
10803   SDValue Chain = Op.getOperand(0);
10804   SDValue Size  = Op.getOperand(1);
10805 
10806   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10807                               DAG.getConstant(2, MVT::i32));
10808 
10809   SDValue Flag;
10810   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10811   Flag = Chain.getValue(1);
10812 
10813   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10814   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10815 
10816   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10817   Chain = NewSP.getValue(1);
10818 
10819   SDValue Ops[2] = { NewSP, Chain };
10820   return DAG.getMergeValues(Ops, DL);
10821 }
10822 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const10823 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10824   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10825          "Unexpected type for custom-lowering FP_EXTEND");
10826 
10827   RTLIB::Libcall LC;
10828   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10829 
10830   SDValue SrcVal = Op.getOperand(0);
10831   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10832                      /*isSigned*/ false, SDLoc(Op)).first;
10833 }
10834 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const10835 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10836   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10837          Subtarget->isFPOnlySP() &&
10838          "Unexpected type for custom-lowering FP_ROUND");
10839 
10840   RTLIB::Libcall LC;
10841   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10842 
10843   SDValue SrcVal = Op.getOperand(0);
10844   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10845                      /*isSigned*/ false, SDLoc(Op)).first;
10846 }
10847 
10848 bool
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const10849 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10850   // The ARM target isn't yet aware of offsets.
10851   return false;
10852 }
10853 
isBitFieldInvertedMask(unsigned v)10854 bool ARM::isBitFieldInvertedMask(unsigned v) {
10855   if (v == 0xffffffff)
10856     return false;
10857 
10858   // there can be 1's on either or both "outsides", all the "inside"
10859   // bits must be 0's
10860   return isShiftedMask_32(~v);
10861 }
10862 
10863 /// isFPImmLegal - Returns true if the target can instruction select the
10864 /// specified FP immediate natively. If false, the legalizer will
10865 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT) const10866 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10867   if (!Subtarget->hasVFP3())
10868     return false;
10869   if (VT == MVT::f32)
10870     return ARM_AM::getFP32Imm(Imm) != -1;
10871   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10872     return ARM_AM::getFP64Imm(Imm) != -1;
10873   return false;
10874 }
10875 
10876 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10877 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10878 /// specified in the intrinsic calls.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,unsigned Intrinsic) const10879 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10880                                            const CallInst &I,
10881                                            unsigned Intrinsic) const {
10882   switch (Intrinsic) {
10883   case Intrinsic::arm_neon_vld1:
10884   case Intrinsic::arm_neon_vld2:
10885   case Intrinsic::arm_neon_vld3:
10886   case Intrinsic::arm_neon_vld4:
10887   case Intrinsic::arm_neon_vld2lane:
10888   case Intrinsic::arm_neon_vld3lane:
10889   case Intrinsic::arm_neon_vld4lane: {
10890     Info.opc = ISD::INTRINSIC_W_CHAIN;
10891     // Conservatively set memVT to the entire set of vectors loaded.
10892     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10893     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10894     Info.ptrVal = I.getArgOperand(0);
10895     Info.offset = 0;
10896     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10897     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10898     Info.vol = false; // volatile loads with NEON intrinsics not supported
10899     Info.readMem = true;
10900     Info.writeMem = false;
10901     return true;
10902   }
10903   case Intrinsic::arm_neon_vst1:
10904   case Intrinsic::arm_neon_vst2:
10905   case Intrinsic::arm_neon_vst3:
10906   case Intrinsic::arm_neon_vst4:
10907   case Intrinsic::arm_neon_vst2lane:
10908   case Intrinsic::arm_neon_vst3lane:
10909   case Intrinsic::arm_neon_vst4lane: {
10910     Info.opc = ISD::INTRINSIC_VOID;
10911     // Conservatively set memVT to the entire set of vectors stored.
10912     unsigned NumElts = 0;
10913     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10914       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10915       if (!ArgTy->isVectorTy())
10916         break;
10917       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10918     }
10919     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10920     Info.ptrVal = I.getArgOperand(0);
10921     Info.offset = 0;
10922     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10923     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10924     Info.vol = false; // volatile stores with NEON intrinsics not supported
10925     Info.readMem = false;
10926     Info.writeMem = true;
10927     return true;
10928   }
10929   case Intrinsic::arm_ldaex:
10930   case Intrinsic::arm_ldrex: {
10931     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10932     Info.opc = ISD::INTRINSIC_W_CHAIN;
10933     Info.memVT = MVT::getVT(PtrTy->getElementType());
10934     Info.ptrVal = I.getArgOperand(0);
10935     Info.offset = 0;
10936     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10937     Info.vol = true;
10938     Info.readMem = true;
10939     Info.writeMem = false;
10940     return true;
10941   }
10942   case Intrinsic::arm_stlex:
10943   case Intrinsic::arm_strex: {
10944     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10945     Info.opc = ISD::INTRINSIC_W_CHAIN;
10946     Info.memVT = MVT::getVT(PtrTy->getElementType());
10947     Info.ptrVal = I.getArgOperand(1);
10948     Info.offset = 0;
10949     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10950     Info.vol = true;
10951     Info.readMem = false;
10952     Info.writeMem = true;
10953     return true;
10954   }
10955   case Intrinsic::arm_stlexd:
10956   case Intrinsic::arm_strexd: {
10957     Info.opc = ISD::INTRINSIC_W_CHAIN;
10958     Info.memVT = MVT::i64;
10959     Info.ptrVal = I.getArgOperand(2);
10960     Info.offset = 0;
10961     Info.align = 8;
10962     Info.vol = true;
10963     Info.readMem = false;
10964     Info.writeMem = true;
10965     return true;
10966   }
10967   case Intrinsic::arm_ldaexd:
10968   case Intrinsic::arm_ldrexd: {
10969     Info.opc = ISD::INTRINSIC_W_CHAIN;
10970     Info.memVT = MVT::i64;
10971     Info.ptrVal = I.getArgOperand(0);
10972     Info.offset = 0;
10973     Info.align = 8;
10974     Info.vol = true;
10975     Info.readMem = true;
10976     Info.writeMem = false;
10977     return true;
10978   }
10979   default:
10980     break;
10981   }
10982 
10983   return false;
10984 }
10985 
10986 /// \brief Returns true if it is beneficial to convert a load of a constant
10987 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const10988 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10989                                                           Type *Ty) const {
10990   assert(Ty->isIntegerTy());
10991 
10992   unsigned Bits = Ty->getPrimitiveSizeInBits();
10993   if (Bits == 0 || Bits > 32)
10994     return false;
10995   return true;
10996 }
10997 
hasLoadLinkedStoreConditional() const10998 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
10999 
makeDMB(IRBuilder<> & Builder,ARM_MB::MemBOpt Domain) const11000 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11001                                         ARM_MB::MemBOpt Domain) const {
11002   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11003 
11004   // First, if the target has no DMB, see what fallback we can use.
11005   if (!Subtarget->hasDataBarrier()) {
11006     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11007     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11008     // here.
11009     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11010       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11011       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11012                         Builder.getInt32(0), Builder.getInt32(7),
11013                         Builder.getInt32(10), Builder.getInt32(5)};
11014       return Builder.CreateCall(MCR, args);
11015     } else {
11016       // Instead of using barriers, atomic accesses on these subtargets use
11017       // libcalls.
11018       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11019     }
11020   } else {
11021     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11022     // Only a full system barrier exists in the M-class architectures.
11023     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11024     Constant *CDomain = Builder.getInt32(Domain);
11025     return Builder.CreateCall(DMB, CDomain);
11026   }
11027 }
11028 
11029 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
emitLeadingFence(IRBuilder<> & Builder,AtomicOrdering Ord,bool IsStore,bool IsLoad) const11030 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11031                                          AtomicOrdering Ord, bool IsStore,
11032                                          bool IsLoad) const {
11033   if (!getInsertFencesForAtomic())
11034     return nullptr;
11035 
11036   switch (Ord) {
11037   case NotAtomic:
11038   case Unordered:
11039     llvm_unreachable("Invalid fence: unordered/non-atomic");
11040   case Monotonic:
11041   case Acquire:
11042     return nullptr; // Nothing to do
11043   case SequentiallyConsistent:
11044     if (!IsStore)
11045       return nullptr; // Nothing to do
11046     /*FALLTHROUGH*/
11047   case Release:
11048   case AcquireRelease:
11049     if (Subtarget->isSwift())
11050       return makeDMB(Builder, ARM_MB::ISHST);
11051     // FIXME: add a comment with a link to documentation justifying this.
11052     else
11053       return makeDMB(Builder, ARM_MB::ISH);
11054   }
11055   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11056 }
11057 
emitTrailingFence(IRBuilder<> & Builder,AtomicOrdering Ord,bool IsStore,bool IsLoad) const11058 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11059                                           AtomicOrdering Ord, bool IsStore,
11060                                           bool IsLoad) const {
11061   if (!getInsertFencesForAtomic())
11062     return nullptr;
11063 
11064   switch (Ord) {
11065   case NotAtomic:
11066   case Unordered:
11067     llvm_unreachable("Invalid fence: unordered/not-atomic");
11068   case Monotonic:
11069   case Release:
11070     return nullptr; // Nothing to do
11071   case Acquire:
11072   case AcquireRelease:
11073   case SequentiallyConsistent:
11074     return makeDMB(Builder, ARM_MB::ISH);
11075   }
11076   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11077 }
11078 
11079 // Loads and stores less than 64-bits are already atomic; ones above that
11080 // are doomed anyway, so defer to the default libcall and blame the OS when
11081 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11082 // anything for those.
shouldExpandAtomicStoreInIR(StoreInst * SI) const11083 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11084   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11085   return (Size == 64) && !Subtarget->isMClass();
11086 }
11087 
11088 // Loads and stores less than 64-bits are already atomic; ones above that
11089 // are doomed anyway, so defer to the default libcall and blame the OS when
11090 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11091 // anything for those.
11092 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11093 // guarantee, see DDI0406C ARM architecture reference manual,
11094 // sections A8.8.72-74 LDRD)
shouldExpandAtomicLoadInIR(LoadInst * LI) const11095 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11096   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11097   return (Size == 64) && !Subtarget->isMClass();
11098 }
11099 
11100 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11101 // and up to 64 bits on the non-M profiles
11102 TargetLoweringBase::AtomicRMWExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const11103 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11104   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11105   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11106              ? AtomicRMWExpansionKind::LLSC
11107              : AtomicRMWExpansionKind::None;
11108 }
11109 
11110 // This has so far only been implemented for MachO.
useLoadStackGuardNode() const11111 bool ARMTargetLowering::useLoadStackGuardNode() const {
11112   return Subtarget->isTargetMachO();
11113 }
11114 
canCombineStoreAndExtract(Type * VectorTy,Value * Idx,unsigned & Cost) const11115 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11116                                                   unsigned &Cost) const {
11117   // If we do not have NEON, vector types are not natively supported.
11118   if (!Subtarget->hasNEON())
11119     return false;
11120 
11121   // Floating point values and vector values map to the same register file.
11122   // Therefore, althought we could do a store extract of a vector type, this is
11123   // better to leave at float as we have more freedom in the addressing mode for
11124   // those.
11125   if (VectorTy->isFPOrFPVectorTy())
11126     return false;
11127 
11128   // If the index is unknown at compile time, this is very expensive to lower
11129   // and it is not possible to combine the store with the extract.
11130   if (!isa<ConstantInt>(Idx))
11131     return false;
11132 
11133   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11134   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11135   // We can do a store + vector extract on any vector that fits perfectly in a D
11136   // or Q register.
11137   if (BitWidth == 64 || BitWidth == 128) {
11138     Cost = 0;
11139     return true;
11140   }
11141   return false;
11142 }
11143 
emitLoadLinked(IRBuilder<> & Builder,Value * Addr,AtomicOrdering Ord) const11144 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11145                                          AtomicOrdering Ord) const {
11146   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11147   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11148   bool IsAcquire = isAtLeastAcquire(Ord);
11149 
11150   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11151   // intrinsic must return {i32, i32} and we have to recombine them into a
11152   // single i64 here.
11153   if (ValTy->getPrimitiveSizeInBits() == 64) {
11154     Intrinsic::ID Int =
11155         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11156     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11157 
11158     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11159     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11160 
11161     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11162     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11163     if (!Subtarget->isLittle())
11164       std::swap (Lo, Hi);
11165     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11166     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11167     return Builder.CreateOr(
11168         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11169   }
11170 
11171   Type *Tys[] = { Addr->getType() };
11172   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11173   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11174 
11175   return Builder.CreateTruncOrBitCast(
11176       Builder.CreateCall(Ldrex, Addr),
11177       cast<PointerType>(Addr->getType())->getElementType());
11178 }
11179 
emitStoreConditional(IRBuilder<> & Builder,Value * Val,Value * Addr,AtomicOrdering Ord) const11180 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11181                                                Value *Addr,
11182                                                AtomicOrdering Ord) const {
11183   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11184   bool IsRelease = isAtLeastRelease(Ord);
11185 
11186   // Since the intrinsics must have legal type, the i64 intrinsics take two
11187   // parameters: "i32, i32". We must marshal Val into the appropriate form
11188   // before the call.
11189   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11190     Intrinsic::ID Int =
11191         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11192     Function *Strex = Intrinsic::getDeclaration(M, Int);
11193     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11194 
11195     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11196     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11197     if (!Subtarget->isLittle())
11198       std::swap (Lo, Hi);
11199     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11200     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11201   }
11202 
11203   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11204   Type *Tys[] = { Addr->getType() };
11205   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11206 
11207   return Builder.CreateCall2(
11208       Strex, Builder.CreateZExtOrBitCast(
11209                  Val, Strex->getFunctionType()->getParamType(0)),
11210       Addr);
11211 }
11212 
11213 enum HABaseType {
11214   HA_UNKNOWN = 0,
11215   HA_FLOAT,
11216   HA_DOUBLE,
11217   HA_VECT64,
11218   HA_VECT128
11219 };
11220 
isHomogeneousAggregate(Type * Ty,HABaseType & Base,uint64_t & Members)11221 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11222                                    uint64_t &Members) {
11223   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11224     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11225       uint64_t SubMembers = 0;
11226       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11227         return false;
11228       Members += SubMembers;
11229     }
11230   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11231     uint64_t SubMembers = 0;
11232     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11233       return false;
11234     Members += SubMembers * AT->getNumElements();
11235   } else if (Ty->isFloatTy()) {
11236     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11237       return false;
11238     Members = 1;
11239     Base = HA_FLOAT;
11240   } else if (Ty->isDoubleTy()) {
11241     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11242       return false;
11243     Members = 1;
11244     Base = HA_DOUBLE;
11245   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11246     Members = 1;
11247     switch (Base) {
11248     case HA_FLOAT:
11249     case HA_DOUBLE:
11250       return false;
11251     case HA_VECT64:
11252       return VT->getBitWidth() == 64;
11253     case HA_VECT128:
11254       return VT->getBitWidth() == 128;
11255     case HA_UNKNOWN:
11256       switch (VT->getBitWidth()) {
11257       case 64:
11258         Base = HA_VECT64;
11259         return true;
11260       case 128:
11261         Base = HA_VECT128;
11262         return true;
11263       default:
11264         return false;
11265       }
11266     }
11267   }
11268 
11269   return (Members > 0 && Members <= 4);
11270 }
11271 
11272 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11273 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11274 /// passing according to AAPCS rules.
functionArgumentNeedsConsecutiveRegisters(Type * Ty,CallingConv::ID CallConv,bool isVarArg) const11275 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11276     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11277   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11278       CallingConv::ARM_AAPCS_VFP)
11279     return false;
11280 
11281   HABaseType Base = HA_UNKNOWN;
11282   uint64_t Members = 0;
11283   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11284   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11285 
11286   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11287   return IsHA || IsIntArray;
11288 }
11289