1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
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"
57 #define DEBUG_TYPE "arm-isel"
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");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (VT.isInteger()) {
147 setOperationAction(ISD::SABSDIFF, VT, Legal);
148 setOperationAction(ISD::UABSDIFF, VT, Legal);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPairRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163 const ARMSubtarget &STI)
164 : TargetLowering(TM), Subtarget(&STI) {
165 RegInfo = Subtarget->getRegisterInfo();
166 Itins = Subtarget->getInstrItineraryData();
168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
170 if (Subtarget->isTargetMachO()) {
171 // Uses VFP for Thumb libfuncs if available.
172 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174 static const struct {
175 const RTLIB::Libcall Op;
176 const char * const Name;
177 const ISD::CondCode Cond;
179 // Single-precision floating-point arithmetic.
180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
185 // Double-precision floating-point arithmetic.
186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
191 // Single-precision comparisons.
192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
201 // Double-precision comparisons.
202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
211 // Floating-point to integer conversions.
212 // i64 conversions are done via library routines even when generating VFP
213 // instructions, so use the same ones.
214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
219 // Conversions between floating types.
220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
223 // Integer to floating-point conversions.
224 // i64 conversions are done via library routines even when generating VFP
225 // instructions, so use the same ones.
226 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227 // e.g., __floatunsidf vs. __floatunssidfvfp.
228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
234 for (const auto &LC : LibraryCalls) {
235 setLibcallName(LC.Op, LC.Name);
236 if (LC.Cond != ISD::SETCC_INVALID)
237 setCmpLibcallCC(LC.Op, LC.Cond);
242 // These libcalls are not available in 32-bit.
243 setLibcallName(RTLIB::SHL_I128, nullptr);
244 setLibcallName(RTLIB::SRL_I128, nullptr);
245 setLibcallName(RTLIB::SRA_I128, nullptr);
247 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248 !Subtarget->isTargetWindows()) {
249 static const struct {
250 const RTLIB::Libcall Op;
251 const char * const Name;
252 const CallingConv::ID CC;
253 const ISD::CondCode Cond;
255 // Double-precision floating-point arithmetic helper functions
256 // RTABI chapter 4.1.2, Table 2
257 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262 // Double-precision floating-point comparison helper functions
263 // RTABI chapter 4.1.2, Table 3
264 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
273 // Single-precision floating-point arithmetic helper functions
274 // RTABI chapter 4.1.2, Table 4
275 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280 // Single-precision floating-point comparison helper functions
281 // RTABI chapter 4.1.2, Table 5
282 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
291 // Floating-point to integer conversions.
292 // RTABI chapter 4.1.2, Table 6
293 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 // Conversions between floating types.
303 // RTABI chapter 4.1.2, Table 7
304 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 // Integer to floating-point conversions.
309 // RTABI chapter 4.1.2, Table 8
310 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 // Long long helper functions
320 // RTABI chapter 4.2, Table 9
321 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 // Integer division functions
327 // RTABI chapter 4.3.1
328 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 // RTABI chapter 4.3.4
339 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 for (const auto &LC : LibraryCalls) {
345 setLibcallName(LC.Op, LC.Name);
346 setLibcallCallingConv(LC.Op, LC.CC);
347 if (LC.Cond != ISD::SETCC_INVALID)
348 setCmpLibcallCC(LC.Op, LC.Cond);
352 if (Subtarget->isTargetWindows()) {
353 static const struct {
354 const RTLIB::Libcall Op;
355 const char * const Name;
356 const CallingConv::ID CC;
358 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
373 for (const auto &LC : LibraryCalls) {
374 setLibcallName(LC.Op, LC.Name);
375 setLibcallCallingConv(LC.Op, LC.CC);
379 // Use divmod compiler-rt calls for iOS 5.0 and later.
380 if (Subtarget->getTargetTriple().isiOS() &&
381 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
386 // The half <-> float conversion functions are always soft-float, but are
387 // needed for some targets which use a hard-float calling convention by
389 if (Subtarget->isAAPCS_ABI()) {
390 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
399 if (Subtarget->isThumb1Only())
400 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404 !Subtarget->isThumb1Only()) {
405 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
409 for (MVT VT : MVT::vector_valuetypes()) {
410 for (MVT InnerVT : MVT::vector_valuetypes()) {
411 setTruncStoreAction(VT, InnerVT, Expand);
412 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
417 setOperationAction(ISD::MULHS, VT, Expand);
418 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422 setOperationAction(ISD::BSWAP, VT, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
431 if (Subtarget->hasNEON()) {
432 addDRTypeForNEON(MVT::v2f32);
433 addDRTypeForNEON(MVT::v8i8);
434 addDRTypeForNEON(MVT::v4i16);
435 addDRTypeForNEON(MVT::v2i32);
436 addDRTypeForNEON(MVT::v1i64);
438 addQRTypeForNEON(MVT::v4f32);
439 addQRTypeForNEON(MVT::v2f64);
440 addQRTypeForNEON(MVT::v16i8);
441 addQRTypeForNEON(MVT::v8i16);
442 addQRTypeForNEON(MVT::v4i32);
443 addQRTypeForNEON(MVT::v2i64);
445 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446 // neither Neon nor VFP support any arithmetic operations on it.
447 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448 // supported for v4f32.
449 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452 // FIXME: Code duplication: FDIV and FREM are expanded always, see
453 // ARMTargetLowering::addTypeForNEON method for details.
454 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456 // FIXME: Create unittest.
457 // In another words, find a way when "copysign" appears in DAG with vector
459 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460 // FIXME: Code duplication: SETCC has custom operation action, see
461 // ARMTargetLowering::addTypeForNEON method for details.
462 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463 // FIXME: Create unittest for FNEG and for FABS.
464 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
484 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
500 // Mark v2f32 intrinsics.
501 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
517 // Neon does not support some operations on v1i64 and v2i64 types.
518 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519 // Custom handling for some quad-vector types to detect VMULL.
520 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523 // Custom handling for some vector types to avoid expensive expansions
524 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531 // a destination type that is wider than the source, and nor does
532 // it have a FP_TO_[SU]INT instruction with a narrower destination than
534 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
540 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
542 // NEON does not have single instruction CTPOP for vectors with element
543 // types wider than 8-bits. However, custom lowering can leverage the
544 // v8i8/v16i8 vcnt instruction.
545 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
546 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
550 // NEON does not have single instruction CTTZ for vectors.
551 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
556 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
566 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
571 // NEON only has FMA instructions as of VFP4.
572 if (!Subtarget->hasVFP4()) {
573 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
577 setTargetDAGCombine(ISD::INTRINSIC_VOID);
578 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580 setTargetDAGCombine(ISD::SHL);
581 setTargetDAGCombine(ISD::SRL);
582 setTargetDAGCombine(ISD::SRA);
583 setTargetDAGCombine(ISD::SIGN_EXTEND);
584 setTargetDAGCombine(ISD::ZERO_EXTEND);
585 setTargetDAGCombine(ISD::ANY_EXTEND);
586 setTargetDAGCombine(ISD::BUILD_VECTOR);
587 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589 setTargetDAGCombine(ISD::STORE);
590 setTargetDAGCombine(ISD::FP_TO_SINT);
591 setTargetDAGCombine(ISD::FP_TO_UINT);
592 setTargetDAGCombine(ISD::FDIV);
593 setTargetDAGCombine(ISD::LOAD);
595 // It is legal to extload from v4i8 to v4i16 or v4i32.
596 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
598 for (MVT VT : MVT::integer_vector_valuetypes()) {
599 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
600 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
601 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
606 // ARM and Thumb2 support UMLAL/SMLAL.
607 if (!Subtarget->isThumb1Only())
608 setTargetDAGCombine(ISD::ADDC);
610 if (Subtarget->isFPOnlySP()) {
611 // When targeting a floating-point unit with only single-precision
612 // operations, f64 is legal for the few double-precision instructions which
613 // are present However, no double-precision operations other than moves,
614 // loads and stores are provided by the hardware.
615 setOperationAction(ISD::FADD, MVT::f64, Expand);
616 setOperationAction(ISD::FSUB, MVT::f64, Expand);
617 setOperationAction(ISD::FMUL, MVT::f64, Expand);
618 setOperationAction(ISD::FMA, MVT::f64, Expand);
619 setOperationAction(ISD::FDIV, MVT::f64, Expand);
620 setOperationAction(ISD::FREM, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
623 setOperationAction(ISD::FNEG, MVT::f64, Expand);
624 setOperationAction(ISD::FABS, MVT::f64, Expand);
625 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
626 setOperationAction(ISD::FSIN, MVT::f64, Expand);
627 setOperationAction(ISD::FCOS, MVT::f64, Expand);
628 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
629 setOperationAction(ISD::FPOW, MVT::f64, Expand);
630 setOperationAction(ISD::FLOG, MVT::f64, Expand);
631 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
632 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
633 setOperationAction(ISD::FEXP, MVT::f64, Expand);
634 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
635 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
636 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
637 setOperationAction(ISD::FRINT, MVT::f64, Expand);
638 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
639 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
640 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
641 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
642 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
645 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
646 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
647 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
650 computeRegisterProperties(Subtarget->getRegisterInfo());
652 // ARM does not have floating-point extending loads.
653 for (MVT VT : MVT::fp_valuetypes()) {
654 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
655 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
658 // ... or truncating stores
659 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
660 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663 // ARM does not have i1 sign extending load.
664 for (MVT VT : MVT::integer_valuetypes())
665 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
667 // ARM supports all 4 flavors of integer indexed load / store.
668 if (!Subtarget->isThumb1Only()) {
669 for (unsigned im = (unsigned)ISD::PRE_INC;
670 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
671 setIndexedLoadAction(im, MVT::i1, Legal);
672 setIndexedLoadAction(im, MVT::i8, Legal);
673 setIndexedLoadAction(im, MVT::i16, Legal);
674 setIndexedLoadAction(im, MVT::i32, Legal);
675 setIndexedStoreAction(im, MVT::i1, Legal);
676 setIndexedStoreAction(im, MVT::i8, Legal);
677 setIndexedStoreAction(im, MVT::i16, Legal);
678 setIndexedStoreAction(im, MVT::i32, Legal);
682 setOperationAction(ISD::SADDO, MVT::i32, Custom);
683 setOperationAction(ISD::UADDO, MVT::i32, Custom);
684 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
685 setOperationAction(ISD::USUBO, MVT::i32, Custom);
687 // i64 operation support.
688 setOperationAction(ISD::MUL, MVT::i64, Expand);
689 setOperationAction(ISD::MULHU, MVT::i32, Expand);
690 if (Subtarget->isThumb1Only()) {
691 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
694 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
695 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
696 setOperationAction(ISD::MULHS, MVT::i32, Expand);
698 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
699 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
700 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRL, MVT::i64, Custom);
702 setOperationAction(ISD::SRA, MVT::i64, Custom);
704 if (!Subtarget->isThumb1Only()) {
705 // FIXME: We should do this for Thumb1 as well.
706 setOperationAction(ISD::ADDC, MVT::i32, Custom);
707 setOperationAction(ISD::ADDE, MVT::i32, Custom);
708 setOperationAction(ISD::SUBC, MVT::i32, Custom);
709 setOperationAction(ISD::SUBE, MVT::i32, Custom);
712 // ARM does not have ROTL.
713 setOperationAction(ISD::ROTL, MVT::i32, Expand);
714 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
715 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
716 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
717 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
719 // These just redirect to CTTZ and CTLZ on ARM.
720 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
721 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
723 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
725 // Only ARMv6 has BSWAP.
726 if (!Subtarget->hasV6Ops())
727 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
729 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
730 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
731 // These are expanded into libcalls if the cpu doesn't have HW divider.
732 setOperationAction(ISD::SDIV, MVT::i32, Expand);
733 setOperationAction(ISD::UDIV, MVT::i32, Expand);
736 // FIXME: Also set divmod for SREM on EABI/androideabi
737 setOperationAction(ISD::SREM, MVT::i32, Expand);
738 setOperationAction(ISD::UREM, MVT::i32, Expand);
739 // Register based DivRem for AEABI (RTABI 4.2)
740 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
741 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
742 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
743 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
744 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
745 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
746 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
747 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
748 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
750 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
751 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
752 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
753 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
754 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
755 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
756 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
757 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
759 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
760 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
762 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
763 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
766 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
767 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
768 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
769 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
770 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
772 setOperationAction(ISD::TRAP, MVT::Other, Legal);
774 // Use the default implementation.
775 setOperationAction(ISD::VASTART, MVT::Other, Custom);
776 setOperationAction(ISD::VAARG, MVT::Other, Expand);
777 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
778 setOperationAction(ISD::VAEND, MVT::Other, Expand);
779 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
780 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
782 if (!Subtarget->isTargetMachO()) {
783 // Non-MachO platforms may return values in these registers via the
784 // personality function.
785 setExceptionPointerRegister(ARM::R0);
786 setExceptionSelectorRegister(ARM::R1);
789 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
790 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
792 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
794 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
795 // the default expansion. If we are targeting a single threaded system,
796 // then set them all for expand so we can lower them later into their
798 if (TM.Options.ThreadModel == ThreadModel::Single)
799 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
800 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
801 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
802 // to ldrex/strex loops already.
803 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
805 // On v8, we have particularly efficient implementations of atomic fences
806 // if they can be combined with nearby atomic loads and stores.
807 if (!Subtarget->hasV8Ops()) {
808 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
809 setInsertFencesForAtomic(true);
812 // If there's anything we can use as a barrier, go through custom lowering
814 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
815 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
817 // Set them all for expansion, which will force libcalls.
818 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
819 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
820 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
821 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
822 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
823 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
824 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
825 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
826 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
827 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
828 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
829 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
830 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
831 // Unordered/Monotonic case.
832 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
833 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
836 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
838 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
839 if (!Subtarget->hasV6Ops()) {
840 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
841 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
843 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
845 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
846 !Subtarget->isThumb1Only()) {
847 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
848 // iff target supports vfp2.
849 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
850 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
853 // We want to custom lower some of our intrinsics.
854 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
855 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
856 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
857 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
858 if (Subtarget->isTargetDarwin())
859 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
861 setOperationAction(ISD::SETCC, MVT::i32, Expand);
862 setOperationAction(ISD::SETCC, MVT::f32, Expand);
863 setOperationAction(ISD::SETCC, MVT::f64, Expand);
864 setOperationAction(ISD::SELECT, MVT::i32, Custom);
865 setOperationAction(ISD::SELECT, MVT::f32, Custom);
866 setOperationAction(ISD::SELECT, MVT::f64, Custom);
867 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
868 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
869 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
871 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
872 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
873 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
874 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
875 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
877 // We don't support sin/cos/fmod/copysign/pow
878 setOperationAction(ISD::FSIN, MVT::f64, Expand);
879 setOperationAction(ISD::FSIN, MVT::f32, Expand);
880 setOperationAction(ISD::FCOS, MVT::f32, Expand);
881 setOperationAction(ISD::FCOS, MVT::f64, Expand);
882 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
883 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
884 setOperationAction(ISD::FREM, MVT::f64, Expand);
885 setOperationAction(ISD::FREM, MVT::f32, Expand);
886 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
887 !Subtarget->isThumb1Only()) {
888 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
889 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
891 setOperationAction(ISD::FPOW, MVT::f64, Expand);
892 setOperationAction(ISD::FPOW, MVT::f32, Expand);
894 if (!Subtarget->hasVFP4()) {
895 setOperationAction(ISD::FMA, MVT::f64, Expand);
896 setOperationAction(ISD::FMA, MVT::f32, Expand);
899 // Various VFP goodness
900 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
901 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
902 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
903 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
904 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
907 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
908 if (!Subtarget->hasFP16()) {
909 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
910 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
914 // Combine sin / cos into one node or libcall if possible.
915 if (Subtarget->hasSinCos()) {
916 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
917 setLibcallName(RTLIB::SINCOS_F64, "sincos");
918 if (Subtarget->getTargetTriple().isiOS()) {
919 // For iOS, we don't want to the normal expansion of a libcall to
920 // sincos. We want to issue a libcall to __sincos_stret.
921 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
922 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
926 // FP-ARMv8 implements a lot of rounding-like FP operations.
927 if (Subtarget->hasFPARMv8()) {
928 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
929 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
930 setOperationAction(ISD::FROUND, MVT::f32, Legal);
931 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
932 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
933 setOperationAction(ISD::FRINT, MVT::f32, Legal);
934 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
935 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
936 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
937 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
938 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
939 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
941 if (!Subtarget->isFPOnlySP()) {
942 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
943 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
944 setOperationAction(ISD::FROUND, MVT::f64, Legal);
945 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
946 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
947 setOperationAction(ISD::FRINT, MVT::f64, Legal);
948 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
949 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
953 if (Subtarget->hasNEON()) {
954 // vmin and vmax aren't available in a scalar form, so we use
955 // a NEON instruction with an undef lane instead.
956 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
957 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
958 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
959 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
960 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
961 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
964 // We have target-specific dag combine patterns for the following nodes:
965 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
966 setTargetDAGCombine(ISD::ADD);
967 setTargetDAGCombine(ISD::SUB);
968 setTargetDAGCombine(ISD::MUL);
969 setTargetDAGCombine(ISD::AND);
970 setTargetDAGCombine(ISD::OR);
971 setTargetDAGCombine(ISD::XOR);
973 if (Subtarget->hasV6Ops())
974 setTargetDAGCombine(ISD::SRL);
976 setStackPointerRegisterToSaveRestore(ARM::SP);
978 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
979 !Subtarget->hasVFP2())
980 setSchedulingPreference(Sched::RegPressure);
982 setSchedulingPreference(Sched::Hybrid);
984 //// temporary - rewrite interface to use type
985 MaxStoresPerMemset = 8;
986 MaxStoresPerMemsetOptSize = 4;
987 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
988 MaxStoresPerMemcpyOptSize = 2;
989 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
990 MaxStoresPerMemmoveOptSize = 2;
992 // On ARM arguments smaller than 4 bytes are extended, so all arguments
993 // are at least 4 bytes aligned.
994 setMinStackArgumentAlignment(4);
996 // Prefer likely predicted branches to selects on out-of-order cores.
997 PredictableSelectIsExpensive = Subtarget->isLikeA9();
999 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1002 bool ARMTargetLowering::useSoftFloat() const {
1003 return Subtarget->useSoftFloat();
1006 // FIXME: It might make sense to define the representative register class as the
1007 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1008 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1009 // SPR's representative would be DPR_VFP2. This should work well if register
1010 // pressure tracking were modified such that a register use would increment the
1011 // pressure of the register class's representative and all of it's super
1012 // classes' representatives transitively. We have not implemented this because
1013 // of the difficulty prior to coalescing of modeling operand register classes
1014 // due to the common occurrence of cross class copies and subregister insertions
1016 std::pair<const TargetRegisterClass *, uint8_t>
1017 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1019 const TargetRegisterClass *RRC = nullptr;
1021 switch (VT.SimpleTy) {
1023 return TargetLowering::findRepresentativeClass(TRI, VT);
1024 // Use DPR as representative register class for all floating point
1025 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1026 // the cost is 1 for both f32 and f64.
1027 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1028 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1029 RRC = &ARM::DPRRegClass;
1030 // When NEON is used for SP, only half of the register file is available
1031 // because operations that define both SP and DP results will be constrained
1032 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1033 // coalescing by double-counting the SP regs. See the FIXME above.
1034 if (Subtarget->useNEONForSinglePrecisionFP())
1037 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1038 case MVT::v4f32: case MVT::v2f64:
1039 RRC = &ARM::DPRRegClass;
1043 RRC = &ARM::DPRRegClass;
1047 RRC = &ARM::DPRRegClass;
1051 return std::make_pair(RRC, Cost);
1054 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1055 switch ((ARMISD::NodeType)Opcode) {
1056 case ARMISD::FIRST_NUMBER: break;
1057 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1058 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1059 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1060 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1061 case ARMISD::CALL: return "ARMISD::CALL";
1062 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1063 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1064 case ARMISD::tCALL: return "ARMISD::tCALL";
1065 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1066 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1067 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1068 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1069 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1070 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1071 case ARMISD::CMP: return "ARMISD::CMP";
1072 case ARMISD::CMN: return "ARMISD::CMN";
1073 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1074 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1075 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1076 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1077 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1079 case ARMISD::CMOV: return "ARMISD::CMOV";
1081 case ARMISD::RBIT: return "ARMISD::RBIT";
1083 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1084 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1085 case ARMISD::RRX: return "ARMISD::RRX";
1087 case ARMISD::ADDC: return "ARMISD::ADDC";
1088 case ARMISD::ADDE: return "ARMISD::ADDE";
1089 case ARMISD::SUBC: return "ARMISD::SUBC";
1090 case ARMISD::SUBE: return "ARMISD::SUBE";
1092 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1093 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1095 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1096 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1097 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1099 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1101 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1103 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1105 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1107 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1109 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1111 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1112 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1113 case ARMISD::VCGE: return "ARMISD::VCGE";
1114 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1115 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1116 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1117 case ARMISD::VCGT: return "ARMISD::VCGT";
1118 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1119 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1120 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1121 case ARMISD::VTST: return "ARMISD::VTST";
1123 case ARMISD::VSHL: return "ARMISD::VSHL";
1124 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1125 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1126 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1127 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1128 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1129 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1130 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1131 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1132 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1133 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1134 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1135 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1136 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1137 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1138 case ARMISD::VSLI: return "ARMISD::VSLI";
1139 case ARMISD::VSRI: return "ARMISD::VSRI";
1140 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1141 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1142 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1143 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1144 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1145 case ARMISD::VDUP: return "ARMISD::VDUP";
1146 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1147 case ARMISD::VEXT: return "ARMISD::VEXT";
1148 case ARMISD::VREV64: return "ARMISD::VREV64";
1149 case ARMISD::VREV32: return "ARMISD::VREV32";
1150 case ARMISD::VREV16: return "ARMISD::VREV16";
1151 case ARMISD::VZIP: return "ARMISD::VZIP";
1152 case ARMISD::VUZP: return "ARMISD::VUZP";
1153 case ARMISD::VTRN: return "ARMISD::VTRN";
1154 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1155 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1156 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1157 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1158 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1159 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1160 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1161 case ARMISD::BFI: return "ARMISD::BFI";
1162 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1163 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1164 case ARMISD::VBSL: return "ARMISD::VBSL";
1165 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1166 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1167 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1168 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1169 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1170 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1171 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1172 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1173 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1174 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1175 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1176 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1177 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1178 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1179 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1180 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1181 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1182 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1183 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1184 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1189 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1192 return getPointerTy(DL);
1193 return VT.changeVectorElementTypeToInteger();
1196 /// getRegClassFor - Return the register class that should be used for the
1197 /// specified value type.
1198 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1199 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1200 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1201 // load / store 4 to 8 consecutive D registers.
1202 if (Subtarget->hasNEON()) {
1203 if (VT == MVT::v4i64)
1204 return &ARM::QQPRRegClass;
1205 if (VT == MVT::v8i64)
1206 return &ARM::QQQQPRRegClass;
1208 return TargetLowering::getRegClassFor(VT);
1211 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1212 // source/dest is aligned and the copy size is large enough. We therefore want
1213 // to align such objects passed to memory intrinsics.
1214 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1215 unsigned &PrefAlign) const {
1216 if (!isa<MemIntrinsic>(CI))
1219 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1220 // cycle faster than 4-byte aligned LDM.
1221 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1225 // Create a fast isel object.
1227 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1228 const TargetLibraryInfo *libInfo) const {
1229 return ARM::createFastISel(funcInfo, libInfo);
1232 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1233 unsigned NumVals = N->getNumValues();
1235 return Sched::RegPressure;
1237 for (unsigned i = 0; i != NumVals; ++i) {
1238 EVT VT = N->getValueType(i);
1239 if (VT == MVT::Glue || VT == MVT::Other)
1241 if (VT.isFloatingPoint() || VT.isVector())
1245 if (!N->isMachineOpcode())
1246 return Sched::RegPressure;
1248 // Load are scheduled for latency even if there instruction itinerary
1249 // is not available.
1250 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1251 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1253 if (MCID.getNumDefs() == 0)
1254 return Sched::RegPressure;
1255 if (!Itins->isEmpty() &&
1256 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1259 return Sched::RegPressure;
1262 //===----------------------------------------------------------------------===//
1264 //===----------------------------------------------------------------------===//
1266 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1267 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1269 default: llvm_unreachable("Unknown condition code!");
1270 case ISD::SETNE: return ARMCC::NE;
1271 case ISD::SETEQ: return ARMCC::EQ;
1272 case ISD::SETGT: return ARMCC::GT;
1273 case ISD::SETGE: return ARMCC::GE;
1274 case ISD::SETLT: return ARMCC::LT;
1275 case ISD::SETLE: return ARMCC::LE;
1276 case ISD::SETUGT: return ARMCC::HI;
1277 case ISD::SETUGE: return ARMCC::HS;
1278 case ISD::SETULT: return ARMCC::LO;
1279 case ISD::SETULE: return ARMCC::LS;
1283 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1284 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1285 ARMCC::CondCodes &CondCode2) {
1286 CondCode2 = ARMCC::AL;
1288 default: llvm_unreachable("Unknown FP condition!");
1290 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1292 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1294 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1295 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1296 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1297 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1298 case ISD::SETO: CondCode = ARMCC::VC; break;
1299 case ISD::SETUO: CondCode = ARMCC::VS; break;
1300 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1301 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1302 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1304 case ISD::SETULT: CondCode = ARMCC::LT; break;
1306 case ISD::SETULE: CondCode = ARMCC::LE; break;
1308 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1312 //===----------------------------------------------------------------------===//
1313 // Calling Convention Implementation
1314 //===----------------------------------------------------------------------===//
1316 #include "ARMGenCallingConv.inc"
1318 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1319 /// account presence of floating point hardware and calling convention
1320 /// limitations, such as support for variadic functions.
1322 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1323 bool isVarArg) const {
1326 llvm_unreachable("Unsupported calling convention");
1327 case CallingConv::ARM_AAPCS:
1328 case CallingConv::ARM_APCS:
1329 case CallingConv::GHC:
1331 case CallingConv::ARM_AAPCS_VFP:
1332 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1333 case CallingConv::C:
1334 if (!Subtarget->isAAPCS_ABI())
1335 return CallingConv::ARM_APCS;
1336 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1337 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1339 return CallingConv::ARM_AAPCS_VFP;
1341 return CallingConv::ARM_AAPCS;
1342 case CallingConv::Fast:
1343 if (!Subtarget->isAAPCS_ABI()) {
1344 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1345 return CallingConv::Fast;
1346 return CallingConv::ARM_APCS;
1347 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1348 return CallingConv::ARM_AAPCS_VFP;
1350 return CallingConv::ARM_AAPCS;
1354 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1355 /// CallingConvention.
1356 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1358 bool isVarArg) const {
1359 switch (getEffectiveCallingConv(CC, isVarArg)) {
1361 llvm_unreachable("Unsupported calling convention");
1362 case CallingConv::ARM_APCS:
1363 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1364 case CallingConv::ARM_AAPCS:
1365 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1366 case CallingConv::ARM_AAPCS_VFP:
1367 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1368 case CallingConv::Fast:
1369 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1370 case CallingConv::GHC:
1371 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1375 /// LowerCallResult - Lower the result values of a call into the
1376 /// appropriate copies out of appropriate physical registers.
1378 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1379 CallingConv::ID CallConv, bool isVarArg,
1380 const SmallVectorImpl<ISD::InputArg> &Ins,
1381 SDLoc dl, SelectionDAG &DAG,
1382 SmallVectorImpl<SDValue> &InVals,
1383 bool isThisReturn, SDValue ThisVal) const {
1385 // Assign locations to each value returned by this call.
1386 SmallVector<CCValAssign, 16> RVLocs;
1387 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1388 *DAG.getContext(), Call);
1389 CCInfo.AnalyzeCallResult(Ins,
1390 CCAssignFnForNode(CallConv, /* Return*/ true,
1393 // Copy all of the result registers out of their specified physreg.
1394 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1395 CCValAssign VA = RVLocs[i];
1397 // Pass 'this' value directly from the argument to return value, to avoid
1398 // reg unit interference
1399 if (i == 0 && isThisReturn) {
1400 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1401 "unexpected return calling convention register assignment");
1402 InVals.push_back(ThisVal);
1407 if (VA.needsCustom()) {
1408 // Handle f64 or half of a v2f64.
1409 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1411 Chain = Lo.getValue(1);
1412 InFlag = Lo.getValue(2);
1413 VA = RVLocs[++i]; // skip ahead to next loc
1414 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1416 Chain = Hi.getValue(1);
1417 InFlag = Hi.getValue(2);
1418 if (!Subtarget->isLittle())
1420 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1422 if (VA.getLocVT() == MVT::v2f64) {
1423 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1424 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1425 DAG.getConstant(0, dl, MVT::i32));
1427 VA = RVLocs[++i]; // skip ahead to next loc
1428 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1429 Chain = Lo.getValue(1);
1430 InFlag = Lo.getValue(2);
1431 VA = RVLocs[++i]; // skip ahead to next loc
1432 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1433 Chain = Hi.getValue(1);
1434 InFlag = Hi.getValue(2);
1435 if (!Subtarget->isLittle())
1437 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1438 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1439 DAG.getConstant(1, dl, MVT::i32));
1442 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1444 Chain = Val.getValue(1);
1445 InFlag = Val.getValue(2);
1448 switch (VA.getLocInfo()) {
1449 default: llvm_unreachable("Unknown loc info!");
1450 case CCValAssign::Full: break;
1451 case CCValAssign::BCvt:
1452 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1456 InVals.push_back(Val);
1462 /// LowerMemOpCallTo - Store the argument to the stack.
1464 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1465 SDValue StackPtr, SDValue Arg,
1466 SDLoc dl, SelectionDAG &DAG,
1467 const CCValAssign &VA,
1468 ISD::ArgFlagsTy Flags) const {
1469 unsigned LocMemOffset = VA.getLocMemOffset();
1470 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1471 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1473 return DAG.getStore(
1474 Chain, dl, Arg, PtrOff,
1475 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1479 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1480 SDValue Chain, SDValue &Arg,
1481 RegsToPassVector &RegsToPass,
1482 CCValAssign &VA, CCValAssign &NextVA,
1484 SmallVectorImpl<SDValue> &MemOpChains,
1485 ISD::ArgFlagsTy Flags) const {
1487 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1488 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1489 unsigned id = Subtarget->isLittle() ? 0 : 1;
1490 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1492 if (NextVA.isRegLoc())
1493 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1495 assert(NextVA.isMemLoc());
1496 if (!StackPtr.getNode())
1497 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1498 getPointerTy(DAG.getDataLayout()));
1500 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1506 /// LowerCall - Lowering a call into a callseq_start <-
1507 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1510 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1511 SmallVectorImpl<SDValue> &InVals) const {
1512 SelectionDAG &DAG = CLI.DAG;
1514 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1515 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1516 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1517 SDValue Chain = CLI.Chain;
1518 SDValue Callee = CLI.Callee;
1519 bool &isTailCall = CLI.IsTailCall;
1520 CallingConv::ID CallConv = CLI.CallConv;
1521 bool doesNotRet = CLI.DoesNotReturn;
1522 bool isVarArg = CLI.IsVarArg;
1524 MachineFunction &MF = DAG.getMachineFunction();
1525 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1526 bool isThisReturn = false;
1527 bool isSibCall = false;
1528 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1530 // Disable tail calls if they're not supported.
1531 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1535 // Check if it's really possible to do a tail call.
1536 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1537 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1538 Outs, OutVals, Ins, DAG);
1539 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1540 report_fatal_error("failed to perform tail call elimination on a call "
1541 "site marked musttail");
1542 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1543 // detected sibcalls.
1550 // Analyze operands of the call, assigning locations to each operand.
1551 SmallVector<CCValAssign, 16> ArgLocs;
1552 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1553 *DAG.getContext(), Call);
1554 CCInfo.AnalyzeCallOperands(Outs,
1555 CCAssignFnForNode(CallConv, /* Return*/ false,
1558 // Get a count of how many bytes are to be pushed on the stack.
1559 unsigned NumBytes = CCInfo.getNextStackOffset();
1561 // For tail calls, memory operands are available in our caller's stack.
1565 // Adjust the stack pointer for the new arguments...
1566 // These operations are automatically eliminated by the prolog/epilog pass
1568 Chain = DAG.getCALLSEQ_START(Chain,
1569 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1572 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1574 RegsToPassVector RegsToPass;
1575 SmallVector<SDValue, 8> MemOpChains;
1577 // Walk the register/memloc assignments, inserting copies/loads. In the case
1578 // of tail call optimization, arguments are handled later.
1579 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1581 ++i, ++realArgIdx) {
1582 CCValAssign &VA = ArgLocs[i];
1583 SDValue Arg = OutVals[realArgIdx];
1584 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1585 bool isByVal = Flags.isByVal();
1587 // Promote the value if needed.
1588 switch (VA.getLocInfo()) {
1589 default: llvm_unreachable("Unknown loc info!");
1590 case CCValAssign::Full: break;
1591 case CCValAssign::SExt:
1592 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1594 case CCValAssign::ZExt:
1595 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1597 case CCValAssign::AExt:
1598 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1600 case CCValAssign::BCvt:
1601 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1605 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1606 if (VA.needsCustom()) {
1607 if (VA.getLocVT() == MVT::v2f64) {
1608 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1609 DAG.getConstant(0, dl, MVT::i32));
1610 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1611 DAG.getConstant(1, dl, MVT::i32));
1613 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1614 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1616 VA = ArgLocs[++i]; // skip ahead to next loc
1617 if (VA.isRegLoc()) {
1618 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1619 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1621 assert(VA.isMemLoc());
1623 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1624 dl, DAG, VA, Flags));
1627 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1628 StackPtr, MemOpChains, Flags);
1630 } else if (VA.isRegLoc()) {
1631 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1632 assert(VA.getLocVT() == MVT::i32 &&
1633 "unexpected calling convention register assignment");
1634 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1635 "unexpected use of 'returned'");
1636 isThisReturn = true;
1638 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1639 } else if (isByVal) {
1640 assert(VA.isMemLoc());
1641 unsigned offset = 0;
1643 // True if this byval aggregate will be split between registers
1645 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1646 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1648 if (CurByValIdx < ByValArgsCount) {
1650 unsigned RegBegin, RegEnd;
1651 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1654 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1656 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1657 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1658 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1659 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1660 MachinePointerInfo(),
1661 false, false, false,
1662 DAG.InferPtrAlignment(AddArg));
1663 MemOpChains.push_back(Load.getValue(1));
1664 RegsToPass.push_back(std::make_pair(j, Load));
1667 // If parameter size outsides register area, "offset" value
1668 // helps us to calculate stack slot for remained part properly.
1669 offset = RegEnd - RegBegin;
1671 CCInfo.nextInRegsParam();
1674 if (Flags.getByValSize() > 4*offset) {
1675 auto PtrVT = getPointerTy(DAG.getDataLayout());
1676 unsigned LocMemOffset = VA.getLocMemOffset();
1677 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1678 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1679 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1680 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1681 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1683 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1686 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1687 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1688 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1691 } else if (!isSibCall) {
1692 assert(VA.isMemLoc());
1694 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1695 dl, DAG, VA, Flags));
1699 if (!MemOpChains.empty())
1700 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1702 // Build a sequence of copy-to-reg nodes chained together with token chain
1703 // and flag operands which copy the outgoing args into the appropriate regs.
1705 // Tail call byval lowering might overwrite argument registers so in case of
1706 // tail call optimization the copies to registers are lowered later.
1708 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1709 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1710 RegsToPass[i].second, InFlag);
1711 InFlag = Chain.getValue(1);
1714 // For tail calls lower the arguments to the 'real' stack slot.
1716 // Force all the incoming stack arguments to be loaded from the stack
1717 // before any new outgoing arguments are stored to the stack, because the
1718 // outgoing stack slots may alias the incoming argument stack slots, and
1719 // the alias isn't otherwise explicit. This is slightly more conservative
1720 // than necessary, because it means that each store effectively depends
1721 // on every argument instead of just those arguments it would clobber.
1723 // Do not flag preceding copytoreg stuff together with the following stuff.
1725 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1726 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1727 RegsToPass[i].second, InFlag);
1728 InFlag = Chain.getValue(1);
1733 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1734 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1735 // node so that legalize doesn't hack it.
1736 bool isDirect = false;
1737 bool isARMFunc = false;
1738 bool isLocalARMFunc = false;
1739 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1740 auto PtrVt = getPointerTy(DAG.getDataLayout());
1742 if (Subtarget->genLongCalls()) {
1743 assert((Subtarget->isTargetWindows() ||
1744 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1745 "long-calls with non-static relocation model!");
1746 // Handle a global address or an external symbol. If it's not one of
1747 // those, the target's already in a register, so we don't need to do
1749 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1750 const GlobalValue *GV = G->getGlobal();
1751 // Create a constant pool entry for the callee address
1752 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1753 ARMConstantPoolValue *CPV =
1754 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1756 // Get the address of the callee into a register
1757 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1758 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1759 Callee = DAG.getLoad(
1760 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1761 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1763 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1764 const char *Sym = S->getSymbol();
1766 // Create a constant pool entry for the callee address
1767 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1768 ARMConstantPoolValue *CPV =
1769 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1770 ARMPCLabelIndex, 0);
1771 // Get the address of the callee into a register
1772 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1773 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1774 Callee = DAG.getLoad(
1775 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1776 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1779 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1780 const GlobalValue *GV = G->getGlobal();
1782 bool isDef = GV->isStrongDefinitionForLinker();
1783 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1784 getTargetMachine().getRelocationModel() != Reloc::Static;
1785 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1786 // ARM call to a local ARM function is predicable.
1787 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1788 // tBX takes a register source operand.
1789 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1790 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1791 Callee = DAG.getNode(
1792 ARMISD::WrapperPIC, dl, PtrVt,
1793 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1794 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1795 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1796 false, false, true, 0);
1797 } else if (Subtarget->isTargetCOFF()) {
1798 assert(Subtarget->isTargetWindows() &&
1799 "Windows is the only supported COFF target");
1800 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1801 ? ARMII::MO_DLLIMPORT
1802 : ARMII::MO_NO_FLAG;
1804 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1805 if (GV->hasDLLImportStorageClass())
1807 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1808 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1809 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1810 false, false, false, 0);
1812 // On ELF targets for PIC code, direct calls should go through the PLT
1813 unsigned OpFlags = 0;
1814 if (Subtarget->isTargetELF() &&
1815 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1816 OpFlags = ARMII::MO_PLT;
1817 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1819 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1821 bool isStub = Subtarget->isTargetMachO() &&
1822 getTargetMachine().getRelocationModel() != Reloc::Static;
1823 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1824 // tBX takes a register source operand.
1825 const char *Sym = S->getSymbol();
1826 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1827 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1828 ARMConstantPoolValue *CPV =
1829 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1830 ARMPCLabelIndex, 4);
1831 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1832 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1833 Callee = DAG.getLoad(
1834 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1835 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1837 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1838 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1840 unsigned OpFlags = 0;
1841 // On ELF targets for PIC code, direct calls should go through the PLT
1842 if (Subtarget->isTargetELF() &&
1843 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1844 OpFlags = ARMII::MO_PLT;
1845 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1849 // FIXME: handle tail calls differently.
1851 if (Subtarget->isThumb()) {
1852 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1853 CallOpc = ARMISD::CALL_NOLINK;
1855 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1857 if (!isDirect && !Subtarget->hasV5TOps())
1858 CallOpc = ARMISD::CALL_NOLINK;
1859 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1860 // Emit regular call when code size is the priority
1861 !MF.getFunction()->optForMinSize())
1862 // "mov lr, pc; b _foo" to avoid confusing the RSP
1863 CallOpc = ARMISD::CALL_NOLINK;
1865 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1868 std::vector<SDValue> Ops;
1869 Ops.push_back(Chain);
1870 Ops.push_back(Callee);
1872 // Add argument registers to the end of the list so that they are known live
1874 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1875 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1876 RegsToPass[i].second.getValueType()));
1878 // Add a register mask operand representing the call-preserved registers.
1880 const uint32_t *Mask;
1881 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1883 // For 'this' returns, use the R0-preserving mask if applicable
1884 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1886 // Set isThisReturn to false if the calling convention is not one that
1887 // allows 'returned' to be modeled in this way, so LowerCallResult does
1888 // not try to pass 'this' straight through
1889 isThisReturn = false;
1890 Mask = ARI->getCallPreservedMask(MF, CallConv);
1893 Mask = ARI->getCallPreservedMask(MF, CallConv);
1895 assert(Mask && "Missing call preserved mask for calling convention");
1896 Ops.push_back(DAG.getRegisterMask(Mask));
1899 if (InFlag.getNode())
1900 Ops.push_back(InFlag);
1902 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1904 MF.getFrameInfo()->setHasTailCall();
1905 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1908 // Returns a chain and a flag for retval copy to use.
1909 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1910 InFlag = Chain.getValue(1);
1912 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1913 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1915 InFlag = Chain.getValue(1);
1917 // Handle result values, copying them out of physregs into vregs that we
1919 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1920 InVals, isThisReturn,
1921 isThisReturn ? OutVals[0] : SDValue());
1924 /// HandleByVal - Every parameter *after* a byval parameter is passed
1925 /// on the stack. Remember the next parameter register to allocate,
1926 /// and then confiscate the rest of the parameter registers to insure
1928 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1929 unsigned Align) const {
1930 assert((State->getCallOrPrologue() == Prologue ||
1931 State->getCallOrPrologue() == Call) &&
1932 "unhandled ParmContext");
1934 // Byval (as with any stack) slots are always at least 4 byte aligned.
1935 Align = std::max(Align, 4U);
1937 unsigned Reg = State->AllocateReg(GPRArgRegs);
1941 unsigned AlignInRegs = Align / 4;
1942 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1943 for (unsigned i = 0; i < Waste; ++i)
1944 Reg = State->AllocateReg(GPRArgRegs);
1949 unsigned Excess = 4 * (ARM::R4 - Reg);
1951 // Special case when NSAA != SP and parameter size greater than size of
1952 // all remained GPR regs. In that case we can't split parameter, we must
1953 // send it to stack. We also must set NCRN to R4, so waste all
1954 // remained registers.
1955 const unsigned NSAAOffset = State->getNextStackOffset();
1956 if (NSAAOffset != 0 && Size > Excess) {
1957 while (State->AllocateReg(GPRArgRegs))
1962 // First register for byval parameter is the first register that wasn't
1963 // allocated before this method call, so it would be "reg".
1964 // If parameter is small enough to be saved in range [reg, r4), then
1965 // the end (first after last) register would be reg + param-size-in-regs,
1966 // else parameter would be splitted between registers and stack,
1967 // end register would be r4 in this case.
1968 unsigned ByValRegBegin = Reg;
1969 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1970 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1971 // Note, first register is allocated in the beginning of function already,
1972 // allocate remained amount of registers we need.
1973 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1974 State->AllocateReg(GPRArgRegs);
1975 // A byval parameter that is split between registers and memory needs its
1976 // size truncated here.
1977 // In the case where the entire structure fits in registers, we set the
1978 // size in memory to zero.
1979 Size = std::max<int>(Size - Excess, 0);
1982 /// MatchingStackOffset - Return true if the given stack call argument is
1983 /// already available in the same position (relatively) of the caller's
1984 /// incoming argument stack.
1986 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1987 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1988 const TargetInstrInfo *TII) {
1989 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1991 if (Arg.getOpcode() == ISD::CopyFromReg) {
1992 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1993 if (!TargetRegisterInfo::isVirtualRegister(VR))
1995 MachineInstr *Def = MRI->getVRegDef(VR);
1998 if (!Flags.isByVal()) {
1999 if (!TII->isLoadFromStackSlot(Def, FI))
2004 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2005 if (Flags.isByVal())
2006 // ByVal argument is passed in as a pointer but it's now being
2007 // dereferenced. e.g.
2008 // define @foo(%struct.X* %A) {
2009 // tail call @bar(%struct.X* byval %A)
2012 SDValue Ptr = Ld->getBasePtr();
2013 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2016 FI = FINode->getIndex();
2020 assert(FI != INT_MAX);
2021 if (!MFI->isFixedObjectIndex(FI))
2023 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2026 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2027 /// for tail call optimization. Targets which want to do tail call
2028 /// optimization should implement this function.
2030 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2031 CallingConv::ID CalleeCC,
2033 bool isCalleeStructRet,
2034 bool isCallerStructRet,
2035 const SmallVectorImpl<ISD::OutputArg> &Outs,
2036 const SmallVectorImpl<SDValue> &OutVals,
2037 const SmallVectorImpl<ISD::InputArg> &Ins,
2038 SelectionDAG& DAG) const {
2039 const Function *CallerF = DAG.getMachineFunction().getFunction();
2040 CallingConv::ID CallerCC = CallerF->getCallingConv();
2041 bool CCMatch = CallerCC == CalleeCC;
2043 // Look for obvious safe cases to perform tail call optimization that do not
2044 // require ABI changes. This is what gcc calls sibcall.
2046 // Do not sibcall optimize vararg calls unless the call site is not passing
2048 if (isVarArg && !Outs.empty())
2051 // Exception-handling functions need a special set of instructions to indicate
2052 // a return to the hardware. Tail-calling another function would probably
2054 if (CallerF->hasFnAttribute("interrupt"))
2057 // Also avoid sibcall optimization if either caller or callee uses struct
2058 // return semantics.
2059 if (isCalleeStructRet || isCallerStructRet)
2062 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2063 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2064 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2065 // support in the assembler and linker to be used. This would need to be
2066 // fixed to fully support tail calls in Thumb1.
2068 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2069 // LR. This means if we need to reload LR, it takes an extra instructions,
2070 // which outweighs the value of the tail call; but here we don't know yet
2071 // whether LR is going to be used. Probably the right approach is to
2072 // generate the tail call here and turn it back into CALL/RET in
2073 // emitEpilogue if LR is used.
2075 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2076 // but we need to make sure there are enough registers; the only valid
2077 // registers are the 4 used for parameters. We don't currently do this
2079 if (Subtarget->isThumb1Only())
2082 // Externally-defined functions with weak linkage should not be
2083 // tail-called on ARM when the OS does not support dynamic
2084 // pre-emption of symbols, as the AAELF spec requires normal calls
2085 // to undefined weak functions to be replaced with a NOP or jump to the
2086 // next instruction. The behaviour of branch instructions in this
2087 // situation (as used for tail calls) is implementation-defined, so we
2088 // cannot rely on the linker replacing the tail call with a return.
2089 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2090 const GlobalValue *GV = G->getGlobal();
2091 const Triple &TT = getTargetMachine().getTargetTriple();
2092 if (GV->hasExternalWeakLinkage() &&
2093 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2097 // If the calling conventions do not match, then we'd better make sure the
2098 // results are returned in the same way as what the caller expects.
2100 SmallVector<CCValAssign, 16> RVLocs1;
2101 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2102 *DAG.getContext(), Call);
2103 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2105 SmallVector<CCValAssign, 16> RVLocs2;
2106 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2107 *DAG.getContext(), Call);
2108 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2110 if (RVLocs1.size() != RVLocs2.size())
2112 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2113 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2115 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2117 if (RVLocs1[i].isRegLoc()) {
2118 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2121 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2127 // If Caller's vararg or byval argument has been split between registers and
2128 // stack, do not perform tail call, since part of the argument is in caller's
2130 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2131 getInfo<ARMFunctionInfo>();
2132 if (AFI_Caller->getArgRegsSaveSize())
2135 // If the callee takes no arguments then go on to check the results of the
2137 if (!Outs.empty()) {
2138 // Check if stack adjustment is needed. For now, do not do this if any
2139 // argument is passed on the stack.
2140 SmallVector<CCValAssign, 16> ArgLocs;
2141 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2142 *DAG.getContext(), Call);
2143 CCInfo.AnalyzeCallOperands(Outs,
2144 CCAssignFnForNode(CalleeCC, false, isVarArg));
2145 if (CCInfo.getNextStackOffset()) {
2146 MachineFunction &MF = DAG.getMachineFunction();
2148 // Check if the arguments are already laid out in the right way as
2149 // the caller's fixed stack objects.
2150 MachineFrameInfo *MFI = MF.getFrameInfo();
2151 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2152 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2153 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2155 ++i, ++realArgIdx) {
2156 CCValAssign &VA = ArgLocs[i];
2157 EVT RegVT = VA.getLocVT();
2158 SDValue Arg = OutVals[realArgIdx];
2159 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2160 if (VA.getLocInfo() == CCValAssign::Indirect)
2162 if (VA.needsCustom()) {
2163 // f64 and vector types are split into multiple registers or
2164 // register/stack-slot combinations. The types will not match
2165 // the registers; give up on memory f64 refs until we figure
2166 // out what to do about this.
2169 if (!ArgLocs[++i].isRegLoc())
2171 if (RegVT == MVT::v2f64) {
2172 if (!ArgLocs[++i].isRegLoc())
2174 if (!ArgLocs[++i].isRegLoc())
2177 } else if (!VA.isRegLoc()) {
2178 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2190 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2191 MachineFunction &MF, bool isVarArg,
2192 const SmallVectorImpl<ISD::OutputArg> &Outs,
2193 LLVMContext &Context) const {
2194 SmallVector<CCValAssign, 16> RVLocs;
2195 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2196 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2200 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2201 SDLoc DL, SelectionDAG &DAG) {
2202 const MachineFunction &MF = DAG.getMachineFunction();
2203 const Function *F = MF.getFunction();
2205 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2207 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2208 // version of the "preferred return address". These offsets affect the return
2209 // instruction if this is a return from PL1 without hypervisor extensions.
2210 // IRQ/FIQ: +4 "subs pc, lr, #4"
2211 // SWI: 0 "subs pc, lr, #0"
2212 // ABORT: +4 "subs pc, lr, #4"
2213 // UNDEF: +4/+2 "subs pc, lr, #0"
2214 // UNDEF varies depending on where the exception came from ARM or Thumb
2215 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2218 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2221 else if (IntKind == "SWI" || IntKind == "UNDEF")
2224 report_fatal_error("Unsupported interrupt attribute. If present, value "
2225 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2227 RetOps.insert(RetOps.begin() + 1,
2228 DAG.getConstant(LROffset, DL, MVT::i32, false));
2230 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2234 ARMTargetLowering::LowerReturn(SDValue Chain,
2235 CallingConv::ID CallConv, bool isVarArg,
2236 const SmallVectorImpl<ISD::OutputArg> &Outs,
2237 const SmallVectorImpl<SDValue> &OutVals,
2238 SDLoc dl, SelectionDAG &DAG) const {
2240 // CCValAssign - represent the assignment of the return value to a location.
2241 SmallVector<CCValAssign, 16> RVLocs;
2243 // CCState - Info about the registers and stack slots.
2244 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2245 *DAG.getContext(), Call);
2247 // Analyze outgoing return values.
2248 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2252 SmallVector<SDValue, 4> RetOps;
2253 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2254 bool isLittleEndian = Subtarget->isLittle();
2256 MachineFunction &MF = DAG.getMachineFunction();
2257 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2258 AFI->setReturnRegsCount(RVLocs.size());
2260 // Copy the result values into the output registers.
2261 for (unsigned i = 0, realRVLocIdx = 0;
2263 ++i, ++realRVLocIdx) {
2264 CCValAssign &VA = RVLocs[i];
2265 assert(VA.isRegLoc() && "Can only return in registers!");
2267 SDValue Arg = OutVals[realRVLocIdx];
2269 switch (VA.getLocInfo()) {
2270 default: llvm_unreachable("Unknown loc info!");
2271 case CCValAssign::Full: break;
2272 case CCValAssign::BCvt:
2273 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2277 if (VA.needsCustom()) {
2278 if (VA.getLocVT() == MVT::v2f64) {
2279 // Extract the first half and return it in two registers.
2280 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2281 DAG.getConstant(0, dl, MVT::i32));
2282 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2283 DAG.getVTList(MVT::i32, MVT::i32), Half);
2285 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2286 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2288 Flag = Chain.getValue(1);
2289 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2290 VA = RVLocs[++i]; // skip ahead to next loc
2291 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2292 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2294 Flag = Chain.getValue(1);
2295 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2296 VA = RVLocs[++i]; // skip ahead to next loc
2298 // Extract the 2nd half and fall through to handle it as an f64 value.
2299 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2300 DAG.getConstant(1, dl, MVT::i32));
2302 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2304 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2305 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2306 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2307 fmrrd.getValue(isLittleEndian ? 0 : 1),
2309 Flag = Chain.getValue(1);
2310 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2311 VA = RVLocs[++i]; // skip ahead to next loc
2312 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2313 fmrrd.getValue(isLittleEndian ? 1 : 0),
2316 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2318 // Guarantee that all emitted copies are
2319 // stuck together, avoiding something bad.
2320 Flag = Chain.getValue(1);
2321 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2324 // Update chain and glue.
2327 RetOps.push_back(Flag);
2329 // CPUs which aren't M-class use a special sequence to return from
2330 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2331 // though we use "subs pc, lr, #N").
2333 // M-class CPUs actually use a normal return sequence with a special
2334 // (hardware-provided) value in LR, so the normal code path works.
2335 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2336 !Subtarget->isMClass()) {
2337 if (Subtarget->isThumb1Only())
2338 report_fatal_error("interrupt attribute is not supported in Thumb1");
2339 return LowerInterruptReturn(RetOps, dl, DAG);
2342 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2345 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2346 if (N->getNumValues() != 1)
2348 if (!N->hasNUsesOfValue(1, 0))
2351 SDValue TCChain = Chain;
2352 SDNode *Copy = *N->use_begin();
2353 if (Copy->getOpcode() == ISD::CopyToReg) {
2354 // If the copy has a glue operand, we conservatively assume it isn't safe to
2355 // perform a tail call.
2356 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2358 TCChain = Copy->getOperand(0);
2359 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2360 SDNode *VMov = Copy;
2361 // f64 returned in a pair of GPRs.
2362 SmallPtrSet<SDNode*, 2> Copies;
2363 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2365 if (UI->getOpcode() != ISD::CopyToReg)
2369 if (Copies.size() > 2)
2372 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2374 SDValue UseChain = UI->getOperand(0);
2375 if (Copies.count(UseChain.getNode()))
2379 // We are at the top of this chain.
2380 // If the copy has a glue operand, we conservatively assume it
2381 // isn't safe to perform a tail call.
2382 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2388 } else if (Copy->getOpcode() == ISD::BITCAST) {
2389 // f32 returned in a single GPR.
2390 if (!Copy->hasOneUse())
2392 Copy = *Copy->use_begin();
2393 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2395 // If the copy has a glue operand, we conservatively assume it isn't safe to
2396 // perform a tail call.
2397 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2399 TCChain = Copy->getOperand(0);
2404 bool HasRet = false;
2405 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2407 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2408 UI->getOpcode() != ARMISD::INTRET_FLAG)
2420 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2421 if (!Subtarget->supportsTailCall())
2425 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2426 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2429 return !Subtarget->isThumb1Only();
2432 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2433 // and pass the lower and high parts through.
2434 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2436 SDValue WriteValue = Op->getOperand(2);
2438 // This function is only supposed to be called for i64 type argument.
2439 assert(WriteValue.getValueType() == MVT::i64
2440 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2442 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2443 DAG.getConstant(0, DL, MVT::i32));
2444 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2445 DAG.getConstant(1, DL, MVT::i32));
2446 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2447 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2450 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2451 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2452 // one of the above mentioned nodes. It has to be wrapped because otherwise
2453 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2454 // be used to form addressing mode. These wrapped nodes will be selected
2456 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2457 EVT PtrVT = Op.getValueType();
2458 // FIXME there is no actual debug info here
2460 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2462 if (CP->isMachineConstantPoolEntry())
2463 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2464 CP->getAlignment());
2466 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2467 CP->getAlignment());
2468 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2471 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2472 return MachineJumpTableInfo::EK_Inline;
2475 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2476 SelectionDAG &DAG) const {
2477 MachineFunction &MF = DAG.getMachineFunction();
2478 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2479 unsigned ARMPCLabelIndex = 0;
2481 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2482 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2483 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2485 if (RelocM == Reloc::Static) {
2486 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2488 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2489 ARMPCLabelIndex = AFI->createPICLabelUId();
2490 ARMConstantPoolValue *CPV =
2491 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2492 ARMCP::CPBlockAddress, PCAdj);
2493 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2495 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2497 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2498 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2499 false, false, false, 0);
2500 if (RelocM == Reloc::Static)
2502 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2503 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2506 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2508 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2509 SelectionDAG &DAG) const {
2511 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2512 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2513 MachineFunction &MF = DAG.getMachineFunction();
2514 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2515 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2516 ARMConstantPoolValue *CPV =
2517 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2518 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2519 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2520 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2522 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2523 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2524 false, false, false, 0);
2525 SDValue Chain = Argument.getValue(1);
2527 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2528 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2530 // call __tls_get_addr.
2533 Entry.Node = Argument;
2534 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2535 Args.push_back(Entry);
2537 // FIXME: is there useful debug info available here?
2538 TargetLowering::CallLoweringInfo CLI(DAG);
2539 CLI.setDebugLoc(dl).setChain(Chain)
2540 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2541 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2544 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2545 return CallResult.first;
2548 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2549 // "local exec" model.
2551 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2553 TLSModel::Model model) const {
2554 const GlobalValue *GV = GA->getGlobal();
2557 SDValue Chain = DAG.getEntryNode();
2558 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2559 // Get the Thread Pointer
2560 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2562 if (model == TLSModel::InitialExec) {
2563 MachineFunction &MF = DAG.getMachineFunction();
2564 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2565 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2566 // Initial exec model.
2567 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2568 ARMConstantPoolValue *CPV =
2569 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2570 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2572 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2573 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2574 Offset = DAG.getLoad(
2575 PtrVT, dl, Chain, Offset,
2576 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2578 Chain = Offset.getValue(1);
2580 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2581 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2583 Offset = DAG.getLoad(
2584 PtrVT, dl, Chain, Offset,
2585 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2589 assert(model == TLSModel::LocalExec);
2590 ARMConstantPoolValue *CPV =
2591 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2592 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2593 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2594 Offset = DAG.getLoad(
2595 PtrVT, dl, Chain, Offset,
2596 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2600 // The address of the thread local variable is the add of the thread
2601 // pointer with the offset of the variable.
2602 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2606 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2607 // TODO: implement the "local dynamic" model
2608 assert(Subtarget->isTargetELF() &&
2609 "TLS not implemented for non-ELF targets");
2610 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2611 if (DAG.getTarget().Options.EmulatedTLS)
2612 return LowerToTLSEmulatedModel(GA, DAG);
2614 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2617 case TLSModel::GeneralDynamic:
2618 case TLSModel::LocalDynamic:
2619 return LowerToTLSGeneralDynamicModel(GA, DAG);
2620 case TLSModel::InitialExec:
2621 case TLSModel::LocalExec:
2622 return LowerToTLSExecModels(GA, DAG, model);
2624 llvm_unreachable("bogus TLS model");
2627 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2628 SelectionDAG &DAG) const {
2629 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2631 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2632 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2633 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2634 ARMConstantPoolValue *CPV =
2635 ARMConstantPoolConstant::Create(GV,
2636 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2637 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2638 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2639 SDValue Result = DAG.getLoad(
2640 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2641 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2643 SDValue Chain = Result.getValue(1);
2644 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2645 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2647 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2648 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2649 false, false, false, 0);
2653 // If we have T2 ops, we can materialize the address directly via movt/movw
2654 // pair. This is always cheaper.
2655 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2657 // FIXME: Once remat is capable of dealing with instructions with register
2658 // operands, expand this into two nodes.
2659 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2660 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2662 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2663 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2665 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2666 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2671 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2672 SelectionDAG &DAG) const {
2673 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2675 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2676 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2678 if (Subtarget->useMovt(DAG.getMachineFunction()))
2681 // FIXME: Once remat is capable of dealing with instructions with register
2682 // operands, expand this into multiple nodes
2684 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2686 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2687 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2689 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2690 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2691 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2692 false, false, false, 0);
2696 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2697 SelectionDAG &DAG) const {
2698 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2699 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2700 "Windows on ARM expects to use movw/movt");
2702 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2703 const ARMII::TOF TargetFlags =
2704 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2705 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2711 // FIXME: Once remat is capable of dealing with instructions with register
2712 // operands, expand this into two nodes.
2713 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2714 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2716 if (GV->hasDLLImportStorageClass())
2717 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2718 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2719 false, false, false, 0);
2723 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2724 SelectionDAG &DAG) const {
2725 assert(Subtarget->isTargetELF() &&
2726 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2727 MachineFunction &MF = DAG.getMachineFunction();
2728 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2729 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2730 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2732 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2733 ARMConstantPoolValue *CPV =
2734 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2735 ARMPCLabelIndex, PCAdj);
2736 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2737 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2739 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2740 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2741 false, false, false, 0);
2742 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2743 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2747 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2749 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2750 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2751 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2752 Op.getOperand(1), Val);
2756 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2758 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2759 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2762 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2763 SelectionDAG &DAG) const {
2765 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2770 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2771 const ARMSubtarget *Subtarget) const {
2772 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2775 default: return SDValue(); // Don't custom lower most intrinsics.
2776 case Intrinsic::arm_rbit: {
2777 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2778 "RBIT intrinsic must have i32 type!");
2779 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2781 case Intrinsic::arm_thread_pointer: {
2782 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2783 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2785 case Intrinsic::eh_sjlj_lsda: {
2786 MachineFunction &MF = DAG.getMachineFunction();
2787 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2788 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2789 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2790 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2792 unsigned PCAdj = (RelocM != Reloc::PIC_)
2793 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2794 ARMConstantPoolValue *CPV =
2795 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2796 ARMCP::CPLSDA, PCAdj);
2797 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2798 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2799 SDValue Result = DAG.getLoad(
2800 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2801 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2804 if (RelocM == Reloc::PIC_) {
2805 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2806 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2810 case Intrinsic::arm_neon_vmulls:
2811 case Intrinsic::arm_neon_vmullu: {
2812 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2813 ? ARMISD::VMULLs : ARMISD::VMULLu;
2814 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2815 Op.getOperand(1), Op.getOperand(2));
2817 case Intrinsic::arm_neon_vminnm:
2818 case Intrinsic::arm_neon_vmaxnm: {
2819 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2820 ? ISD::FMINNUM : ISD::FMAXNUM;
2821 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2822 Op.getOperand(1), Op.getOperand(2));
2824 case Intrinsic::arm_neon_vmins:
2825 case Intrinsic::arm_neon_vmaxs: {
2826 // v{min,max}s is overloaded between signed integers and floats.
2827 if (!Op.getValueType().isFloatingPoint())
2829 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2830 ? ISD::FMINNAN : ISD::FMAXNAN;
2831 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2832 Op.getOperand(1), Op.getOperand(2));
2837 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2838 const ARMSubtarget *Subtarget) {
2839 // FIXME: handle "fence singlethread" more efficiently.
2841 if (!Subtarget->hasDataBarrier()) {
2842 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2843 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2845 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2846 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2847 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2848 DAG.getConstant(0, dl, MVT::i32));
2851 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2852 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2853 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2854 if (Subtarget->isMClass()) {
2855 // Only a full system barrier exists in the M-class architectures.
2856 Domain = ARM_MB::SY;
2857 } else if (Subtarget->isSwift() && Ord == Release) {
2858 // Swift happens to implement ISHST barriers in a way that's compatible with
2859 // Release semantics but weaker than ISH so we'd be fools not to use
2860 // it. Beware: other processors probably don't!
2861 Domain = ARM_MB::ISHST;
2864 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2865 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2866 DAG.getConstant(Domain, dl, MVT::i32));
2869 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2870 const ARMSubtarget *Subtarget) {
2871 // ARM pre v5TE and Thumb1 does not have preload instructions.
2872 if (!(Subtarget->isThumb2() ||
2873 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2874 // Just preserve the chain.
2875 return Op.getOperand(0);
2878 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2880 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2881 // ARMv7 with MP extension has PLDW.
2882 return Op.getOperand(0);
2884 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2885 if (Subtarget->isThumb()) {
2887 isRead = ~isRead & 1;
2888 isData = ~isData & 1;
2891 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2892 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2893 DAG.getConstant(isData, dl, MVT::i32));
2896 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2897 MachineFunction &MF = DAG.getMachineFunction();
2898 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2900 // vastart just stores the address of the VarArgsFrameIndex slot into the
2901 // memory location argument.
2903 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2904 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2905 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2906 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2907 MachinePointerInfo(SV), false, false, 0);
2911 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2912 SDValue &Root, SelectionDAG &DAG,
2914 MachineFunction &MF = DAG.getMachineFunction();
2915 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2917 const TargetRegisterClass *RC;
2918 if (AFI->isThumb1OnlyFunction())
2919 RC = &ARM::tGPRRegClass;
2921 RC = &ARM::GPRRegClass;
2923 // Transform the arguments stored in physical registers into virtual ones.
2924 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2925 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2928 if (NextVA.isMemLoc()) {
2929 MachineFrameInfo *MFI = MF.getFrameInfo();
2930 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2932 // Create load node to retrieve arguments from the stack.
2933 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2934 ArgValue2 = DAG.getLoad(
2935 MVT::i32, dl, Root, FIN,
2936 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2939 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2940 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2942 if (!Subtarget->isLittle())
2943 std::swap (ArgValue, ArgValue2);
2944 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2947 // The remaining GPRs hold either the beginning of variable-argument
2948 // data, or the beginning of an aggregate passed by value (usually
2949 // byval). Either way, we allocate stack slots adjacent to the data
2950 // provided by our caller, and store the unallocated registers there.
2951 // If this is a variadic function, the va_list pointer will begin with
2952 // these values; otherwise, this reassembles a (byval) structure that
2953 // was split between registers and memory.
2954 // Return: The frame index registers were stored into.
2956 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2957 SDLoc dl, SDValue &Chain,
2958 const Value *OrigArg,
2959 unsigned InRegsParamRecordIdx,
2961 unsigned ArgSize) const {
2962 // Currently, two use-cases possible:
2963 // Case #1. Non-var-args function, and we meet first byval parameter.
2964 // Setup first unallocated register as first byval register;
2965 // eat all remained registers
2966 // (these two actions are performed by HandleByVal method).
2967 // Then, here, we initialize stack frame with
2968 // "store-reg" instructions.
2969 // Case #2. Var-args function, that doesn't contain byval parameters.
2970 // The same: eat all remained unallocated registers,
2971 // initialize stack frame.
2973 MachineFunction &MF = DAG.getMachineFunction();
2974 MachineFrameInfo *MFI = MF.getFrameInfo();
2975 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2976 unsigned RBegin, REnd;
2977 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2978 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2980 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2981 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2986 ArgOffset = -4 * (ARM::R4 - RBegin);
2988 auto PtrVT = getPointerTy(DAG.getDataLayout());
2989 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2990 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2992 SmallVector<SDValue, 4> MemOps;
2993 const TargetRegisterClass *RC =
2994 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2996 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2997 unsigned VReg = MF.addLiveIn(Reg, RC);
2998 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3000 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3001 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3002 MemOps.push_back(Store);
3003 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3006 if (!MemOps.empty())
3007 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3011 // Setup stack frame, the va_list pointer will start from.
3013 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3014 SDLoc dl, SDValue &Chain,
3016 unsigned TotalArgRegsSaveSize,
3017 bool ForceMutable) const {
3018 MachineFunction &MF = DAG.getMachineFunction();
3019 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3021 // Try to store any remaining integer argument regs
3022 // to their spots on the stack so that they may be loaded by deferencing
3023 // the result of va_next.
3024 // If there is no regs to be stored, just point address after last
3025 // argument passed via stack.
3026 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3027 CCInfo.getInRegsParamsCount(),
3028 CCInfo.getNextStackOffset(), 4);
3029 AFI->setVarArgsFrameIndex(FrameIndex);
3033 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3034 CallingConv::ID CallConv, bool isVarArg,
3035 const SmallVectorImpl<ISD::InputArg>
3037 SDLoc dl, SelectionDAG &DAG,
3038 SmallVectorImpl<SDValue> &InVals)
3040 MachineFunction &MF = DAG.getMachineFunction();
3041 MachineFrameInfo *MFI = MF.getFrameInfo();
3043 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3045 // Assign locations to all of the incoming arguments.
3046 SmallVector<CCValAssign, 16> ArgLocs;
3047 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3048 *DAG.getContext(), Prologue);
3049 CCInfo.AnalyzeFormalArguments(Ins,
3050 CCAssignFnForNode(CallConv, /* Return*/ false,
3053 SmallVector<SDValue, 16> ArgValues;
3055 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3056 unsigned CurArgIdx = 0;
3058 // Initially ArgRegsSaveSize is zero.
3059 // Then we increase this value each time we meet byval parameter.
3060 // We also increase this value in case of varargs function.
3061 AFI->setArgRegsSaveSize(0);
3063 // Calculate the amount of stack space that we need to allocate to store
3064 // byval and variadic arguments that are passed in registers.
3065 // We need to know this before we allocate the first byval or variadic
3066 // argument, as they will be allocated a stack slot below the CFA (Canonical
3067 // Frame Address, the stack pointer at entry to the function).
3068 unsigned ArgRegBegin = ARM::R4;
3069 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3070 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3073 CCValAssign &VA = ArgLocs[i];
3074 unsigned Index = VA.getValNo();
3075 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3076 if (!Flags.isByVal())
3079 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3080 unsigned RBegin, REnd;
3081 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3082 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3084 CCInfo.nextInRegsParam();
3086 CCInfo.rewindByValRegsInfo();
3088 int lastInsIndex = -1;
3089 if (isVarArg && MFI->hasVAStart()) {
3090 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3091 if (RegIdx != array_lengthof(GPRArgRegs))
3092 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3095 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3096 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3097 auto PtrVT = getPointerTy(DAG.getDataLayout());
3099 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3100 CCValAssign &VA = ArgLocs[i];
3101 if (Ins[VA.getValNo()].isOrigArg()) {
3102 std::advance(CurOrigArg,
3103 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3104 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3106 // Arguments stored in registers.
3107 if (VA.isRegLoc()) {
3108 EVT RegVT = VA.getLocVT();
3110 if (VA.needsCustom()) {
3111 // f64 and vector types are split up into multiple registers or
3112 // combinations of registers and stack slots.
3113 if (VA.getLocVT() == MVT::v2f64) {
3114 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3116 VA = ArgLocs[++i]; // skip ahead to next loc
3118 if (VA.isMemLoc()) {
3119 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3120 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3121 ArgValue2 = DAG.getLoad(
3122 MVT::f64, dl, Chain, FIN,
3123 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3124 false, false, false, 0);
3126 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3129 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3130 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3131 ArgValue, ArgValue1,
3132 DAG.getIntPtrConstant(0, dl));
3133 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3134 ArgValue, ArgValue2,
3135 DAG.getIntPtrConstant(1, dl));
3137 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3140 const TargetRegisterClass *RC;
3142 if (RegVT == MVT::f32)
3143 RC = &ARM::SPRRegClass;
3144 else if (RegVT == MVT::f64)
3145 RC = &ARM::DPRRegClass;
3146 else if (RegVT == MVT::v2f64)
3147 RC = &ARM::QPRRegClass;
3148 else if (RegVT == MVT::i32)
3149 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3150 : &ARM::GPRRegClass;
3152 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3154 // Transform the arguments in physical registers into virtual ones.
3155 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3156 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3159 // If this is an 8 or 16-bit value, it is really passed promoted
3160 // to 32 bits. Insert an assert[sz]ext to capture this, then
3161 // truncate to the right size.
3162 switch (VA.getLocInfo()) {
3163 default: llvm_unreachable("Unknown loc info!");
3164 case CCValAssign::Full: break;
3165 case CCValAssign::BCvt:
3166 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3168 case CCValAssign::SExt:
3169 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3170 DAG.getValueType(VA.getValVT()));
3171 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3173 case CCValAssign::ZExt:
3174 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3175 DAG.getValueType(VA.getValVT()));
3176 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3180 InVals.push_back(ArgValue);
3182 } else { // VA.isRegLoc()
3185 assert(VA.isMemLoc());
3186 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3188 int index = VA.getValNo();
3190 // Some Ins[] entries become multiple ArgLoc[] entries.
3191 // Process them only once.
3192 if (index != lastInsIndex)
3194 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3195 // FIXME: For now, all byval parameter objects are marked mutable.
3196 // This can be changed with more analysis.
3197 // In case of tail call optimization mark all arguments mutable.
3198 // Since they could be overwritten by lowering of arguments in case of
3200 if (Flags.isByVal()) {
3201 assert(Ins[index].isOrigArg() &&
3202 "Byval arguments cannot be implicit");
3203 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3205 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3206 CurByValIndex, VA.getLocMemOffset(),
3207 Flags.getByValSize());
3208 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3209 CCInfo.nextInRegsParam();
3211 unsigned FIOffset = VA.getLocMemOffset();
3212 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3215 // Create load nodes to retrieve arguments from the stack.
3216 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3217 InVals.push_back(DAG.getLoad(
3218 VA.getValVT(), dl, Chain, FIN,
3219 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3220 false, false, false, 0));
3222 lastInsIndex = index;
3228 if (isVarArg && MFI->hasVAStart())
3229 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3230 CCInfo.getNextStackOffset(),
3231 TotalArgRegsSaveSize);
3233 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3238 /// isFloatingPointZero - Return true if this is +0.0.
3239 static bool isFloatingPointZero(SDValue Op) {
3240 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3241 return CFP->getValueAPF().isPosZero();
3242 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3243 // Maybe this has already been legalized into the constant pool?
3244 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3245 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3246 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3247 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3248 return CFP->getValueAPF().isPosZero();
3250 } else if (Op->getOpcode() == ISD::BITCAST &&
3251 Op->getValueType(0) == MVT::f64) {
3252 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3253 // created by LowerConstantFP().
3254 SDValue BitcastOp = Op->getOperand(0);
3255 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3256 SDValue MoveOp = BitcastOp->getOperand(0);
3257 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3258 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3266 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3267 /// the given operands.
3269 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3270 SDValue &ARMcc, SelectionDAG &DAG,
3272 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3273 unsigned C = RHSC->getZExtValue();
3274 if (!isLegalICmpImmediate(C)) {
3275 // Constant does not fit, try adjusting it by one?
3280 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3281 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3282 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3287 if (C != 0 && isLegalICmpImmediate(C-1)) {
3288 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3289 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3294 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3295 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3296 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3301 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3302 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3303 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3310 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3311 ARMISD::NodeType CompareType;
3314 CompareType = ARMISD::CMP;
3319 CompareType = ARMISD::CMPZ;
3322 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3323 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3326 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3328 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3330 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3332 if (!isFloatingPointZero(RHS))
3333 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3335 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3336 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3339 /// duplicateCmp - Glue values can have only one use, so this function
3340 /// duplicates a comparison node.
3342 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3343 unsigned Opc = Cmp.getOpcode();
3345 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3346 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3348 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3349 Cmp = Cmp.getOperand(0);
3350 Opc = Cmp.getOpcode();
3351 if (Opc == ARMISD::CMPFP)
3352 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3354 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3355 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3357 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3360 std::pair<SDValue, SDValue>
3361 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3362 SDValue &ARMcc) const {
3363 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3365 SDValue Value, OverflowCmp;
3366 SDValue LHS = Op.getOperand(0);
3367 SDValue RHS = Op.getOperand(1);
3370 // FIXME: We are currently always generating CMPs because we don't support
3371 // generating CMN through the backend. This is not as good as the natural
3372 // CMP case because it causes a register dependency and cannot be folded
3375 switch (Op.getOpcode()) {
3377 llvm_unreachable("Unknown overflow instruction!");
3379 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3380 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3381 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3384 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3385 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3386 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3389 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3390 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3391 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3394 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3395 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3396 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3400 return std::make_pair(Value, OverflowCmp);
3405 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3406 // Let legalize expand this if it isn't a legal type yet.
3407 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3410 SDValue Value, OverflowCmp;
3412 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3413 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3415 // We use 0 and 1 as false and true values.
3416 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3417 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3418 EVT VT = Op.getValueType();
3420 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3421 ARMcc, CCR, OverflowCmp);
3423 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3424 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3428 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3429 SDValue Cond = Op.getOperand(0);
3430 SDValue SelectTrue = Op.getOperand(1);
3431 SDValue SelectFalse = Op.getOperand(2);
3433 unsigned Opc = Cond.getOpcode();
3435 if (Cond.getResNo() == 1 &&
3436 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3437 Opc == ISD::USUBO)) {
3438 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3441 SDValue Value, OverflowCmp;
3443 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3444 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3445 EVT VT = Op.getValueType();
3447 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3453 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3454 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3456 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3457 const ConstantSDNode *CMOVTrue =
3458 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3459 const ConstantSDNode *CMOVFalse =
3460 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3462 if (CMOVTrue && CMOVFalse) {
3463 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3464 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3468 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3470 False = SelectFalse;
3471 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3476 if (True.getNode() && False.getNode()) {
3477 EVT VT = Op.getValueType();
3478 SDValue ARMcc = Cond.getOperand(2);
3479 SDValue CCR = Cond.getOperand(3);
3480 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3481 assert(True.getValueType() == VT);
3482 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3487 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3488 // undefined bits before doing a full-word comparison with zero.
3489 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3490 DAG.getConstant(1, dl, Cond.getValueType()));
3492 return DAG.getSelectCC(dl, Cond,
3493 DAG.getConstant(0, dl, Cond.getValueType()),
3494 SelectTrue, SelectFalse, ISD::SETNE);
3497 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3498 bool &swpCmpOps, bool &swpVselOps) {
3499 // Start by selecting the GE condition code for opcodes that return true for
3501 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3503 CondCode = ARMCC::GE;
3505 // and GT for opcodes that return false for 'equality'.
3506 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3508 CondCode = ARMCC::GT;
3510 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3511 // to swap the compare operands.
3512 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3516 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3517 // If we have an unordered opcode, we need to swap the operands to the VSEL
3518 // instruction (effectively negating the condition).
3520 // This also has the effect of swapping which one of 'less' or 'greater'
3521 // returns true, so we also swap the compare operands. It also switches
3522 // whether we return true for 'equality', so we compensate by picking the
3523 // opposite condition code to our original choice.
3524 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3525 CC == ISD::SETUGT) {
3526 swpCmpOps = !swpCmpOps;
3527 swpVselOps = !swpVselOps;
3528 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3531 // 'ordered' is 'anything but unordered', so use the VS condition code and
3532 // swap the VSEL operands.
3533 if (CC == ISD::SETO) {
3534 CondCode = ARMCC::VS;
3538 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3539 // code and swap the VSEL operands.
3540 if (CC == ISD::SETUNE) {
3541 CondCode = ARMCC::EQ;
3546 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3547 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3548 SDValue Cmp, SelectionDAG &DAG) const {
3549 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3550 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3551 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3552 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3553 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3555 SDValue TrueLow = TrueVal.getValue(0);
3556 SDValue TrueHigh = TrueVal.getValue(1);
3557 SDValue FalseLow = FalseVal.getValue(0);
3558 SDValue FalseHigh = FalseVal.getValue(1);
3560 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3562 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3563 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3565 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3567 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3572 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3573 EVT VT = Op.getValueType();
3574 SDValue LHS = Op.getOperand(0);
3575 SDValue RHS = Op.getOperand(1);
3576 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3577 SDValue TrueVal = Op.getOperand(2);
3578 SDValue FalseVal = Op.getOperand(3);
3581 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3582 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3585 // If softenSetCCOperands only returned one value, we should compare it to
3587 if (!RHS.getNode()) {
3588 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3593 if (LHS.getValueType() == MVT::i32) {
3594 // Try to generate VSEL on ARMv8.
3595 // The VSEL instruction can't use all the usual ARM condition
3596 // codes: it only has two bits to select the condition code, so it's
3597 // constrained to use only GE, GT, VS and EQ.
3599 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3600 // swap the operands of the previous compare instruction (effectively
3601 // inverting the compare condition, swapping 'less' and 'greater') and
3602 // sometimes need to swap the operands to the VSEL (which inverts the
3603 // condition in the sense of firing whenever the previous condition didn't)
3604 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3605 TrueVal.getValueType() == MVT::f64)) {
3606 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3607 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3608 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3609 CC = ISD::getSetCCInverse(CC, true);
3610 std::swap(TrueVal, FalseVal);
3615 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3616 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3617 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3620 ARMCC::CondCodes CondCode, CondCode2;
3621 FPCCToARMCC(CC, CondCode, CondCode2);
3623 // Try to generate VMAXNM/VMINNM on ARMv8.
3624 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3625 TrueVal.getValueType() == MVT::f64)) {
3626 bool swpCmpOps = false;
3627 bool swpVselOps = false;
3628 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3630 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3631 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3633 std::swap(LHS, RHS);
3635 std::swap(TrueVal, FalseVal);
3639 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3640 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3641 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3642 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3643 if (CondCode2 != ARMCC::AL) {
3644 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3645 // FIXME: Needs another CMP because flag can have but one use.
3646 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3647 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3652 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3653 /// to morph to an integer compare sequence.
3654 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3655 const ARMSubtarget *Subtarget) {
3656 SDNode *N = Op.getNode();
3657 if (!N->hasOneUse())
3658 // Otherwise it requires moving the value from fp to integer registers.
3660 if (!N->getNumValues())
3662 EVT VT = Op.getValueType();
3663 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3664 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3665 // vmrs are very slow, e.g. cortex-a8.
3668 if (isFloatingPointZero(Op)) {
3672 return ISD::isNormalLoad(N);
3675 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3676 if (isFloatingPointZero(Op))
3677 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3679 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3680 return DAG.getLoad(MVT::i32, SDLoc(Op),
3681 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3682 Ld->isVolatile(), Ld->isNonTemporal(),
3683 Ld->isInvariant(), Ld->getAlignment());
3685 llvm_unreachable("Unknown VFP cmp argument!");
3688 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3689 SDValue &RetVal1, SDValue &RetVal2) {
3692 if (isFloatingPointZero(Op)) {
3693 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3694 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3698 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3699 SDValue Ptr = Ld->getBasePtr();
3700 RetVal1 = DAG.getLoad(MVT::i32, dl,
3701 Ld->getChain(), Ptr,
3702 Ld->getPointerInfo(),
3703 Ld->isVolatile(), Ld->isNonTemporal(),
3704 Ld->isInvariant(), Ld->getAlignment());
3706 EVT PtrType = Ptr.getValueType();
3707 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3708 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3709 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3710 RetVal2 = DAG.getLoad(MVT::i32, dl,
3711 Ld->getChain(), NewPtr,
3712 Ld->getPointerInfo().getWithOffset(4),
3713 Ld->isVolatile(), Ld->isNonTemporal(),
3714 Ld->isInvariant(), NewAlign);
3718 llvm_unreachable("Unknown VFP cmp argument!");
3721 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3722 /// f32 and even f64 comparisons to integer ones.
3724 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3725 SDValue Chain = Op.getOperand(0);
3726 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3727 SDValue LHS = Op.getOperand(2);
3728 SDValue RHS = Op.getOperand(3);
3729 SDValue Dest = Op.getOperand(4);
3732 bool LHSSeenZero = false;
3733 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3734 bool RHSSeenZero = false;
3735 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3736 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3737 // If unsafe fp math optimization is enabled and there are no other uses of
3738 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3739 // to an integer comparison.
3740 if (CC == ISD::SETOEQ)
3742 else if (CC == ISD::SETUNE)
3745 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3747 if (LHS.getValueType() == MVT::f32) {
3748 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3749 bitcastf32Toi32(LHS, DAG), Mask);
3750 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3751 bitcastf32Toi32(RHS, DAG), Mask);
3752 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3753 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3754 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3755 Chain, Dest, ARMcc, CCR, Cmp);
3760 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3761 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3762 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3763 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3764 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3765 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3766 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3767 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3768 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3774 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3775 SDValue Chain = Op.getOperand(0);
3776 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3777 SDValue LHS = Op.getOperand(2);
3778 SDValue RHS = Op.getOperand(3);
3779 SDValue Dest = Op.getOperand(4);
3782 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3783 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3786 // If softenSetCCOperands only returned one value, we should compare it to
3788 if (!RHS.getNode()) {
3789 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3794 if (LHS.getValueType() == MVT::i32) {
3796 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3797 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3798 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3799 Chain, Dest, ARMcc, CCR, Cmp);
3802 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3804 if (getTargetMachine().Options.UnsafeFPMath &&
3805 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3806 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3807 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3808 if (Result.getNode())
3812 ARMCC::CondCodes CondCode, CondCode2;
3813 FPCCToARMCC(CC, CondCode, CondCode2);
3815 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3816 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3817 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3819 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3820 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3821 if (CondCode2 != ARMCC::AL) {
3822 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3823 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3824 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3829 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3830 SDValue Chain = Op.getOperand(0);
3831 SDValue Table = Op.getOperand(1);
3832 SDValue Index = Op.getOperand(2);
3835 EVT PTy = getPointerTy(DAG.getDataLayout());
3836 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3837 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3838 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3839 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3840 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3841 if (Subtarget->isThumb2()) {
3842 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3843 // which does another jump to the destination. This also makes it easier
3844 // to translate it to TBB / TBH later.
3845 // FIXME: This might not work if the function is extremely large.
3846 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3847 Addr, Op.getOperand(2), JTI);
3849 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3851 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3852 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3853 false, false, false, 0);
3854 Chain = Addr.getValue(1);
3855 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3856 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3859 DAG.getLoad(PTy, dl, Chain, Addr,
3860 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3861 false, false, false, 0);
3862 Chain = Addr.getValue(1);
3863 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3867 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3868 EVT VT = Op.getValueType();
3871 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3872 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3874 return DAG.UnrollVectorOp(Op.getNode());
3877 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3878 "Invalid type for custom lowering!");
3879 if (VT != MVT::v4i16)
3880 return DAG.UnrollVectorOp(Op.getNode());
3882 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3883 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3886 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3887 EVT VT = Op.getValueType();
3889 return LowerVectorFP_TO_INT(Op, DAG);
3890 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3892 if (Op.getOpcode() == ISD::FP_TO_SINT)
3893 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3896 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3898 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3899 /*isSigned*/ false, SDLoc(Op)).first;
3905 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3906 EVT VT = Op.getValueType();
3909 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3910 if (VT.getVectorElementType() == MVT::f32)
3912 return DAG.UnrollVectorOp(Op.getNode());
3915 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3916 "Invalid type for custom lowering!");
3917 if (VT != MVT::v4f32)
3918 return DAG.UnrollVectorOp(Op.getNode());
3922 switch (Op.getOpcode()) {
3923 default: llvm_unreachable("Invalid opcode!");
3924 case ISD::SINT_TO_FP:
3925 CastOpc = ISD::SIGN_EXTEND;
3926 Opc = ISD::SINT_TO_FP;
3928 case ISD::UINT_TO_FP:
3929 CastOpc = ISD::ZERO_EXTEND;
3930 Opc = ISD::UINT_TO_FP;
3934 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3935 return DAG.getNode(Opc, dl, VT, Op);
3938 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3939 EVT VT = Op.getValueType();
3941 return LowerVectorINT_TO_FP(Op, DAG);
3942 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3944 if (Op.getOpcode() == ISD::SINT_TO_FP)
3945 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3948 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3950 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3951 /*isSigned*/ false, SDLoc(Op)).first;
3957 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3958 // Implement fcopysign with a fabs and a conditional fneg.
3959 SDValue Tmp0 = Op.getOperand(0);
3960 SDValue Tmp1 = Op.getOperand(1);
3962 EVT VT = Op.getValueType();
3963 EVT SrcVT = Tmp1.getValueType();
3964 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3965 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3966 bool UseNEON = !InGPR && Subtarget->hasNEON();
3969 // Use VBSL to copy the sign bit.
3970 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3971 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3972 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3973 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3975 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3976 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3977 DAG.getConstant(32, dl, MVT::i32));
3978 else /*if (VT == MVT::f32)*/
3979 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3980 if (SrcVT == MVT::f32) {
3981 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3983 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3984 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3985 DAG.getConstant(32, dl, MVT::i32));
3986 } else if (VT == MVT::f32)
3987 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3988 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3989 DAG.getConstant(32, dl, MVT::i32));
3990 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3991 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3993 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3995 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3996 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3997 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3999 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4000 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4001 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4002 if (VT == MVT::f32) {
4003 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4004 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4005 DAG.getConstant(0, dl, MVT::i32));
4007 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4013 // Bitcast operand 1 to i32.
4014 if (SrcVT == MVT::f64)
4015 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4017 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4019 // Or in the signbit with integer operations.
4020 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4021 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4022 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4023 if (VT == MVT::f32) {
4024 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4025 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4026 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4027 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4030 // f64: Or the high part with signbit and then combine two parts.
4031 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4033 SDValue Lo = Tmp0.getValue(0);
4034 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4035 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4036 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4039 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4040 MachineFunction &MF = DAG.getMachineFunction();
4041 MachineFrameInfo *MFI = MF.getFrameInfo();
4042 MFI->setReturnAddressIsTaken(true);
4044 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4047 EVT VT = Op.getValueType();
4049 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4051 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4052 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4053 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4054 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4055 MachinePointerInfo(), false, false, false, 0);
4058 // Return LR, which contains the return address. Mark it an implicit live-in.
4059 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4060 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4063 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4064 const ARMBaseRegisterInfo &ARI =
4065 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4066 MachineFunction &MF = DAG.getMachineFunction();
4067 MachineFrameInfo *MFI = MF.getFrameInfo();
4068 MFI->setFrameAddressIsTaken(true);
4070 EVT VT = Op.getValueType();
4071 SDLoc dl(Op); // FIXME probably not meaningful
4072 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4073 unsigned FrameReg = ARI.getFrameRegister(MF);
4074 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4076 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4077 MachinePointerInfo(),
4078 false, false, false, 0);
4082 // FIXME? Maybe this could be a TableGen attribute on some registers and
4083 // this table could be generated automatically from RegInfo.
4084 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4085 SelectionDAG &DAG) const {
4086 unsigned Reg = StringSwitch<unsigned>(RegName)
4087 .Case("sp", ARM::SP)
4091 report_fatal_error(Twine("Invalid register name \""
4092 + StringRef(RegName) + "\"."));
4095 // Result is 64 bit value so split into two 32 bit values and return as a
4097 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4098 SelectionDAG &DAG) {
4101 // This function is only supposed to be called for i64 type destination.
4102 assert(N->getValueType(0) == MVT::i64
4103 && "ExpandREAD_REGISTER called for non-i64 type result.");
4105 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4106 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4110 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4112 Results.push_back(Read.getOperand(0));
4115 /// ExpandBITCAST - If the target supports VFP, this function is called to
4116 /// expand a bit convert where either the source or destination type is i64 to
4117 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4118 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4119 /// vectors), since the legalizer won't know what to do with that.
4120 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4123 SDValue Op = N->getOperand(0);
4125 // This function is only supposed to be called for i64 types, either as the
4126 // source or destination of the bit convert.
4127 EVT SrcVT = Op.getValueType();
4128 EVT DstVT = N->getValueType(0);
4129 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4130 "ExpandBITCAST called for non-i64 type");
4132 // Turn i64->f64 into VMOVDRR.
4133 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4134 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4135 DAG.getConstant(0, dl, MVT::i32));
4136 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4137 DAG.getConstant(1, dl, MVT::i32));
4138 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4139 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4142 // Turn f64->i64 into VMOVRRD.
4143 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4145 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4146 SrcVT.getVectorNumElements() > 1)
4147 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4148 DAG.getVTList(MVT::i32, MVT::i32),
4149 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4151 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4152 DAG.getVTList(MVT::i32, MVT::i32), Op);
4153 // Merge the pieces into a single i64 value.
4154 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4160 /// getZeroVector - Returns a vector of specified type with all zero elements.
4161 /// Zero vectors are used to represent vector negation and in those cases
4162 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4163 /// not support i64 elements, so sometimes the zero vectors will need to be
4164 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4166 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4167 assert(VT.isVector() && "Expected a vector type");
4168 // The canonical modified immediate encoding of a zero vector is....0!
4169 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4170 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4171 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4172 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4175 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4176 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4177 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4178 SelectionDAG &DAG) const {
4179 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4180 EVT VT = Op.getValueType();
4181 unsigned VTBits = VT.getSizeInBits();
4183 SDValue ShOpLo = Op.getOperand(0);
4184 SDValue ShOpHi = Op.getOperand(1);
4185 SDValue ShAmt = Op.getOperand(2);
4187 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4189 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4191 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4192 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4193 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4194 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4195 DAG.getConstant(VTBits, dl, MVT::i32));
4196 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4197 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4198 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4200 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4201 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4202 ISD::SETGE, ARMcc, DAG, dl);
4203 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4204 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4207 SDValue Ops[2] = { Lo, Hi };
4208 return DAG.getMergeValues(Ops, dl);
4211 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4212 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4213 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4214 SelectionDAG &DAG) const {
4215 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4216 EVT VT = Op.getValueType();
4217 unsigned VTBits = VT.getSizeInBits();
4219 SDValue ShOpLo = Op.getOperand(0);
4220 SDValue ShOpHi = Op.getOperand(1);
4221 SDValue ShAmt = Op.getOperand(2);
4224 assert(Op.getOpcode() == ISD::SHL_PARTS);
4225 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4226 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4227 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4228 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4229 DAG.getConstant(VTBits, dl, MVT::i32));
4230 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4231 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4233 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4234 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4235 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4236 ISD::SETGE, ARMcc, DAG, dl);
4237 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4238 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4241 SDValue Ops[2] = { Lo, Hi };
4242 return DAG.getMergeValues(Ops, dl);
4245 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4246 SelectionDAG &DAG) const {
4247 // The rounding mode is in bits 23:22 of the FPSCR.
4248 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4249 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4250 // so that the shift + and get folded into a bitfield extract.
4252 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4253 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4255 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4256 DAG.getConstant(1U << 22, dl, MVT::i32));
4257 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4258 DAG.getConstant(22, dl, MVT::i32));
4259 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4260 DAG.getConstant(3, dl, MVT::i32));
4263 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4264 const ARMSubtarget *ST) {
4266 EVT VT = N->getValueType(0);
4267 if (VT.isVector()) {
4268 assert(ST->hasNEON());
4270 // Compute the least significant set bit: LSB = X & -X
4271 SDValue X = N->getOperand(0);
4272 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4273 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4275 EVT ElemTy = VT.getVectorElementType();
4277 if (ElemTy == MVT::i8) {
4278 // Compute with: cttz(x) = ctpop(lsb - 1)
4279 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4280 DAG.getTargetConstant(1, dl, ElemTy));
4281 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4282 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4285 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4286 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4287 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4288 unsigned NumBits = ElemTy.getSizeInBits();
4289 SDValue WidthMinus1 =
4290 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4291 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4292 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4293 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4296 // Compute with: cttz(x) = ctpop(lsb - 1)
4298 // Since we can only compute the number of bits in a byte with vcnt.8, we
4299 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4304 if (ElemTy == MVT::i64) {
4305 // Load constant 0xffff'ffff'ffff'ffff to register.
4306 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4307 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4308 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4310 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4311 DAG.getTargetConstant(1, dl, ElemTy));
4312 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4315 // Count #bits with vcnt.8.
4316 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4317 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4318 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4320 // Gather the #bits with vpaddl (pairwise add.)
4321 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4322 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4323 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4325 if (ElemTy == MVT::i16)
4328 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4329 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4330 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4332 if (ElemTy == MVT::i32)
4335 assert(ElemTy == MVT::i64);
4336 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4337 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4342 if (!ST->hasV6T2Ops())
4345 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4346 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4349 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4350 /// for each 16-bit element from operand, repeated. The basic idea is to
4351 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4353 /// Trace for v4i16:
4354 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4355 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4356 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4357 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4358 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4359 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4360 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4361 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4362 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4363 EVT VT = N->getValueType(0);
4366 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4367 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4368 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4369 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4370 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4371 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4374 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4375 /// bit-count for each 16-bit element from the operand. We need slightly
4376 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4377 /// 64/128-bit registers.
4379 /// Trace for v4i16:
4380 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4381 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4382 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4383 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4384 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4385 EVT VT = N->getValueType(0);
4388 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4389 if (VT.is64BitVector()) {
4390 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4391 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4392 DAG.getIntPtrConstant(0, DL));
4394 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4395 BitCounts, DAG.getIntPtrConstant(0, DL));
4396 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4400 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4401 /// bit-count for each 32-bit element from the operand. The idea here is
4402 /// to split the vector into 16-bit elements, leverage the 16-bit count
4403 /// routine, and then combine the results.
4405 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4406 /// input = [v0 v1 ] (vi: 32-bit elements)
4407 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4408 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4409 /// vrev: N0 = [k1 k0 k3 k2 ]
4411 /// N1 =+[k1 k0 k3 k2 ]
4413 /// N2 =+[k1 k3 k0 k2 ]
4415 /// Extended =+[k1 k3 k0 k2 ]
4417 /// Extracted=+[k1 k3 ]
4419 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4420 EVT VT = N->getValueType(0);
4423 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4425 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4426 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4427 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4428 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4429 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4431 if (VT.is64BitVector()) {
4432 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4433 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4434 DAG.getIntPtrConstant(0, DL));
4436 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4437 DAG.getIntPtrConstant(0, DL));
4438 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4442 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4443 const ARMSubtarget *ST) {
4444 EVT VT = N->getValueType(0);
4446 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4447 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4448 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4449 "Unexpected type for custom ctpop lowering");
4451 if (VT.getVectorElementType() == MVT::i32)
4452 return lowerCTPOP32BitElements(N, DAG);
4454 return lowerCTPOP16BitElements(N, DAG);
4457 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4458 const ARMSubtarget *ST) {
4459 EVT VT = N->getValueType(0);
4465 // Lower vector shifts on NEON to use VSHL.
4466 assert(ST->hasNEON() && "unexpected vector shift");
4468 // Left shifts translate directly to the vshiftu intrinsic.
4469 if (N->getOpcode() == ISD::SHL)
4470 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4471 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4473 N->getOperand(0), N->getOperand(1));
4475 assert((N->getOpcode() == ISD::SRA ||
4476 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4478 // NEON uses the same intrinsics for both left and right shifts. For
4479 // right shifts, the shift amounts are negative, so negate the vector of
4481 EVT ShiftVT = N->getOperand(1).getValueType();
4482 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4483 getZeroVector(ShiftVT, DAG, dl),
4485 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4486 Intrinsic::arm_neon_vshifts :
4487 Intrinsic::arm_neon_vshiftu);
4488 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4489 DAG.getConstant(vshiftInt, dl, MVT::i32),
4490 N->getOperand(0), NegatedCount);
4493 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4494 const ARMSubtarget *ST) {
4495 EVT VT = N->getValueType(0);
4498 // We can get here for a node like i32 = ISD::SHL i32, i64
4502 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4503 "Unknown shift to lower!");
4505 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4506 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4507 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4510 // If we are in thumb mode, we don't have RRX.
4511 if (ST->isThumb1Only()) return SDValue();
4513 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4514 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4515 DAG.getConstant(0, dl, MVT::i32));
4516 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4517 DAG.getConstant(1, dl, MVT::i32));
4519 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4520 // captures the result into a carry flag.
4521 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4522 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4524 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4525 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4527 // Merge the pieces into a single i64 value.
4528 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4531 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4532 SDValue TmpOp0, TmpOp1;
4533 bool Invert = false;
4537 SDValue Op0 = Op.getOperand(0);
4538 SDValue Op1 = Op.getOperand(1);
4539 SDValue CC = Op.getOperand(2);
4540 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4541 EVT VT = Op.getValueType();
4542 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4545 if (Op1.getValueType().isFloatingPoint()) {
4546 switch (SetCCOpcode) {
4547 default: llvm_unreachable("Illegal FP comparison");
4549 case ISD::SETNE: Invert = true; // Fallthrough
4551 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4553 case ISD::SETLT: Swap = true; // Fallthrough
4555 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4557 case ISD::SETLE: Swap = true; // Fallthrough
4559 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4560 case ISD::SETUGE: Swap = true; // Fallthrough
4561 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4562 case ISD::SETUGT: Swap = true; // Fallthrough
4563 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4564 case ISD::SETUEQ: Invert = true; // Fallthrough
4566 // Expand this to (OLT | OGT).
4570 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4571 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4573 case ISD::SETUO: Invert = true; // Fallthrough
4575 // Expand this to (OLT | OGE).
4579 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4580 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4584 // Integer comparisons.
4585 switch (SetCCOpcode) {
4586 default: llvm_unreachable("Illegal integer comparison");
4587 case ISD::SETNE: Invert = true;
4588 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4589 case ISD::SETLT: Swap = true;
4590 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4591 case ISD::SETLE: Swap = true;
4592 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4593 case ISD::SETULT: Swap = true;
4594 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4595 case ISD::SETULE: Swap = true;
4596 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4599 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4600 if (Opc == ARMISD::VCEQ) {
4603 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4605 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4608 // Ignore bitconvert.
4609 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4610 AndOp = AndOp.getOperand(0);
4612 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4614 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4615 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4622 std::swap(Op0, Op1);
4624 // If one of the operands is a constant vector zero, attempt to fold the
4625 // comparison to a specialized compare-against-zero form.
4627 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4629 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4630 if (Opc == ARMISD::VCGE)
4631 Opc = ARMISD::VCLEZ;
4632 else if (Opc == ARMISD::VCGT)
4633 Opc = ARMISD::VCLTZ;
4638 if (SingleOp.getNode()) {
4641 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4643 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4645 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4647 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4649 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4651 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4654 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4657 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4660 Result = DAG.getNOT(dl, Result, VT);
4665 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4666 /// valid vector constant for a NEON instruction with a "modified immediate"
4667 /// operand (e.g., VMOV). If so, return the encoded value.
4668 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4669 unsigned SplatBitSize, SelectionDAG &DAG,
4670 SDLoc dl, EVT &VT, bool is128Bits,
4671 NEONModImmType type) {
4672 unsigned OpCmode, Imm;
4674 // SplatBitSize is set to the smallest size that splats the vector, so a
4675 // zero vector will always have SplatBitSize == 8. However, NEON modified
4676 // immediate instructions others than VMOV do not support the 8-bit encoding
4677 // of a zero vector, and the default encoding of zero is supposed to be the
4682 switch (SplatBitSize) {
4684 if (type != VMOVModImm)
4686 // Any 1-byte value is OK. Op=0, Cmode=1110.
4687 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4690 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4694 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4695 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4696 if ((SplatBits & ~0xff) == 0) {
4697 // Value = 0x00nn: Op=x, Cmode=100x.
4702 if ((SplatBits & ~0xff00) == 0) {
4703 // Value = 0xnn00: Op=x, Cmode=101x.
4705 Imm = SplatBits >> 8;
4711 // NEON's 32-bit VMOV supports splat values where:
4712 // * only one byte is nonzero, or
4713 // * the least significant byte is 0xff and the second byte is nonzero, or
4714 // * the least significant 2 bytes are 0xff and the third is nonzero.
4715 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4716 if ((SplatBits & ~0xff) == 0) {
4717 // Value = 0x000000nn: Op=x, Cmode=000x.
4722 if ((SplatBits & ~0xff00) == 0) {
4723 // Value = 0x0000nn00: Op=x, Cmode=001x.
4725 Imm = SplatBits >> 8;
4728 if ((SplatBits & ~0xff0000) == 0) {
4729 // Value = 0x00nn0000: Op=x, Cmode=010x.
4731 Imm = SplatBits >> 16;
4734 if ((SplatBits & ~0xff000000) == 0) {
4735 // Value = 0xnn000000: Op=x, Cmode=011x.
4737 Imm = SplatBits >> 24;
4741 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4742 if (type == OtherModImm) return SDValue();
4744 if ((SplatBits & ~0xffff) == 0 &&
4745 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4746 // Value = 0x0000nnff: Op=x, Cmode=1100.
4748 Imm = SplatBits >> 8;
4752 if ((SplatBits & ~0xffffff) == 0 &&
4753 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4754 // Value = 0x00nnffff: Op=x, Cmode=1101.
4756 Imm = SplatBits >> 16;
4760 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4761 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4762 // VMOV.I32. A (very) minor optimization would be to replicate the value
4763 // and fall through here to test for a valid 64-bit splat. But, then the
4764 // caller would also need to check and handle the change in size.
4768 if (type != VMOVModImm)
4770 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4771 uint64_t BitMask = 0xff;
4773 unsigned ImmMask = 1;
4775 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4776 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4779 } else if ((SplatBits & BitMask) != 0) {
4786 if (DAG.getDataLayout().isBigEndian())
4787 // swap higher and lower 32 bit word
4788 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4790 // Op=1, Cmode=1110.
4792 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4797 llvm_unreachable("unexpected size for isNEONModifiedImm");
4800 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4801 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4804 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4805 const ARMSubtarget *ST) const {
4809 bool IsDouble = Op.getValueType() == MVT::f64;
4810 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4812 // Use the default (constant pool) lowering for double constants when we have
4814 if (IsDouble && Subtarget->isFPOnlySP())
4817 // Try splatting with a VMOV.f32...
4818 APFloat FPVal = CFP->getValueAPF();
4819 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4822 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4823 // We have code in place to select a valid ConstantFP already, no need to
4828 // It's a float and we are trying to use NEON operations where
4829 // possible. Lower it to a splat followed by an extract.
4831 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4832 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4834 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4835 DAG.getConstant(0, DL, MVT::i32));
4838 // The rest of our options are NEON only, make sure that's allowed before
4840 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4844 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4846 // It wouldn't really be worth bothering for doubles except for one very
4847 // important value, which does happen to match: 0.0. So make sure we don't do
4849 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4852 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4853 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4854 VMovVT, false, VMOVModImm);
4855 if (NewVal != SDValue()) {
4857 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4860 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4862 // It's a float: cast and extract a vector element.
4863 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4865 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4866 DAG.getConstant(0, DL, MVT::i32));
4869 // Finally, try a VMVN.i32
4870 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4872 if (NewVal != SDValue()) {
4874 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4877 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4879 // It's a float: cast and extract a vector element.
4880 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4883 DAG.getConstant(0, DL, MVT::i32));
4889 // check if an VEXT instruction can handle the shuffle mask when the
4890 // vector sources of the shuffle are the same.
4891 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4892 unsigned NumElts = VT.getVectorNumElements();
4894 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4900 // If this is a VEXT shuffle, the immediate value is the index of the first
4901 // element. The other shuffle indices must be the successive elements after
4903 unsigned ExpectedElt = Imm;
4904 for (unsigned i = 1; i < NumElts; ++i) {
4905 // Increment the expected index. If it wraps around, just follow it
4906 // back to index zero and keep going.
4908 if (ExpectedElt == NumElts)
4911 if (M[i] < 0) continue; // ignore UNDEF indices
4912 if (ExpectedElt != static_cast<unsigned>(M[i]))
4920 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4921 bool &ReverseVEXT, unsigned &Imm) {
4922 unsigned NumElts = VT.getVectorNumElements();
4923 ReverseVEXT = false;
4925 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4931 // If this is a VEXT shuffle, the immediate value is the index of the first
4932 // element. The other shuffle indices must be the successive elements after
4934 unsigned ExpectedElt = Imm;
4935 for (unsigned i = 1; i < NumElts; ++i) {
4936 // Increment the expected index. If it wraps around, it may still be
4937 // a VEXT but the source vectors must be swapped.
4939 if (ExpectedElt == NumElts * 2) {
4944 if (M[i] < 0) continue; // ignore UNDEF indices
4945 if (ExpectedElt != static_cast<unsigned>(M[i]))
4949 // Adjust the index value if the source operands will be swapped.
4956 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4957 /// instruction with the specified blocksize. (The order of the elements
4958 /// within each block of the vector is reversed.)
4959 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4960 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4961 "Only possible block sizes for VREV are: 16, 32, 64");
4963 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4967 unsigned NumElts = VT.getVectorNumElements();
4968 unsigned BlockElts = M[0] + 1;
4969 // If the first shuffle index is UNDEF, be optimistic.
4971 BlockElts = BlockSize / EltSz;
4973 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4976 for (unsigned i = 0; i < NumElts; ++i) {
4977 if (M[i] < 0) continue; // ignore UNDEF indices
4978 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4985 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4986 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4987 // range, then 0 is placed into the resulting vector. So pretty much any mask
4988 // of 8 elements can work here.
4989 return VT == MVT::v8i8 && M.size() == 8;
4992 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
4993 // checking that pairs of elements in the shuffle mask represent the same index
4994 // in each vector, incrementing the expected index by 2 at each step.
4995 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
4996 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
4998 // WhichResult gives the offset for each element in the mask based on which
4999 // of the two results it belongs to.
5001 // The transpose can be represented either as:
5002 // result1 = shufflevector v1, v2, result1_shuffle_mask
5003 // result2 = shufflevector v1, v2, result2_shuffle_mask
5004 // where v1/v2 and the shuffle masks have the same number of elements
5005 // (here WhichResult (see below) indicates which result is being checked)
5008 // results = shufflevector v1, v2, shuffle_mask
5009 // where both results are returned in one vector and the shuffle mask has twice
5010 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5011 // want to check the low half and high half of the shuffle mask as if it were
5013 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5014 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5018 unsigned NumElts = VT.getVectorNumElements();
5019 if (M.size() != NumElts && M.size() != NumElts*2)
5022 // If the mask is twice as long as the result then we need to check the upper
5023 // and lower parts of the mask
5024 for (unsigned i = 0; i < M.size(); i += NumElts) {
5025 WhichResult = M[i] == 0 ? 0 : 1;
5026 for (unsigned j = 0; j < NumElts; j += 2) {
5027 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5028 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5033 if (M.size() == NumElts*2)
5039 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5040 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5041 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5042 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5043 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5047 unsigned NumElts = VT.getVectorNumElements();
5048 if (M.size() != NumElts && M.size() != NumElts*2)
5051 for (unsigned i = 0; i < M.size(); i += NumElts) {
5052 WhichResult = M[i] == 0 ? 0 : 1;
5053 for (unsigned j = 0; j < NumElts; j += 2) {
5054 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5055 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5060 if (M.size() == NumElts*2)
5066 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5067 // that the mask elements are either all even and in steps of size 2 or all odd
5068 // and in steps of size 2.
5069 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5070 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5072 // Requires similar checks to that of isVTRNMask with
5073 // respect the how results are returned.
5074 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5075 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5079 unsigned NumElts = VT.getVectorNumElements();
5080 if (M.size() != NumElts && M.size() != NumElts*2)
5083 for (unsigned i = 0; i < M.size(); i += NumElts) {
5084 WhichResult = M[i] == 0 ? 0 : 1;
5085 for (unsigned j = 0; j < NumElts; ++j) {
5086 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5091 if (M.size() == NumElts*2)
5094 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5095 if (VT.is64BitVector() && EltSz == 32)
5101 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5102 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5103 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5104 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5105 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5109 unsigned NumElts = VT.getVectorNumElements();
5110 if (M.size() != NumElts && M.size() != NumElts*2)
5113 unsigned Half = NumElts / 2;
5114 for (unsigned i = 0; i < M.size(); i += NumElts) {
5115 WhichResult = M[i] == 0 ? 0 : 1;
5116 for (unsigned j = 0; j < NumElts; j += Half) {
5117 unsigned Idx = WhichResult;
5118 for (unsigned k = 0; k < Half; ++k) {
5119 int MIdx = M[i + j + k];
5120 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5127 if (M.size() == NumElts*2)
5130 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5131 if (VT.is64BitVector() && EltSz == 32)
5137 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5138 // that pairs of elements of the shufflemask represent the same index in each
5139 // vector incrementing sequentially through the vectors.
5140 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5141 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5143 // Requires similar checks to that of isVTRNMask with respect the how results
5145 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5146 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5150 unsigned NumElts = VT.getVectorNumElements();
5151 if (M.size() != NumElts && M.size() != NumElts*2)
5154 for (unsigned i = 0; i < M.size(); i += NumElts) {
5155 WhichResult = M[i] == 0 ? 0 : 1;
5156 unsigned Idx = WhichResult * NumElts / 2;
5157 for (unsigned j = 0; j < NumElts; j += 2) {
5158 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5159 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5165 if (M.size() == NumElts*2)
5168 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5169 if (VT.is64BitVector() && EltSz == 32)
5175 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5176 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5177 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5178 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5179 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5183 unsigned NumElts = VT.getVectorNumElements();
5184 if (M.size() != NumElts && M.size() != NumElts*2)
5187 for (unsigned i = 0; i < M.size(); i += NumElts) {
5188 WhichResult = M[i] == 0 ? 0 : 1;
5189 unsigned Idx = WhichResult * NumElts / 2;
5190 for (unsigned j = 0; j < NumElts; j += 2) {
5191 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5192 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5198 if (M.size() == NumElts*2)
5201 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5202 if (VT.is64BitVector() && EltSz == 32)
5208 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5209 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5210 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5211 unsigned &WhichResult,
5214 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5215 return ARMISD::VTRN;
5216 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5217 return ARMISD::VUZP;
5218 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5219 return ARMISD::VZIP;
5222 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5223 return ARMISD::VTRN;
5224 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5225 return ARMISD::VUZP;
5226 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5227 return ARMISD::VZIP;
5232 /// \return true if this is a reverse operation on an vector.
5233 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5234 unsigned NumElts = VT.getVectorNumElements();
5235 // Make sure the mask has the right size.
5236 if (NumElts != M.size())
5239 // Look for <15, ..., 3, -1, 1, 0>.
5240 for (unsigned i = 0; i != NumElts; ++i)
5241 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5247 // If N is an integer constant that can be moved into a register in one
5248 // instruction, return an SDValue of such a constant (will become a MOV
5249 // instruction). Otherwise return null.
5250 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5251 const ARMSubtarget *ST, SDLoc dl) {
5253 if (!isa<ConstantSDNode>(N))
5255 Val = cast<ConstantSDNode>(N)->getZExtValue();
5257 if (ST->isThumb1Only()) {
5258 if (Val <= 255 || ~Val <= 255)
5259 return DAG.getConstant(Val, dl, MVT::i32);
5261 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5262 return DAG.getConstant(Val, dl, MVT::i32);
5267 // If this is a case we can't handle, return null and let the default
5268 // expansion code take care of it.
5269 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5270 const ARMSubtarget *ST) const {
5271 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5273 EVT VT = Op.getValueType();
5275 APInt SplatBits, SplatUndef;
5276 unsigned SplatBitSize;
5278 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5279 if (SplatBitSize <= 64) {
5280 // Check if an immediate VMOV works.
5282 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5283 SplatUndef.getZExtValue(), SplatBitSize,
5284 DAG, dl, VmovVT, VT.is128BitVector(),
5286 if (Val.getNode()) {
5287 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5288 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5291 // Try an immediate VMVN.
5292 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5293 Val = isNEONModifiedImm(NegatedImm,
5294 SplatUndef.getZExtValue(), SplatBitSize,
5295 DAG, dl, VmovVT, VT.is128BitVector(),
5297 if (Val.getNode()) {
5298 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5299 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5302 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5303 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5304 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5306 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5307 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5313 // Scan through the operands to see if only one value is used.
5315 // As an optimisation, even if more than one value is used it may be more
5316 // profitable to splat with one value then change some lanes.
5318 // Heuristically we decide to do this if the vector has a "dominant" value,
5319 // defined as splatted to more than half of the lanes.
5320 unsigned NumElts = VT.getVectorNumElements();
5321 bool isOnlyLowElement = true;
5322 bool usesOnlyOneValue = true;
5323 bool hasDominantValue = false;
5324 bool isConstant = true;
5326 // Map of the number of times a particular SDValue appears in the
5328 DenseMap<SDValue, unsigned> ValueCounts;
5330 for (unsigned i = 0; i < NumElts; ++i) {
5331 SDValue V = Op.getOperand(i);
5332 if (V.getOpcode() == ISD::UNDEF)
5335 isOnlyLowElement = false;
5336 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5339 ValueCounts.insert(std::make_pair(V, 0));
5340 unsigned &Count = ValueCounts[V];
5342 // Is this value dominant? (takes up more than half of the lanes)
5343 if (++Count > (NumElts / 2)) {
5344 hasDominantValue = true;
5348 if (ValueCounts.size() != 1)
5349 usesOnlyOneValue = false;
5350 if (!Value.getNode() && ValueCounts.size() > 0)
5351 Value = ValueCounts.begin()->first;
5353 if (ValueCounts.size() == 0)
5354 return DAG.getUNDEF(VT);
5356 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5357 // Keep going if we are hitting this case.
5358 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5359 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5361 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5363 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5364 // i32 and try again.
5365 if (hasDominantValue && EltSize <= 32) {
5369 // If we are VDUPing a value that comes directly from a vector, that will
5370 // cause an unnecessary move to and from a GPR, where instead we could
5371 // just use VDUPLANE. We can only do this if the lane being extracted
5372 // is at a constant index, as the VDUP from lane instructions only have
5373 // constant-index forms.
5374 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5375 isa<ConstantSDNode>(Value->getOperand(1))) {
5376 // We need to create a new undef vector to use for the VDUPLANE if the
5377 // size of the vector from which we get the value is different than the
5378 // size of the vector that we need to create. We will insert the element
5379 // such that the register coalescer will remove unnecessary copies.
5380 if (VT != Value->getOperand(0).getValueType()) {
5381 ConstantSDNode *constIndex;
5382 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5383 assert(constIndex && "The index is not a constant!");
5384 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5385 VT.getVectorNumElements();
5386 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5387 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5388 Value, DAG.getConstant(index, dl, MVT::i32)),
5389 DAG.getConstant(index, dl, MVT::i32));
5391 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5392 Value->getOperand(0), Value->getOperand(1));
5394 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5396 if (!usesOnlyOneValue) {
5397 // The dominant value was splatted as 'N', but we now have to insert
5398 // all differing elements.
5399 for (unsigned I = 0; I < NumElts; ++I) {
5400 if (Op.getOperand(I) == Value)
5402 SmallVector<SDValue, 3> Ops;
5404 Ops.push_back(Op.getOperand(I));
5405 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5406 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5411 if (VT.getVectorElementType().isFloatingPoint()) {
5412 SmallVector<SDValue, 8> Ops;
5413 for (unsigned i = 0; i < NumElts; ++i)
5414 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5416 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5417 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5418 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5420 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5422 if (usesOnlyOneValue) {
5423 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5424 if (isConstant && Val.getNode())
5425 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5429 // If all elements are constants and the case above didn't get hit, fall back
5430 // to the default expansion, which will generate a load from the constant
5435 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5437 SDValue shuffle = ReconstructShuffle(Op, DAG);
5438 if (shuffle != SDValue())
5442 // Vectors with 32- or 64-bit elements can be built by directly assigning
5443 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5444 // will be legalized.
5445 if (EltSize >= 32) {
5446 // Do the expansion with floating-point types, since that is what the VFP
5447 // registers are defined to use, and since i64 is not legal.
5448 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5449 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5450 SmallVector<SDValue, 8> Ops;
5451 for (unsigned i = 0; i < NumElts; ++i)
5452 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5453 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5454 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5457 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5458 // know the default expansion would otherwise fall back on something even
5459 // worse. For a vector with one or two non-undef values, that's
5460 // scalar_to_vector for the elements followed by a shuffle (provided the
5461 // shuffle is valid for the target) and materialization element by element
5462 // on the stack followed by a load for everything else.
5463 if (!isConstant && !usesOnlyOneValue) {
5464 SDValue Vec = DAG.getUNDEF(VT);
5465 for (unsigned i = 0 ; i < NumElts; ++i) {
5466 SDValue V = Op.getOperand(i);
5467 if (V.getOpcode() == ISD::UNDEF)
5469 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5470 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5478 /// getExtFactor - Determine the adjustment factor for the position when
5479 /// generating an "extract from vector registers" instruction.
5480 static unsigned getExtFactor(SDValue &V) {
5481 EVT EltType = V.getValueType().getVectorElementType();
5482 return EltType.getSizeInBits() / 8;
5485 // Gather data to see if the operation can be modelled as a
5486 // shuffle in combination with VEXTs.
5487 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5488 SelectionDAG &DAG) const {
5489 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5491 EVT VT = Op.getValueType();
5492 unsigned NumElts = VT.getVectorNumElements();
5494 struct ShuffleSourceInfo {
5499 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5500 // be compatible with the shuffle we intend to construct. As a result
5501 // ShuffleVec will be some sliding window into the original Vec.
5504 // Code should guarantee that element i in Vec starts at element "WindowBase
5505 // + i * WindowScale in ShuffleVec".
5509 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5510 ShuffleSourceInfo(SDValue Vec)
5511 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5515 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5517 SmallVector<ShuffleSourceInfo, 2> Sources;
5518 for (unsigned i = 0; i < NumElts; ++i) {
5519 SDValue V = Op.getOperand(i);
5520 if (V.getOpcode() == ISD::UNDEF)
5522 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5523 // A shuffle can only come from building a vector from various
5524 // elements of other vectors.
5528 // Add this element source to the list if it's not already there.
5529 SDValue SourceVec = V.getOperand(0);
5530 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5531 if (Source == Sources.end())
5532 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5534 // Update the minimum and maximum lane number seen.
5535 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5536 Source->MinElt = std::min(Source->MinElt, EltNo);
5537 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5540 // Currently only do something sane when at most two source vectors
5542 if (Sources.size() > 2)
5545 // Find out the smallest element size among result and two sources, and use
5546 // it as element size to build the shuffle_vector.
5547 EVT SmallestEltTy = VT.getVectorElementType();
5548 for (auto &Source : Sources) {
5549 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5550 if (SrcEltTy.bitsLT(SmallestEltTy))
5551 SmallestEltTy = SrcEltTy;
5553 unsigned ResMultiplier =
5554 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5555 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5556 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5558 // If the source vector is too wide or too narrow, we may nevertheless be able
5559 // to construct a compatible shuffle either by concatenating it with UNDEF or
5560 // extracting a suitable range of elements.
5561 for (auto &Src : Sources) {
5562 EVT SrcVT = Src.ShuffleVec.getValueType();
5564 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5567 // This stage of the search produces a source with the same element type as
5568 // the original, but with a total width matching the BUILD_VECTOR output.
5569 EVT EltVT = SrcVT.getVectorElementType();
5570 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5571 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5573 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5574 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5576 // We can pad out the smaller vector for free, so if it's part of a
5579 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5580 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5584 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5587 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5588 // Span too large for a VEXT to cope
5592 if (Src.MinElt >= NumSrcElts) {
5593 // The extraction can just take the second half
5595 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5596 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5597 Src.WindowBase = -NumSrcElts;
5598 } else if (Src.MaxElt < NumSrcElts) {
5599 // The extraction can just take the first half
5601 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5602 DAG.getConstant(0, dl, MVT::i32));
5604 // An actual VEXT is needed
5606 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5607 DAG.getConstant(0, dl, MVT::i32));
5609 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5610 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5611 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5613 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5615 DAG.getConstant(Imm, dl, MVT::i32));
5616 Src.WindowBase = -Src.MinElt;
5620 // Another possible incompatibility occurs from the vector element types. We
5621 // can fix this by bitcasting the source vectors to the same type we intend
5623 for (auto &Src : Sources) {
5624 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5625 if (SrcEltTy == SmallestEltTy)
5627 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5628 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5629 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5630 Src.WindowBase *= Src.WindowScale;
5633 // Final sanity check before we try to actually produce a shuffle.
5635 for (auto Src : Sources)
5636 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5639 // The stars all align, our next step is to produce the mask for the shuffle.
5640 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5641 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5642 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5643 SDValue Entry = Op.getOperand(i);
5644 if (Entry.getOpcode() == ISD::UNDEF)
5647 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5648 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5650 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5651 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5653 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5654 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5655 VT.getVectorElementType().getSizeInBits());
5656 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5658 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5659 // starting at the appropriate offset.
5660 int *LaneMask = &Mask[i * ResMultiplier];
5662 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5663 ExtractBase += NumElts * (Src - Sources.begin());
5664 for (int j = 0; j < LanesDefined; ++j)
5665 LaneMask[j] = ExtractBase + j;
5668 // Final check before we try to produce nonsense...
5669 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5672 // We can't handle more than two sources. This should have already
5673 // been checked before this point.
5674 assert(Sources.size() <= 2 && "Too many sources!");
5676 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5677 for (unsigned i = 0; i < Sources.size(); ++i)
5678 ShuffleOps[i] = Sources[i].ShuffleVec;
5680 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5681 ShuffleOps[1], &Mask[0]);
5682 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5685 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5686 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5687 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5688 /// are assumed to be legal.
5690 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5692 if (VT.getVectorNumElements() == 4 &&
5693 (VT.is128BitVector() || VT.is64BitVector())) {
5694 unsigned PFIndexes[4];
5695 for (unsigned i = 0; i != 4; ++i) {
5699 PFIndexes[i] = M[i];
5702 // Compute the index in the perfect shuffle table.
5703 unsigned PFTableIndex =
5704 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5705 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5706 unsigned Cost = (PFEntry >> 30);
5712 bool ReverseVEXT, isV_UNDEF;
5713 unsigned Imm, WhichResult;
5715 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5716 return (EltSize >= 32 ||
5717 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5718 isVREVMask(M, VT, 64) ||
5719 isVREVMask(M, VT, 32) ||
5720 isVREVMask(M, VT, 16) ||
5721 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5722 isVTBLMask(M, VT) ||
5723 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5724 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5727 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5728 /// the specified operations to build the shuffle.
5729 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5730 SDValue RHS, SelectionDAG &DAG,
5732 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5733 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5734 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5737 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5746 OP_VUZPL, // VUZP, left result
5747 OP_VUZPR, // VUZP, right result
5748 OP_VZIPL, // VZIP, left result
5749 OP_VZIPR, // VZIP, right result
5750 OP_VTRNL, // VTRN, left result
5751 OP_VTRNR // VTRN, right result
5754 if (OpNum == OP_COPY) {
5755 if (LHSID == (1*9+2)*9+3) return LHS;
5756 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5760 SDValue OpLHS, OpRHS;
5761 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5762 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5763 EVT VT = OpLHS.getValueType();
5766 default: llvm_unreachable("Unknown shuffle opcode!");
5768 // VREV divides the vector in half and swaps within the half.
5769 if (VT.getVectorElementType() == MVT::i32 ||
5770 VT.getVectorElementType() == MVT::f32)
5771 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5772 // vrev <4 x i16> -> VREV32
5773 if (VT.getVectorElementType() == MVT::i16)
5774 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5775 // vrev <4 x i8> -> VREV16
5776 assert(VT.getVectorElementType() == MVT::i8);
5777 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5782 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5783 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5787 return DAG.getNode(ARMISD::VEXT, dl, VT,
5789 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5792 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5793 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5796 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5797 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5800 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5801 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5805 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5806 ArrayRef<int> ShuffleMask,
5807 SelectionDAG &DAG) {
5808 // Check to see if we can use the VTBL instruction.
5809 SDValue V1 = Op.getOperand(0);
5810 SDValue V2 = Op.getOperand(1);
5813 SmallVector<SDValue, 8> VTBLMask;
5814 for (ArrayRef<int>::iterator
5815 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5816 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5818 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5819 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5820 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5822 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5823 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5826 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5827 SelectionDAG &DAG) {
5829 SDValue OpLHS = Op.getOperand(0);
5830 EVT VT = OpLHS.getValueType();
5832 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5833 "Expect an v8i16/v16i8 type");
5834 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5835 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5836 // extract the first 8 bytes into the top double word and the last 8 bytes
5837 // into the bottom double word. The v8i16 case is similar.
5838 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5839 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5840 DAG.getConstant(ExtractNum, DL, MVT::i32));
5843 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5844 SDValue V1 = Op.getOperand(0);
5845 SDValue V2 = Op.getOperand(1);
5847 EVT VT = Op.getValueType();
5848 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5850 // Convert shuffles that are directly supported on NEON to target-specific
5851 // DAG nodes, instead of keeping them as shuffles and matching them again
5852 // during code selection. This is more efficient and avoids the possibility
5853 // of inconsistencies between legalization and selection.
5854 // FIXME: floating-point vectors should be canonicalized to integer vectors
5855 // of the same time so that they get CSEd properly.
5856 ArrayRef<int> ShuffleMask = SVN->getMask();
5858 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5859 if (EltSize <= 32) {
5860 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5861 int Lane = SVN->getSplatIndex();
5862 // If this is undef splat, generate it via "just" vdup, if possible.
5863 if (Lane == -1) Lane = 0;
5865 // Test if V1 is a SCALAR_TO_VECTOR.
5866 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5867 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5869 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5870 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5872 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5873 !isa<ConstantSDNode>(V1.getOperand(0))) {
5874 bool IsScalarToVector = true;
5875 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5876 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5877 IsScalarToVector = false;
5880 if (IsScalarToVector)
5881 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5883 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5884 DAG.getConstant(Lane, dl, MVT::i32));
5889 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5892 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5893 DAG.getConstant(Imm, dl, MVT::i32));
5896 if (isVREVMask(ShuffleMask, VT, 64))
5897 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5898 if (isVREVMask(ShuffleMask, VT, 32))
5899 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5900 if (isVREVMask(ShuffleMask, VT, 16))
5901 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5903 if (V2->getOpcode() == ISD::UNDEF &&
5904 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5905 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5906 DAG.getConstant(Imm, dl, MVT::i32));
5909 // Check for Neon shuffles that modify both input vectors in place.
5910 // If both results are used, i.e., if there are two shuffles with the same
5911 // source operands and with masks corresponding to both results of one of
5912 // these operations, DAG memoization will ensure that a single node is
5913 // used for both shuffles.
5914 unsigned WhichResult;
5916 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5917 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5920 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5921 .getValue(WhichResult);
5924 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5925 // shuffles that produce a result larger than their operands with:
5926 // shuffle(concat(v1, undef), concat(v2, undef))
5928 // shuffle(concat(v1, v2), undef)
5929 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5931 // This is useful in the general case, but there are special cases where
5932 // native shuffles produce larger results: the two-result ops.
5934 // Look through the concat when lowering them:
5935 // shuffle(concat(v1, v2), undef)
5937 // concat(VZIP(v1, v2):0, :1)
5939 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5940 V2->getOpcode() == ISD::UNDEF) {
5941 SDValue SubV1 = V1->getOperand(0);
5942 SDValue SubV2 = V1->getOperand(1);
5943 EVT SubVT = SubV1.getValueType();
5945 // We expect these to have been canonicalized to -1.
5946 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5947 return i < (int)VT.getVectorNumElements();
5948 }) && "Unexpected shuffle index into UNDEF operand!");
5950 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5951 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5954 assert((WhichResult == 0) &&
5955 "In-place shuffle of concat can only have one result!");
5956 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5958 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5964 // If the shuffle is not directly supported and it has 4 elements, use
5965 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5966 unsigned NumElts = VT.getVectorNumElements();
5968 unsigned PFIndexes[4];
5969 for (unsigned i = 0; i != 4; ++i) {
5970 if (ShuffleMask[i] < 0)
5973 PFIndexes[i] = ShuffleMask[i];
5976 // Compute the index in the perfect shuffle table.
5977 unsigned PFTableIndex =
5978 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5979 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5980 unsigned Cost = (PFEntry >> 30);
5983 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5986 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5987 if (EltSize >= 32) {
5988 // Do the expansion with floating-point types, since that is what the VFP
5989 // registers are defined to use, and since i64 is not legal.
5990 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5991 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5992 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5993 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5994 SmallVector<SDValue, 8> Ops;
5995 for (unsigned i = 0; i < NumElts; ++i) {
5996 if (ShuffleMask[i] < 0)
5997 Ops.push_back(DAG.getUNDEF(EltVT));
5999 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6000 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6001 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6004 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6005 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6008 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6009 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6011 if (VT == MVT::v8i8) {
6012 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6013 if (NewOp.getNode())
6020 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6021 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6022 SDValue Lane = Op.getOperand(2);
6023 if (!isa<ConstantSDNode>(Lane))
6029 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6030 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6031 SDValue Lane = Op.getOperand(1);
6032 if (!isa<ConstantSDNode>(Lane))
6035 SDValue Vec = Op.getOperand(0);
6036 if (Op.getValueType() == MVT::i32 &&
6037 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6039 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6045 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6046 // The only time a CONCAT_VECTORS operation can have legal types is when
6047 // two 64-bit vectors are concatenated to a 128-bit vector.
6048 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6049 "unexpected CONCAT_VECTORS");
6051 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6052 SDValue Op0 = Op.getOperand(0);
6053 SDValue Op1 = Op.getOperand(1);
6054 if (Op0.getOpcode() != ISD::UNDEF)
6055 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6056 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6057 DAG.getIntPtrConstant(0, dl));
6058 if (Op1.getOpcode() != ISD::UNDEF)
6059 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6060 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6061 DAG.getIntPtrConstant(1, dl));
6062 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6065 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6066 /// element has been zero/sign-extended, depending on the isSigned parameter,
6067 /// from an integer type half its size.
6068 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6070 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6071 EVT VT = N->getValueType(0);
6072 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6073 SDNode *BVN = N->getOperand(0).getNode();
6074 if (BVN->getValueType(0) != MVT::v4i32 ||
6075 BVN->getOpcode() != ISD::BUILD_VECTOR)
6077 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6078 unsigned HiElt = 1 - LoElt;
6079 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6080 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6081 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6082 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6083 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6086 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6087 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6090 if (Hi0->isNullValue() && Hi1->isNullValue())
6096 if (N->getOpcode() != ISD::BUILD_VECTOR)
6099 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6100 SDNode *Elt = N->getOperand(i).getNode();
6101 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6102 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6103 unsigned HalfSize = EltSize / 2;
6105 if (!isIntN(HalfSize, C->getSExtValue()))
6108 if (!isUIntN(HalfSize, C->getZExtValue()))
6119 /// isSignExtended - Check if a node is a vector value that is sign-extended
6120 /// or a constant BUILD_VECTOR with sign-extended elements.
6121 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6122 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6124 if (isExtendedBUILD_VECTOR(N, DAG, true))
6129 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6130 /// or a constant BUILD_VECTOR with zero-extended elements.
6131 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6132 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6134 if (isExtendedBUILD_VECTOR(N, DAG, false))
6139 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6140 if (OrigVT.getSizeInBits() >= 64)
6143 assert(OrigVT.isSimple() && "Expecting a simple value type");
6145 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6146 switch (OrigSimpleTy) {
6147 default: llvm_unreachable("Unexpected Vector Type");
6156 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6157 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6158 /// We insert the required extension here to get the vector to fill a D register.
6159 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6162 unsigned ExtOpcode) {
6163 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6164 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6165 // 64-bits we need to insert a new extension so that it will be 64-bits.
6166 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6167 if (OrigTy.getSizeInBits() >= 64)
6170 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6171 EVT NewVT = getExtensionTo64Bits(OrigTy);
6173 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6176 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6177 /// does not do any sign/zero extension. If the original vector is less
6178 /// than 64 bits, an appropriate extension will be added after the load to
6179 /// reach a total size of 64 bits. We have to add the extension separately
6180 /// because ARM does not have a sign/zero extending load for vectors.
6181 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6182 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6184 // The load already has the right type.
6185 if (ExtendedTy == LD->getMemoryVT())
6186 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6187 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6188 LD->isNonTemporal(), LD->isInvariant(),
6189 LD->getAlignment());
6191 // We need to create a zextload/sextload. We cannot just create a load
6192 // followed by a zext/zext node because LowerMUL is also run during normal
6193 // operation legalization where we can't create illegal types.
6194 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6195 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6196 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6197 LD->isNonTemporal(), LD->getAlignment());
6200 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6201 /// extending load, or BUILD_VECTOR with extended elements, return the
6202 /// unextended value. The unextended vector should be 64 bits so that it can
6203 /// be used as an operand to a VMULL instruction. If the original vector size
6204 /// before extension is less than 64 bits we add a an extension to resize
6205 /// the vector to 64 bits.
6206 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6207 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6208 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6209 N->getOperand(0)->getValueType(0),
6213 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6214 return SkipLoadExtensionForVMULL(LD, DAG);
6216 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6217 // have been legalized as a BITCAST from v4i32.
6218 if (N->getOpcode() == ISD::BITCAST) {
6219 SDNode *BVN = N->getOperand(0).getNode();
6220 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6221 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6222 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6223 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6224 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6226 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6227 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6228 EVT VT = N->getValueType(0);
6229 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6230 unsigned NumElts = VT.getVectorNumElements();
6231 MVT TruncVT = MVT::getIntegerVT(EltSize);
6232 SmallVector<SDValue, 8> Ops;
6234 for (unsigned i = 0; i != NumElts; ++i) {
6235 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6236 const APInt &CInt = C->getAPIntValue();
6237 // Element types smaller than 32 bits are not legal, so use i32 elements.
6238 // The values are implicitly truncated so sext vs. zext doesn't matter.
6239 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6241 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6242 MVT::getVectorVT(TruncVT, NumElts), Ops);
6245 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6246 unsigned Opcode = N->getOpcode();
6247 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6248 SDNode *N0 = N->getOperand(0).getNode();
6249 SDNode *N1 = N->getOperand(1).getNode();
6250 return N0->hasOneUse() && N1->hasOneUse() &&
6251 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6256 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6257 unsigned Opcode = N->getOpcode();
6258 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6259 SDNode *N0 = N->getOperand(0).getNode();
6260 SDNode *N1 = N->getOperand(1).getNode();
6261 return N0->hasOneUse() && N1->hasOneUse() &&
6262 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6267 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6268 // Multiplications are only custom-lowered for 128-bit vectors so that
6269 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6270 EVT VT = Op.getValueType();
6271 assert(VT.is128BitVector() && VT.isInteger() &&
6272 "unexpected type for custom-lowering ISD::MUL");
6273 SDNode *N0 = Op.getOperand(0).getNode();
6274 SDNode *N1 = Op.getOperand(1).getNode();
6275 unsigned NewOpc = 0;
6277 bool isN0SExt = isSignExtended(N0, DAG);
6278 bool isN1SExt = isSignExtended(N1, DAG);
6279 if (isN0SExt && isN1SExt)
6280 NewOpc = ARMISD::VMULLs;
6282 bool isN0ZExt = isZeroExtended(N0, DAG);
6283 bool isN1ZExt = isZeroExtended(N1, DAG);
6284 if (isN0ZExt && isN1ZExt)
6285 NewOpc = ARMISD::VMULLu;
6286 else if (isN1SExt || isN1ZExt) {
6287 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6288 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6289 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6290 NewOpc = ARMISD::VMULLs;
6292 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6293 NewOpc = ARMISD::VMULLu;
6295 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6297 NewOpc = ARMISD::VMULLu;
6303 if (VT == MVT::v2i64)
6304 // Fall through to expand this. It is not legal.
6307 // Other vector multiplications are legal.
6312 // Legalize to a VMULL instruction.
6315 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6317 Op0 = SkipExtensionForVMULL(N0, DAG);
6318 assert(Op0.getValueType().is64BitVector() &&
6319 Op1.getValueType().is64BitVector() &&
6320 "unexpected types for extended operands to VMULL");
6321 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6324 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6325 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6332 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6333 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6334 EVT Op1VT = Op1.getValueType();
6335 return DAG.getNode(N0->getOpcode(), DL, VT,
6336 DAG.getNode(NewOpc, DL, VT,
6337 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6338 DAG.getNode(NewOpc, DL, VT,
6339 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6343 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6345 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6346 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6347 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6348 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6349 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6350 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6351 // Get reciprocal estimate.
6352 // float4 recip = vrecpeq_f32(yf);
6353 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6354 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6356 // Because char has a smaller range than uchar, we can actually get away
6357 // without any newton steps. This requires that we use a weird bias
6358 // of 0xb000, however (again, this has been exhaustively tested).
6359 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6360 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6361 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6362 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6363 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6364 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6365 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6366 // Convert back to short.
6367 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6368 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6373 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6375 // Convert to float.
6376 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6377 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6378 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6379 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6380 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6381 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6383 // Use reciprocal estimate and one refinement step.
6384 // float4 recip = vrecpeq_f32(yf);
6385 // recip *= vrecpsq_f32(yf, recip);
6386 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6387 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6389 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6390 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6392 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6393 // Because short has a smaller range than ushort, we can actually get away
6394 // with only a single newton step. This requires that we use a weird bias
6395 // of 89, however (again, this has been exhaustively tested).
6396 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6397 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6398 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6399 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6400 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6401 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6402 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6403 // Convert back to integer and return.
6404 // return vmovn_s32(vcvt_s32_f32(result));
6405 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6406 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6410 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6411 EVT VT = Op.getValueType();
6412 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6413 "unexpected type for custom-lowering ISD::SDIV");
6416 SDValue N0 = Op.getOperand(0);
6417 SDValue N1 = Op.getOperand(1);
6420 if (VT == MVT::v8i8) {
6421 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6422 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6424 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6425 DAG.getIntPtrConstant(4, dl));
6426 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6427 DAG.getIntPtrConstant(4, dl));
6428 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6429 DAG.getIntPtrConstant(0, dl));
6430 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6431 DAG.getIntPtrConstant(0, dl));
6433 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6434 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6436 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6437 N0 = LowerCONCAT_VECTORS(N0, DAG);
6439 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6442 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6445 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6446 EVT VT = Op.getValueType();
6447 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6448 "unexpected type for custom-lowering ISD::UDIV");
6451 SDValue N0 = Op.getOperand(0);
6452 SDValue N1 = Op.getOperand(1);
6455 if (VT == MVT::v8i8) {
6456 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6457 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6459 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6460 DAG.getIntPtrConstant(4, dl));
6461 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6462 DAG.getIntPtrConstant(4, dl));
6463 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6464 DAG.getIntPtrConstant(0, dl));
6465 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6466 DAG.getIntPtrConstant(0, dl));
6468 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6469 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6471 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6472 N0 = LowerCONCAT_VECTORS(N0, DAG);
6474 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6475 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6481 // v4i16 sdiv ... Convert to float.
6482 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6483 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6484 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6485 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6486 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6487 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6489 // Use reciprocal estimate and two refinement steps.
6490 // float4 recip = vrecpeq_f32(yf);
6491 // recip *= vrecpsq_f32(yf, recip);
6492 // recip *= vrecpsq_f32(yf, recip);
6493 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6494 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6496 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6497 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6499 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6500 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6501 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6503 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6504 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6505 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6506 // and that it will never cause us to return an answer too large).
6507 // float4 result = as_float4(as_int4(xf*recip) + 2);
6508 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6509 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6510 N1 = DAG.getConstant(2, dl, MVT::i32);
6511 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6512 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6513 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6514 // Convert back to integer and return.
6515 // return vmovn_u32(vcvt_s32_f32(result));
6516 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6517 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6521 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6522 EVT VT = Op.getNode()->getValueType(0);
6523 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6526 bool ExtraOp = false;
6527 switch (Op.getOpcode()) {
6528 default: llvm_unreachable("Invalid code");
6529 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6530 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6531 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6532 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6536 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6538 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6539 Op.getOperand(1), Op.getOperand(2));
6542 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6543 assert(Subtarget->isTargetDarwin());
6545 // For iOS, we want to call an alternative entry point: __sincos_stret,
6546 // return values are passed via sret.
6548 SDValue Arg = Op.getOperand(0);
6549 EVT ArgVT = Arg.getValueType();
6550 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6551 auto PtrVT = getPointerTy(DAG.getDataLayout());
6553 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6555 // Pair of floats / doubles used to pass the result.
6556 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6558 // Create stack object for sret.
6559 auto &DL = DAG.getDataLayout();
6560 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6561 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6562 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6563 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6569 Entry.Ty = RetTy->getPointerTo();
6570 Entry.isSExt = false;
6571 Entry.isZExt = false;
6572 Entry.isSRet = true;
6573 Args.push_back(Entry);
6577 Entry.isSExt = false;
6578 Entry.isZExt = false;
6579 Args.push_back(Entry);
6581 const char *LibcallName = (ArgVT == MVT::f64)
6582 ? "__sincos_stret" : "__sincosf_stret";
6583 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6585 TargetLowering::CallLoweringInfo CLI(DAG);
6586 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6587 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6589 .setDiscardResult();
6591 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6593 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6594 MachinePointerInfo(), false, false, false, 0);
6596 // Address of cos field.
6597 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6598 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6599 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6600 MachinePointerInfo(), false, false, false, 0);
6602 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6603 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6604 LoadSin.getValue(0), LoadCos.getValue(0));
6607 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6608 // Monotonic load/store is legal for all targets
6609 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6612 // Acquire/Release load/store is not legal for targets without a
6613 // dmb or equivalent available.
6617 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6618 SmallVectorImpl<SDValue> &Results,
6620 const ARMSubtarget *Subtarget) {
6622 SDValue Cycles32, OutChain;
6624 if (Subtarget->hasPerfMon()) {
6625 // Under Power Management extensions, the cycle-count is:
6626 // mrc p15, #0, <Rt>, c9, c13, #0
6627 SDValue Ops[] = { N->getOperand(0), // Chain
6628 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6629 DAG.getConstant(15, DL, MVT::i32),
6630 DAG.getConstant(0, DL, MVT::i32),
6631 DAG.getConstant(9, DL, MVT::i32),
6632 DAG.getConstant(13, DL, MVT::i32),
6633 DAG.getConstant(0, DL, MVT::i32)
6636 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6637 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6638 OutChain = Cycles32.getValue(1);
6640 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6641 // there are older ARM CPUs that have implementation-specific ways of
6642 // obtaining this information (FIXME!).
6643 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6644 OutChain = DAG.getEntryNode();
6648 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6649 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6650 Results.push_back(Cycles64);
6651 Results.push_back(OutChain);
6654 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6655 switch (Op.getOpcode()) {
6656 default: llvm_unreachable("Don't know how to custom lower this!");
6657 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6658 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6659 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6660 case ISD::GlobalAddress:
6661 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6662 default: llvm_unreachable("unknown object format");
6664 return LowerGlobalAddressWindows(Op, DAG);
6666 return LowerGlobalAddressELF(Op, DAG);
6668 return LowerGlobalAddressDarwin(Op, DAG);
6670 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6671 case ISD::SELECT: return LowerSELECT(Op, DAG);
6672 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6673 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6674 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6675 case ISD::VASTART: return LowerVASTART(Op, DAG);
6676 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6677 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6678 case ISD::SINT_TO_FP:
6679 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6680 case ISD::FP_TO_SINT:
6681 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6682 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6683 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6684 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6685 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6686 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6687 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6688 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6689 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6691 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6694 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6695 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6696 case ISD::SRL_PARTS:
6697 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6699 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6700 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6701 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6702 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6703 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6704 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6705 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6706 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6707 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6708 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6709 case ISD::MUL: return LowerMUL(Op, DAG);
6710 case ISD::SDIV: return LowerSDIV(Op, DAG);
6711 case ISD::UDIV: return LowerUDIV(Op, DAG);
6715 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6720 return LowerXALUO(Op, DAG);
6721 case ISD::ATOMIC_LOAD:
6722 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6723 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6725 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6726 case ISD::DYNAMIC_STACKALLOC:
6727 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6728 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6729 llvm_unreachable("Don't know how to custom lower this!");
6730 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6731 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6735 /// ReplaceNodeResults - Replace the results of node with an illegal result
6736 /// type with new values built out of custom code.
6737 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6738 SmallVectorImpl<SDValue>&Results,
6739 SelectionDAG &DAG) const {
6741 switch (N->getOpcode()) {
6743 llvm_unreachable("Don't know how to custom expand this!");
6744 case ISD::READ_REGISTER:
6745 ExpandREAD_REGISTER(N, Results, DAG);
6748 Res = ExpandBITCAST(N, DAG);
6752 Res = Expand64BitShift(N, DAG, Subtarget);
6754 case ISD::READCYCLECOUNTER:
6755 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6759 Results.push_back(Res);
6762 //===----------------------------------------------------------------------===//
6763 // ARM Scheduler Hooks
6764 //===----------------------------------------------------------------------===//
6766 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6767 /// registers the function context.
6768 void ARMTargetLowering::
6769 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6770 MachineBasicBlock *DispatchBB, int FI) const {
6771 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6772 DebugLoc dl = MI->getDebugLoc();
6773 MachineFunction *MF = MBB->getParent();
6774 MachineRegisterInfo *MRI = &MF->getRegInfo();
6775 MachineConstantPool *MCP = MF->getConstantPool();
6776 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6777 const Function *F = MF->getFunction();
6779 bool isThumb = Subtarget->isThumb();
6780 bool isThumb2 = Subtarget->isThumb2();
6782 unsigned PCLabelId = AFI->createPICLabelUId();
6783 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6784 ARMConstantPoolValue *CPV =
6785 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6786 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6788 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6789 : &ARM::GPRRegClass;
6791 // Grab constant pool and fixed stack memory operands.
6792 MachineMemOperand *CPMMO =
6793 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6794 MachineMemOperand::MOLoad, 4, 4);
6796 MachineMemOperand *FIMMOSt =
6797 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6798 MachineMemOperand::MOStore, 4, 4);
6800 // Load the address of the dispatch MBB into the jump buffer.
6802 // Incoming value: jbuf
6803 // ldr.n r5, LCPI1_1
6806 // str r5, [$jbuf, #+4] ; &jbuf[1]
6807 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6808 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6809 .addConstantPoolIndex(CPI)
6810 .addMemOperand(CPMMO));
6811 // Set the low bit because of thumb mode.
6812 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6814 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6815 .addReg(NewVReg1, RegState::Kill)
6817 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6818 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6819 .addReg(NewVReg2, RegState::Kill)
6821 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6822 .addReg(NewVReg3, RegState::Kill)
6824 .addImm(36) // &jbuf[1] :: pc
6825 .addMemOperand(FIMMOSt));
6826 } else if (isThumb) {
6827 // Incoming value: jbuf
6828 // ldr.n r1, LCPI1_4
6832 // add r2, $jbuf, #+4 ; &jbuf[1]
6834 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6835 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6836 .addConstantPoolIndex(CPI)
6837 .addMemOperand(CPMMO));
6838 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6839 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6840 .addReg(NewVReg1, RegState::Kill)
6842 // Set the low bit because of thumb mode.
6843 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6844 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6845 .addReg(ARM::CPSR, RegState::Define)
6847 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6848 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6849 .addReg(ARM::CPSR, RegState::Define)
6850 .addReg(NewVReg2, RegState::Kill)
6851 .addReg(NewVReg3, RegState::Kill));
6852 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6853 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6855 .addImm(36); // &jbuf[1] :: pc
6856 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6857 .addReg(NewVReg4, RegState::Kill)
6858 .addReg(NewVReg5, RegState::Kill)
6860 .addMemOperand(FIMMOSt));
6862 // Incoming value: jbuf
6865 // str r1, [$jbuf, #+4] ; &jbuf[1]
6866 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6867 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6868 .addConstantPoolIndex(CPI)
6870 .addMemOperand(CPMMO));
6871 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6872 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6873 .addReg(NewVReg1, RegState::Kill)
6874 .addImm(PCLabelId));
6875 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6876 .addReg(NewVReg2, RegState::Kill)
6878 .addImm(36) // &jbuf[1] :: pc
6879 .addMemOperand(FIMMOSt));
6883 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6884 MachineBasicBlock *MBB) const {
6885 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6886 DebugLoc dl = MI->getDebugLoc();
6887 MachineFunction *MF = MBB->getParent();
6888 MachineRegisterInfo *MRI = &MF->getRegInfo();
6889 MachineFrameInfo *MFI = MF->getFrameInfo();
6890 int FI = MFI->getFunctionContextIndex();
6892 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6893 : &ARM::GPRnopcRegClass;
6895 // Get a mapping of the call site numbers to all of the landing pads they're
6897 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6898 unsigned MaxCSNum = 0;
6899 MachineModuleInfo &MMI = MF->getMMI();
6900 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6902 if (!BB->isLandingPad()) continue;
6904 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6906 for (MachineBasicBlock::iterator
6907 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6908 if (!II->isEHLabel()) continue;
6910 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6911 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6913 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6914 for (SmallVectorImpl<unsigned>::iterator
6915 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6916 CSI != CSE; ++CSI) {
6917 CallSiteNumToLPad[*CSI].push_back(BB);
6918 MaxCSNum = std::max(MaxCSNum, *CSI);
6924 // Get an ordered list of the machine basic blocks for the jump table.
6925 std::vector<MachineBasicBlock*> LPadList;
6926 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6927 LPadList.reserve(CallSiteNumToLPad.size());
6928 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6929 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6930 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6931 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6932 LPadList.push_back(*II);
6933 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6937 assert(!LPadList.empty() &&
6938 "No landing pad destinations for the dispatch jump table!");
6940 // Create the jump table and associated information.
6941 MachineJumpTableInfo *JTI =
6942 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6943 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6944 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6946 // Create the MBBs for the dispatch code.
6948 // Shove the dispatch's address into the return slot in the function context.
6949 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6950 DispatchBB->setIsLandingPad();
6952 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6953 unsigned trap_opcode;
6954 if (Subtarget->isThumb())
6955 trap_opcode = ARM::tTRAP;
6957 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6959 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6960 DispatchBB->addSuccessor(TrapBB);
6962 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6963 DispatchBB->addSuccessor(DispContBB);
6966 MF->insert(MF->end(), DispatchBB);
6967 MF->insert(MF->end(), DispContBB);
6968 MF->insert(MF->end(), TrapBB);
6970 // Insert code into the entry block that creates and registers the function
6972 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6974 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
6975 MachinePointerInfo::getFixedStack(*MF, FI),
6976 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
6978 MachineInstrBuilder MIB;
6979 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6981 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6982 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6984 // Add a register mask with no preserved registers. This results in all
6985 // registers being marked as clobbered.
6986 MIB.addRegMask(RI.getNoPreservedMask());
6988 unsigned NumLPads = LPadList.size();
6989 if (Subtarget->isThumb2()) {
6990 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6991 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6994 .addMemOperand(FIMMOLd));
6996 if (NumLPads < 256) {
6997 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6999 .addImm(LPadList.size()));
7001 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7002 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7003 .addImm(NumLPads & 0xFFFF));
7005 unsigned VReg2 = VReg1;
7006 if ((NumLPads & 0xFFFF0000) != 0) {
7007 VReg2 = MRI->createVirtualRegister(TRC);
7008 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7010 .addImm(NumLPads >> 16));
7013 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7018 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7023 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7024 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7025 .addJumpTableIndex(MJTI));
7027 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7030 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7031 .addReg(NewVReg3, RegState::Kill)
7033 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7035 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7036 .addReg(NewVReg4, RegState::Kill)
7038 .addJumpTableIndex(MJTI);
7039 } else if (Subtarget->isThumb()) {
7040 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7041 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7044 .addMemOperand(FIMMOLd));
7046 if (NumLPads < 256) {
7047 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7051 MachineConstantPool *ConstantPool = MF->getConstantPool();
7052 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7053 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7055 // MachineConstantPool wants an explicit alignment.
7056 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7058 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7059 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7061 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7062 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7063 .addReg(VReg1, RegState::Define)
7064 .addConstantPoolIndex(Idx));
7065 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7070 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7075 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7076 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7077 .addReg(ARM::CPSR, RegState::Define)
7081 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7082 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7083 .addJumpTableIndex(MJTI));
7085 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7086 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7087 .addReg(ARM::CPSR, RegState::Define)
7088 .addReg(NewVReg2, RegState::Kill)
7091 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7092 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7094 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7095 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7096 .addReg(NewVReg4, RegState::Kill)
7098 .addMemOperand(JTMMOLd));
7100 unsigned NewVReg6 = NewVReg5;
7101 if (RelocM == Reloc::PIC_) {
7102 NewVReg6 = MRI->createVirtualRegister(TRC);
7103 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7104 .addReg(ARM::CPSR, RegState::Define)
7105 .addReg(NewVReg5, RegState::Kill)
7109 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7110 .addReg(NewVReg6, RegState::Kill)
7111 .addJumpTableIndex(MJTI);
7113 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7114 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7117 .addMemOperand(FIMMOLd));
7119 if (NumLPads < 256) {
7120 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7123 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7124 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7125 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7126 .addImm(NumLPads & 0xFFFF));
7128 unsigned VReg2 = VReg1;
7129 if ((NumLPads & 0xFFFF0000) != 0) {
7130 VReg2 = MRI->createVirtualRegister(TRC);
7131 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7133 .addImm(NumLPads >> 16));
7136 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7140 MachineConstantPool *ConstantPool = MF->getConstantPool();
7141 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7142 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7144 // MachineConstantPool wants an explicit alignment.
7145 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7147 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7148 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7150 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7151 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7152 .addReg(VReg1, RegState::Define)
7153 .addConstantPoolIndex(Idx)
7155 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7157 .addReg(VReg1, RegState::Kill));
7160 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7165 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7167 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7169 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7170 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7171 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7172 .addJumpTableIndex(MJTI));
7174 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7175 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7176 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7178 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7179 .addReg(NewVReg3, RegState::Kill)
7182 .addMemOperand(JTMMOLd));
7184 if (RelocM == Reloc::PIC_) {
7185 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7186 .addReg(NewVReg5, RegState::Kill)
7188 .addJumpTableIndex(MJTI);
7190 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7191 .addReg(NewVReg5, RegState::Kill)
7192 .addJumpTableIndex(MJTI);
7196 // Add the jump table entries as successors to the MBB.
7197 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7198 for (std::vector<MachineBasicBlock*>::iterator
7199 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7200 MachineBasicBlock *CurMBB = *I;
7201 if (SeenMBBs.insert(CurMBB).second)
7202 DispContBB->addSuccessor(CurMBB);
7205 // N.B. the order the invoke BBs are processed in doesn't matter here.
7206 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7207 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7208 for (MachineBasicBlock *BB : InvokeBBs) {
7210 // Remove the landing pad successor from the invoke block and replace it
7211 // with the new dispatch block.
7212 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7214 while (!Successors.empty()) {
7215 MachineBasicBlock *SMBB = Successors.pop_back_val();
7216 if (SMBB->isLandingPad()) {
7217 BB->removeSuccessor(SMBB);
7218 MBBLPads.push_back(SMBB);
7222 BB->addSuccessor(DispatchBB);
7224 // Find the invoke call and mark all of the callee-saved registers as
7225 // 'implicit defined' so that they're spilled. This prevents code from
7226 // moving instructions to before the EH block, where they will never be
7228 for (MachineBasicBlock::reverse_iterator
7229 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7230 if (!II->isCall()) continue;
7232 DenseMap<unsigned, bool> DefRegs;
7233 for (MachineInstr::mop_iterator
7234 OI = II->operands_begin(), OE = II->operands_end();
7236 if (!OI->isReg()) continue;
7237 DefRegs[OI->getReg()] = true;
7240 MachineInstrBuilder MIB(*MF, &*II);
7242 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7243 unsigned Reg = SavedRegs[i];
7244 if (Subtarget->isThumb2() &&
7245 !ARM::tGPRRegClass.contains(Reg) &&
7246 !ARM::hGPRRegClass.contains(Reg))
7248 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7250 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7253 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7260 // Mark all former landing pads as non-landing pads. The dispatch is the only
7262 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7263 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7264 (*I)->setIsLandingPad(false);
7266 // The instruction is gone now.
7267 MI->eraseFromParent();
7271 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7272 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7273 E = MBB->succ_end(); I != E; ++I)
7276 llvm_unreachable("Expecting a BB with two successors!");
7279 /// Return the load opcode for a given load size. If load size >= 8,
7280 /// neon opcode will be returned.
7281 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7283 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7284 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7286 return LdSize == 4 ? ARM::tLDRi
7287 : LdSize == 2 ? ARM::tLDRHi
7288 : LdSize == 1 ? ARM::tLDRBi : 0;
7290 return LdSize == 4 ? ARM::t2LDR_POST
7291 : LdSize == 2 ? ARM::t2LDRH_POST
7292 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7293 return LdSize == 4 ? ARM::LDR_POST_IMM
7294 : LdSize == 2 ? ARM::LDRH_POST
7295 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7298 /// Return the store opcode for a given store size. If store size >= 8,
7299 /// neon opcode will be returned.
7300 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7302 return StSize == 16 ? ARM::VST1q32wb_fixed
7303 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7305 return StSize == 4 ? ARM::tSTRi
7306 : StSize == 2 ? ARM::tSTRHi
7307 : StSize == 1 ? ARM::tSTRBi : 0;
7309 return StSize == 4 ? ARM::t2STR_POST
7310 : StSize == 2 ? ARM::t2STRH_POST
7311 : StSize == 1 ? ARM::t2STRB_POST : 0;
7312 return StSize == 4 ? ARM::STR_POST_IMM
7313 : StSize == 2 ? ARM::STRH_POST
7314 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7317 /// Emit a post-increment load operation with given size. The instructions
7318 /// will be added to BB at Pos.
7319 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7320 const TargetInstrInfo *TII, DebugLoc dl,
7321 unsigned LdSize, unsigned Data, unsigned AddrIn,
7322 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7323 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7324 assert(LdOpc != 0 && "Should have a load opcode");
7326 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7327 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7329 } else if (IsThumb1) {
7330 // load + update AddrIn
7331 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7332 .addReg(AddrIn).addImm(0));
7333 MachineInstrBuilder MIB =
7334 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7335 MIB = AddDefaultT1CC(MIB);
7336 MIB.addReg(AddrIn).addImm(LdSize);
7337 AddDefaultPred(MIB);
7338 } else if (IsThumb2) {
7339 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7340 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7343 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7344 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7345 .addReg(0).addImm(LdSize));
7349 /// Emit a post-increment store operation with given size. The instructions
7350 /// will be added to BB at Pos.
7351 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7352 const TargetInstrInfo *TII, DebugLoc dl,
7353 unsigned StSize, unsigned Data, unsigned AddrIn,
7354 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7355 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7356 assert(StOpc != 0 && "Should have a store opcode");
7358 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7359 .addReg(AddrIn).addImm(0).addReg(Data));
7360 } else if (IsThumb1) {
7361 // store + update AddrIn
7362 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7363 .addReg(AddrIn).addImm(0));
7364 MachineInstrBuilder MIB =
7365 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7366 MIB = AddDefaultT1CC(MIB);
7367 MIB.addReg(AddrIn).addImm(StSize);
7368 AddDefaultPred(MIB);
7369 } else if (IsThumb2) {
7370 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7371 .addReg(Data).addReg(AddrIn).addImm(StSize));
7373 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7374 .addReg(Data).addReg(AddrIn).addReg(0)
7380 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7381 MachineBasicBlock *BB) const {
7382 // This pseudo instruction has 3 operands: dst, src, size
7383 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7384 // Otherwise, we will generate unrolled scalar copies.
7385 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7386 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7387 MachineFunction::iterator It = BB;
7390 unsigned dest = MI->getOperand(0).getReg();
7391 unsigned src = MI->getOperand(1).getReg();
7392 unsigned SizeVal = MI->getOperand(2).getImm();
7393 unsigned Align = MI->getOperand(3).getImm();
7394 DebugLoc dl = MI->getDebugLoc();
7396 MachineFunction *MF = BB->getParent();
7397 MachineRegisterInfo &MRI = MF->getRegInfo();
7398 unsigned UnitSize = 0;
7399 const TargetRegisterClass *TRC = nullptr;
7400 const TargetRegisterClass *VecTRC = nullptr;
7402 bool IsThumb1 = Subtarget->isThumb1Only();
7403 bool IsThumb2 = Subtarget->isThumb2();
7407 } else if (Align & 2) {
7410 // Check whether we can use NEON instructions.
7411 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7412 Subtarget->hasNEON()) {
7413 if ((Align % 16 == 0) && SizeVal >= 16)
7415 else if ((Align % 8 == 0) && SizeVal >= 8)
7418 // Can't use NEON instructions.
7423 // Select the correct opcode and register class for unit size load/store
7424 bool IsNeon = UnitSize >= 8;
7425 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7427 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7428 : UnitSize == 8 ? &ARM::DPRRegClass
7431 unsigned BytesLeft = SizeVal % UnitSize;
7432 unsigned LoopSize = SizeVal - BytesLeft;
7434 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7435 // Use LDR and STR to copy.
7436 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7437 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7438 unsigned srcIn = src;
7439 unsigned destIn = dest;
7440 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7441 unsigned srcOut = MRI.createVirtualRegister(TRC);
7442 unsigned destOut = MRI.createVirtualRegister(TRC);
7443 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7444 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7445 IsThumb1, IsThumb2);
7446 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7447 IsThumb1, IsThumb2);
7452 // Handle the leftover bytes with LDRB and STRB.
7453 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7454 // [destOut] = STRB_POST(scratch, destIn, 1)
7455 for (unsigned i = 0; i < BytesLeft; i++) {
7456 unsigned srcOut = MRI.createVirtualRegister(TRC);
7457 unsigned destOut = MRI.createVirtualRegister(TRC);
7458 unsigned scratch = MRI.createVirtualRegister(TRC);
7459 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7460 IsThumb1, IsThumb2);
7461 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7462 IsThumb1, IsThumb2);
7466 MI->eraseFromParent(); // The instruction is gone now.
7470 // Expand the pseudo op to a loop.
7473 // movw varEnd, # --> with thumb2
7475 // ldrcp varEnd, idx --> without thumb2
7476 // fallthrough --> loopMBB
7478 // PHI varPhi, varEnd, varLoop
7479 // PHI srcPhi, src, srcLoop
7480 // PHI destPhi, dst, destLoop
7481 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7482 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7483 // subs varLoop, varPhi, #UnitSize
7485 // fallthrough --> exitMBB
7487 // epilogue to handle left-over bytes
7488 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7489 // [destOut] = STRB_POST(scratch, destLoop, 1)
7490 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7491 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7492 MF->insert(It, loopMBB);
7493 MF->insert(It, exitMBB);
7495 // Transfer the remainder of BB and its successor edges to exitMBB.
7496 exitMBB->splice(exitMBB->begin(), BB,
7497 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7498 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7500 // Load an immediate to varEnd.
7501 unsigned varEnd = MRI.createVirtualRegister(TRC);
7502 if (Subtarget->useMovt(*MF)) {
7503 unsigned Vtmp = varEnd;
7504 if ((LoopSize & 0xFFFF0000) != 0)
7505 Vtmp = MRI.createVirtualRegister(TRC);
7506 AddDefaultPred(BuildMI(BB, dl,
7507 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7508 Vtmp).addImm(LoopSize & 0xFFFF));
7510 if ((LoopSize & 0xFFFF0000) != 0)
7511 AddDefaultPred(BuildMI(BB, dl,
7512 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7515 .addImm(LoopSize >> 16));
7517 MachineConstantPool *ConstantPool = MF->getConstantPool();
7518 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7519 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7521 // MachineConstantPool wants an explicit alignment.
7522 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7524 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7525 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7528 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7529 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7531 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7532 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7534 BB->addSuccessor(loopMBB);
7536 // Generate the loop body:
7537 // varPhi = PHI(varLoop, varEnd)
7538 // srcPhi = PHI(srcLoop, src)
7539 // destPhi = PHI(destLoop, dst)
7540 MachineBasicBlock *entryBB = BB;
7542 unsigned varLoop = MRI.createVirtualRegister(TRC);
7543 unsigned varPhi = MRI.createVirtualRegister(TRC);
7544 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7545 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7546 unsigned destLoop = MRI.createVirtualRegister(TRC);
7547 unsigned destPhi = MRI.createVirtualRegister(TRC);
7549 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7550 .addReg(varLoop).addMBB(loopMBB)
7551 .addReg(varEnd).addMBB(entryBB);
7552 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7553 .addReg(srcLoop).addMBB(loopMBB)
7554 .addReg(src).addMBB(entryBB);
7555 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7556 .addReg(destLoop).addMBB(loopMBB)
7557 .addReg(dest).addMBB(entryBB);
7559 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7560 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7561 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7562 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7563 IsThumb1, IsThumb2);
7564 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7565 IsThumb1, IsThumb2);
7567 // Decrement loop variable by UnitSize.
7569 MachineInstrBuilder MIB =
7570 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7571 MIB = AddDefaultT1CC(MIB);
7572 MIB.addReg(varPhi).addImm(UnitSize);
7573 AddDefaultPred(MIB);
7575 MachineInstrBuilder MIB =
7576 BuildMI(*BB, BB->end(), dl,
7577 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7578 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7579 MIB->getOperand(5).setReg(ARM::CPSR);
7580 MIB->getOperand(5).setIsDef(true);
7582 BuildMI(*BB, BB->end(), dl,
7583 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7584 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7586 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7587 BB->addSuccessor(loopMBB);
7588 BB->addSuccessor(exitMBB);
7590 // Add epilogue to handle BytesLeft.
7592 MachineInstr *StartOfExit = exitMBB->begin();
7594 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7595 // [destOut] = STRB_POST(scratch, destLoop, 1)
7596 unsigned srcIn = srcLoop;
7597 unsigned destIn = destLoop;
7598 for (unsigned i = 0; i < BytesLeft; i++) {
7599 unsigned srcOut = MRI.createVirtualRegister(TRC);
7600 unsigned destOut = MRI.createVirtualRegister(TRC);
7601 unsigned scratch = MRI.createVirtualRegister(TRC);
7602 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7603 IsThumb1, IsThumb2);
7604 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7605 IsThumb1, IsThumb2);
7610 MI->eraseFromParent(); // The instruction is gone now.
7615 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7616 MachineBasicBlock *MBB) const {
7617 const TargetMachine &TM = getTargetMachine();
7618 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7619 DebugLoc DL = MI->getDebugLoc();
7621 assert(Subtarget->isTargetWindows() &&
7622 "__chkstk is only supported on Windows");
7623 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7625 // __chkstk takes the number of words to allocate on the stack in R4, and
7626 // returns the stack adjustment in number of bytes in R4. This will not
7627 // clober any other registers (other than the obvious lr).
7629 // Although, technically, IP should be considered a register which may be
7630 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7631 // thumb-2 environment, so there is no interworking required. As a result, we
7632 // do not expect a veneer to be emitted by the linker, clobbering IP.
7634 // Each module receives its own copy of __chkstk, so no import thunk is
7635 // required, again, ensuring that IP is not clobbered.
7637 // Finally, although some linkers may theoretically provide a trampoline for
7638 // out of range calls (which is quite common due to a 32M range limitation of
7639 // branches for Thumb), we can generate the long-call version via
7640 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7643 switch (TM.getCodeModel()) {
7644 case CodeModel::Small:
7645 case CodeModel::Medium:
7646 case CodeModel::Default:
7647 case CodeModel::Kernel:
7648 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7649 .addImm((unsigned)ARMCC::AL).addReg(0)
7650 .addExternalSymbol("__chkstk")
7651 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7652 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7653 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7655 case CodeModel::Large:
7656 case CodeModel::JITDefault: {
7657 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7658 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7660 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7661 .addExternalSymbol("__chkstk");
7662 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7663 .addImm((unsigned)ARMCC::AL).addReg(0)
7664 .addReg(Reg, RegState::Kill)
7665 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7666 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7667 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7672 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7674 .addReg(ARM::SP).addReg(ARM::R4)));
7676 MI->eraseFromParent();
7681 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7682 MachineBasicBlock *BB) const {
7683 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7684 DebugLoc dl = MI->getDebugLoc();
7685 bool isThumb2 = Subtarget->isThumb2();
7686 switch (MI->getOpcode()) {
7689 llvm_unreachable("Unexpected instr type to insert");
7691 // The Thumb2 pre-indexed stores have the same MI operands, they just
7692 // define them differently in the .td files from the isel patterns, so
7693 // they need pseudos.
7694 case ARM::t2STR_preidx:
7695 MI->setDesc(TII->get(ARM::t2STR_PRE));
7697 case ARM::t2STRB_preidx:
7698 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7700 case ARM::t2STRH_preidx:
7701 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7704 case ARM::STRi_preidx:
7705 case ARM::STRBi_preidx: {
7706 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7707 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7708 // Decode the offset.
7709 unsigned Offset = MI->getOperand(4).getImm();
7710 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7711 Offset = ARM_AM::getAM2Offset(Offset);
7715 MachineMemOperand *MMO = *MI->memoperands_begin();
7716 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7717 .addOperand(MI->getOperand(0)) // Rn_wb
7718 .addOperand(MI->getOperand(1)) // Rt
7719 .addOperand(MI->getOperand(2)) // Rn
7720 .addImm(Offset) // offset (skip GPR==zero_reg)
7721 .addOperand(MI->getOperand(5)) // pred
7722 .addOperand(MI->getOperand(6))
7723 .addMemOperand(MMO);
7724 MI->eraseFromParent();
7727 case ARM::STRr_preidx:
7728 case ARM::STRBr_preidx:
7729 case ARM::STRH_preidx: {
7731 switch (MI->getOpcode()) {
7732 default: llvm_unreachable("unexpected opcode!");
7733 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7734 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7735 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7737 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7738 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7739 MIB.addOperand(MI->getOperand(i));
7740 MI->eraseFromParent();
7744 case ARM::tMOVCCr_pseudo: {
7745 // To "insert" a SELECT_CC instruction, we actually have to insert the
7746 // diamond control-flow pattern. The incoming instruction knows the
7747 // destination vreg to set, the condition code register to branch on, the
7748 // true/false values to select between, and a branch opcode to use.
7749 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7750 MachineFunction::iterator It = BB;
7756 // cmpTY ccX, r1, r2
7758 // fallthrough --> copy0MBB
7759 MachineBasicBlock *thisMBB = BB;
7760 MachineFunction *F = BB->getParent();
7761 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7762 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7763 F->insert(It, copy0MBB);
7764 F->insert(It, sinkMBB);
7766 // Transfer the remainder of BB and its successor edges to sinkMBB.
7767 sinkMBB->splice(sinkMBB->begin(), BB,
7768 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7769 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7771 BB->addSuccessor(copy0MBB);
7772 BB->addSuccessor(sinkMBB);
7774 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7775 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7778 // %FalseValue = ...
7779 // # fallthrough to sinkMBB
7782 // Update machine-CFG edges
7783 BB->addSuccessor(sinkMBB);
7786 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7789 BuildMI(*BB, BB->begin(), dl,
7790 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7791 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7792 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7794 MI->eraseFromParent(); // The pseudo instruction is gone now.
7799 case ARM::BCCZi64: {
7800 // If there is an unconditional branch to the other successor, remove it.
7801 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7803 // Compare both parts that make up the double comparison separately for
7805 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7807 unsigned LHS1 = MI->getOperand(1).getReg();
7808 unsigned LHS2 = MI->getOperand(2).getReg();
7810 AddDefaultPred(BuildMI(BB, dl,
7811 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7812 .addReg(LHS1).addImm(0));
7813 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7814 .addReg(LHS2).addImm(0)
7815 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7817 unsigned RHS1 = MI->getOperand(3).getReg();
7818 unsigned RHS2 = MI->getOperand(4).getReg();
7819 AddDefaultPred(BuildMI(BB, dl,
7820 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7821 .addReg(LHS1).addReg(RHS1));
7822 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7823 .addReg(LHS2).addReg(RHS2)
7824 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7827 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7828 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7829 if (MI->getOperand(0).getImm() == ARMCC::NE)
7830 std::swap(destMBB, exitMBB);
7832 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7833 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7835 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7837 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7839 MI->eraseFromParent(); // The pseudo instruction is gone now.
7843 case ARM::Int_eh_sjlj_setjmp:
7844 case ARM::Int_eh_sjlj_setjmp_nofp:
7845 case ARM::tInt_eh_sjlj_setjmp:
7846 case ARM::t2Int_eh_sjlj_setjmp:
7847 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7850 case ARM::Int_eh_sjlj_setup_dispatch:
7851 EmitSjLjDispatchBlock(MI, BB);
7856 // To insert an ABS instruction, we have to insert the
7857 // diamond control-flow pattern. The incoming instruction knows the
7858 // source vreg to test against 0, the destination vreg to set,
7859 // the condition code register to branch on, the
7860 // true/false values to select between, and a branch opcode to use.
7865 // BCC (branch to SinkBB if V0 >= 0)
7866 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7867 // SinkBB: V1 = PHI(V2, V3)
7868 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7869 MachineFunction::iterator BBI = BB;
7871 MachineFunction *Fn = BB->getParent();
7872 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7873 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7874 Fn->insert(BBI, RSBBB);
7875 Fn->insert(BBI, SinkBB);
7877 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7878 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7879 bool ABSSrcKIll = MI->getOperand(1).isKill();
7880 bool isThumb2 = Subtarget->isThumb2();
7881 MachineRegisterInfo &MRI = Fn->getRegInfo();
7882 // In Thumb mode S must not be specified if source register is the SP or
7883 // PC and if destination register is the SP, so restrict register class
7884 unsigned NewRsbDstReg =
7885 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7887 // Transfer the remainder of BB and its successor edges to sinkMBB.
7888 SinkBB->splice(SinkBB->begin(), BB,
7889 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7890 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7892 BB->addSuccessor(RSBBB);
7893 BB->addSuccessor(SinkBB);
7895 // fall through to SinkMBB
7896 RSBBB->addSuccessor(SinkBB);
7898 // insert a cmp at the end of BB
7899 AddDefaultPred(BuildMI(BB, dl,
7900 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7901 .addReg(ABSSrcReg).addImm(0));
7903 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7905 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7906 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7908 // insert rsbri in RSBBB
7909 // Note: BCC and rsbri will be converted into predicated rsbmi
7910 // by if-conversion pass
7911 BuildMI(*RSBBB, RSBBB->begin(), dl,
7912 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7913 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7914 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7916 // insert PHI in SinkBB,
7917 // reuse ABSDstReg to not change uses of ABS instruction
7918 BuildMI(*SinkBB, SinkBB->begin(), dl,
7919 TII->get(ARM::PHI), ABSDstReg)
7920 .addReg(NewRsbDstReg).addMBB(RSBBB)
7921 .addReg(ABSSrcReg).addMBB(BB);
7923 // remove ABS instruction
7924 MI->eraseFromParent();
7926 // return last added BB
7929 case ARM::COPY_STRUCT_BYVAL_I32:
7931 return EmitStructByval(MI, BB);
7932 case ARM::WIN__CHKSTK:
7933 return EmitLowered__chkstk(MI, BB);
7937 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7938 SDNode *Node) const {
7939 const MCInstrDesc *MCID = &MI->getDesc();
7940 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7941 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7942 // operand is still set to noreg. If needed, set the optional operand's
7943 // register to CPSR, and remove the redundant implicit def.
7945 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7947 // Rename pseudo opcodes.
7948 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7950 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7951 MCID = &TII->get(NewOpc);
7953 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7954 "converted opcode should be the same except for cc_out");
7958 // Add the optional cc_out operand
7959 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7961 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7963 // Any ARM instruction that sets the 's' bit should specify an optional
7964 // "cc_out" operand in the last operand position.
7965 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7966 assert(!NewOpc && "Optional cc_out operand required");
7969 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7970 // since we already have an optional CPSR def.
7971 bool definesCPSR = false;
7972 bool deadCPSR = false;
7973 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7975 const MachineOperand &MO = MI->getOperand(i);
7976 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7980 MI->RemoveOperand(i);
7985 assert(!NewOpc && "Optional cc_out operand required");
7988 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7990 assert(!MI->getOperand(ccOutIdx).getReg() &&
7991 "expect uninitialized optional cc_out operand");
7995 // If this instruction was defined with an optional CPSR def and its dag node
7996 // had a live implicit CPSR def, then activate the optional CPSR def.
7997 MachineOperand &MO = MI->getOperand(ccOutIdx);
7998 MO.setReg(ARM::CPSR);
8002 //===----------------------------------------------------------------------===//
8003 // ARM Optimization Hooks
8004 //===----------------------------------------------------------------------===//
8006 // Helper function that checks if N is a null or all ones constant.
8007 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8008 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8011 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8014 // Return true if N is conditionally 0 or all ones.
8015 // Detects these expressions where cc is an i1 value:
8017 // (select cc 0, y) [AllOnes=0]
8018 // (select cc y, 0) [AllOnes=0]
8019 // (zext cc) [AllOnes=0]
8020 // (sext cc) [AllOnes=0/1]
8021 // (select cc -1, y) [AllOnes=1]
8022 // (select cc y, -1) [AllOnes=1]
8024 // Invert is set when N is the null/all ones constant when CC is false.
8025 // OtherOp is set to the alternative value of N.
8026 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8027 SDValue &CC, bool &Invert,
8029 SelectionDAG &DAG) {
8030 switch (N->getOpcode()) {
8031 default: return false;
8033 CC = N->getOperand(0);
8034 SDValue N1 = N->getOperand(1);
8035 SDValue N2 = N->getOperand(2);
8036 if (isZeroOrAllOnes(N1, AllOnes)) {
8041 if (isZeroOrAllOnes(N2, AllOnes)) {
8048 case ISD::ZERO_EXTEND:
8049 // (zext cc) can never be the all ones value.
8053 case ISD::SIGN_EXTEND: {
8055 EVT VT = N->getValueType(0);
8056 CC = N->getOperand(0);
8057 if (CC.getValueType() != MVT::i1)
8061 // When looking for an AllOnes constant, N is an sext, and the 'other'
8063 OtherOp = DAG.getConstant(0, dl, VT);
8064 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8065 // When looking for a 0 constant, N can be zext or sext.
8066 OtherOp = DAG.getConstant(1, dl, VT);
8068 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8075 // Combine a constant select operand into its use:
8077 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8078 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8079 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8080 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8081 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8083 // The transform is rejected if the select doesn't have a constant operand that
8084 // is null, or all ones when AllOnes is set.
8086 // Also recognize sext/zext from i1:
8088 // (add (zext cc), x) -> (select cc (add x, 1), x)
8089 // (add (sext cc), x) -> (select cc (add x, -1), x)
8091 // These transformations eventually create predicated instructions.
8093 // @param N The node to transform.
8094 // @param Slct The N operand that is a select.
8095 // @param OtherOp The other N operand (x above).
8096 // @param DCI Context.
8097 // @param AllOnes Require the select constant to be all ones instead of null.
8098 // @returns The new node, or SDValue() on failure.
8100 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8101 TargetLowering::DAGCombinerInfo &DCI,
8102 bool AllOnes = false) {
8103 SelectionDAG &DAG = DCI.DAG;
8104 EVT VT = N->getValueType(0);
8105 SDValue NonConstantVal;
8108 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8109 NonConstantVal, DAG))
8112 // Slct is now know to be the desired identity constant when CC is true.
8113 SDValue TrueVal = OtherOp;
8114 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8115 OtherOp, NonConstantVal);
8116 // Unless SwapSelectOps says CC should be false.
8118 std::swap(TrueVal, FalseVal);
8120 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8121 CCOp, TrueVal, FalseVal);
8124 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8126 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8127 TargetLowering::DAGCombinerInfo &DCI) {
8128 SDValue N0 = N->getOperand(0);
8129 SDValue N1 = N->getOperand(1);
8130 if (N0.getNode()->hasOneUse()) {
8131 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8132 if (Result.getNode())
8135 if (N1.getNode()->hasOneUse()) {
8136 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8137 if (Result.getNode())
8143 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8144 // (only after legalization).
8145 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8146 TargetLowering::DAGCombinerInfo &DCI,
8147 const ARMSubtarget *Subtarget) {
8149 // Only perform optimization if after legalize, and if NEON is available. We
8150 // also expected both operands to be BUILD_VECTORs.
8151 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8152 || N0.getOpcode() != ISD::BUILD_VECTOR
8153 || N1.getOpcode() != ISD::BUILD_VECTOR)
8156 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8157 EVT VT = N->getValueType(0);
8158 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8161 // Check that the vector operands are of the right form.
8162 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8163 // operands, where N is the size of the formed vector.
8164 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8165 // index such that we have a pair wise add pattern.
8167 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8168 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8170 SDValue Vec = N0->getOperand(0)->getOperand(0);
8171 SDNode *V = Vec.getNode();
8172 unsigned nextIndex = 0;
8174 // For each operands to the ADD which are BUILD_VECTORs,
8175 // check to see if each of their operands are an EXTRACT_VECTOR with
8176 // the same vector and appropriate index.
8177 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8178 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8179 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8181 SDValue ExtVec0 = N0->getOperand(i);
8182 SDValue ExtVec1 = N1->getOperand(i);
8184 // First operand is the vector, verify its the same.
8185 if (V != ExtVec0->getOperand(0).getNode() ||
8186 V != ExtVec1->getOperand(0).getNode())
8189 // Second is the constant, verify its correct.
8190 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8191 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8193 // For the constant, we want to see all the even or all the odd.
8194 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8195 || C1->getZExtValue() != nextIndex+1)
8204 // Create VPADDL node.
8205 SelectionDAG &DAG = DCI.DAG;
8206 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8210 // Build operand list.
8211 SmallVector<SDValue, 8> Ops;
8212 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8213 TLI.getPointerTy(DAG.getDataLayout())));
8215 // Input is the vector.
8218 // Get widened type and narrowed type.
8220 unsigned numElem = VT.getVectorNumElements();
8222 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8223 switch (inputLaneType.getSimpleVT().SimpleTy) {
8224 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8225 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8226 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8228 llvm_unreachable("Invalid vector element type for padd optimization.");
8231 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8232 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8233 return DAG.getNode(ExtOp, dl, VT, tmp);
8236 static SDValue findMUL_LOHI(SDValue V) {
8237 if (V->getOpcode() == ISD::UMUL_LOHI ||
8238 V->getOpcode() == ISD::SMUL_LOHI)
8243 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8244 TargetLowering::DAGCombinerInfo &DCI,
8245 const ARMSubtarget *Subtarget) {
8247 if (Subtarget->isThumb1Only()) return SDValue();
8249 // Only perform the checks after legalize when the pattern is available.
8250 if (DCI.isBeforeLegalize()) return SDValue();
8252 // Look for multiply add opportunities.
8253 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8254 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8255 // a glue link from the first add to the second add.
8256 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8257 // a S/UMLAL instruction.
8260 // / \ [no multiline comment]
8266 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8267 SDValue AddcOp0 = AddcNode->getOperand(0);
8268 SDValue AddcOp1 = AddcNode->getOperand(1);
8270 // Check if the two operands are from the same mul_lohi node.
8271 if (AddcOp0.getNode() == AddcOp1.getNode())
8274 assert(AddcNode->getNumValues() == 2 &&
8275 AddcNode->getValueType(0) == MVT::i32 &&
8276 "Expect ADDC with two result values. First: i32");
8278 // Check that we have a glued ADDC node.
8279 if (AddcNode->getValueType(1) != MVT::Glue)
8282 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8283 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8284 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8285 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8286 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8289 // Look for the glued ADDE.
8290 SDNode* AddeNode = AddcNode->getGluedUser();
8294 // Make sure it is really an ADDE.
8295 if (AddeNode->getOpcode() != ISD::ADDE)
8298 assert(AddeNode->getNumOperands() == 3 &&
8299 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8300 "ADDE node has the wrong inputs");
8302 // Check for the triangle shape.
8303 SDValue AddeOp0 = AddeNode->getOperand(0);
8304 SDValue AddeOp1 = AddeNode->getOperand(1);
8306 // Make sure that the ADDE operands are not coming from the same node.
8307 if (AddeOp0.getNode() == AddeOp1.getNode())
8310 // Find the MUL_LOHI node walking up ADDE's operands.
8311 bool IsLeftOperandMUL = false;
8312 SDValue MULOp = findMUL_LOHI(AddeOp0);
8313 if (MULOp == SDValue())
8314 MULOp = findMUL_LOHI(AddeOp1);
8316 IsLeftOperandMUL = true;
8317 if (MULOp == SDValue())
8320 // Figure out the right opcode.
8321 unsigned Opc = MULOp->getOpcode();
8322 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8324 // Figure out the high and low input values to the MLAL node.
8325 SDValue* HiAdd = nullptr;
8326 SDValue* LoMul = nullptr;
8327 SDValue* LowAdd = nullptr;
8329 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8330 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8333 if (IsLeftOperandMUL)
8339 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8340 // whose low result is fed to the ADDC we are checking.
8342 if (AddcOp0 == MULOp.getValue(0)) {
8346 if (AddcOp1 == MULOp.getValue(0)) {
8354 // Create the merged node.
8355 SelectionDAG &DAG = DCI.DAG;
8357 // Build operand list.
8358 SmallVector<SDValue, 8> Ops;
8359 Ops.push_back(LoMul->getOperand(0));
8360 Ops.push_back(LoMul->getOperand(1));
8361 Ops.push_back(*LowAdd);
8362 Ops.push_back(*HiAdd);
8364 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8365 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8367 // Replace the ADDs' nodes uses by the MLA node's values.
8368 SDValue HiMLALResult(MLALNode.getNode(), 1);
8369 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8371 SDValue LoMLALResult(MLALNode.getNode(), 0);
8372 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8374 // Return original node to notify the driver to stop replacing.
8375 SDValue resNode(AddcNode, 0);
8379 /// PerformADDCCombine - Target-specific dag combine transform from
8380 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8381 static SDValue PerformADDCCombine(SDNode *N,
8382 TargetLowering::DAGCombinerInfo &DCI,
8383 const ARMSubtarget *Subtarget) {
8385 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8389 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8390 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8391 /// called with the default operands, and if that fails, with commuted
8393 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8394 TargetLowering::DAGCombinerInfo &DCI,
8395 const ARMSubtarget *Subtarget){
8397 // Attempt to create vpaddl for this add.
8398 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8399 if (Result.getNode())
8402 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8403 if (N0.getNode()->hasOneUse()) {
8404 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8405 if (Result.getNode()) return Result;
8410 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8412 static SDValue PerformADDCombine(SDNode *N,
8413 TargetLowering::DAGCombinerInfo &DCI,
8414 const ARMSubtarget *Subtarget) {
8415 SDValue N0 = N->getOperand(0);
8416 SDValue N1 = N->getOperand(1);
8418 // First try with the default operand order.
8419 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8420 if (Result.getNode())
8423 // If that didn't work, try again with the operands commuted.
8424 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8427 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8429 static SDValue PerformSUBCombine(SDNode *N,
8430 TargetLowering::DAGCombinerInfo &DCI) {
8431 SDValue N0 = N->getOperand(0);
8432 SDValue N1 = N->getOperand(1);
8434 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8435 if (N1.getNode()->hasOneUse()) {
8436 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8437 if (Result.getNode()) return Result;
8443 /// PerformVMULCombine
8444 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8445 /// special multiplier accumulator forwarding.
8451 // However, for (A + B) * (A + B),
8458 static SDValue PerformVMULCombine(SDNode *N,
8459 TargetLowering::DAGCombinerInfo &DCI,
8460 const ARMSubtarget *Subtarget) {
8461 if (!Subtarget->hasVMLxForwarding())
8464 SelectionDAG &DAG = DCI.DAG;
8465 SDValue N0 = N->getOperand(0);
8466 SDValue N1 = N->getOperand(1);
8467 unsigned Opcode = N0.getOpcode();
8468 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8469 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8470 Opcode = N1.getOpcode();
8471 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8472 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8480 EVT VT = N->getValueType(0);
8482 SDValue N00 = N0->getOperand(0);
8483 SDValue N01 = N0->getOperand(1);
8484 return DAG.getNode(Opcode, DL, VT,
8485 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8486 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8489 static SDValue PerformMULCombine(SDNode *N,
8490 TargetLowering::DAGCombinerInfo &DCI,
8491 const ARMSubtarget *Subtarget) {
8492 SelectionDAG &DAG = DCI.DAG;
8494 if (Subtarget->isThumb1Only())
8497 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8500 EVT VT = N->getValueType(0);
8501 if (VT.is64BitVector() || VT.is128BitVector())
8502 return PerformVMULCombine(N, DCI, Subtarget);
8506 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8510 int64_t MulAmt = C->getSExtValue();
8511 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8513 ShiftAmt = ShiftAmt & (32 - 1);
8514 SDValue V = N->getOperand(0);
8518 MulAmt >>= ShiftAmt;
8521 if (isPowerOf2_32(MulAmt - 1)) {
8522 // (mul x, 2^N + 1) => (add (shl x, N), x)
8523 Res = DAG.getNode(ISD::ADD, DL, VT,
8525 DAG.getNode(ISD::SHL, DL, VT,
8527 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8529 } else if (isPowerOf2_32(MulAmt + 1)) {
8530 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8531 Res = DAG.getNode(ISD::SUB, DL, VT,
8532 DAG.getNode(ISD::SHL, DL, VT,
8534 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8540 uint64_t MulAmtAbs = -MulAmt;
8541 if (isPowerOf2_32(MulAmtAbs + 1)) {
8542 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8543 Res = DAG.getNode(ISD::SUB, DL, VT,
8545 DAG.getNode(ISD::SHL, DL, VT,
8547 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8549 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8550 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8551 Res = DAG.getNode(ISD::ADD, DL, VT,
8553 DAG.getNode(ISD::SHL, DL, VT,
8555 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8557 Res = DAG.getNode(ISD::SUB, DL, VT,
8558 DAG.getConstant(0, DL, MVT::i32), Res);
8565 Res = DAG.getNode(ISD::SHL, DL, VT,
8566 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8568 // Do not add new nodes to DAG combiner worklist.
8569 DCI.CombineTo(N, Res, false);
8573 static SDValue PerformANDCombine(SDNode *N,
8574 TargetLowering::DAGCombinerInfo &DCI,
8575 const ARMSubtarget *Subtarget) {
8577 // Attempt to use immediate-form VBIC
8578 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8580 EVT VT = N->getValueType(0);
8581 SelectionDAG &DAG = DCI.DAG;
8583 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8586 APInt SplatBits, SplatUndef;
8587 unsigned SplatBitSize;
8590 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8591 if (SplatBitSize <= 64) {
8593 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8594 SplatUndef.getZExtValue(), SplatBitSize,
8595 DAG, dl, VbicVT, VT.is128BitVector(),
8597 if (Val.getNode()) {
8599 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8600 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8601 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8606 if (!Subtarget->isThumb1Only()) {
8607 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8608 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8609 if (Result.getNode())
8616 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8617 static SDValue PerformORCombine(SDNode *N,
8618 TargetLowering::DAGCombinerInfo &DCI,
8619 const ARMSubtarget *Subtarget) {
8620 // Attempt to use immediate-form VORR
8621 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8623 EVT VT = N->getValueType(0);
8624 SelectionDAG &DAG = DCI.DAG;
8626 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8629 APInt SplatBits, SplatUndef;
8630 unsigned SplatBitSize;
8632 if (BVN && Subtarget->hasNEON() &&
8633 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8634 if (SplatBitSize <= 64) {
8636 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8637 SplatUndef.getZExtValue(), SplatBitSize,
8638 DAG, dl, VorrVT, VT.is128BitVector(),
8640 if (Val.getNode()) {
8642 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8643 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8644 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8649 if (!Subtarget->isThumb1Only()) {
8650 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8651 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8652 if (Result.getNode())
8656 // The code below optimizes (or (and X, Y), Z).
8657 // The AND operand needs to have a single user to make these optimizations
8659 SDValue N0 = N->getOperand(0);
8660 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8662 SDValue N1 = N->getOperand(1);
8664 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8665 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8666 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8668 unsigned SplatBitSize;
8671 APInt SplatBits0, SplatBits1;
8672 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8673 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8674 // Ensure that the second operand of both ands are constants
8675 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8676 HasAnyUndefs) && !HasAnyUndefs) {
8677 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8678 HasAnyUndefs) && !HasAnyUndefs) {
8679 // Ensure that the bit width of the constants are the same and that
8680 // the splat arguments are logical inverses as per the pattern we
8681 // are trying to simplify.
8682 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8683 SplatBits0 == ~SplatBits1) {
8684 // Canonicalize the vector type to make instruction selection
8686 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8687 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8691 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8697 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8700 // BFI is only available on V6T2+
8701 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8705 // 1) or (and A, mask), val => ARMbfi A, val, mask
8706 // iff (val & mask) == val
8708 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8709 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8710 // && mask == ~mask2
8711 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8712 // && ~mask == mask2
8713 // (i.e., copy a bitfield value into another bitfield of the same width)
8718 SDValue N00 = N0.getOperand(0);
8720 // The value and the mask need to be constants so we can verify this is
8721 // actually a bitfield set. If the mask is 0xffff, we can do better
8722 // via a movt instruction, so don't use BFI in that case.
8723 SDValue MaskOp = N0.getOperand(1);
8724 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8727 unsigned Mask = MaskC->getZExtValue();
8731 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8734 unsigned Val = N1C->getZExtValue();
8735 if ((Val & ~Mask) != Val)
8738 if (ARM::isBitFieldInvertedMask(Mask)) {
8739 Val >>= countTrailingZeros(~Mask);
8741 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8742 DAG.getConstant(Val, DL, MVT::i32),
8743 DAG.getConstant(Mask, DL, MVT::i32));
8745 // Do not add new nodes to DAG combiner worklist.
8746 DCI.CombineTo(N, Res, false);
8749 } else if (N1.getOpcode() == ISD::AND) {
8750 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8751 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8754 unsigned Mask2 = N11C->getZExtValue();
8756 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8758 if (ARM::isBitFieldInvertedMask(Mask) &&
8760 // The pack halfword instruction works better for masks that fit it,
8761 // so use that when it's available.
8762 if (Subtarget->hasT2ExtractPack() &&
8763 (Mask == 0xffff || Mask == 0xffff0000))
8766 unsigned amt = countTrailingZeros(Mask2);
8767 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8768 DAG.getConstant(amt, DL, MVT::i32));
8769 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8770 DAG.getConstant(Mask, DL, MVT::i32));
8771 // Do not add new nodes to DAG combiner worklist.
8772 DCI.CombineTo(N, Res, false);
8774 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8776 // The pack halfword instruction works better for masks that fit it,
8777 // so use that when it's available.
8778 if (Subtarget->hasT2ExtractPack() &&
8779 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8782 unsigned lsb = countTrailingZeros(Mask);
8783 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8784 DAG.getConstant(lsb, DL, MVT::i32));
8785 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8786 DAG.getConstant(Mask2, DL, MVT::i32));
8787 // Do not add new nodes to DAG combiner worklist.
8788 DCI.CombineTo(N, Res, false);
8793 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8794 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8795 ARM::isBitFieldInvertedMask(~Mask)) {
8796 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8797 // where lsb(mask) == #shamt and masked bits of B are known zero.
8798 SDValue ShAmt = N00.getOperand(1);
8799 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8800 unsigned LSB = countTrailingZeros(Mask);
8804 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8805 DAG.getConstant(~Mask, DL, MVT::i32));
8807 // Do not add new nodes to DAG combiner worklist.
8808 DCI.CombineTo(N, Res, false);
8814 static SDValue PerformXORCombine(SDNode *N,
8815 TargetLowering::DAGCombinerInfo &DCI,
8816 const ARMSubtarget *Subtarget) {
8817 EVT VT = N->getValueType(0);
8818 SelectionDAG &DAG = DCI.DAG;
8820 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8823 if (!Subtarget->isThumb1Only()) {
8824 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8825 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8826 if (Result.getNode())
8833 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8834 /// the bits being cleared by the AND are not demanded by the BFI.
8835 static SDValue PerformBFICombine(SDNode *N,
8836 TargetLowering::DAGCombinerInfo &DCI) {
8837 SDValue N1 = N->getOperand(1);
8838 if (N1.getOpcode() == ISD::AND) {
8839 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8842 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8843 unsigned LSB = countTrailingZeros(~InvMask);
8844 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8846 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8847 "undefined behavior");
8848 unsigned Mask = (1u << Width) - 1;
8849 unsigned Mask2 = N11C->getZExtValue();
8850 if ((Mask & (~Mask2)) == 0)
8851 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8852 N->getOperand(0), N1.getOperand(0),
8858 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8859 /// ARMISD::VMOVRRD.
8860 static SDValue PerformVMOVRRDCombine(SDNode *N,
8861 TargetLowering::DAGCombinerInfo &DCI,
8862 const ARMSubtarget *Subtarget) {
8863 // vmovrrd(vmovdrr x, y) -> x,y
8864 SDValue InDouble = N->getOperand(0);
8865 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8866 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8868 // vmovrrd(load f64) -> (load i32), (load i32)
8869 SDNode *InNode = InDouble.getNode();
8870 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8871 InNode->getValueType(0) == MVT::f64 &&
8872 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8873 !cast<LoadSDNode>(InNode)->isVolatile()) {
8874 // TODO: Should this be done for non-FrameIndex operands?
8875 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8877 SelectionDAG &DAG = DCI.DAG;
8879 SDValue BasePtr = LD->getBasePtr();
8880 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8881 LD->getPointerInfo(), LD->isVolatile(),
8882 LD->isNonTemporal(), LD->isInvariant(),
8883 LD->getAlignment());
8885 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8886 DAG.getConstant(4, DL, MVT::i32));
8887 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8888 LD->getPointerInfo(), LD->isVolatile(),
8889 LD->isNonTemporal(), LD->isInvariant(),
8890 std::min(4U, LD->getAlignment() / 2));
8892 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8893 if (DCI.DAG.getDataLayout().isBigEndian())
8894 std::swap (NewLD1, NewLD2);
8895 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8902 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8903 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8904 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8905 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8906 SDValue Op0 = N->getOperand(0);
8907 SDValue Op1 = N->getOperand(1);
8908 if (Op0.getOpcode() == ISD::BITCAST)
8909 Op0 = Op0.getOperand(0);
8910 if (Op1.getOpcode() == ISD::BITCAST)
8911 Op1 = Op1.getOperand(0);
8912 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8913 Op0.getNode() == Op1.getNode() &&
8914 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8915 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8916 N->getValueType(0), Op0.getOperand(0));
8920 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8921 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8922 /// i64 vector to have f64 elements, since the value can then be loaded
8923 /// directly into a VFP register.
8924 static bool hasNormalLoadOperand(SDNode *N) {
8925 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8926 for (unsigned i = 0; i < NumElts; ++i) {
8927 SDNode *Elt = N->getOperand(i).getNode();
8928 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8934 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8935 /// ISD::BUILD_VECTOR.
8936 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8937 TargetLowering::DAGCombinerInfo &DCI,
8938 const ARMSubtarget *Subtarget) {
8939 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8940 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8941 // into a pair of GPRs, which is fine when the value is used as a scalar,
8942 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8943 SelectionDAG &DAG = DCI.DAG;
8944 if (N->getNumOperands() == 2) {
8945 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8950 // Load i64 elements as f64 values so that type legalization does not split
8951 // them up into i32 values.
8952 EVT VT = N->getValueType(0);
8953 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8956 SmallVector<SDValue, 8> Ops;
8957 unsigned NumElts = VT.getVectorNumElements();
8958 for (unsigned i = 0; i < NumElts; ++i) {
8959 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8961 // Make the DAGCombiner fold the bitcast.
8962 DCI.AddToWorklist(V.getNode());
8964 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8965 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8966 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8969 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8971 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8972 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8973 // At that time, we may have inserted bitcasts from integer to float.
8974 // If these bitcasts have survived DAGCombine, change the lowering of this
8975 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8976 // force to use floating point types.
8978 // Make sure we can change the type of the vector.
8979 // This is possible iff:
8980 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8981 // 1.1. Vector is used only once.
8982 // 1.2. Use is a bit convert to an integer type.
8983 // 2. The size of its operands are 32-bits (64-bits are not legal).
8984 EVT VT = N->getValueType(0);
8985 EVT EltVT = VT.getVectorElementType();
8987 // Check 1.1. and 2.
8988 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8991 // By construction, the input type must be float.
8992 assert(EltVT == MVT::f32 && "Unexpected type!");
8995 SDNode *Use = *N->use_begin();
8996 if (Use->getOpcode() != ISD::BITCAST ||
8997 Use->getValueType(0).isFloatingPoint())
9000 // Check profitability.
9001 // Model is, if more than half of the relevant operands are bitcast from
9002 // i32, turn the build_vector into a sequence of insert_vector_elt.
9003 // Relevant operands are everything that is not statically
9004 // (i.e., at compile time) bitcasted.
9005 unsigned NumOfBitCastedElts = 0;
9006 unsigned NumElts = VT.getVectorNumElements();
9007 unsigned NumOfRelevantElts = NumElts;
9008 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9009 SDValue Elt = N->getOperand(Idx);
9010 if (Elt->getOpcode() == ISD::BITCAST) {
9011 // Assume only bit cast to i32 will go away.
9012 if (Elt->getOperand(0).getValueType() == MVT::i32)
9013 ++NumOfBitCastedElts;
9014 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9015 // Constants are statically casted, thus do not count them as
9016 // relevant operands.
9017 --NumOfRelevantElts;
9020 // Check if more than half of the elements require a non-free bitcast.
9021 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9024 SelectionDAG &DAG = DCI.DAG;
9025 // Create the new vector type.
9026 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9027 // Check if the type is legal.
9028 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9029 if (!TLI.isTypeLegal(VecVT))
9033 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9034 // => BITCAST INSERT_VECTOR_ELT
9035 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9037 SDValue Vec = DAG.getUNDEF(VecVT);
9039 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9040 SDValue V = N->getOperand(Idx);
9041 if (V.getOpcode() == ISD::UNDEF)
9043 if (V.getOpcode() == ISD::BITCAST &&
9044 V->getOperand(0).getValueType() == MVT::i32)
9045 // Fold obvious case.
9046 V = V.getOperand(0);
9048 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9049 // Make the DAGCombiner fold the bitcasts.
9050 DCI.AddToWorklist(V.getNode());
9052 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9053 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9055 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9056 // Make the DAGCombiner fold the bitcasts.
9057 DCI.AddToWorklist(Vec.getNode());
9061 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9062 /// ISD::INSERT_VECTOR_ELT.
9063 static SDValue PerformInsertEltCombine(SDNode *N,
9064 TargetLowering::DAGCombinerInfo &DCI) {
9065 // Bitcast an i64 load inserted into a vector to f64.
9066 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9067 EVT VT = N->getValueType(0);
9068 SDNode *Elt = N->getOperand(1).getNode();
9069 if (VT.getVectorElementType() != MVT::i64 ||
9070 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9073 SelectionDAG &DAG = DCI.DAG;
9075 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9076 VT.getVectorNumElements());
9077 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9078 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9079 // Make the DAGCombiner fold the bitcasts.
9080 DCI.AddToWorklist(Vec.getNode());
9081 DCI.AddToWorklist(V.getNode());
9082 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9083 Vec, V, N->getOperand(2));
9084 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9087 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9088 /// ISD::VECTOR_SHUFFLE.
9089 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9090 // The LLVM shufflevector instruction does not require the shuffle mask
9091 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9092 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9093 // operands do not match the mask length, they are extended by concatenating
9094 // them with undef vectors. That is probably the right thing for other
9095 // targets, but for NEON it is better to concatenate two double-register
9096 // size vector operands into a single quad-register size vector. Do that
9097 // transformation here:
9098 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9099 // shuffle(concat(v1, v2), undef)
9100 SDValue Op0 = N->getOperand(0);
9101 SDValue Op1 = N->getOperand(1);
9102 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9103 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9104 Op0.getNumOperands() != 2 ||
9105 Op1.getNumOperands() != 2)
9107 SDValue Concat0Op1 = Op0.getOperand(1);
9108 SDValue Concat1Op1 = Op1.getOperand(1);
9109 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9110 Concat1Op1.getOpcode() != ISD::UNDEF)
9112 // Skip the transformation if any of the types are illegal.
9113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9114 EVT VT = N->getValueType(0);
9115 if (!TLI.isTypeLegal(VT) ||
9116 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9117 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9120 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9121 Op0.getOperand(0), Op1.getOperand(0));
9122 // Translate the shuffle mask.
9123 SmallVector<int, 16> NewMask;
9124 unsigned NumElts = VT.getVectorNumElements();
9125 unsigned HalfElts = NumElts/2;
9126 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9127 for (unsigned n = 0; n < NumElts; ++n) {
9128 int MaskElt = SVN->getMaskElt(n);
9130 if (MaskElt < (int)HalfElts)
9132 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9133 NewElt = HalfElts + MaskElt - NumElts;
9134 NewMask.push_back(NewElt);
9136 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9137 DAG.getUNDEF(VT), NewMask.data());
9140 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9141 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9142 /// base address updates.
9143 /// For generic load/stores, the memory type is assumed to be a vector.
9144 /// The caller is assumed to have checked legality.
9145 static SDValue CombineBaseUpdate(SDNode *N,
9146 TargetLowering::DAGCombinerInfo &DCI) {
9147 SelectionDAG &DAG = DCI.DAG;
9148 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9149 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9150 const bool isStore = N->getOpcode() == ISD::STORE;
9151 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9152 SDValue Addr = N->getOperand(AddrOpIdx);
9153 MemSDNode *MemN = cast<MemSDNode>(N);
9156 // Search for a use of the address operand that is an increment.
9157 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9158 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9160 if (User->getOpcode() != ISD::ADD ||
9161 UI.getUse().getResNo() != Addr.getResNo())
9164 // Check that the add is independent of the load/store. Otherwise, folding
9165 // it would create a cycle.
9166 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9169 // Find the new opcode for the updating load/store.
9170 bool isLoadOp = true;
9171 bool isLaneOp = false;
9172 unsigned NewOpc = 0;
9173 unsigned NumVecs = 0;
9175 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9177 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9178 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9180 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9182 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9184 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9186 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9187 NumVecs = 2; isLaneOp = true; break;
9188 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9189 NumVecs = 3; isLaneOp = true; break;
9190 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9191 NumVecs = 4; isLaneOp = true; break;
9192 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9193 NumVecs = 1; isLoadOp = false; break;
9194 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9195 NumVecs = 2; isLoadOp = false; break;
9196 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9197 NumVecs = 3; isLoadOp = false; break;
9198 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9199 NumVecs = 4; isLoadOp = false; break;
9200 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9201 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9202 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9203 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9204 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9205 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9209 switch (N->getOpcode()) {
9210 default: llvm_unreachable("unexpected opcode for Neon base update");
9211 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9212 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9213 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9214 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9215 NumVecs = 1; isLaneOp = false; break;
9216 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9217 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9221 // Find the size of memory referenced by the load/store.
9224 VecTy = N->getValueType(0);
9225 } else if (isIntrinsic) {
9226 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9228 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9229 VecTy = N->getOperand(1).getValueType();
9232 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9234 NumBytes /= VecTy.getVectorNumElements();
9236 // If the increment is a constant, it must match the memory ref size.
9237 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9238 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9239 uint64_t IncVal = CInc->getZExtValue();
9240 if (IncVal != NumBytes)
9242 } else if (NumBytes >= 3 * 16) {
9243 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9244 // separate instructions that make it harder to use a non-constant update.
9248 // OK, we found an ADD we can fold into the base update.
9249 // Now, create a _UPD node, taking care of not breaking alignment.
9251 EVT AlignedVecTy = VecTy;
9252 unsigned Alignment = MemN->getAlignment();
9254 // If this is a less-than-standard-aligned load/store, change the type to
9255 // match the standard alignment.
9256 // The alignment is overlooked when selecting _UPD variants; and it's
9257 // easier to introduce bitcasts here than fix that.
9258 // There are 3 ways to get to this base-update combine:
9259 // - intrinsics: they are assumed to be properly aligned (to the standard
9260 // alignment of the memory type), so we don't need to do anything.
9261 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9262 // intrinsics, so, likewise, there's nothing to do.
9263 // - generic load/store instructions: the alignment is specified as an
9264 // explicit operand, rather than implicitly as the standard alignment
9265 // of the memory type (like the intrisics). We need to change the
9266 // memory type to match the explicit alignment. That way, we don't
9267 // generate non-standard-aligned ARMISD::VLDx nodes.
9268 if (isa<LSBaseSDNode>(N)) {
9271 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9272 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9273 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9274 assert(!isLaneOp && "Unexpected generic load/store lane.");
9275 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9276 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9278 // Don't set an explicit alignment on regular load/stores that we want
9279 // to transform to VLD/VST 1_UPD nodes.
9280 // This matches the behavior of regular load/stores, which only get an
9281 // explicit alignment if the MMO alignment is larger than the standard
9282 // alignment of the memory type.
9283 // Intrinsics, however, always get an explicit alignment, set to the
9284 // alignment of the MMO.
9288 // Create the new updating load/store node.
9289 // First, create an SDVTList for the new updating node's results.
9291 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9293 for (n = 0; n < NumResultVecs; ++n)
9294 Tys[n] = AlignedVecTy;
9295 Tys[n++] = MVT::i32;
9296 Tys[n] = MVT::Other;
9297 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9299 // Then, gather the new node's operands.
9300 SmallVector<SDValue, 8> Ops;
9301 Ops.push_back(N->getOperand(0)); // incoming chain
9302 Ops.push_back(N->getOperand(AddrOpIdx));
9305 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9306 // Try to match the intrinsic's signature
9307 Ops.push_back(StN->getValue());
9309 // Loads (and of course intrinsics) match the intrinsics' signature,
9310 // so just add all but the alignment operand.
9311 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9312 Ops.push_back(N->getOperand(i));
9315 // For all node types, the alignment operand is always the last one.
9316 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9318 // If this is a non-standard-aligned STORE, the penultimate operand is the
9319 // stored value. Bitcast it to the aligned type.
9320 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9321 SDValue &StVal = Ops[Ops.size()-2];
9322 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9325 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9327 MemN->getMemOperand());
9330 SmallVector<SDValue, 5> NewResults;
9331 for (unsigned i = 0; i < NumResultVecs; ++i)
9332 NewResults.push_back(SDValue(UpdN.getNode(), i));
9334 // If this is an non-standard-aligned LOAD, the first result is the loaded
9335 // value. Bitcast it to the expected result type.
9336 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9337 SDValue &LdVal = NewResults[0];
9338 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9341 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9342 DCI.CombineTo(N, NewResults);
9343 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9350 static SDValue PerformVLDCombine(SDNode *N,
9351 TargetLowering::DAGCombinerInfo &DCI) {
9352 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9355 return CombineBaseUpdate(N, DCI);
9358 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9359 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9360 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9362 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9363 SelectionDAG &DAG = DCI.DAG;
9364 EVT VT = N->getValueType(0);
9365 // vldN-dup instructions only support 64-bit vectors for N > 1.
9366 if (!VT.is64BitVector())
9369 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9370 SDNode *VLD = N->getOperand(0).getNode();
9371 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9373 unsigned NumVecs = 0;
9374 unsigned NewOpc = 0;
9375 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9376 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9378 NewOpc = ARMISD::VLD2DUP;
9379 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9381 NewOpc = ARMISD::VLD3DUP;
9382 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9384 NewOpc = ARMISD::VLD4DUP;
9389 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9390 // numbers match the load.
9391 unsigned VLDLaneNo =
9392 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9393 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9395 // Ignore uses of the chain result.
9396 if (UI.getUse().getResNo() == NumVecs)
9399 if (User->getOpcode() != ARMISD::VDUPLANE ||
9400 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9404 // Create the vldN-dup node.
9407 for (n = 0; n < NumVecs; ++n)
9409 Tys[n] = MVT::Other;
9410 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9411 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9412 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9413 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9414 Ops, VLDMemInt->getMemoryVT(),
9415 VLDMemInt->getMemOperand());
9418 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9420 unsigned ResNo = UI.getUse().getResNo();
9421 // Ignore uses of the chain result.
9422 if (ResNo == NumVecs)
9425 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9428 // Now the vldN-lane intrinsic is dead except for its chain result.
9429 // Update uses of the chain.
9430 std::vector<SDValue> VLDDupResults;
9431 for (unsigned n = 0; n < NumVecs; ++n)
9432 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9433 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9434 DCI.CombineTo(VLD, VLDDupResults);
9439 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9440 /// ARMISD::VDUPLANE.
9441 static SDValue PerformVDUPLANECombine(SDNode *N,
9442 TargetLowering::DAGCombinerInfo &DCI) {
9443 SDValue Op = N->getOperand(0);
9445 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9446 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9447 if (CombineVLDDUP(N, DCI))
9448 return SDValue(N, 0);
9450 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9451 // redundant. Ignore bit_converts for now; element sizes are checked below.
9452 while (Op.getOpcode() == ISD::BITCAST)
9453 Op = Op.getOperand(0);
9454 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9457 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9458 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9459 // The canonical VMOV for a zero vector uses a 32-bit element size.
9460 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9462 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9464 EVT VT = N->getValueType(0);
9465 if (EltSize > VT.getVectorElementType().getSizeInBits())
9468 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9471 static SDValue PerformLOADCombine(SDNode *N,
9472 TargetLowering::DAGCombinerInfo &DCI) {
9473 EVT VT = N->getValueType(0);
9475 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9476 if (ISD::isNormalLoad(N) && VT.isVector() &&
9477 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9478 return CombineBaseUpdate(N, DCI);
9483 /// PerformSTORECombine - Target-specific dag combine xforms for
9485 static SDValue PerformSTORECombine(SDNode *N,
9486 TargetLowering::DAGCombinerInfo &DCI) {
9487 StoreSDNode *St = cast<StoreSDNode>(N);
9488 if (St->isVolatile())
9491 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9492 // pack all of the elements in one place. Next, store to memory in fewer
9494 SDValue StVal = St->getValue();
9495 EVT VT = StVal.getValueType();
9496 if (St->isTruncatingStore() && VT.isVector()) {
9497 SelectionDAG &DAG = DCI.DAG;
9498 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9499 EVT StVT = St->getMemoryVT();
9500 unsigned NumElems = VT.getVectorNumElements();
9501 assert(StVT != VT && "Cannot truncate to the same type");
9502 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9503 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9505 // From, To sizes and ElemCount must be pow of two
9506 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9508 // We are going to use the original vector elt for storing.
9509 // Accumulated smaller vector elements must be a multiple of the store size.
9510 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9512 unsigned SizeRatio = FromEltSz / ToEltSz;
9513 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9515 // Create a type on which we perform the shuffle.
9516 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9517 NumElems*SizeRatio);
9518 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9521 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9522 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9523 for (unsigned i = 0; i < NumElems; ++i)
9524 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9525 ? (i + 1) * SizeRatio - 1
9528 // Can't shuffle using an illegal type.
9529 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9531 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9532 DAG.getUNDEF(WideVec.getValueType()),
9534 // At this point all of the data is stored at the bottom of the
9535 // register. We now need to save it to mem.
9537 // Find the largest store unit
9538 MVT StoreType = MVT::i8;
9539 for (MVT Tp : MVT::integer_valuetypes()) {
9540 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9543 // Didn't find a legal store type.
9544 if (!TLI.isTypeLegal(StoreType))
9547 // Bitcast the original vector into a vector of store-size units
9548 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9549 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9550 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9551 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9552 SmallVector<SDValue, 8> Chains;
9553 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9554 TLI.getPointerTy(DAG.getDataLayout()));
9555 SDValue BasePtr = St->getBasePtr();
9557 // Perform one or more big stores into memory.
9558 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9559 for (unsigned I = 0; I < E; I++) {
9560 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9561 StoreType, ShuffWide,
9562 DAG.getIntPtrConstant(I, DL));
9563 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9564 St->getPointerInfo(), St->isVolatile(),
9565 St->isNonTemporal(), St->getAlignment());
9566 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9568 Chains.push_back(Ch);
9570 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9573 if (!ISD::isNormalStore(St))
9576 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9577 // ARM stores of arguments in the same cache line.
9578 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9579 StVal.getNode()->hasOneUse()) {
9580 SelectionDAG &DAG = DCI.DAG;
9581 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9583 SDValue BasePtr = St->getBasePtr();
9584 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9585 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9586 BasePtr, St->getPointerInfo(), St->isVolatile(),
9587 St->isNonTemporal(), St->getAlignment());
9589 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9590 DAG.getConstant(4, DL, MVT::i32));
9591 return DAG.getStore(NewST1.getValue(0), DL,
9592 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9593 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9594 St->isNonTemporal(),
9595 std::min(4U, St->getAlignment() / 2));
9598 if (StVal.getValueType() == MVT::i64 &&
9599 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9601 // Bitcast an i64 store extracted from a vector to f64.
9602 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9603 SelectionDAG &DAG = DCI.DAG;
9605 SDValue IntVec = StVal.getOperand(0);
9606 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9607 IntVec.getValueType().getVectorNumElements());
9608 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9609 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9610 Vec, StVal.getOperand(1));
9612 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9613 // Make the DAGCombiner fold the bitcasts.
9614 DCI.AddToWorklist(Vec.getNode());
9615 DCI.AddToWorklist(ExtElt.getNode());
9616 DCI.AddToWorklist(V.getNode());
9617 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9618 St->getPointerInfo(), St->isVolatile(),
9619 St->isNonTemporal(), St->getAlignment(),
9623 // If this is a legal vector store, try to combine it into a VST1_UPD.
9624 if (ISD::isNormalStore(N) && VT.isVector() &&
9625 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9626 return CombineBaseUpdate(N, DCI);
9631 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9632 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9633 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9637 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9639 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9644 APFloat APF = C->getValueAPF();
9645 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9646 != APFloat::opOK || !isExact)
9649 c0 = (I == 0) ? cN : c0;
9650 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9657 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9658 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9659 /// when the VMUL has a constant operand that is a power of 2.
9661 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9662 /// vmul.f32 d16, d17, d16
9663 /// vcvt.s32.f32 d16, d16
9665 /// vcvt.s32.f32 d16, d16, #3
9666 static SDValue PerformVCVTCombine(SDNode *N,
9667 TargetLowering::DAGCombinerInfo &DCI,
9668 const ARMSubtarget *Subtarget) {
9669 SelectionDAG &DAG = DCI.DAG;
9670 SDValue Op = N->getOperand(0);
9672 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9673 Op.getOpcode() != ISD::FMUL)
9677 SDValue N0 = Op->getOperand(0);
9678 SDValue ConstVec = Op->getOperand(1);
9679 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9681 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9682 !isConstVecPow2(ConstVec, isSigned, C))
9685 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9686 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9687 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9688 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9690 // These instructions only exist converting from f32 to i32. We can handle
9691 // smaller integers by generating an extra truncate, but larger ones would
9692 // be lossy. We also can't handle more then 4 lanes, since these intructions
9693 // only support v2i32/v4i32 types.
9698 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9699 Intrinsic::arm_neon_vcvtfp2fxu;
9700 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9701 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9702 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9704 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9706 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9707 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9712 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9713 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9714 /// when the VDIV has a constant operand that is a power of 2.
9716 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9717 /// vcvt.f32.s32 d16, d16
9718 /// vdiv.f32 d16, d17, d16
9720 /// vcvt.f32.s32 d16, d16, #3
9721 static SDValue PerformVDIVCombine(SDNode *N,
9722 TargetLowering::DAGCombinerInfo &DCI,
9723 const ARMSubtarget *Subtarget) {
9724 SelectionDAG &DAG = DCI.DAG;
9725 SDValue Op = N->getOperand(0);
9726 unsigned OpOpcode = Op.getNode()->getOpcode();
9728 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9729 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9733 SDValue ConstVec = N->getOperand(1);
9734 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9736 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9737 !isConstVecPow2(ConstVec, isSigned, C))
9740 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9741 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9742 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9743 // These instructions only exist converting from i32 to f32. We can handle
9744 // smaller integers by generating an extra extend, but larger ones would
9750 SDValue ConvInput = Op.getOperand(0);
9751 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9752 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9753 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9754 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9757 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9758 Intrinsic::arm_neon_vcvtfxu2fp;
9759 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9761 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9762 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9765 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9766 /// operand of a vector shift operation, where all the elements of the
9767 /// build_vector must have the same constant integer value.
9768 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9769 // Ignore bit_converts.
9770 while (Op.getOpcode() == ISD::BITCAST)
9771 Op = Op.getOperand(0);
9772 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9773 APInt SplatBits, SplatUndef;
9774 unsigned SplatBitSize;
9776 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9777 HasAnyUndefs, ElementBits) ||
9778 SplatBitSize > ElementBits)
9780 Cnt = SplatBits.getSExtValue();
9784 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9785 /// operand of a vector shift left operation. That value must be in the range:
9786 /// 0 <= Value < ElementBits for a left shift; or
9787 /// 0 <= Value <= ElementBits for a long left shift.
9788 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9789 assert(VT.isVector() && "vector shift count is not a vector type");
9790 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9791 if (! getVShiftImm(Op, ElementBits, Cnt))
9793 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9796 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9797 /// operand of a vector shift right operation. For a shift opcode, the value
9798 /// is positive, but for an intrinsic the value count must be negative. The
9799 /// absolute value must be in the range:
9800 /// 1 <= |Value| <= ElementBits for a right shift; or
9801 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9802 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9804 assert(VT.isVector() && "vector shift count is not a vector type");
9805 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9806 if (! getVShiftImm(Op, ElementBits, Cnt))
9809 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9810 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9817 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9818 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9819 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9822 // Don't do anything for most intrinsics.
9825 case Intrinsic::arm_neon_vabds:
9826 if (!N->getValueType(0).isInteger())
9828 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9829 N->getOperand(1), N->getOperand(2));
9830 case Intrinsic::arm_neon_vabdu:
9831 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9832 N->getOperand(1), N->getOperand(2));
9834 // Vector shifts: check for immediate versions and lower them.
9835 // Note: This is done during DAG combining instead of DAG legalizing because
9836 // the build_vectors for 64-bit vector element shift counts are generally
9837 // not legal, and it is hard to see their values after they get legalized to
9838 // loads from a constant pool.
9839 case Intrinsic::arm_neon_vshifts:
9840 case Intrinsic::arm_neon_vshiftu:
9841 case Intrinsic::arm_neon_vrshifts:
9842 case Intrinsic::arm_neon_vrshiftu:
9843 case Intrinsic::arm_neon_vrshiftn:
9844 case Intrinsic::arm_neon_vqshifts:
9845 case Intrinsic::arm_neon_vqshiftu:
9846 case Intrinsic::arm_neon_vqshiftsu:
9847 case Intrinsic::arm_neon_vqshiftns:
9848 case Intrinsic::arm_neon_vqshiftnu:
9849 case Intrinsic::arm_neon_vqshiftnsu:
9850 case Intrinsic::arm_neon_vqrshiftns:
9851 case Intrinsic::arm_neon_vqrshiftnu:
9852 case Intrinsic::arm_neon_vqrshiftnsu: {
9853 EVT VT = N->getOperand(1).getValueType();
9855 unsigned VShiftOpc = 0;
9858 case Intrinsic::arm_neon_vshifts:
9859 case Intrinsic::arm_neon_vshiftu:
9860 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9861 VShiftOpc = ARMISD::VSHL;
9864 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9865 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9866 ARMISD::VSHRs : ARMISD::VSHRu);
9871 case Intrinsic::arm_neon_vrshifts:
9872 case Intrinsic::arm_neon_vrshiftu:
9873 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9877 case Intrinsic::arm_neon_vqshifts:
9878 case Intrinsic::arm_neon_vqshiftu:
9879 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9883 case Intrinsic::arm_neon_vqshiftsu:
9884 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9886 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9888 case Intrinsic::arm_neon_vrshiftn:
9889 case Intrinsic::arm_neon_vqshiftns:
9890 case Intrinsic::arm_neon_vqshiftnu:
9891 case Intrinsic::arm_neon_vqshiftnsu:
9892 case Intrinsic::arm_neon_vqrshiftns:
9893 case Intrinsic::arm_neon_vqrshiftnu:
9894 case Intrinsic::arm_neon_vqrshiftnsu:
9895 // Narrowing shifts require an immediate right shift.
9896 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9898 llvm_unreachable("invalid shift count for narrowing vector shift "
9902 llvm_unreachable("unhandled vector shift");
9906 case Intrinsic::arm_neon_vshifts:
9907 case Intrinsic::arm_neon_vshiftu:
9908 // Opcode already set above.
9910 case Intrinsic::arm_neon_vrshifts:
9911 VShiftOpc = ARMISD::VRSHRs; break;
9912 case Intrinsic::arm_neon_vrshiftu:
9913 VShiftOpc = ARMISD::VRSHRu; break;
9914 case Intrinsic::arm_neon_vrshiftn:
9915 VShiftOpc = ARMISD::VRSHRN; break;
9916 case Intrinsic::arm_neon_vqshifts:
9917 VShiftOpc = ARMISD::VQSHLs; break;
9918 case Intrinsic::arm_neon_vqshiftu:
9919 VShiftOpc = ARMISD::VQSHLu; break;
9920 case Intrinsic::arm_neon_vqshiftsu:
9921 VShiftOpc = ARMISD::VQSHLsu; break;
9922 case Intrinsic::arm_neon_vqshiftns:
9923 VShiftOpc = ARMISD::VQSHRNs; break;
9924 case Intrinsic::arm_neon_vqshiftnu:
9925 VShiftOpc = ARMISD::VQSHRNu; break;
9926 case Intrinsic::arm_neon_vqshiftnsu:
9927 VShiftOpc = ARMISD::VQSHRNsu; break;
9928 case Intrinsic::arm_neon_vqrshiftns:
9929 VShiftOpc = ARMISD::VQRSHRNs; break;
9930 case Intrinsic::arm_neon_vqrshiftnu:
9931 VShiftOpc = ARMISD::VQRSHRNu; break;
9932 case Intrinsic::arm_neon_vqrshiftnsu:
9933 VShiftOpc = ARMISD::VQRSHRNsu; break;
9937 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9938 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9941 case Intrinsic::arm_neon_vshiftins: {
9942 EVT VT = N->getOperand(1).getValueType();
9944 unsigned VShiftOpc = 0;
9946 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9947 VShiftOpc = ARMISD::VSLI;
9948 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9949 VShiftOpc = ARMISD::VSRI;
9951 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9955 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9956 N->getOperand(1), N->getOperand(2),
9957 DAG.getConstant(Cnt, dl, MVT::i32));
9960 case Intrinsic::arm_neon_vqrshifts:
9961 case Intrinsic::arm_neon_vqrshiftu:
9962 // No immediate versions of these to check for.
9969 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9970 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9971 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9972 /// vector element shift counts are generally not legal, and it is hard to see
9973 /// their values after they get legalized to loads from a constant pool.
9974 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9975 const ARMSubtarget *ST) {
9976 EVT VT = N->getValueType(0);
9977 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9978 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9979 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9980 SDValue N1 = N->getOperand(1);
9981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9982 SDValue N0 = N->getOperand(0);
9983 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9984 DAG.MaskedValueIsZero(N0.getOperand(0),
9985 APInt::getHighBitsSet(32, 16)))
9986 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9990 // Nothing to be done for scalar shifts.
9991 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9992 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9995 assert(ST->hasNEON() && "unexpected vector shift");
9998 switch (N->getOpcode()) {
9999 default: llvm_unreachable("unexpected shift opcode");
10002 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10004 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10005 DAG.getConstant(Cnt, dl, MVT::i32));
10011 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10012 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10013 ARMISD::VSHRs : ARMISD::VSHRu);
10015 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10016 DAG.getConstant(Cnt, dl, MVT::i32));
10022 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10023 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10024 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10025 const ARMSubtarget *ST) {
10026 SDValue N0 = N->getOperand(0);
10028 // Check for sign- and zero-extensions of vector extract operations of 8-
10029 // and 16-bit vector elements. NEON supports these directly. They are
10030 // handled during DAG combining because type legalization will promote them
10031 // to 32-bit types and it is messy to recognize the operations after that.
10032 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10033 SDValue Vec = N0.getOperand(0);
10034 SDValue Lane = N0.getOperand(1);
10035 EVT VT = N->getValueType(0);
10036 EVT EltVT = N0.getValueType();
10037 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10039 if (VT == MVT::i32 &&
10040 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10041 TLI.isTypeLegal(Vec.getValueType()) &&
10042 isa<ConstantSDNode>(Lane)) {
10045 switch (N->getOpcode()) {
10046 default: llvm_unreachable("unexpected opcode");
10047 case ISD::SIGN_EXTEND:
10048 Opc = ARMISD::VGETLANEs;
10050 case ISD::ZERO_EXTEND:
10051 case ISD::ANY_EXTEND:
10052 Opc = ARMISD::VGETLANEu;
10055 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10062 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10064 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10065 SDValue Cmp = N->getOperand(4);
10066 if (Cmp.getOpcode() != ARMISD::CMPZ)
10067 // Only looking at EQ and NE cases.
10070 EVT VT = N->getValueType(0);
10072 SDValue LHS = Cmp.getOperand(0);
10073 SDValue RHS = Cmp.getOperand(1);
10074 SDValue FalseVal = N->getOperand(0);
10075 SDValue TrueVal = N->getOperand(1);
10076 SDValue ARMcc = N->getOperand(2);
10077 ARMCC::CondCodes CC =
10078 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10096 /// FIXME: Turn this into a target neutral optimization?
10098 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10099 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10100 N->getOperand(3), Cmp);
10101 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10103 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10104 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10105 N->getOperand(3), NewCmp);
10108 if (Res.getNode()) {
10109 APInt KnownZero, KnownOne;
10110 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10111 // Capture demanded bits information that would be otherwise lost.
10112 if (KnownZero == 0xfffffffe)
10113 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10114 DAG.getValueType(MVT::i1));
10115 else if (KnownZero == 0xffffff00)
10116 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10117 DAG.getValueType(MVT::i8));
10118 else if (KnownZero == 0xffff0000)
10119 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10120 DAG.getValueType(MVT::i16));
10126 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10127 DAGCombinerInfo &DCI) const {
10128 switch (N->getOpcode()) {
10130 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10131 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10132 case ISD::SUB: return PerformSUBCombine(N, DCI);
10133 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10134 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10135 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10136 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10137 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10138 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10139 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10140 case ISD::STORE: return PerformSTORECombine(N, DCI);
10141 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10142 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10143 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10144 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10145 case ISD::FP_TO_SINT:
10146 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10147 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10148 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10151 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10152 case ISD::SIGN_EXTEND:
10153 case ISD::ZERO_EXTEND:
10154 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10155 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10156 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10157 case ARMISD::VLD2DUP:
10158 case ARMISD::VLD3DUP:
10159 case ARMISD::VLD4DUP:
10160 return PerformVLDCombine(N, DCI);
10161 case ARMISD::BUILD_VECTOR:
10162 return PerformARMBUILD_VECTORCombine(N, DCI);
10163 case ISD::INTRINSIC_VOID:
10164 case ISD::INTRINSIC_W_CHAIN:
10165 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10166 case Intrinsic::arm_neon_vld1:
10167 case Intrinsic::arm_neon_vld2:
10168 case Intrinsic::arm_neon_vld3:
10169 case Intrinsic::arm_neon_vld4:
10170 case Intrinsic::arm_neon_vld2lane:
10171 case Intrinsic::arm_neon_vld3lane:
10172 case Intrinsic::arm_neon_vld4lane:
10173 case Intrinsic::arm_neon_vst1:
10174 case Intrinsic::arm_neon_vst2:
10175 case Intrinsic::arm_neon_vst3:
10176 case Intrinsic::arm_neon_vst4:
10177 case Intrinsic::arm_neon_vst2lane:
10178 case Intrinsic::arm_neon_vst3lane:
10179 case Intrinsic::arm_neon_vst4lane:
10180 return PerformVLDCombine(N, DCI);
10188 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10190 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10193 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10196 bool *Fast) const {
10197 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10198 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10200 switch (VT.getSimpleVT().SimpleTy) {
10206 // Unaligned access can use (for example) LRDB, LRDH, LDR
10207 if (AllowsUnaligned) {
10209 *Fast = Subtarget->hasV7Ops();
10216 // For any little-endian targets with neon, we can support unaligned ld/st
10217 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10218 // A big-endian target may also explicitly support unaligned accesses
10219 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10229 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10230 unsigned AlignCheck) {
10231 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10232 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10235 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10236 unsigned DstAlign, unsigned SrcAlign,
10237 bool IsMemset, bool ZeroMemset,
10239 MachineFunction &MF) const {
10240 const Function *F = MF.getFunction();
10242 // See if we can use NEON instructions for this...
10243 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10244 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10247 (memOpAlign(SrcAlign, DstAlign, 16) ||
10248 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10250 } else if (Size >= 8 &&
10251 (memOpAlign(SrcAlign, DstAlign, 8) ||
10252 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10258 // Lowering to i32/i16 if the size permits.
10261 else if (Size >= 2)
10264 // Let the target-independent logic figure it out.
10268 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10269 if (Val.getOpcode() != ISD::LOAD)
10272 EVT VT1 = Val.getValueType();
10273 if (!VT1.isSimple() || !VT1.isInteger() ||
10274 !VT2.isSimple() || !VT2.isInteger())
10277 switch (VT1.getSimpleVT().SimpleTy) {
10282 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10289 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10290 EVT VT = ExtVal.getValueType();
10292 if (!isTypeLegal(VT))
10295 // Don't create a loadext if we can fold the extension into a wide/long
10297 // If there's more than one user instruction, the loadext is desirable no
10298 // matter what. There can be two uses by the same instruction.
10299 if (ExtVal->use_empty() ||
10300 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10303 SDNode *U = *ExtVal->use_begin();
10304 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10305 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10311 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10312 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10315 if (!isTypeLegal(EVT::getEVT(Ty1)))
10318 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10320 // Assuming the caller doesn't have a zeroext or signext return parameter,
10321 // truncation all the way down to i1 is valid.
10326 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10330 unsigned Scale = 1;
10331 switch (VT.getSimpleVT().SimpleTy) {
10332 default: return false;
10347 if ((V & (Scale - 1)) != 0)
10350 return V == (V & ((1LL << 5) - 1));
10353 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10354 const ARMSubtarget *Subtarget) {
10355 bool isNeg = false;
10361 switch (VT.getSimpleVT().SimpleTy) {
10362 default: return false;
10367 // + imm12 or - imm8
10369 return V == (V & ((1LL << 8) - 1));
10370 return V == (V & ((1LL << 12) - 1));
10373 // Same as ARM mode. FIXME: NEON?
10374 if (!Subtarget->hasVFP2())
10379 return V == (V & ((1LL << 8) - 1));
10383 /// isLegalAddressImmediate - Return true if the integer value can be used
10384 /// as the offset of the target addressing mode for load / store of the
10386 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10387 const ARMSubtarget *Subtarget) {
10391 if (!VT.isSimple())
10394 if (Subtarget->isThumb1Only())
10395 return isLegalT1AddressImmediate(V, VT);
10396 else if (Subtarget->isThumb2())
10397 return isLegalT2AddressImmediate(V, VT, Subtarget);
10402 switch (VT.getSimpleVT().SimpleTy) {
10403 default: return false;
10408 return V == (V & ((1LL << 12) - 1));
10411 return V == (V & ((1LL << 8) - 1));
10414 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10419 return V == (V & ((1LL << 8) - 1));
10423 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10425 int Scale = AM.Scale;
10429 switch (VT.getSimpleVT().SimpleTy) {
10430 default: return false;
10438 Scale = Scale & ~1;
10439 return Scale == 2 || Scale == 4 || Scale == 8;
10442 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10446 // Note, we allow "void" uses (basically, uses that aren't loads or
10447 // stores), because arm allows folding a scale into many arithmetic
10448 // operations. This should be made more precise and revisited later.
10450 // Allow r << imm, but the imm has to be a multiple of two.
10451 if (Scale & 1) return false;
10452 return isPowerOf2_32(Scale);
10456 /// isLegalAddressingMode - Return true if the addressing mode represented
10457 /// by AM is legal for this target, for a load/store of the specified type.
10458 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10459 const AddrMode &AM, Type *Ty,
10460 unsigned AS) const {
10461 EVT VT = getValueType(DL, Ty, true);
10462 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10465 // Can never fold addr of global into load/store.
10469 switch (AM.Scale) {
10470 case 0: // no scale reg, must be "r+i" or "r", or "i".
10473 if (Subtarget->isThumb1Only())
10477 // ARM doesn't support any R+R*scale+imm addr modes.
10481 if (!VT.isSimple())
10484 if (Subtarget->isThumb2())
10485 return isLegalT2ScaledAddressingMode(AM, VT);
10487 int Scale = AM.Scale;
10488 switch (VT.getSimpleVT().SimpleTy) {
10489 default: return false;
10493 if (Scale < 0) Scale = -Scale;
10497 return isPowerOf2_32(Scale & ~1);
10501 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10506 // Note, we allow "void" uses (basically, uses that aren't loads or
10507 // stores), because arm allows folding a scale into many arithmetic
10508 // operations. This should be made more precise and revisited later.
10510 // Allow r << imm, but the imm has to be a multiple of two.
10511 if (Scale & 1) return false;
10512 return isPowerOf2_32(Scale);
10518 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10519 /// icmp immediate, that is the target has icmp instructions which can compare
10520 /// a register against the immediate without having to materialize the
10521 /// immediate into a register.
10522 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10523 // Thumb2 and ARM modes can use cmn for negative immediates.
10524 if (!Subtarget->isThumb())
10525 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10526 if (Subtarget->isThumb2())
10527 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10528 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10529 return Imm >= 0 && Imm <= 255;
10532 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10533 /// *or sub* immediate, that is the target has add or sub instructions which can
10534 /// add a register with the immediate without having to materialize the
10535 /// immediate into a register.
10536 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10537 // Same encoding for add/sub, just flip the sign.
10538 int64_t AbsImm = std::abs(Imm);
10539 if (!Subtarget->isThumb())
10540 return ARM_AM::getSOImmVal(AbsImm) != -1;
10541 if (Subtarget->isThumb2())
10542 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10543 // Thumb1 only has 8-bit unsigned immediate.
10544 return AbsImm >= 0 && AbsImm <= 255;
10547 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10548 bool isSEXTLoad, SDValue &Base,
10549 SDValue &Offset, bool &isInc,
10550 SelectionDAG &DAG) {
10551 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10554 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10555 // AddressingMode 3
10556 Base = Ptr->getOperand(0);
10557 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10558 int RHSC = (int)RHS->getZExtValue();
10559 if (RHSC < 0 && RHSC > -256) {
10560 assert(Ptr->getOpcode() == ISD::ADD);
10562 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10566 isInc = (Ptr->getOpcode() == ISD::ADD);
10567 Offset = Ptr->getOperand(1);
10569 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10570 // AddressingMode 2
10571 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10572 int RHSC = (int)RHS->getZExtValue();
10573 if (RHSC < 0 && RHSC > -0x1000) {
10574 assert(Ptr->getOpcode() == ISD::ADD);
10576 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10577 Base = Ptr->getOperand(0);
10582 if (Ptr->getOpcode() == ISD::ADD) {
10584 ARM_AM::ShiftOpc ShOpcVal=
10585 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10586 if (ShOpcVal != ARM_AM::no_shift) {
10587 Base = Ptr->getOperand(1);
10588 Offset = Ptr->getOperand(0);
10590 Base = Ptr->getOperand(0);
10591 Offset = Ptr->getOperand(1);
10596 isInc = (Ptr->getOpcode() == ISD::ADD);
10597 Base = Ptr->getOperand(0);
10598 Offset = Ptr->getOperand(1);
10602 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10606 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10607 bool isSEXTLoad, SDValue &Base,
10608 SDValue &Offset, bool &isInc,
10609 SelectionDAG &DAG) {
10610 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10613 Base = Ptr->getOperand(0);
10614 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10615 int RHSC = (int)RHS->getZExtValue();
10616 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10617 assert(Ptr->getOpcode() == ISD::ADD);
10619 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10621 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10622 isInc = Ptr->getOpcode() == ISD::ADD;
10623 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10631 /// getPreIndexedAddressParts - returns true by value, base pointer and
10632 /// offset pointer and addressing mode by reference if the node's address
10633 /// can be legally represented as pre-indexed load / store address.
10635 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10637 ISD::MemIndexedMode &AM,
10638 SelectionDAG &DAG) const {
10639 if (Subtarget->isThumb1Only())
10644 bool isSEXTLoad = false;
10645 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10646 Ptr = LD->getBasePtr();
10647 VT = LD->getMemoryVT();
10648 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10649 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10650 Ptr = ST->getBasePtr();
10651 VT = ST->getMemoryVT();
10656 bool isLegal = false;
10657 if (Subtarget->isThumb2())
10658 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10659 Offset, isInc, DAG);
10661 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10662 Offset, isInc, DAG);
10666 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10670 /// getPostIndexedAddressParts - returns true by value, base pointer and
10671 /// offset pointer and addressing mode by reference if this node can be
10672 /// combined with a load / store to form a post-indexed load / store.
10673 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10676 ISD::MemIndexedMode &AM,
10677 SelectionDAG &DAG) const {
10678 if (Subtarget->isThumb1Only())
10683 bool isSEXTLoad = false;
10684 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10685 VT = LD->getMemoryVT();
10686 Ptr = LD->getBasePtr();
10687 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10688 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10689 VT = ST->getMemoryVT();
10690 Ptr = ST->getBasePtr();
10695 bool isLegal = false;
10696 if (Subtarget->isThumb2())
10697 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10700 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10706 // Swap base ptr and offset to catch more post-index load / store when
10707 // it's legal. In Thumb2 mode, offset must be an immediate.
10708 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10709 !Subtarget->isThumb2())
10710 std::swap(Base, Offset);
10712 // Post-indexed load / store update the base pointer.
10717 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10721 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10724 const SelectionDAG &DAG,
10725 unsigned Depth) const {
10726 unsigned BitWidth = KnownOne.getBitWidth();
10727 KnownZero = KnownOne = APInt(BitWidth, 0);
10728 switch (Op.getOpcode()) {
10734 // These nodes' second result is a boolean
10735 if (Op.getResNo() == 0)
10737 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10739 case ARMISD::CMOV: {
10740 // Bits are known zero/one if known on the LHS and RHS.
10741 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10742 if (KnownZero == 0 && KnownOne == 0) return;
10744 APInt KnownZeroRHS, KnownOneRHS;
10745 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10746 KnownZero &= KnownZeroRHS;
10747 KnownOne &= KnownOneRHS;
10750 case ISD::INTRINSIC_W_CHAIN: {
10751 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10752 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10755 case Intrinsic::arm_ldaex:
10756 case Intrinsic::arm_ldrex: {
10757 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10758 unsigned MemBits = VT.getScalarType().getSizeInBits();
10759 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10767 //===----------------------------------------------------------------------===//
10768 // ARM Inline Assembly Support
10769 //===----------------------------------------------------------------------===//
10771 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10772 // Looking for "rev" which is V6+.
10773 if (!Subtarget->hasV6Ops())
10776 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10777 std::string AsmStr = IA->getAsmString();
10778 SmallVector<StringRef, 4> AsmPieces;
10779 SplitString(AsmStr, AsmPieces, ";\n");
10781 switch (AsmPieces.size()) {
10782 default: return false;
10784 AsmStr = AsmPieces[0];
10786 SplitString(AsmStr, AsmPieces, " \t,");
10789 if (AsmPieces.size() == 3 &&
10790 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10791 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10792 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10793 if (Ty && Ty->getBitWidth() == 32)
10794 return IntrinsicLowering::LowerToByteSwap(CI);
10802 /// getConstraintType - Given a constraint letter, return the type of
10803 /// constraint it is for this target.
10804 ARMTargetLowering::ConstraintType
10805 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10806 if (Constraint.size() == 1) {
10807 switch (Constraint[0]) {
10809 case 'l': return C_RegisterClass;
10810 case 'w': return C_RegisterClass;
10811 case 'h': return C_RegisterClass;
10812 case 'x': return C_RegisterClass;
10813 case 't': return C_RegisterClass;
10814 case 'j': return C_Other; // Constant for movw.
10815 // An address with a single base register. Due to the way we
10816 // currently handle addresses it is the same as an 'r' memory constraint.
10817 case 'Q': return C_Memory;
10819 } else if (Constraint.size() == 2) {
10820 switch (Constraint[0]) {
10822 // All 'U+' constraints are addresses.
10823 case 'U': return C_Memory;
10826 return TargetLowering::getConstraintType(Constraint);
10829 /// Examine constraint type and operand type and determine a weight value.
10830 /// This object must already have been set up with the operand type
10831 /// and the current alternative constraint selected.
10832 TargetLowering::ConstraintWeight
10833 ARMTargetLowering::getSingleConstraintMatchWeight(
10834 AsmOperandInfo &info, const char *constraint) const {
10835 ConstraintWeight weight = CW_Invalid;
10836 Value *CallOperandVal = info.CallOperandVal;
10837 // If we don't have a value, we can't do a match,
10838 // but allow it at the lowest weight.
10839 if (!CallOperandVal)
10841 Type *type = CallOperandVal->getType();
10842 // Look at the constraint type.
10843 switch (*constraint) {
10845 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10848 if (type->isIntegerTy()) {
10849 if (Subtarget->isThumb())
10850 weight = CW_SpecificReg;
10852 weight = CW_Register;
10856 if (type->isFloatingPointTy())
10857 weight = CW_Register;
10863 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10864 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10865 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10866 if (Constraint.size() == 1) {
10867 // GCC ARM Constraint Letters
10868 switch (Constraint[0]) {
10869 case 'l': // Low regs or general regs.
10870 if (Subtarget->isThumb())
10871 return RCPair(0U, &ARM::tGPRRegClass);
10872 return RCPair(0U, &ARM::GPRRegClass);
10873 case 'h': // High regs or no regs.
10874 if (Subtarget->isThumb())
10875 return RCPair(0U, &ARM::hGPRRegClass);
10878 if (Subtarget->isThumb1Only())
10879 return RCPair(0U, &ARM::tGPRRegClass);
10880 return RCPair(0U, &ARM::GPRRegClass);
10882 if (VT == MVT::Other)
10884 if (VT == MVT::f32)
10885 return RCPair(0U, &ARM::SPRRegClass);
10886 if (VT.getSizeInBits() == 64)
10887 return RCPair(0U, &ARM::DPRRegClass);
10888 if (VT.getSizeInBits() == 128)
10889 return RCPair(0U, &ARM::QPRRegClass);
10892 if (VT == MVT::Other)
10894 if (VT == MVT::f32)
10895 return RCPair(0U, &ARM::SPR_8RegClass);
10896 if (VT.getSizeInBits() == 64)
10897 return RCPair(0U, &ARM::DPR_8RegClass);
10898 if (VT.getSizeInBits() == 128)
10899 return RCPair(0U, &ARM::QPR_8RegClass);
10902 if (VT == MVT::f32)
10903 return RCPair(0U, &ARM::SPRRegClass);
10907 if (StringRef("{cc}").equals_lower(Constraint))
10908 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10910 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10913 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10914 /// vector. If it is invalid, don't add anything to Ops.
10915 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10916 std::string &Constraint,
10917 std::vector<SDValue>&Ops,
10918 SelectionDAG &DAG) const {
10921 // Currently only support length 1 constraints.
10922 if (Constraint.length() != 1) return;
10924 char ConstraintLetter = Constraint[0];
10925 switch (ConstraintLetter) {
10928 case 'I': case 'J': case 'K': case 'L':
10929 case 'M': case 'N': case 'O':
10930 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10934 int64_t CVal64 = C->getSExtValue();
10935 int CVal = (int) CVal64;
10936 // None of these constraints allow values larger than 32 bits. Check
10937 // that the value fits in an int.
10938 if (CVal != CVal64)
10941 switch (ConstraintLetter) {
10943 // Constant suitable for movw, must be between 0 and
10945 if (Subtarget->hasV6T2Ops())
10946 if (CVal >= 0 && CVal <= 65535)
10950 if (Subtarget->isThumb1Only()) {
10951 // This must be a constant between 0 and 255, for ADD
10953 if (CVal >= 0 && CVal <= 255)
10955 } else if (Subtarget->isThumb2()) {
10956 // A constant that can be used as an immediate value in a
10957 // data-processing instruction.
10958 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10961 // A constant that can be used as an immediate value in a
10962 // data-processing instruction.
10963 if (ARM_AM::getSOImmVal(CVal) != -1)
10969 if (Subtarget->isThumb()) { // FIXME thumb2
10970 // This must be a constant between -255 and -1, for negated ADD
10971 // immediates. This can be used in GCC with an "n" modifier that
10972 // prints the negated value, for use with SUB instructions. It is
10973 // not useful otherwise but is implemented for compatibility.
10974 if (CVal >= -255 && CVal <= -1)
10977 // This must be a constant between -4095 and 4095. It is not clear
10978 // what this constraint is intended for. Implemented for
10979 // compatibility with GCC.
10980 if (CVal >= -4095 && CVal <= 4095)
10986 if (Subtarget->isThumb1Only()) {
10987 // A 32-bit value where only one byte has a nonzero value. Exclude
10988 // zero to match GCC. This constraint is used by GCC internally for
10989 // constants that can be loaded with a move/shift combination.
10990 // It is not useful otherwise but is implemented for compatibility.
10991 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10993 } else if (Subtarget->isThumb2()) {
10994 // A constant whose bitwise inverse can be used as an immediate
10995 // value in a data-processing instruction. This can be used in GCC
10996 // with a "B" modifier that prints the inverted value, for use with
10997 // BIC and MVN instructions. It is not useful otherwise but is
10998 // implemented for compatibility.
10999 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11002 // A constant whose bitwise inverse can be used as an immediate
11003 // value in a data-processing instruction. This can be used in GCC
11004 // with a "B" modifier that prints the inverted value, for use with
11005 // BIC and MVN instructions. It is not useful otherwise but is
11006 // implemented for compatibility.
11007 if (ARM_AM::getSOImmVal(~CVal) != -1)
11013 if (Subtarget->isThumb1Only()) {
11014 // This must be a constant between -7 and 7,
11015 // for 3-operand ADD/SUB immediate instructions.
11016 if (CVal >= -7 && CVal < 7)
11018 } else if (Subtarget->isThumb2()) {
11019 // A constant whose negation can be used as an immediate value in a
11020 // data-processing instruction. This can be used in GCC with an "n"
11021 // modifier that prints the negated value, for use with SUB
11022 // instructions. It is not useful otherwise but is implemented for
11024 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11027 // A constant whose negation can be used as an immediate value in a
11028 // data-processing instruction. This can be used in GCC with an "n"
11029 // modifier that prints the negated value, for use with SUB
11030 // instructions. It is not useful otherwise but is implemented for
11032 if (ARM_AM::getSOImmVal(-CVal) != -1)
11038 if (Subtarget->isThumb()) { // FIXME thumb2
11039 // This must be a multiple of 4 between 0 and 1020, for
11040 // ADD sp + immediate.
11041 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11044 // A power of two or a constant between 0 and 32. This is used in
11045 // GCC for the shift amount on shifted register operands, but it is
11046 // useful in general for any shift amounts.
11047 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11053 if (Subtarget->isThumb()) { // FIXME thumb2
11054 // This must be a constant between 0 and 31, for shift amounts.
11055 if (CVal >= 0 && CVal <= 31)
11061 if (Subtarget->isThumb()) { // FIXME thumb2
11062 // This must be a multiple of 4 between -508 and 508, for
11063 // ADD/SUB sp = sp + immediate.
11064 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11069 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11073 if (Result.getNode()) {
11074 Ops.push_back(Result);
11077 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11080 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11081 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11082 "Register-based DivRem lowering only");
11083 unsigned Opcode = Op->getOpcode();
11084 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11085 "Invalid opcode for Div/Rem lowering");
11086 bool isSigned = (Opcode == ISD::SDIVREM);
11087 EVT VT = Op->getValueType(0);
11088 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11091 switch (VT.getSimpleVT().SimpleTy) {
11092 default: llvm_unreachable("Unexpected request for libcall!");
11093 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11094 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11095 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11096 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11099 SDValue InChain = DAG.getEntryNode();
11101 TargetLowering::ArgListTy Args;
11102 TargetLowering::ArgListEntry Entry;
11103 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11104 EVT ArgVT = Op->getOperand(i).getValueType();
11105 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11106 Entry.Node = Op->getOperand(i);
11108 Entry.isSExt = isSigned;
11109 Entry.isZExt = !isSigned;
11110 Args.push_back(Entry);
11113 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11114 getPointerTy(DAG.getDataLayout()));
11116 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11119 TargetLowering::CallLoweringInfo CLI(DAG);
11120 CLI.setDebugLoc(dl).setChain(InChain)
11121 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11122 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11124 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11125 return CallInfo.first;
11129 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11130 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11134 SDValue Chain = Op.getOperand(0);
11135 SDValue Size = Op.getOperand(1);
11137 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11138 DAG.getConstant(2, DL, MVT::i32));
11141 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11142 Flag = Chain.getValue(1);
11144 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11145 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11147 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11148 Chain = NewSP.getValue(1);
11150 SDValue Ops[2] = { NewSP, Chain };
11151 return DAG.getMergeValues(Ops, DL);
11154 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11155 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11156 "Unexpected type for custom-lowering FP_EXTEND");
11159 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11161 SDValue SrcVal = Op.getOperand(0);
11162 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11163 /*isSigned*/ false, SDLoc(Op)).first;
11166 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11167 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11168 Subtarget->isFPOnlySP() &&
11169 "Unexpected type for custom-lowering FP_ROUND");
11172 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11174 SDValue SrcVal = Op.getOperand(0);
11175 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11176 /*isSigned*/ false, SDLoc(Op)).first;
11180 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11181 // The ARM target isn't yet aware of offsets.
11185 bool ARM::isBitFieldInvertedMask(unsigned v) {
11186 if (v == 0xffffffff)
11189 // there can be 1's on either or both "outsides", all the "inside"
11190 // bits must be 0's
11191 return isShiftedMask_32(~v);
11194 /// isFPImmLegal - Returns true if the target can instruction select the
11195 /// specified FP immediate natively. If false, the legalizer will
11196 /// materialize the FP immediate as a load from a constant pool.
11197 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11198 if (!Subtarget->hasVFP3())
11200 if (VT == MVT::f32)
11201 return ARM_AM::getFP32Imm(Imm) != -1;
11202 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11203 return ARM_AM::getFP64Imm(Imm) != -1;
11207 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11208 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11209 /// specified in the intrinsic calls.
11210 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11212 unsigned Intrinsic) const {
11213 switch (Intrinsic) {
11214 case Intrinsic::arm_neon_vld1:
11215 case Intrinsic::arm_neon_vld2:
11216 case Intrinsic::arm_neon_vld3:
11217 case Intrinsic::arm_neon_vld4:
11218 case Intrinsic::arm_neon_vld2lane:
11219 case Intrinsic::arm_neon_vld3lane:
11220 case Intrinsic::arm_neon_vld4lane: {
11221 Info.opc = ISD::INTRINSIC_W_CHAIN;
11222 // Conservatively set memVT to the entire set of vectors loaded.
11223 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11224 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11225 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11226 Info.ptrVal = I.getArgOperand(0);
11228 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11229 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11230 Info.vol = false; // volatile loads with NEON intrinsics not supported
11231 Info.readMem = true;
11232 Info.writeMem = false;
11235 case Intrinsic::arm_neon_vst1:
11236 case Intrinsic::arm_neon_vst2:
11237 case Intrinsic::arm_neon_vst3:
11238 case Intrinsic::arm_neon_vst4:
11239 case Intrinsic::arm_neon_vst2lane:
11240 case Intrinsic::arm_neon_vst3lane:
11241 case Intrinsic::arm_neon_vst4lane: {
11242 Info.opc = ISD::INTRINSIC_VOID;
11243 // Conservatively set memVT to the entire set of vectors stored.
11244 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11245 unsigned NumElts = 0;
11246 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11247 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11248 if (!ArgTy->isVectorTy())
11250 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11252 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11253 Info.ptrVal = I.getArgOperand(0);
11255 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11256 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11257 Info.vol = false; // volatile stores with NEON intrinsics not supported
11258 Info.readMem = false;
11259 Info.writeMem = true;
11262 case Intrinsic::arm_ldaex:
11263 case Intrinsic::arm_ldrex: {
11264 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11265 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11266 Info.opc = ISD::INTRINSIC_W_CHAIN;
11267 Info.memVT = MVT::getVT(PtrTy->getElementType());
11268 Info.ptrVal = I.getArgOperand(0);
11270 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11272 Info.readMem = true;
11273 Info.writeMem = false;
11276 case Intrinsic::arm_stlex:
11277 case Intrinsic::arm_strex: {
11278 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11279 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11280 Info.opc = ISD::INTRINSIC_W_CHAIN;
11281 Info.memVT = MVT::getVT(PtrTy->getElementType());
11282 Info.ptrVal = I.getArgOperand(1);
11284 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11286 Info.readMem = false;
11287 Info.writeMem = true;
11290 case Intrinsic::arm_stlexd:
11291 case Intrinsic::arm_strexd: {
11292 Info.opc = ISD::INTRINSIC_W_CHAIN;
11293 Info.memVT = MVT::i64;
11294 Info.ptrVal = I.getArgOperand(2);
11298 Info.readMem = false;
11299 Info.writeMem = true;
11302 case Intrinsic::arm_ldaexd:
11303 case Intrinsic::arm_ldrexd: {
11304 Info.opc = ISD::INTRINSIC_W_CHAIN;
11305 Info.memVT = MVT::i64;
11306 Info.ptrVal = I.getArgOperand(0);
11310 Info.readMem = true;
11311 Info.writeMem = false;
11321 /// \brief Returns true if it is beneficial to convert a load of a constant
11322 /// to just the constant itself.
11323 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11325 assert(Ty->isIntegerTy());
11327 unsigned Bits = Ty->getPrimitiveSizeInBits();
11328 if (Bits == 0 || Bits > 32)
11333 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11335 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11336 ARM_MB::MemBOpt Domain) const {
11337 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11339 // First, if the target has no DMB, see what fallback we can use.
11340 if (!Subtarget->hasDataBarrier()) {
11341 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11342 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11344 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11345 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11346 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11347 Builder.getInt32(0), Builder.getInt32(7),
11348 Builder.getInt32(10), Builder.getInt32(5)};
11349 return Builder.CreateCall(MCR, args);
11351 // Instead of using barriers, atomic accesses on these subtargets use
11353 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11356 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11357 // Only a full system barrier exists in the M-class architectures.
11358 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11359 Constant *CDomain = Builder.getInt32(Domain);
11360 return Builder.CreateCall(DMB, CDomain);
11364 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11365 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11366 AtomicOrdering Ord, bool IsStore,
11367 bool IsLoad) const {
11368 if (!getInsertFencesForAtomic())
11374 llvm_unreachable("Invalid fence: unordered/non-atomic");
11377 return nullptr; // Nothing to do
11378 case SequentiallyConsistent:
11380 return nullptr; // Nothing to do
11383 case AcquireRelease:
11384 if (Subtarget->isSwift())
11385 return makeDMB(Builder, ARM_MB::ISHST);
11386 // FIXME: add a comment with a link to documentation justifying this.
11388 return makeDMB(Builder, ARM_MB::ISH);
11390 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11393 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11394 AtomicOrdering Ord, bool IsStore,
11395 bool IsLoad) const {
11396 if (!getInsertFencesForAtomic())
11402 llvm_unreachable("Invalid fence: unordered/not-atomic");
11405 return nullptr; // Nothing to do
11407 case AcquireRelease:
11408 case SequentiallyConsistent:
11409 return makeDMB(Builder, ARM_MB::ISH);
11411 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11414 // Loads and stores less than 64-bits are already atomic; ones above that
11415 // are doomed anyway, so defer to the default libcall and blame the OS when
11416 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11417 // anything for those.
11418 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11419 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11420 return (Size == 64) && !Subtarget->isMClass();
11423 // Loads and stores less than 64-bits are already atomic; ones above that
11424 // are doomed anyway, so defer to the default libcall and blame the OS when
11425 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11426 // anything for those.
11427 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11428 // guarantee, see DDI0406C ARM architecture reference manual,
11429 // sections A8.8.72-74 LDRD)
11430 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11431 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11432 return (Size == 64) && !Subtarget->isMClass();
11435 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11436 // and up to 64 bits on the non-M profiles
11437 TargetLoweringBase::AtomicRMWExpansionKind
11438 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11439 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11440 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11441 ? AtomicRMWExpansionKind::LLSC
11442 : AtomicRMWExpansionKind::None;
11445 // This has so far only been implemented for MachO.
11446 bool ARMTargetLowering::useLoadStackGuardNode() const {
11447 return Subtarget->isTargetMachO();
11450 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11451 unsigned &Cost) const {
11452 // If we do not have NEON, vector types are not natively supported.
11453 if (!Subtarget->hasNEON())
11456 // Floating point values and vector values map to the same register file.
11457 // Therefore, although we could do a store extract of a vector type, this is
11458 // better to leave at float as we have more freedom in the addressing mode for
11460 if (VectorTy->isFPOrFPVectorTy())
11463 // If the index is unknown at compile time, this is very expensive to lower
11464 // and it is not possible to combine the store with the extract.
11465 if (!isa<ConstantInt>(Idx))
11468 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11469 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11470 // We can do a store + vector extract on any vector that fits perfectly in a D
11472 if (BitWidth == 64 || BitWidth == 128) {
11479 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11480 AtomicOrdering Ord) const {
11481 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11482 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11483 bool IsAcquire = isAtLeastAcquire(Ord);
11485 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11486 // intrinsic must return {i32, i32} and we have to recombine them into a
11487 // single i64 here.
11488 if (ValTy->getPrimitiveSizeInBits() == 64) {
11489 Intrinsic::ID Int =
11490 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11491 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11493 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11494 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11496 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11497 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11498 if (!Subtarget->isLittle())
11499 std::swap (Lo, Hi);
11500 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11501 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11502 return Builder.CreateOr(
11503 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11506 Type *Tys[] = { Addr->getType() };
11507 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11508 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11510 return Builder.CreateTruncOrBitCast(
11511 Builder.CreateCall(Ldrex, Addr),
11512 cast<PointerType>(Addr->getType())->getElementType());
11515 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11517 AtomicOrdering Ord) const {
11518 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11519 bool IsRelease = isAtLeastRelease(Ord);
11521 // Since the intrinsics must have legal type, the i64 intrinsics take two
11522 // parameters: "i32, i32". We must marshal Val into the appropriate form
11523 // before the call.
11524 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11525 Intrinsic::ID Int =
11526 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11527 Function *Strex = Intrinsic::getDeclaration(M, Int);
11528 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11530 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11531 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11532 if (!Subtarget->isLittle())
11533 std::swap (Lo, Hi);
11534 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11535 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11538 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11539 Type *Tys[] = { Addr->getType() };
11540 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11542 return Builder.CreateCall(
11543 Strex, {Builder.CreateZExtOrBitCast(
11544 Val, Strex->getFunctionType()->getParamType(0)),
11548 /// \brief Lower an interleaved load into a vldN intrinsic.
11550 /// E.g. Lower an interleaved load (Factor = 2):
11551 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11552 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11553 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11556 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11557 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11558 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11559 bool ARMTargetLowering::lowerInterleavedLoad(
11560 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11561 ArrayRef<unsigned> Indices, unsigned Factor) const {
11562 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11563 "Invalid interleave factor");
11564 assert(!Shuffles.empty() && "Empty shufflevector input");
11565 assert(Shuffles.size() == Indices.size() &&
11566 "Unmatched number of shufflevectors and indices");
11568 VectorType *VecTy = Shuffles[0]->getType();
11569 Type *EltTy = VecTy->getVectorElementType();
11571 const DataLayout &DL = LI->getModule()->getDataLayout();
11572 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11573 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11575 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11576 // support i64/f64 element).
11577 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11580 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11581 // load integer vectors first and then convert to pointer vectors.
11582 if (EltTy->isPointerTy())
11584 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11586 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11587 Intrinsic::arm_neon_vld3,
11588 Intrinsic::arm_neon_vld4};
11590 Function *VldnFunc =
11591 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11593 IRBuilder<> Builder(LI);
11594 SmallVector<Value *, 2> Ops;
11596 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11597 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11598 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11600 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11602 // Replace uses of each shufflevector with the corresponding vector loaded
11604 for (unsigned i = 0; i < Shuffles.size(); i++) {
11605 ShuffleVectorInst *SV = Shuffles[i];
11606 unsigned Index = Indices[i];
11608 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11610 // Convert the integer vector to pointer vector if the element is pointer.
11611 if (EltTy->isPointerTy())
11612 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11614 SV->replaceAllUsesWith(SubVec);
11620 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11622 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11623 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11624 unsigned NumElts) {
11625 SmallVector<Constant *, 16> Mask;
11626 for (unsigned i = 0; i < NumElts; i++)
11627 Mask.push_back(Builder.getInt32(Start + i));
11629 return ConstantVector::get(Mask);
11632 /// \brief Lower an interleaved store into a vstN intrinsic.
11634 /// E.g. Lower an interleaved store (Factor = 3):
11635 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11636 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11637 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11640 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11641 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11642 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11643 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11645 /// Note that the new shufflevectors will be removed and we'll only generate one
11646 /// vst3 instruction in CodeGen.
11647 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11648 ShuffleVectorInst *SVI,
11649 unsigned Factor) const {
11650 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11651 "Invalid interleave factor");
11653 VectorType *VecTy = SVI->getType();
11654 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11655 "Invalid interleaved store");
11657 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11658 Type *EltTy = VecTy->getVectorElementType();
11659 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11661 const DataLayout &DL = SI->getModule()->getDataLayout();
11662 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11663 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11665 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11666 // doesn't support i64/f64 element).
11667 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11670 Value *Op0 = SVI->getOperand(0);
11671 Value *Op1 = SVI->getOperand(1);
11672 IRBuilder<> Builder(SI);
11674 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11675 // vectors to integer vectors.
11676 if (EltTy->isPointerTy()) {
11677 Type *IntTy = DL.getIntPtrType(EltTy);
11679 // Convert to the corresponding integer vector.
11681 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11682 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11683 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11685 SubVecTy = VectorType::get(IntTy, NumSubElts);
11688 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11689 Intrinsic::arm_neon_vst3,
11690 Intrinsic::arm_neon_vst4};
11691 Function *VstNFunc = Intrinsic::getDeclaration(
11692 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11694 SmallVector<Value *, 6> Ops;
11696 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11697 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11699 // Split the shufflevector operands into sub vectors for the new vstN call.
11700 for (unsigned i = 0; i < Factor; i++)
11701 Ops.push_back(Builder.CreateShuffleVector(
11702 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11704 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11705 Builder.CreateCall(VstNFunc, Ops);
11717 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11718 uint64_t &Members) {
11719 if (auto *ST = dyn_cast<StructType>(Ty)) {
11720 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11721 uint64_t SubMembers = 0;
11722 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11724 Members += SubMembers;
11726 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11727 uint64_t SubMembers = 0;
11728 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11730 Members += SubMembers * AT->getNumElements();
11731 } else if (Ty->isFloatTy()) {
11732 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11736 } else if (Ty->isDoubleTy()) {
11737 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11741 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11748 return VT->getBitWidth() == 64;
11750 return VT->getBitWidth() == 128;
11752 switch (VT->getBitWidth()) {
11765 return (Members > 0 && Members <= 4);
11768 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11769 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11770 /// passing according to AAPCS rules.
11771 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11772 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11773 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11774 CallingConv::ARM_AAPCS_VFP)
11777 HABaseType Base = HA_UNKNOWN;
11778 uint64_t Members = 0;
11779 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11780 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11782 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11783 return IsHA || IsIntArray;