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);
150 if (!VT.isFloatingPoint() &&
151 VT != MVT::v2i64 && VT != MVT::v1i64)
152 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153 setOperationAction(Opcode, VT, Legal);
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPRRegClass);
159 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163 addRegisterClass(VT, &ARM::DPairRegClass);
164 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168 const ARMSubtarget &STI)
169 : TargetLowering(TM), Subtarget(&STI) {
170 RegInfo = Subtarget->getRegisterInfo();
171 Itins = Subtarget->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179 static const struct {
180 const RTLIB::Libcall Op;
181 const char * const Name;
182 const ISD::CondCode Cond;
184 // Single-precision floating-point arithmetic.
185 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
190 // Double-precision floating-point arithmetic.
191 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
196 // Single-precision comparisons.
197 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
198 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
199 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
200 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
201 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
202 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
203 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
204 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
206 // Double-precision comparisons.
207 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
208 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
209 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
210 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
211 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
212 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
213 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
214 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
216 // Floating-point to integer conversions.
217 // i64 conversions are done via library routines even when generating VFP
218 // instructions, so use the same ones.
219 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
220 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
222 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
224 // Conversions between floating types.
225 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
226 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
228 // Integer to floating-point conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232 // e.g., __floatunsidf vs. __floatunssidfvfp.
233 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
234 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
236 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
239 for (const auto &LC : LibraryCalls) {
240 setLibcallName(LC.Op, LC.Name);
241 if (LC.Cond != ISD::SETCC_INVALID)
242 setCmpLibcallCC(LC.Op, LC.Cond);
247 // These libcalls are not available in 32-bit.
248 setLibcallName(RTLIB::SHL_I128, nullptr);
249 setLibcallName(RTLIB::SRL_I128, nullptr);
250 setLibcallName(RTLIB::SRA_I128, nullptr);
252 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253 !Subtarget->isTargetWindows()) {
254 static const struct {
255 const RTLIB::Libcall Op;
256 const char * const Name;
257 const CallingConv::ID CC;
258 const ISD::CondCode Cond;
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267 // Double-precision floating-point comparison helper functions
268 // RTABI chapter 4.1.2, Table 3
269 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278 // Single-precision floating-point arithmetic helper functions
279 // RTABI chapter 4.1.2, Table 4
280 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285 // Single-precision floating-point comparison helper functions
286 // RTABI chapter 4.1.2, Table 5
287 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296 // Floating-point to integer conversions.
297 // RTABI chapter 4.1.2, Table 6
298 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 // Conversions between floating types.
308 // RTABI chapter 4.1.2, Table 7
309 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 // Integer to floating-point conversions.
314 // RTABI chapter 4.1.2, Table 8
315 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 // Long long helper functions
325 // RTABI chapter 4.2, Table 9
326 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 // Integer division functions
332 // RTABI chapter 4.3.1
333 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 // RTABI chapter 4.3.4
344 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 for (const auto &LC : LibraryCalls) {
350 setLibcallName(LC.Op, LC.Name);
351 setLibcallCallingConv(LC.Op, LC.CC);
352 if (LC.Cond != ISD::SETCC_INVALID)
353 setCmpLibcallCC(LC.Op, LC.Cond);
357 if (Subtarget->isTargetWindows()) {
358 static const struct {
359 const RTLIB::Libcall Op;
360 const char * const Name;
361 const CallingConv::ID CC;
363 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
378 for (const auto &LC : LibraryCalls) {
379 setLibcallName(LC.Op, LC.Name);
380 setLibcallCallingConv(LC.Op, LC.CC);
384 // Use divmod compiler-rt calls for iOS 5.0 and later.
385 if (Subtarget->getTargetTriple().isiOS() &&
386 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
391 // The half <-> float conversion functions are always soft-float, but are
392 // needed for some targets which use a hard-float calling convention by
394 if (Subtarget->isAAPCS_ABI()) {
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
404 if (Subtarget->isThumb1Only())
405 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
409 !Subtarget->isThumb1Only()) {
410 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
414 for (MVT VT : MVT::vector_valuetypes()) {
415 for (MVT InnerVT : MVT::vector_valuetypes()) {
416 setTruncStoreAction(VT, InnerVT, Expand);
417 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
418 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
419 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
422 setOperationAction(ISD::MULHS, VT, Expand);
423 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
424 setOperationAction(ISD::MULHU, VT, Expand);
425 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
427 setOperationAction(ISD::BSWAP, VT, Expand);
430 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
431 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
433 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
434 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
436 if (Subtarget->hasNEON()) {
437 addDRTypeForNEON(MVT::v2f32);
438 addDRTypeForNEON(MVT::v8i8);
439 addDRTypeForNEON(MVT::v4i16);
440 addDRTypeForNEON(MVT::v2i32);
441 addDRTypeForNEON(MVT::v1i64);
443 addQRTypeForNEON(MVT::v4f32);
444 addQRTypeForNEON(MVT::v2f64);
445 addQRTypeForNEON(MVT::v16i8);
446 addQRTypeForNEON(MVT::v8i16);
447 addQRTypeForNEON(MVT::v4i32);
448 addQRTypeForNEON(MVT::v2i64);
450 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451 // neither Neon nor VFP support any arithmetic operations on it.
452 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453 // supported for v4f32.
454 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457 // FIXME: Code duplication: FDIV and FREM are expanded always, see
458 // ARMTargetLowering::addTypeForNEON method for details.
459 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461 // FIXME: Create unittest.
462 // In another words, find a way when "copysign" appears in DAG with vector
464 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465 // FIXME: Code duplication: SETCC has custom operation action, see
466 // ARMTargetLowering::addTypeForNEON method for details.
467 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468 // FIXME: Create unittest for FNEG and for FABS.
469 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
489 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
505 // Mark v2f32 intrinsics.
506 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
545 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
547 // NEON does not have single instruction CTPOP for vectors with element
548 // types wider than 8-bits. However, custom lowering can leverage the
549 // v8i8/v16i8 vcnt instruction.
550 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
551 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
552 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
555 // NEON does not have single instruction CTTZ for vectors.
556 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
557 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
558 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
559 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
561 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
562 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
563 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
564 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
566 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
571 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
572 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
573 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
574 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
576 // NEON only has FMA instructions as of VFP4.
577 if (!Subtarget->hasVFP4()) {
578 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
579 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582 setTargetDAGCombine(ISD::INTRINSIC_VOID);
583 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
584 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
585 setTargetDAGCombine(ISD::SHL);
586 setTargetDAGCombine(ISD::SRL);
587 setTargetDAGCombine(ISD::SRA);
588 setTargetDAGCombine(ISD::SIGN_EXTEND);
589 setTargetDAGCombine(ISD::ZERO_EXTEND);
590 setTargetDAGCombine(ISD::ANY_EXTEND);
591 setTargetDAGCombine(ISD::BUILD_VECTOR);
592 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
593 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
594 setTargetDAGCombine(ISD::STORE);
595 setTargetDAGCombine(ISD::FP_TO_SINT);
596 setTargetDAGCombine(ISD::FP_TO_UINT);
597 setTargetDAGCombine(ISD::FDIV);
598 setTargetDAGCombine(ISD::LOAD);
600 // It is legal to extload from v4i8 to v4i16 or v4i32.
601 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
603 for (MVT VT : MVT::integer_vector_valuetypes()) {
604 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
605 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
606 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
611 // ARM and Thumb2 support UMLAL/SMLAL.
612 if (!Subtarget->isThumb1Only())
613 setTargetDAGCombine(ISD::ADDC);
615 if (Subtarget->isFPOnlySP()) {
616 // When targeting a floating-point unit with only single-precision
617 // operations, f64 is legal for the few double-precision instructions which
618 // are present However, no double-precision operations other than moves,
619 // loads and stores are provided by the hardware.
620 setOperationAction(ISD::FADD, MVT::f64, Expand);
621 setOperationAction(ISD::FSUB, MVT::f64, Expand);
622 setOperationAction(ISD::FMUL, MVT::f64, Expand);
623 setOperationAction(ISD::FMA, MVT::f64, Expand);
624 setOperationAction(ISD::FDIV, MVT::f64, Expand);
625 setOperationAction(ISD::FREM, MVT::f64, Expand);
626 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
627 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
628 setOperationAction(ISD::FNEG, MVT::f64, Expand);
629 setOperationAction(ISD::FABS, MVT::f64, Expand);
630 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
631 setOperationAction(ISD::FSIN, MVT::f64, Expand);
632 setOperationAction(ISD::FCOS, MVT::f64, Expand);
633 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
634 setOperationAction(ISD::FPOW, MVT::f64, Expand);
635 setOperationAction(ISD::FLOG, MVT::f64, Expand);
636 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
637 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
638 setOperationAction(ISD::FEXP, MVT::f64, Expand);
639 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
640 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
641 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
642 setOperationAction(ISD::FRINT, MVT::f64, Expand);
643 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
644 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
645 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
646 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
647 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
648 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
649 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
650 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
651 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
652 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
655 computeRegisterProperties(Subtarget->getRegisterInfo());
657 // ARM does not have floating-point extending loads.
658 for (MVT VT : MVT::fp_valuetypes()) {
659 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
660 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
663 // ... or truncating stores
664 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
665 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
666 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
668 // ARM does not have i1 sign extending load.
669 for (MVT VT : MVT::integer_valuetypes())
670 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
672 // ARM supports all 4 flavors of integer indexed load / store.
673 if (!Subtarget->isThumb1Only()) {
674 for (unsigned im = (unsigned)ISD::PRE_INC;
675 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
676 setIndexedLoadAction(im, MVT::i1, Legal);
677 setIndexedLoadAction(im, MVT::i8, Legal);
678 setIndexedLoadAction(im, MVT::i16, Legal);
679 setIndexedLoadAction(im, MVT::i32, Legal);
680 setIndexedStoreAction(im, MVT::i1, Legal);
681 setIndexedStoreAction(im, MVT::i8, Legal);
682 setIndexedStoreAction(im, MVT::i16, Legal);
683 setIndexedStoreAction(im, MVT::i32, Legal);
687 setOperationAction(ISD::SADDO, MVT::i32, Custom);
688 setOperationAction(ISD::UADDO, MVT::i32, Custom);
689 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
690 setOperationAction(ISD::USUBO, MVT::i32, Custom);
692 // i64 operation support.
693 setOperationAction(ISD::MUL, MVT::i64, Expand);
694 setOperationAction(ISD::MULHU, MVT::i32, Expand);
695 if (Subtarget->isThumb1Only()) {
696 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
697 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
699 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
700 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
701 setOperationAction(ISD::MULHS, MVT::i32, Expand);
703 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
704 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
705 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
706 setOperationAction(ISD::SRL, MVT::i64, Custom);
707 setOperationAction(ISD::SRA, MVT::i64, Custom);
709 if (!Subtarget->isThumb1Only()) {
710 // FIXME: We should do this for Thumb1 as well.
711 setOperationAction(ISD::ADDC, MVT::i32, Custom);
712 setOperationAction(ISD::ADDE, MVT::i32, Custom);
713 setOperationAction(ISD::SUBC, MVT::i32, Custom);
714 setOperationAction(ISD::SUBE, MVT::i32, Custom);
717 // ARM does not have ROTL.
718 setOperationAction(ISD::ROTL, MVT::i32, Expand);
719 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
720 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
721 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
722 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
724 // These just redirect to CTTZ and CTLZ on ARM.
725 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
726 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
728 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
730 // Only ARMv6 has BSWAP.
731 if (!Subtarget->hasV6Ops())
732 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
734 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
735 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
736 // These are expanded into libcalls if the cpu doesn't have HW divider.
737 setOperationAction(ISD::SDIV, MVT::i32, Expand);
738 setOperationAction(ISD::UDIV, MVT::i32, Expand);
741 // FIXME: Also set divmod for SREM on EABI/androideabi
742 setOperationAction(ISD::SREM, MVT::i32, Expand);
743 setOperationAction(ISD::UREM, MVT::i32, Expand);
744 // Register based DivRem for AEABI (RTABI 4.2)
745 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
746 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
747 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
748 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
749 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
750 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
751 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
752 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
753 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
755 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
756 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
757 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
758 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
759 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
760 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
761 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
762 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
764 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
765 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
767 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
768 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
771 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
772 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
773 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
774 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
775 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
777 setOperationAction(ISD::TRAP, MVT::Other, Legal);
779 // Use the default implementation.
780 setOperationAction(ISD::VASTART, MVT::Other, Custom);
781 setOperationAction(ISD::VAARG, MVT::Other, Expand);
782 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
783 setOperationAction(ISD::VAEND, MVT::Other, Expand);
784 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
785 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
787 if (!Subtarget->isTargetMachO()) {
788 // Non-MachO platforms may return values in these registers via the
789 // personality function.
790 setExceptionPointerRegister(ARM::R0);
791 setExceptionSelectorRegister(ARM::R1);
794 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
795 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
797 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
799 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
800 // the default expansion. If we are targeting a single threaded system,
801 // then set them all for expand so we can lower them later into their
803 if (TM.Options.ThreadModel == ThreadModel::Single)
804 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
805 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
806 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
807 // to ldrex/strex loops already.
808 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
810 // On v8, we have particularly efficient implementations of atomic fences
811 // if they can be combined with nearby atomic loads and stores.
812 if (!Subtarget->hasV8Ops()) {
813 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
814 setInsertFencesForAtomic(true);
817 // If there's anything we can use as a barrier, go through custom lowering
819 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
820 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
822 // Set them all for expansion, which will force libcalls.
823 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
824 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
825 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
826 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
827 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
828 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
829 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
830 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
831 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
832 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
833 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
834 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
835 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
836 // Unordered/Monotonic case.
837 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
838 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
841 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
843 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
844 if (!Subtarget->hasV6Ops()) {
845 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
846 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
848 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
850 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
851 !Subtarget->isThumb1Only()) {
852 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
853 // iff target supports vfp2.
854 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
855 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
858 // We want to custom lower some of our intrinsics.
859 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
860 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
861 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
862 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
863 if (Subtarget->isTargetDarwin())
864 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
866 setOperationAction(ISD::SETCC, MVT::i32, Expand);
867 setOperationAction(ISD::SETCC, MVT::f32, Expand);
868 setOperationAction(ISD::SETCC, MVT::f64, Expand);
869 setOperationAction(ISD::SELECT, MVT::i32, Custom);
870 setOperationAction(ISD::SELECT, MVT::f32, Custom);
871 setOperationAction(ISD::SELECT, MVT::f64, Custom);
872 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
873 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
874 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
876 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
877 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
878 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
879 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
880 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
882 // We don't support sin/cos/fmod/copysign/pow
883 setOperationAction(ISD::FSIN, MVT::f64, Expand);
884 setOperationAction(ISD::FSIN, MVT::f32, Expand);
885 setOperationAction(ISD::FCOS, MVT::f32, Expand);
886 setOperationAction(ISD::FCOS, MVT::f64, Expand);
887 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
888 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
889 setOperationAction(ISD::FREM, MVT::f64, Expand);
890 setOperationAction(ISD::FREM, MVT::f32, Expand);
891 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892 !Subtarget->isThumb1Only()) {
893 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
894 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
896 setOperationAction(ISD::FPOW, MVT::f64, Expand);
897 setOperationAction(ISD::FPOW, MVT::f32, Expand);
899 if (!Subtarget->hasVFP4()) {
900 setOperationAction(ISD::FMA, MVT::f64, Expand);
901 setOperationAction(ISD::FMA, MVT::f32, Expand);
904 // Various VFP goodness
905 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
906 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
907 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
908 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
909 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
912 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
913 if (!Subtarget->hasFP16()) {
914 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
915 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
919 // Combine sin / cos into one node or libcall if possible.
920 if (Subtarget->hasSinCos()) {
921 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
922 setLibcallName(RTLIB::SINCOS_F64, "sincos");
923 if (Subtarget->getTargetTriple().isiOS()) {
924 // For iOS, we don't want to the normal expansion of a libcall to
925 // sincos. We want to issue a libcall to __sincos_stret.
926 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
927 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
931 // FP-ARMv8 implements a lot of rounding-like FP operations.
932 if (Subtarget->hasFPARMv8()) {
933 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
934 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
935 setOperationAction(ISD::FROUND, MVT::f32, Legal);
936 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
937 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
938 setOperationAction(ISD::FRINT, MVT::f32, Legal);
939 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
940 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
941 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
942 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
943 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
944 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
946 if (!Subtarget->isFPOnlySP()) {
947 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949 setOperationAction(ISD::FROUND, MVT::f64, Legal);
950 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
951 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
952 setOperationAction(ISD::FRINT, MVT::f64, Legal);
953 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
954 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
958 if (Subtarget->hasNEON()) {
959 // vmin and vmax aren't available in a scalar form, so we use
960 // a NEON instruction with an undef lane instead.
961 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
962 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
963 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
964 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
965 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
966 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
969 // We have target-specific dag combine patterns for the following nodes:
970 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
971 setTargetDAGCombine(ISD::ADD);
972 setTargetDAGCombine(ISD::SUB);
973 setTargetDAGCombine(ISD::MUL);
974 setTargetDAGCombine(ISD::AND);
975 setTargetDAGCombine(ISD::OR);
976 setTargetDAGCombine(ISD::XOR);
978 if (Subtarget->hasV6Ops())
979 setTargetDAGCombine(ISD::SRL);
981 setStackPointerRegisterToSaveRestore(ARM::SP);
983 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
984 !Subtarget->hasVFP2())
985 setSchedulingPreference(Sched::RegPressure);
987 setSchedulingPreference(Sched::Hybrid);
989 //// temporary - rewrite interface to use type
990 MaxStoresPerMemset = 8;
991 MaxStoresPerMemsetOptSize = 4;
992 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
993 MaxStoresPerMemcpyOptSize = 2;
994 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
995 MaxStoresPerMemmoveOptSize = 2;
997 // On ARM arguments smaller than 4 bytes are extended, so all arguments
998 // are at least 4 bytes aligned.
999 setMinStackArgumentAlignment(4);
1001 // Prefer likely predicted branches to selects on out-of-order cores.
1002 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1004 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1007 bool ARMTargetLowering::useSoftFloat() const {
1008 return Subtarget->useSoftFloat();
1011 // FIXME: It might make sense to define the representative register class as the
1012 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1013 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1014 // SPR's representative would be DPR_VFP2. This should work well if register
1015 // pressure tracking were modified such that a register use would increment the
1016 // pressure of the register class's representative and all of it's super
1017 // classes' representatives transitively. We have not implemented this because
1018 // of the difficulty prior to coalescing of modeling operand register classes
1019 // due to the common occurrence of cross class copies and subregister insertions
1021 std::pair<const TargetRegisterClass *, uint8_t>
1022 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1024 const TargetRegisterClass *RRC = nullptr;
1026 switch (VT.SimpleTy) {
1028 return TargetLowering::findRepresentativeClass(TRI, VT);
1029 // Use DPR as representative register class for all floating point
1030 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1031 // the cost is 1 for both f32 and f64.
1032 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1033 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1034 RRC = &ARM::DPRRegClass;
1035 // When NEON is used for SP, only half of the register file is available
1036 // because operations that define both SP and DP results will be constrained
1037 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1038 // coalescing by double-counting the SP regs. See the FIXME above.
1039 if (Subtarget->useNEONForSinglePrecisionFP())
1042 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1043 case MVT::v4f32: case MVT::v2f64:
1044 RRC = &ARM::DPRRegClass;
1048 RRC = &ARM::DPRRegClass;
1052 RRC = &ARM::DPRRegClass;
1056 return std::make_pair(RRC, Cost);
1059 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1060 switch ((ARMISD::NodeType)Opcode) {
1061 case ARMISD::FIRST_NUMBER: break;
1062 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1063 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1064 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1065 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1066 case ARMISD::CALL: return "ARMISD::CALL";
1067 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1068 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1069 case ARMISD::tCALL: return "ARMISD::tCALL";
1070 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1071 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1072 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1073 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1074 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1075 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1076 case ARMISD::CMP: return "ARMISD::CMP";
1077 case ARMISD::CMN: return "ARMISD::CMN";
1078 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1079 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1080 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1081 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1082 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1084 case ARMISD::CMOV: return "ARMISD::CMOV";
1086 case ARMISD::RBIT: return "ARMISD::RBIT";
1088 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1089 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1090 case ARMISD::RRX: return "ARMISD::RRX";
1092 case ARMISD::ADDC: return "ARMISD::ADDC";
1093 case ARMISD::ADDE: return "ARMISD::ADDE";
1094 case ARMISD::SUBC: return "ARMISD::SUBC";
1095 case ARMISD::SUBE: return "ARMISD::SUBE";
1097 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1098 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1100 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1101 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1102 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1104 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1106 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1108 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1110 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1112 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1114 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1116 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1117 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1118 case ARMISD::VCGE: return "ARMISD::VCGE";
1119 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1120 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1121 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1122 case ARMISD::VCGT: return "ARMISD::VCGT";
1123 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1124 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1125 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1126 case ARMISD::VTST: return "ARMISD::VTST";
1128 case ARMISD::VSHL: return "ARMISD::VSHL";
1129 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1130 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1131 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1132 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1133 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1134 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1135 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1136 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1137 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1138 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1139 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1140 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1141 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1142 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1143 case ARMISD::VSLI: return "ARMISD::VSLI";
1144 case ARMISD::VSRI: return "ARMISD::VSRI";
1145 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1146 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1147 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1148 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1149 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1150 case ARMISD::VDUP: return "ARMISD::VDUP";
1151 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1152 case ARMISD::VEXT: return "ARMISD::VEXT";
1153 case ARMISD::VREV64: return "ARMISD::VREV64";
1154 case ARMISD::VREV32: return "ARMISD::VREV32";
1155 case ARMISD::VREV16: return "ARMISD::VREV16";
1156 case ARMISD::VZIP: return "ARMISD::VZIP";
1157 case ARMISD::VUZP: return "ARMISD::VUZP";
1158 case ARMISD::VTRN: return "ARMISD::VTRN";
1159 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1160 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1161 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1162 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1163 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1164 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1165 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1166 case ARMISD::BFI: return "ARMISD::BFI";
1167 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1168 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1169 case ARMISD::VBSL: return "ARMISD::VBSL";
1170 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1171 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1172 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1173 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1174 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1175 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1176 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1177 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1178 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1179 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1180 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1181 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1182 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1183 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1184 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1185 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1186 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1187 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1188 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1189 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1194 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1197 return getPointerTy(DL);
1198 return VT.changeVectorElementTypeToInteger();
1201 /// getRegClassFor - Return the register class that should be used for the
1202 /// specified value type.
1203 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1204 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1205 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1206 // load / store 4 to 8 consecutive D registers.
1207 if (Subtarget->hasNEON()) {
1208 if (VT == MVT::v4i64)
1209 return &ARM::QQPRRegClass;
1210 if (VT == MVT::v8i64)
1211 return &ARM::QQQQPRRegClass;
1213 return TargetLowering::getRegClassFor(VT);
1216 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1217 // source/dest is aligned and the copy size is large enough. We therefore want
1218 // to align such objects passed to memory intrinsics.
1219 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1220 unsigned &PrefAlign) const {
1221 if (!isa<MemIntrinsic>(CI))
1224 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1225 // cycle faster than 4-byte aligned LDM.
1226 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1230 // Create a fast isel object.
1232 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1233 const TargetLibraryInfo *libInfo) const {
1234 return ARM::createFastISel(funcInfo, libInfo);
1237 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1238 unsigned NumVals = N->getNumValues();
1240 return Sched::RegPressure;
1242 for (unsigned i = 0; i != NumVals; ++i) {
1243 EVT VT = N->getValueType(i);
1244 if (VT == MVT::Glue || VT == MVT::Other)
1246 if (VT.isFloatingPoint() || VT.isVector())
1250 if (!N->isMachineOpcode())
1251 return Sched::RegPressure;
1253 // Load are scheduled for latency even if there instruction itinerary
1254 // is not available.
1255 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1256 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1258 if (MCID.getNumDefs() == 0)
1259 return Sched::RegPressure;
1260 if (!Itins->isEmpty() &&
1261 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1264 return Sched::RegPressure;
1267 //===----------------------------------------------------------------------===//
1269 //===----------------------------------------------------------------------===//
1271 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1272 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1274 default: llvm_unreachable("Unknown condition code!");
1275 case ISD::SETNE: return ARMCC::NE;
1276 case ISD::SETEQ: return ARMCC::EQ;
1277 case ISD::SETGT: return ARMCC::GT;
1278 case ISD::SETGE: return ARMCC::GE;
1279 case ISD::SETLT: return ARMCC::LT;
1280 case ISD::SETLE: return ARMCC::LE;
1281 case ISD::SETUGT: return ARMCC::HI;
1282 case ISD::SETUGE: return ARMCC::HS;
1283 case ISD::SETULT: return ARMCC::LO;
1284 case ISD::SETULE: return ARMCC::LS;
1288 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1289 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1290 ARMCC::CondCodes &CondCode2) {
1291 CondCode2 = ARMCC::AL;
1293 default: llvm_unreachable("Unknown FP condition!");
1295 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1297 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1299 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1300 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1301 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1302 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1303 case ISD::SETO: CondCode = ARMCC::VC; break;
1304 case ISD::SETUO: CondCode = ARMCC::VS; break;
1305 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1306 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1307 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1309 case ISD::SETULT: CondCode = ARMCC::LT; break;
1311 case ISD::SETULE: CondCode = ARMCC::LE; break;
1313 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1317 //===----------------------------------------------------------------------===//
1318 // Calling Convention Implementation
1319 //===----------------------------------------------------------------------===//
1321 #include "ARMGenCallingConv.inc"
1323 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1324 /// account presence of floating point hardware and calling convention
1325 /// limitations, such as support for variadic functions.
1327 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1328 bool isVarArg) const {
1331 llvm_unreachable("Unsupported calling convention");
1332 case CallingConv::ARM_AAPCS:
1333 case CallingConv::ARM_APCS:
1334 case CallingConv::GHC:
1336 case CallingConv::ARM_AAPCS_VFP:
1337 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1338 case CallingConv::C:
1339 if (!Subtarget->isAAPCS_ABI())
1340 return CallingConv::ARM_APCS;
1341 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1342 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1344 return CallingConv::ARM_AAPCS_VFP;
1346 return CallingConv::ARM_AAPCS;
1347 case CallingConv::Fast:
1348 if (!Subtarget->isAAPCS_ABI()) {
1349 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1350 return CallingConv::Fast;
1351 return CallingConv::ARM_APCS;
1352 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1353 return CallingConv::ARM_AAPCS_VFP;
1355 return CallingConv::ARM_AAPCS;
1359 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1360 /// CallingConvention.
1361 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1363 bool isVarArg) const {
1364 switch (getEffectiveCallingConv(CC, isVarArg)) {
1366 llvm_unreachable("Unsupported calling convention");
1367 case CallingConv::ARM_APCS:
1368 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1369 case CallingConv::ARM_AAPCS:
1370 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1371 case CallingConv::ARM_AAPCS_VFP:
1372 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1373 case CallingConv::Fast:
1374 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1375 case CallingConv::GHC:
1376 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1380 /// LowerCallResult - Lower the result values of a call into the
1381 /// appropriate copies out of appropriate physical registers.
1383 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1384 CallingConv::ID CallConv, bool isVarArg,
1385 const SmallVectorImpl<ISD::InputArg> &Ins,
1386 SDLoc dl, SelectionDAG &DAG,
1387 SmallVectorImpl<SDValue> &InVals,
1388 bool isThisReturn, SDValue ThisVal) const {
1390 // Assign locations to each value returned by this call.
1391 SmallVector<CCValAssign, 16> RVLocs;
1392 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1393 *DAG.getContext(), Call);
1394 CCInfo.AnalyzeCallResult(Ins,
1395 CCAssignFnForNode(CallConv, /* Return*/ true,
1398 // Copy all of the result registers out of their specified physreg.
1399 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1400 CCValAssign VA = RVLocs[i];
1402 // Pass 'this' value directly from the argument to return value, to avoid
1403 // reg unit interference
1404 if (i == 0 && isThisReturn) {
1405 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1406 "unexpected return calling convention register assignment");
1407 InVals.push_back(ThisVal);
1412 if (VA.needsCustom()) {
1413 // Handle f64 or half of a v2f64.
1414 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1416 Chain = Lo.getValue(1);
1417 InFlag = Lo.getValue(2);
1418 VA = RVLocs[++i]; // skip ahead to next loc
1419 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1421 Chain = Hi.getValue(1);
1422 InFlag = Hi.getValue(2);
1423 if (!Subtarget->isLittle())
1425 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1427 if (VA.getLocVT() == MVT::v2f64) {
1428 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1429 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1430 DAG.getConstant(0, dl, MVT::i32));
1432 VA = RVLocs[++i]; // skip ahead to next loc
1433 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1434 Chain = Lo.getValue(1);
1435 InFlag = Lo.getValue(2);
1436 VA = RVLocs[++i]; // skip ahead to next loc
1437 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1438 Chain = Hi.getValue(1);
1439 InFlag = Hi.getValue(2);
1440 if (!Subtarget->isLittle())
1442 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1443 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1444 DAG.getConstant(1, dl, MVT::i32));
1447 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1449 Chain = Val.getValue(1);
1450 InFlag = Val.getValue(2);
1453 switch (VA.getLocInfo()) {
1454 default: llvm_unreachable("Unknown loc info!");
1455 case CCValAssign::Full: break;
1456 case CCValAssign::BCvt:
1457 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1461 InVals.push_back(Val);
1467 /// LowerMemOpCallTo - Store the argument to the stack.
1469 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1470 SDValue StackPtr, SDValue Arg,
1471 SDLoc dl, SelectionDAG &DAG,
1472 const CCValAssign &VA,
1473 ISD::ArgFlagsTy Flags) const {
1474 unsigned LocMemOffset = VA.getLocMemOffset();
1475 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1476 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1478 return DAG.getStore(
1479 Chain, dl, Arg, PtrOff,
1480 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1484 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1485 SDValue Chain, SDValue &Arg,
1486 RegsToPassVector &RegsToPass,
1487 CCValAssign &VA, CCValAssign &NextVA,
1489 SmallVectorImpl<SDValue> &MemOpChains,
1490 ISD::ArgFlagsTy Flags) const {
1492 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1493 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1494 unsigned id = Subtarget->isLittle() ? 0 : 1;
1495 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1497 if (NextVA.isRegLoc())
1498 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1500 assert(NextVA.isMemLoc());
1501 if (!StackPtr.getNode())
1502 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1503 getPointerTy(DAG.getDataLayout()));
1505 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1511 /// LowerCall - Lowering a call into a callseq_start <-
1512 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1515 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1516 SmallVectorImpl<SDValue> &InVals) const {
1517 SelectionDAG &DAG = CLI.DAG;
1519 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1520 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1521 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1522 SDValue Chain = CLI.Chain;
1523 SDValue Callee = CLI.Callee;
1524 bool &isTailCall = CLI.IsTailCall;
1525 CallingConv::ID CallConv = CLI.CallConv;
1526 bool doesNotRet = CLI.DoesNotReturn;
1527 bool isVarArg = CLI.IsVarArg;
1529 MachineFunction &MF = DAG.getMachineFunction();
1530 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1531 bool isThisReturn = false;
1532 bool isSibCall = false;
1533 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1535 // Disable tail calls if they're not supported.
1536 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1540 // Check if it's really possible to do a tail call.
1541 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1542 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1543 Outs, OutVals, Ins, DAG);
1544 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1545 report_fatal_error("failed to perform tail call elimination on a call "
1546 "site marked musttail");
1547 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1548 // detected sibcalls.
1555 // Analyze operands of the call, assigning locations to each operand.
1556 SmallVector<CCValAssign, 16> ArgLocs;
1557 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1558 *DAG.getContext(), Call);
1559 CCInfo.AnalyzeCallOperands(Outs,
1560 CCAssignFnForNode(CallConv, /* Return*/ false,
1563 // Get a count of how many bytes are to be pushed on the stack.
1564 unsigned NumBytes = CCInfo.getNextStackOffset();
1566 // For tail calls, memory operands are available in our caller's stack.
1570 // Adjust the stack pointer for the new arguments...
1571 // These operations are automatically eliminated by the prolog/epilog pass
1573 Chain = DAG.getCALLSEQ_START(Chain,
1574 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1577 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1579 RegsToPassVector RegsToPass;
1580 SmallVector<SDValue, 8> MemOpChains;
1582 // Walk the register/memloc assignments, inserting copies/loads. In the case
1583 // of tail call optimization, arguments are handled later.
1584 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1586 ++i, ++realArgIdx) {
1587 CCValAssign &VA = ArgLocs[i];
1588 SDValue Arg = OutVals[realArgIdx];
1589 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1590 bool isByVal = Flags.isByVal();
1592 // Promote the value if needed.
1593 switch (VA.getLocInfo()) {
1594 default: llvm_unreachable("Unknown loc info!");
1595 case CCValAssign::Full: break;
1596 case CCValAssign::SExt:
1597 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1599 case CCValAssign::ZExt:
1600 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1602 case CCValAssign::AExt:
1603 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1605 case CCValAssign::BCvt:
1606 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1610 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1611 if (VA.needsCustom()) {
1612 if (VA.getLocVT() == MVT::v2f64) {
1613 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1614 DAG.getConstant(0, dl, MVT::i32));
1615 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1616 DAG.getConstant(1, dl, MVT::i32));
1618 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1619 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1621 VA = ArgLocs[++i]; // skip ahead to next loc
1622 if (VA.isRegLoc()) {
1623 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1624 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1626 assert(VA.isMemLoc());
1628 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1629 dl, DAG, VA, Flags));
1632 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1633 StackPtr, MemOpChains, Flags);
1635 } else if (VA.isRegLoc()) {
1636 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1637 assert(VA.getLocVT() == MVT::i32 &&
1638 "unexpected calling convention register assignment");
1639 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1640 "unexpected use of 'returned'");
1641 isThisReturn = true;
1643 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1644 } else if (isByVal) {
1645 assert(VA.isMemLoc());
1646 unsigned offset = 0;
1648 // True if this byval aggregate will be split between registers
1650 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1651 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1653 if (CurByValIdx < ByValArgsCount) {
1655 unsigned RegBegin, RegEnd;
1656 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1659 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1661 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1662 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1663 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1664 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1665 MachinePointerInfo(),
1666 false, false, false,
1667 DAG.InferPtrAlignment(AddArg));
1668 MemOpChains.push_back(Load.getValue(1));
1669 RegsToPass.push_back(std::make_pair(j, Load));
1672 // If parameter size outsides register area, "offset" value
1673 // helps us to calculate stack slot for remained part properly.
1674 offset = RegEnd - RegBegin;
1676 CCInfo.nextInRegsParam();
1679 if (Flags.getByValSize() > 4*offset) {
1680 auto PtrVT = getPointerTy(DAG.getDataLayout());
1681 unsigned LocMemOffset = VA.getLocMemOffset();
1682 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1683 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1684 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1685 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1686 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1688 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1691 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1692 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1693 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1696 } else if (!isSibCall) {
1697 assert(VA.isMemLoc());
1699 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1700 dl, DAG, VA, Flags));
1704 if (!MemOpChains.empty())
1705 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1707 // Build a sequence of copy-to-reg nodes chained together with token chain
1708 // and flag operands which copy the outgoing args into the appropriate regs.
1710 // Tail call byval lowering might overwrite argument registers so in case of
1711 // tail call optimization the copies to registers are lowered later.
1713 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1714 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1715 RegsToPass[i].second, InFlag);
1716 InFlag = Chain.getValue(1);
1719 // For tail calls lower the arguments to the 'real' stack slot.
1721 // Force all the incoming stack arguments to be loaded from the stack
1722 // before any new outgoing arguments are stored to the stack, because the
1723 // outgoing stack slots may alias the incoming argument stack slots, and
1724 // the alias isn't otherwise explicit. This is slightly more conservative
1725 // than necessary, because it means that each store effectively depends
1726 // on every argument instead of just those arguments it would clobber.
1728 // Do not flag preceding copytoreg stuff together with the following stuff.
1730 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1731 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1732 RegsToPass[i].second, InFlag);
1733 InFlag = Chain.getValue(1);
1738 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1739 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1740 // node so that legalize doesn't hack it.
1741 bool isDirect = false;
1742 bool isARMFunc = false;
1743 bool isLocalARMFunc = false;
1744 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1745 auto PtrVt = getPointerTy(DAG.getDataLayout());
1747 if (Subtarget->genLongCalls()) {
1748 assert((Subtarget->isTargetWindows() ||
1749 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1750 "long-calls with non-static relocation model!");
1751 // Handle a global address or an external symbol. If it's not one of
1752 // those, the target's already in a register, so we don't need to do
1754 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1755 const GlobalValue *GV = G->getGlobal();
1756 // Create a constant pool entry for the callee address
1757 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1758 ARMConstantPoolValue *CPV =
1759 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1761 // Get the address of the callee into a register
1762 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1763 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1764 Callee = DAG.getLoad(
1765 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1766 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1768 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1769 const char *Sym = S->getSymbol();
1771 // Create a constant pool entry for the callee address
1772 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1773 ARMConstantPoolValue *CPV =
1774 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1775 ARMPCLabelIndex, 0);
1776 // Get the address of the callee into a register
1777 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1778 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1779 Callee = DAG.getLoad(
1780 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1781 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1784 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1785 const GlobalValue *GV = G->getGlobal();
1787 bool isDef = GV->isStrongDefinitionForLinker();
1788 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1789 getTargetMachine().getRelocationModel() != Reloc::Static;
1790 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1791 // ARM call to a local ARM function is predicable.
1792 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1793 // tBX takes a register source operand.
1794 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1795 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1796 Callee = DAG.getNode(
1797 ARMISD::WrapperPIC, dl, PtrVt,
1798 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1799 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1800 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1801 false, false, true, 0);
1802 } else if (Subtarget->isTargetCOFF()) {
1803 assert(Subtarget->isTargetWindows() &&
1804 "Windows is the only supported COFF target");
1805 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1806 ? ARMII::MO_DLLIMPORT
1807 : ARMII::MO_NO_FLAG;
1809 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1810 if (GV->hasDLLImportStorageClass())
1812 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1813 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1814 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1815 false, false, false, 0);
1817 // On ELF targets for PIC code, direct calls should go through the PLT
1818 unsigned OpFlags = 0;
1819 if (Subtarget->isTargetELF() &&
1820 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1821 OpFlags = ARMII::MO_PLT;
1822 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1824 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1826 bool isStub = Subtarget->isTargetMachO() &&
1827 getTargetMachine().getRelocationModel() != Reloc::Static;
1828 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1829 // tBX takes a register source operand.
1830 const char *Sym = S->getSymbol();
1831 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1832 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1833 ARMConstantPoolValue *CPV =
1834 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1835 ARMPCLabelIndex, 4);
1836 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1837 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1838 Callee = DAG.getLoad(
1839 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1840 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1842 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1843 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1845 unsigned OpFlags = 0;
1846 // On ELF targets for PIC code, direct calls should go through the PLT
1847 if (Subtarget->isTargetELF() &&
1848 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1849 OpFlags = ARMII::MO_PLT;
1850 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1854 // FIXME: handle tail calls differently.
1856 if (Subtarget->isThumb()) {
1857 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1858 CallOpc = ARMISD::CALL_NOLINK;
1860 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1862 if (!isDirect && !Subtarget->hasV5TOps())
1863 CallOpc = ARMISD::CALL_NOLINK;
1864 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1865 // Emit regular call when code size is the priority
1866 !MF.getFunction()->optForMinSize())
1867 // "mov lr, pc; b _foo" to avoid confusing the RSP
1868 CallOpc = ARMISD::CALL_NOLINK;
1870 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1873 std::vector<SDValue> Ops;
1874 Ops.push_back(Chain);
1875 Ops.push_back(Callee);
1877 // Add argument registers to the end of the list so that they are known live
1879 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1880 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1881 RegsToPass[i].second.getValueType()));
1883 // Add a register mask operand representing the call-preserved registers.
1885 const uint32_t *Mask;
1886 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1888 // For 'this' returns, use the R0-preserving mask if applicable
1889 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1891 // Set isThisReturn to false if the calling convention is not one that
1892 // allows 'returned' to be modeled in this way, so LowerCallResult does
1893 // not try to pass 'this' straight through
1894 isThisReturn = false;
1895 Mask = ARI->getCallPreservedMask(MF, CallConv);
1898 Mask = ARI->getCallPreservedMask(MF, CallConv);
1900 assert(Mask && "Missing call preserved mask for calling convention");
1901 Ops.push_back(DAG.getRegisterMask(Mask));
1904 if (InFlag.getNode())
1905 Ops.push_back(InFlag);
1907 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1909 MF.getFrameInfo()->setHasTailCall();
1910 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1913 // Returns a chain and a flag for retval copy to use.
1914 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1915 InFlag = Chain.getValue(1);
1917 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1918 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1920 InFlag = Chain.getValue(1);
1922 // Handle result values, copying them out of physregs into vregs that we
1924 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1925 InVals, isThisReturn,
1926 isThisReturn ? OutVals[0] : SDValue());
1929 /// HandleByVal - Every parameter *after* a byval parameter is passed
1930 /// on the stack. Remember the next parameter register to allocate,
1931 /// and then confiscate the rest of the parameter registers to insure
1933 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1934 unsigned Align) const {
1935 assert((State->getCallOrPrologue() == Prologue ||
1936 State->getCallOrPrologue() == Call) &&
1937 "unhandled ParmContext");
1939 // Byval (as with any stack) slots are always at least 4 byte aligned.
1940 Align = std::max(Align, 4U);
1942 unsigned Reg = State->AllocateReg(GPRArgRegs);
1946 unsigned AlignInRegs = Align / 4;
1947 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1948 for (unsigned i = 0; i < Waste; ++i)
1949 Reg = State->AllocateReg(GPRArgRegs);
1954 unsigned Excess = 4 * (ARM::R4 - Reg);
1956 // Special case when NSAA != SP and parameter size greater than size of
1957 // all remained GPR regs. In that case we can't split parameter, we must
1958 // send it to stack. We also must set NCRN to R4, so waste all
1959 // remained registers.
1960 const unsigned NSAAOffset = State->getNextStackOffset();
1961 if (NSAAOffset != 0 && Size > Excess) {
1962 while (State->AllocateReg(GPRArgRegs))
1967 // First register for byval parameter is the first register that wasn't
1968 // allocated before this method call, so it would be "reg".
1969 // If parameter is small enough to be saved in range [reg, r4), then
1970 // the end (first after last) register would be reg + param-size-in-regs,
1971 // else parameter would be splitted between registers and stack,
1972 // end register would be r4 in this case.
1973 unsigned ByValRegBegin = Reg;
1974 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1975 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1976 // Note, first register is allocated in the beginning of function already,
1977 // allocate remained amount of registers we need.
1978 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1979 State->AllocateReg(GPRArgRegs);
1980 // A byval parameter that is split between registers and memory needs its
1981 // size truncated here.
1982 // In the case where the entire structure fits in registers, we set the
1983 // size in memory to zero.
1984 Size = std::max<int>(Size - Excess, 0);
1987 /// MatchingStackOffset - Return true if the given stack call argument is
1988 /// already available in the same position (relatively) of the caller's
1989 /// incoming argument stack.
1991 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1992 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1993 const TargetInstrInfo *TII) {
1994 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1996 if (Arg.getOpcode() == ISD::CopyFromReg) {
1997 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1998 if (!TargetRegisterInfo::isVirtualRegister(VR))
2000 MachineInstr *Def = MRI->getVRegDef(VR);
2003 if (!Flags.isByVal()) {
2004 if (!TII->isLoadFromStackSlot(Def, FI))
2009 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2010 if (Flags.isByVal())
2011 // ByVal argument is passed in as a pointer but it's now being
2012 // dereferenced. e.g.
2013 // define @foo(%struct.X* %A) {
2014 // tail call @bar(%struct.X* byval %A)
2017 SDValue Ptr = Ld->getBasePtr();
2018 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2021 FI = FINode->getIndex();
2025 assert(FI != INT_MAX);
2026 if (!MFI->isFixedObjectIndex(FI))
2028 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2031 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2032 /// for tail call optimization. Targets which want to do tail call
2033 /// optimization should implement this function.
2035 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2036 CallingConv::ID CalleeCC,
2038 bool isCalleeStructRet,
2039 bool isCallerStructRet,
2040 const SmallVectorImpl<ISD::OutputArg> &Outs,
2041 const SmallVectorImpl<SDValue> &OutVals,
2042 const SmallVectorImpl<ISD::InputArg> &Ins,
2043 SelectionDAG& DAG) const {
2044 const Function *CallerF = DAG.getMachineFunction().getFunction();
2045 CallingConv::ID CallerCC = CallerF->getCallingConv();
2046 bool CCMatch = CallerCC == CalleeCC;
2048 // Look for obvious safe cases to perform tail call optimization that do not
2049 // require ABI changes. This is what gcc calls sibcall.
2051 // Do not sibcall optimize vararg calls unless the call site is not passing
2053 if (isVarArg && !Outs.empty())
2056 // Exception-handling functions need a special set of instructions to indicate
2057 // a return to the hardware. Tail-calling another function would probably
2059 if (CallerF->hasFnAttribute("interrupt"))
2062 // Also avoid sibcall optimization if either caller or callee uses struct
2063 // return semantics.
2064 if (isCalleeStructRet || isCallerStructRet)
2067 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2068 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2069 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2070 // support in the assembler and linker to be used. This would need to be
2071 // fixed to fully support tail calls in Thumb1.
2073 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2074 // LR. This means if we need to reload LR, it takes an extra instructions,
2075 // which outweighs the value of the tail call; but here we don't know yet
2076 // whether LR is going to be used. Probably the right approach is to
2077 // generate the tail call here and turn it back into CALL/RET in
2078 // emitEpilogue if LR is used.
2080 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2081 // but we need to make sure there are enough registers; the only valid
2082 // registers are the 4 used for parameters. We don't currently do this
2084 if (Subtarget->isThumb1Only())
2087 // Externally-defined functions with weak linkage should not be
2088 // tail-called on ARM when the OS does not support dynamic
2089 // pre-emption of symbols, as the AAELF spec requires normal calls
2090 // to undefined weak functions to be replaced with a NOP or jump to the
2091 // next instruction. The behaviour of branch instructions in this
2092 // situation (as used for tail calls) is implementation-defined, so we
2093 // cannot rely on the linker replacing the tail call with a return.
2094 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2095 const GlobalValue *GV = G->getGlobal();
2096 const Triple &TT = getTargetMachine().getTargetTriple();
2097 if (GV->hasExternalWeakLinkage() &&
2098 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2102 // If the calling conventions do not match, then we'd better make sure the
2103 // results are returned in the same way as what the caller expects.
2105 SmallVector<CCValAssign, 16> RVLocs1;
2106 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2107 *DAG.getContext(), Call);
2108 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2110 SmallVector<CCValAssign, 16> RVLocs2;
2111 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2112 *DAG.getContext(), Call);
2113 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2115 if (RVLocs1.size() != RVLocs2.size())
2117 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2118 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2120 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2122 if (RVLocs1[i].isRegLoc()) {
2123 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2126 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2132 // If Caller's vararg or byval argument has been split between registers and
2133 // stack, do not perform tail call, since part of the argument is in caller's
2135 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2136 getInfo<ARMFunctionInfo>();
2137 if (AFI_Caller->getArgRegsSaveSize())
2140 // If the callee takes no arguments then go on to check the results of the
2142 if (!Outs.empty()) {
2143 // Check if stack adjustment is needed. For now, do not do this if any
2144 // argument is passed on the stack.
2145 SmallVector<CCValAssign, 16> ArgLocs;
2146 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2147 *DAG.getContext(), Call);
2148 CCInfo.AnalyzeCallOperands(Outs,
2149 CCAssignFnForNode(CalleeCC, false, isVarArg));
2150 if (CCInfo.getNextStackOffset()) {
2151 MachineFunction &MF = DAG.getMachineFunction();
2153 // Check if the arguments are already laid out in the right way as
2154 // the caller's fixed stack objects.
2155 MachineFrameInfo *MFI = MF.getFrameInfo();
2156 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2157 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2158 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2160 ++i, ++realArgIdx) {
2161 CCValAssign &VA = ArgLocs[i];
2162 EVT RegVT = VA.getLocVT();
2163 SDValue Arg = OutVals[realArgIdx];
2164 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2165 if (VA.getLocInfo() == CCValAssign::Indirect)
2167 if (VA.needsCustom()) {
2168 // f64 and vector types are split into multiple registers or
2169 // register/stack-slot combinations. The types will not match
2170 // the registers; give up on memory f64 refs until we figure
2171 // out what to do about this.
2174 if (!ArgLocs[++i].isRegLoc())
2176 if (RegVT == MVT::v2f64) {
2177 if (!ArgLocs[++i].isRegLoc())
2179 if (!ArgLocs[++i].isRegLoc())
2182 } else if (!VA.isRegLoc()) {
2183 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2195 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2196 MachineFunction &MF, bool isVarArg,
2197 const SmallVectorImpl<ISD::OutputArg> &Outs,
2198 LLVMContext &Context) const {
2199 SmallVector<CCValAssign, 16> RVLocs;
2200 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2201 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2205 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2206 SDLoc DL, SelectionDAG &DAG) {
2207 const MachineFunction &MF = DAG.getMachineFunction();
2208 const Function *F = MF.getFunction();
2210 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2212 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2213 // version of the "preferred return address". These offsets affect the return
2214 // instruction if this is a return from PL1 without hypervisor extensions.
2215 // IRQ/FIQ: +4 "subs pc, lr, #4"
2216 // SWI: 0 "subs pc, lr, #0"
2217 // ABORT: +4 "subs pc, lr, #4"
2218 // UNDEF: +4/+2 "subs pc, lr, #0"
2219 // UNDEF varies depending on where the exception came from ARM or Thumb
2220 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2223 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2226 else if (IntKind == "SWI" || IntKind == "UNDEF")
2229 report_fatal_error("Unsupported interrupt attribute. If present, value "
2230 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2232 RetOps.insert(RetOps.begin() + 1,
2233 DAG.getConstant(LROffset, DL, MVT::i32, false));
2235 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2239 ARMTargetLowering::LowerReturn(SDValue Chain,
2240 CallingConv::ID CallConv, bool isVarArg,
2241 const SmallVectorImpl<ISD::OutputArg> &Outs,
2242 const SmallVectorImpl<SDValue> &OutVals,
2243 SDLoc dl, SelectionDAG &DAG) const {
2245 // CCValAssign - represent the assignment of the return value to a location.
2246 SmallVector<CCValAssign, 16> RVLocs;
2248 // CCState - Info about the registers and stack slots.
2249 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2250 *DAG.getContext(), Call);
2252 // Analyze outgoing return values.
2253 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2257 SmallVector<SDValue, 4> RetOps;
2258 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2259 bool isLittleEndian = Subtarget->isLittle();
2261 MachineFunction &MF = DAG.getMachineFunction();
2262 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2263 AFI->setReturnRegsCount(RVLocs.size());
2265 // Copy the result values into the output registers.
2266 for (unsigned i = 0, realRVLocIdx = 0;
2268 ++i, ++realRVLocIdx) {
2269 CCValAssign &VA = RVLocs[i];
2270 assert(VA.isRegLoc() && "Can only return in registers!");
2272 SDValue Arg = OutVals[realRVLocIdx];
2274 switch (VA.getLocInfo()) {
2275 default: llvm_unreachable("Unknown loc info!");
2276 case CCValAssign::Full: break;
2277 case CCValAssign::BCvt:
2278 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2282 if (VA.needsCustom()) {
2283 if (VA.getLocVT() == MVT::v2f64) {
2284 // Extract the first half and return it in two registers.
2285 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2286 DAG.getConstant(0, dl, MVT::i32));
2287 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2288 DAG.getVTList(MVT::i32, MVT::i32), Half);
2290 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2293 Flag = Chain.getValue(1);
2294 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2295 VA = RVLocs[++i]; // skip ahead to next loc
2296 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2297 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2299 Flag = Chain.getValue(1);
2300 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2301 VA = RVLocs[++i]; // skip ahead to next loc
2303 // Extract the 2nd half and fall through to handle it as an f64 value.
2304 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2305 DAG.getConstant(1, dl, MVT::i32));
2307 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2309 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2310 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2311 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2312 fmrrd.getValue(isLittleEndian ? 0 : 1),
2314 Flag = Chain.getValue(1);
2315 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2316 VA = RVLocs[++i]; // skip ahead to next loc
2317 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2318 fmrrd.getValue(isLittleEndian ? 1 : 0),
2321 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2323 // Guarantee that all emitted copies are
2324 // stuck together, avoiding something bad.
2325 Flag = Chain.getValue(1);
2326 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2329 // Update chain and glue.
2332 RetOps.push_back(Flag);
2334 // CPUs which aren't M-class use a special sequence to return from
2335 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2336 // though we use "subs pc, lr, #N").
2338 // M-class CPUs actually use a normal return sequence with a special
2339 // (hardware-provided) value in LR, so the normal code path works.
2340 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2341 !Subtarget->isMClass()) {
2342 if (Subtarget->isThumb1Only())
2343 report_fatal_error("interrupt attribute is not supported in Thumb1");
2344 return LowerInterruptReturn(RetOps, dl, DAG);
2347 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2350 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2351 if (N->getNumValues() != 1)
2353 if (!N->hasNUsesOfValue(1, 0))
2356 SDValue TCChain = Chain;
2357 SDNode *Copy = *N->use_begin();
2358 if (Copy->getOpcode() == ISD::CopyToReg) {
2359 // If the copy has a glue operand, we conservatively assume it isn't safe to
2360 // perform a tail call.
2361 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2363 TCChain = Copy->getOperand(0);
2364 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2365 SDNode *VMov = Copy;
2366 // f64 returned in a pair of GPRs.
2367 SmallPtrSet<SDNode*, 2> Copies;
2368 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2370 if (UI->getOpcode() != ISD::CopyToReg)
2374 if (Copies.size() > 2)
2377 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2379 SDValue UseChain = UI->getOperand(0);
2380 if (Copies.count(UseChain.getNode()))
2384 // We are at the top of this chain.
2385 // If the copy has a glue operand, we conservatively assume it
2386 // isn't safe to perform a tail call.
2387 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2393 } else if (Copy->getOpcode() == ISD::BITCAST) {
2394 // f32 returned in a single GPR.
2395 if (!Copy->hasOneUse())
2397 Copy = *Copy->use_begin();
2398 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2400 // If the copy has a glue operand, we conservatively assume it isn't safe to
2401 // perform a tail call.
2402 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2404 TCChain = Copy->getOperand(0);
2409 bool HasRet = false;
2410 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2412 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2413 UI->getOpcode() != ARMISD::INTRET_FLAG)
2425 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2426 if (!Subtarget->supportsTailCall())
2430 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2431 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2434 return !Subtarget->isThumb1Only();
2437 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2438 // and pass the lower and high parts through.
2439 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2441 SDValue WriteValue = Op->getOperand(2);
2443 // This function is only supposed to be called for i64 type argument.
2444 assert(WriteValue.getValueType() == MVT::i64
2445 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2447 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2448 DAG.getConstant(0, DL, MVT::i32));
2449 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2450 DAG.getConstant(1, DL, MVT::i32));
2451 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2452 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2455 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2456 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2457 // one of the above mentioned nodes. It has to be wrapped because otherwise
2458 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2459 // be used to form addressing mode. These wrapped nodes will be selected
2461 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2462 EVT PtrVT = Op.getValueType();
2463 // FIXME there is no actual debug info here
2465 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2467 if (CP->isMachineConstantPoolEntry())
2468 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2469 CP->getAlignment());
2471 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2472 CP->getAlignment());
2473 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2476 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2477 return MachineJumpTableInfo::EK_Inline;
2480 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2481 SelectionDAG &DAG) const {
2482 MachineFunction &MF = DAG.getMachineFunction();
2483 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484 unsigned ARMPCLabelIndex = 0;
2486 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2487 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2488 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2490 if (RelocM == Reloc::Static) {
2491 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2493 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2494 ARMPCLabelIndex = AFI->createPICLabelUId();
2495 ARMConstantPoolValue *CPV =
2496 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2497 ARMCP::CPBlockAddress, PCAdj);
2498 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2500 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2502 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2503 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2504 false, false, false, 0);
2505 if (RelocM == Reloc::Static)
2507 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2508 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2511 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2513 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2514 SelectionDAG &DAG) const {
2516 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2517 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2518 MachineFunction &MF = DAG.getMachineFunction();
2519 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2520 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2521 ARMConstantPoolValue *CPV =
2522 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2523 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2524 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2525 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2527 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2528 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2529 false, false, false, 0);
2530 SDValue Chain = Argument.getValue(1);
2532 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2533 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2535 // call __tls_get_addr.
2538 Entry.Node = Argument;
2539 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2540 Args.push_back(Entry);
2542 // FIXME: is there useful debug info available here?
2543 TargetLowering::CallLoweringInfo CLI(DAG);
2544 CLI.setDebugLoc(dl).setChain(Chain)
2545 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2546 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2549 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2550 return CallResult.first;
2553 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2554 // "local exec" model.
2556 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2558 TLSModel::Model model) const {
2559 const GlobalValue *GV = GA->getGlobal();
2562 SDValue Chain = DAG.getEntryNode();
2563 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2564 // Get the Thread Pointer
2565 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2567 if (model == TLSModel::InitialExec) {
2568 MachineFunction &MF = DAG.getMachineFunction();
2569 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2571 // Initial exec model.
2572 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2573 ARMConstantPoolValue *CPV =
2574 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2575 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2577 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2578 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2579 Offset = DAG.getLoad(
2580 PtrVT, dl, Chain, Offset,
2581 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2583 Chain = Offset.getValue(1);
2585 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2586 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2588 Offset = DAG.getLoad(
2589 PtrVT, dl, Chain, Offset,
2590 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2594 assert(model == TLSModel::LocalExec);
2595 ARMConstantPoolValue *CPV =
2596 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2597 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2598 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2599 Offset = DAG.getLoad(
2600 PtrVT, dl, Chain, Offset,
2601 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2605 // The address of the thread local variable is the add of the thread
2606 // pointer with the offset of the variable.
2607 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2611 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2612 // TODO: implement the "local dynamic" model
2613 assert(Subtarget->isTargetELF() &&
2614 "TLS not implemented for non-ELF targets");
2615 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2616 if (DAG.getTarget().Options.EmulatedTLS)
2617 return LowerToTLSEmulatedModel(GA, DAG);
2619 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2622 case TLSModel::GeneralDynamic:
2623 case TLSModel::LocalDynamic:
2624 return LowerToTLSGeneralDynamicModel(GA, DAG);
2625 case TLSModel::InitialExec:
2626 case TLSModel::LocalExec:
2627 return LowerToTLSExecModels(GA, DAG, model);
2629 llvm_unreachable("bogus TLS model");
2632 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2633 SelectionDAG &DAG) const {
2634 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2636 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2637 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2638 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2639 ARMConstantPoolValue *CPV =
2640 ARMConstantPoolConstant::Create(GV,
2641 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2642 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2643 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2644 SDValue Result = DAG.getLoad(
2645 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2646 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2648 SDValue Chain = Result.getValue(1);
2649 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2650 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2652 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2653 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2654 false, false, false, 0);
2658 // If we have T2 ops, we can materialize the address directly via movt/movw
2659 // pair. This is always cheaper.
2660 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2662 // FIXME: Once remat is capable of dealing with instructions with register
2663 // operands, expand this into two nodes.
2664 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2665 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2667 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2668 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2670 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2671 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2676 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2677 SelectionDAG &DAG) const {
2678 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2680 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2681 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2683 if (Subtarget->useMovt(DAG.getMachineFunction()))
2686 // FIXME: Once remat is capable of dealing with instructions with register
2687 // operands, expand this into multiple nodes
2689 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2691 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2692 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2694 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2695 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2696 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2697 false, false, false, 0);
2701 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2702 SelectionDAG &DAG) const {
2703 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2704 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2705 "Windows on ARM expects to use movw/movt");
2707 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2708 const ARMII::TOF TargetFlags =
2709 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2710 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2716 // FIXME: Once remat is capable of dealing with instructions with register
2717 // operands, expand this into two nodes.
2718 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2719 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2721 if (GV->hasDLLImportStorageClass())
2722 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2723 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2724 false, false, false, 0);
2728 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2729 SelectionDAG &DAG) const {
2730 assert(Subtarget->isTargetELF() &&
2731 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2732 MachineFunction &MF = DAG.getMachineFunction();
2733 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2734 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2735 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2737 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2738 ARMConstantPoolValue *CPV =
2739 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2740 ARMPCLabelIndex, PCAdj);
2741 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2742 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2744 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2745 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2746 false, false, false, 0);
2747 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2748 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2752 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2754 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2755 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2756 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2757 Op.getOperand(1), Val);
2761 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2763 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2764 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2767 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2768 SelectionDAG &DAG) const {
2770 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2775 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2776 const ARMSubtarget *Subtarget) const {
2777 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2780 default: return SDValue(); // Don't custom lower most intrinsics.
2781 case Intrinsic::arm_rbit: {
2782 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2783 "RBIT intrinsic must have i32 type!");
2784 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2786 case Intrinsic::arm_thread_pointer: {
2787 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2788 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2790 case Intrinsic::eh_sjlj_lsda: {
2791 MachineFunction &MF = DAG.getMachineFunction();
2792 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2793 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2794 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2795 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2797 unsigned PCAdj = (RelocM != Reloc::PIC_)
2798 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2799 ARMConstantPoolValue *CPV =
2800 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2801 ARMCP::CPLSDA, PCAdj);
2802 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2803 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2804 SDValue Result = DAG.getLoad(
2805 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2806 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2809 if (RelocM == Reloc::PIC_) {
2810 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2811 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2815 case Intrinsic::arm_neon_vmulls:
2816 case Intrinsic::arm_neon_vmullu: {
2817 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2818 ? ARMISD::VMULLs : ARMISD::VMULLu;
2819 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2820 Op.getOperand(1), Op.getOperand(2));
2822 case Intrinsic::arm_neon_vminnm:
2823 case Intrinsic::arm_neon_vmaxnm: {
2824 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2825 ? ISD::FMINNUM : ISD::FMAXNUM;
2826 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2827 Op.getOperand(1), Op.getOperand(2));
2829 case Intrinsic::arm_neon_vminu:
2830 case Intrinsic::arm_neon_vmaxu: {
2831 if (Op.getValueType().isFloatingPoint())
2833 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2834 ? ISD::UMIN : ISD::UMAX;
2835 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2836 Op.getOperand(1), Op.getOperand(2));
2838 case Intrinsic::arm_neon_vmins:
2839 case Intrinsic::arm_neon_vmaxs: {
2840 // v{min,max}s is overloaded between signed integers and floats.
2841 if (!Op.getValueType().isFloatingPoint()) {
2842 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2843 ? ISD::SMIN : ISD::SMAX;
2844 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2845 Op.getOperand(1), Op.getOperand(2));
2847 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2848 ? ISD::FMINNAN : ISD::FMAXNAN;
2849 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2850 Op.getOperand(1), Op.getOperand(2));
2855 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2856 const ARMSubtarget *Subtarget) {
2857 // FIXME: handle "fence singlethread" more efficiently.
2859 if (!Subtarget->hasDataBarrier()) {
2860 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2861 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2863 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2864 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2865 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2866 DAG.getConstant(0, dl, MVT::i32));
2869 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2870 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2871 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2872 if (Subtarget->isMClass()) {
2873 // Only a full system barrier exists in the M-class architectures.
2874 Domain = ARM_MB::SY;
2875 } else if (Subtarget->isSwift() && Ord == Release) {
2876 // Swift happens to implement ISHST barriers in a way that's compatible with
2877 // Release semantics but weaker than ISH so we'd be fools not to use
2878 // it. Beware: other processors probably don't!
2879 Domain = ARM_MB::ISHST;
2882 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2883 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2884 DAG.getConstant(Domain, dl, MVT::i32));
2887 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2888 const ARMSubtarget *Subtarget) {
2889 // ARM pre v5TE and Thumb1 does not have preload instructions.
2890 if (!(Subtarget->isThumb2() ||
2891 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2892 // Just preserve the chain.
2893 return Op.getOperand(0);
2896 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2898 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2899 // ARMv7 with MP extension has PLDW.
2900 return Op.getOperand(0);
2902 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2903 if (Subtarget->isThumb()) {
2905 isRead = ~isRead & 1;
2906 isData = ~isData & 1;
2909 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2910 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2911 DAG.getConstant(isData, dl, MVT::i32));
2914 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2915 MachineFunction &MF = DAG.getMachineFunction();
2916 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2918 // vastart just stores the address of the VarArgsFrameIndex slot into the
2919 // memory location argument.
2921 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2922 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2923 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2924 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2925 MachinePointerInfo(SV), false, false, 0);
2929 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2930 SDValue &Root, SelectionDAG &DAG,
2932 MachineFunction &MF = DAG.getMachineFunction();
2933 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2935 const TargetRegisterClass *RC;
2936 if (AFI->isThumb1OnlyFunction())
2937 RC = &ARM::tGPRRegClass;
2939 RC = &ARM::GPRRegClass;
2941 // Transform the arguments stored in physical registers into virtual ones.
2942 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2943 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2946 if (NextVA.isMemLoc()) {
2947 MachineFrameInfo *MFI = MF.getFrameInfo();
2948 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2950 // Create load node to retrieve arguments from the stack.
2951 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2952 ArgValue2 = DAG.getLoad(
2953 MVT::i32, dl, Root, FIN,
2954 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2957 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2958 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2960 if (!Subtarget->isLittle())
2961 std::swap (ArgValue, ArgValue2);
2962 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2965 // The remaining GPRs hold either the beginning of variable-argument
2966 // data, or the beginning of an aggregate passed by value (usually
2967 // byval). Either way, we allocate stack slots adjacent to the data
2968 // provided by our caller, and store the unallocated registers there.
2969 // If this is a variadic function, the va_list pointer will begin with
2970 // these values; otherwise, this reassembles a (byval) structure that
2971 // was split between registers and memory.
2972 // Return: The frame index registers were stored into.
2974 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2975 SDLoc dl, SDValue &Chain,
2976 const Value *OrigArg,
2977 unsigned InRegsParamRecordIdx,
2979 unsigned ArgSize) const {
2980 // Currently, two use-cases possible:
2981 // Case #1. Non-var-args function, and we meet first byval parameter.
2982 // Setup first unallocated register as first byval register;
2983 // eat all remained registers
2984 // (these two actions are performed by HandleByVal method).
2985 // Then, here, we initialize stack frame with
2986 // "store-reg" instructions.
2987 // Case #2. Var-args function, that doesn't contain byval parameters.
2988 // The same: eat all remained unallocated registers,
2989 // initialize stack frame.
2991 MachineFunction &MF = DAG.getMachineFunction();
2992 MachineFrameInfo *MFI = MF.getFrameInfo();
2993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994 unsigned RBegin, REnd;
2995 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2996 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2998 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2999 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3004 ArgOffset = -4 * (ARM::R4 - RBegin);
3006 auto PtrVT = getPointerTy(DAG.getDataLayout());
3007 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3008 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3010 SmallVector<SDValue, 4> MemOps;
3011 const TargetRegisterClass *RC =
3012 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3014 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3015 unsigned VReg = MF.addLiveIn(Reg, RC);
3016 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3018 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3019 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3020 MemOps.push_back(Store);
3021 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3024 if (!MemOps.empty())
3025 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3029 // Setup stack frame, the va_list pointer will start from.
3031 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3032 SDLoc dl, SDValue &Chain,
3034 unsigned TotalArgRegsSaveSize,
3035 bool ForceMutable) const {
3036 MachineFunction &MF = DAG.getMachineFunction();
3037 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3039 // Try to store any remaining integer argument regs
3040 // to their spots on the stack so that they may be loaded by deferencing
3041 // the result of va_next.
3042 // If there is no regs to be stored, just point address after last
3043 // argument passed via stack.
3044 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3045 CCInfo.getInRegsParamsCount(),
3046 CCInfo.getNextStackOffset(), 4);
3047 AFI->setVarArgsFrameIndex(FrameIndex);
3051 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3052 CallingConv::ID CallConv, bool isVarArg,
3053 const SmallVectorImpl<ISD::InputArg>
3055 SDLoc dl, SelectionDAG &DAG,
3056 SmallVectorImpl<SDValue> &InVals)
3058 MachineFunction &MF = DAG.getMachineFunction();
3059 MachineFrameInfo *MFI = MF.getFrameInfo();
3061 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3063 // Assign locations to all of the incoming arguments.
3064 SmallVector<CCValAssign, 16> ArgLocs;
3065 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3066 *DAG.getContext(), Prologue);
3067 CCInfo.AnalyzeFormalArguments(Ins,
3068 CCAssignFnForNode(CallConv, /* Return*/ false,
3071 SmallVector<SDValue, 16> ArgValues;
3073 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3074 unsigned CurArgIdx = 0;
3076 // Initially ArgRegsSaveSize is zero.
3077 // Then we increase this value each time we meet byval parameter.
3078 // We also increase this value in case of varargs function.
3079 AFI->setArgRegsSaveSize(0);
3081 // Calculate the amount of stack space that we need to allocate to store
3082 // byval and variadic arguments that are passed in registers.
3083 // We need to know this before we allocate the first byval or variadic
3084 // argument, as they will be allocated a stack slot below the CFA (Canonical
3085 // Frame Address, the stack pointer at entry to the function).
3086 unsigned ArgRegBegin = ARM::R4;
3087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3088 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3091 CCValAssign &VA = ArgLocs[i];
3092 unsigned Index = VA.getValNo();
3093 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3094 if (!Flags.isByVal())
3097 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3098 unsigned RBegin, REnd;
3099 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3100 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3102 CCInfo.nextInRegsParam();
3104 CCInfo.rewindByValRegsInfo();
3106 int lastInsIndex = -1;
3107 if (isVarArg && MFI->hasVAStart()) {
3108 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3109 if (RegIdx != array_lengthof(GPRArgRegs))
3110 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3113 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3114 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3115 auto PtrVT = getPointerTy(DAG.getDataLayout());
3117 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3118 CCValAssign &VA = ArgLocs[i];
3119 if (Ins[VA.getValNo()].isOrigArg()) {
3120 std::advance(CurOrigArg,
3121 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3122 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3124 // Arguments stored in registers.
3125 if (VA.isRegLoc()) {
3126 EVT RegVT = VA.getLocVT();
3128 if (VA.needsCustom()) {
3129 // f64 and vector types are split up into multiple registers or
3130 // combinations of registers and stack slots.
3131 if (VA.getLocVT() == MVT::v2f64) {
3132 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3134 VA = ArgLocs[++i]; // skip ahead to next loc
3136 if (VA.isMemLoc()) {
3137 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3138 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3139 ArgValue2 = DAG.getLoad(
3140 MVT::f64, dl, Chain, FIN,
3141 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3142 false, false, false, 0);
3144 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3147 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3148 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3149 ArgValue, ArgValue1,
3150 DAG.getIntPtrConstant(0, dl));
3151 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3152 ArgValue, ArgValue2,
3153 DAG.getIntPtrConstant(1, dl));
3155 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3158 const TargetRegisterClass *RC;
3160 if (RegVT == MVT::f32)
3161 RC = &ARM::SPRRegClass;
3162 else if (RegVT == MVT::f64)
3163 RC = &ARM::DPRRegClass;
3164 else if (RegVT == MVT::v2f64)
3165 RC = &ARM::QPRRegClass;
3166 else if (RegVT == MVT::i32)
3167 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3168 : &ARM::GPRRegClass;
3170 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3172 // Transform the arguments in physical registers into virtual ones.
3173 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3174 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3177 // If this is an 8 or 16-bit value, it is really passed promoted
3178 // to 32 bits. Insert an assert[sz]ext to capture this, then
3179 // truncate to the right size.
3180 switch (VA.getLocInfo()) {
3181 default: llvm_unreachable("Unknown loc info!");
3182 case CCValAssign::Full: break;
3183 case CCValAssign::BCvt:
3184 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3186 case CCValAssign::SExt:
3187 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3188 DAG.getValueType(VA.getValVT()));
3189 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3191 case CCValAssign::ZExt:
3192 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3193 DAG.getValueType(VA.getValVT()));
3194 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3198 InVals.push_back(ArgValue);
3200 } else { // VA.isRegLoc()
3203 assert(VA.isMemLoc());
3204 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3206 int index = VA.getValNo();
3208 // Some Ins[] entries become multiple ArgLoc[] entries.
3209 // Process them only once.
3210 if (index != lastInsIndex)
3212 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3213 // FIXME: For now, all byval parameter objects are marked mutable.
3214 // This can be changed with more analysis.
3215 // In case of tail call optimization mark all arguments mutable.
3216 // Since they could be overwritten by lowering of arguments in case of
3218 if (Flags.isByVal()) {
3219 assert(Ins[index].isOrigArg() &&
3220 "Byval arguments cannot be implicit");
3221 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3223 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3224 CurByValIndex, VA.getLocMemOffset(),
3225 Flags.getByValSize());
3226 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3227 CCInfo.nextInRegsParam();
3229 unsigned FIOffset = VA.getLocMemOffset();
3230 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3233 // Create load nodes to retrieve arguments from the stack.
3234 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3235 InVals.push_back(DAG.getLoad(
3236 VA.getValVT(), dl, Chain, FIN,
3237 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3238 false, false, false, 0));
3240 lastInsIndex = index;
3246 if (isVarArg && MFI->hasVAStart())
3247 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3248 CCInfo.getNextStackOffset(),
3249 TotalArgRegsSaveSize);
3251 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3256 /// isFloatingPointZero - Return true if this is +0.0.
3257 static bool isFloatingPointZero(SDValue Op) {
3258 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3259 return CFP->getValueAPF().isPosZero();
3260 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3261 // Maybe this has already been legalized into the constant pool?
3262 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3263 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3264 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3265 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3266 return CFP->getValueAPF().isPosZero();
3268 } else if (Op->getOpcode() == ISD::BITCAST &&
3269 Op->getValueType(0) == MVT::f64) {
3270 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3271 // created by LowerConstantFP().
3272 SDValue BitcastOp = Op->getOperand(0);
3273 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3274 SDValue MoveOp = BitcastOp->getOperand(0);
3275 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3276 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3284 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3285 /// the given operands.
3287 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3288 SDValue &ARMcc, SelectionDAG &DAG,
3290 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3291 unsigned C = RHSC->getZExtValue();
3292 if (!isLegalICmpImmediate(C)) {
3293 // Constant does not fit, try adjusting it by one?
3298 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3299 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3300 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3305 if (C != 0 && isLegalICmpImmediate(C-1)) {
3306 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3307 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3312 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3313 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3314 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3319 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3320 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3321 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3328 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3329 ARMISD::NodeType CompareType;
3332 CompareType = ARMISD::CMP;
3337 CompareType = ARMISD::CMPZ;
3340 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3341 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3344 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3346 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3348 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3350 if (!isFloatingPointZero(RHS))
3351 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3353 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3354 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3357 /// duplicateCmp - Glue values can have only one use, so this function
3358 /// duplicates a comparison node.
3360 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3361 unsigned Opc = Cmp.getOpcode();
3363 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3364 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3366 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3367 Cmp = Cmp.getOperand(0);
3368 Opc = Cmp.getOpcode();
3369 if (Opc == ARMISD::CMPFP)
3370 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3372 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3373 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3375 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3378 std::pair<SDValue, SDValue>
3379 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3380 SDValue &ARMcc) const {
3381 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3383 SDValue Value, OverflowCmp;
3384 SDValue LHS = Op.getOperand(0);
3385 SDValue RHS = Op.getOperand(1);
3388 // FIXME: We are currently always generating CMPs because we don't support
3389 // generating CMN through the backend. This is not as good as the natural
3390 // CMP case because it causes a register dependency and cannot be folded
3393 switch (Op.getOpcode()) {
3395 llvm_unreachable("Unknown overflow instruction!");
3397 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3398 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3399 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3402 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3403 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3404 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3407 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3408 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3409 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3412 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3413 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3414 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3418 return std::make_pair(Value, OverflowCmp);
3423 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3424 // Let legalize expand this if it isn't a legal type yet.
3425 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3428 SDValue Value, OverflowCmp;
3430 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3431 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3433 // We use 0 and 1 as false and true values.
3434 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3435 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3436 EVT VT = Op.getValueType();
3438 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3439 ARMcc, CCR, OverflowCmp);
3441 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3442 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3446 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3447 SDValue Cond = Op.getOperand(0);
3448 SDValue SelectTrue = Op.getOperand(1);
3449 SDValue SelectFalse = Op.getOperand(2);
3451 unsigned Opc = Cond.getOpcode();
3453 if (Cond.getResNo() == 1 &&
3454 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3455 Opc == ISD::USUBO)) {
3456 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3459 SDValue Value, OverflowCmp;
3461 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3462 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3463 EVT VT = Op.getValueType();
3465 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3471 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3472 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3474 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3475 const ConstantSDNode *CMOVTrue =
3476 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3477 const ConstantSDNode *CMOVFalse =
3478 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3480 if (CMOVTrue && CMOVFalse) {
3481 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3482 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3486 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3488 False = SelectFalse;
3489 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3494 if (True.getNode() && False.getNode()) {
3495 EVT VT = Op.getValueType();
3496 SDValue ARMcc = Cond.getOperand(2);
3497 SDValue CCR = Cond.getOperand(3);
3498 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3499 assert(True.getValueType() == VT);
3500 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3505 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3506 // undefined bits before doing a full-word comparison with zero.
3507 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3508 DAG.getConstant(1, dl, Cond.getValueType()));
3510 return DAG.getSelectCC(dl, Cond,
3511 DAG.getConstant(0, dl, Cond.getValueType()),
3512 SelectTrue, SelectFalse, ISD::SETNE);
3515 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3516 bool &swpCmpOps, bool &swpVselOps) {
3517 // Start by selecting the GE condition code for opcodes that return true for
3519 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3521 CondCode = ARMCC::GE;
3523 // and GT for opcodes that return false for 'equality'.
3524 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3526 CondCode = ARMCC::GT;
3528 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3529 // to swap the compare operands.
3530 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3534 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3535 // If we have an unordered opcode, we need to swap the operands to the VSEL
3536 // instruction (effectively negating the condition).
3538 // This also has the effect of swapping which one of 'less' or 'greater'
3539 // returns true, so we also swap the compare operands. It also switches
3540 // whether we return true for 'equality', so we compensate by picking the
3541 // opposite condition code to our original choice.
3542 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3543 CC == ISD::SETUGT) {
3544 swpCmpOps = !swpCmpOps;
3545 swpVselOps = !swpVselOps;
3546 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3549 // 'ordered' is 'anything but unordered', so use the VS condition code and
3550 // swap the VSEL operands.
3551 if (CC == ISD::SETO) {
3552 CondCode = ARMCC::VS;
3556 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3557 // code and swap the VSEL operands.
3558 if (CC == ISD::SETUNE) {
3559 CondCode = ARMCC::EQ;
3564 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3565 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3566 SDValue Cmp, SelectionDAG &DAG) const {
3567 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3568 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3569 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3570 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3571 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3573 SDValue TrueLow = TrueVal.getValue(0);
3574 SDValue TrueHigh = TrueVal.getValue(1);
3575 SDValue FalseLow = FalseVal.getValue(0);
3576 SDValue FalseHigh = FalseVal.getValue(1);
3578 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3580 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3581 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3583 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3585 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3590 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3591 EVT VT = Op.getValueType();
3592 SDValue LHS = Op.getOperand(0);
3593 SDValue RHS = Op.getOperand(1);
3594 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3595 SDValue TrueVal = Op.getOperand(2);
3596 SDValue FalseVal = Op.getOperand(3);
3599 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3600 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3603 // If softenSetCCOperands only returned one value, we should compare it to
3605 if (!RHS.getNode()) {
3606 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3611 if (LHS.getValueType() == MVT::i32) {
3612 // Try to generate VSEL on ARMv8.
3613 // The VSEL instruction can't use all the usual ARM condition
3614 // codes: it only has two bits to select the condition code, so it's
3615 // constrained to use only GE, GT, VS and EQ.
3617 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3618 // swap the operands of the previous compare instruction (effectively
3619 // inverting the compare condition, swapping 'less' and 'greater') and
3620 // sometimes need to swap the operands to the VSEL (which inverts the
3621 // condition in the sense of firing whenever the previous condition didn't)
3622 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3623 TrueVal.getValueType() == MVT::f64)) {
3624 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3625 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3626 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3627 CC = ISD::getSetCCInverse(CC, true);
3628 std::swap(TrueVal, FalseVal);
3633 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3634 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3635 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3638 ARMCC::CondCodes CondCode, CondCode2;
3639 FPCCToARMCC(CC, CondCode, CondCode2);
3641 // Try to generate VMAXNM/VMINNM on ARMv8.
3642 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3643 TrueVal.getValueType() == MVT::f64)) {
3644 bool swpCmpOps = false;
3645 bool swpVselOps = false;
3646 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3648 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3649 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3651 std::swap(LHS, RHS);
3653 std::swap(TrueVal, FalseVal);
3657 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3658 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3659 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3660 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3661 if (CondCode2 != ARMCC::AL) {
3662 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3663 // FIXME: Needs another CMP because flag can have but one use.
3664 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3665 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3670 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3671 /// to morph to an integer compare sequence.
3672 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3673 const ARMSubtarget *Subtarget) {
3674 SDNode *N = Op.getNode();
3675 if (!N->hasOneUse())
3676 // Otherwise it requires moving the value from fp to integer registers.
3678 if (!N->getNumValues())
3680 EVT VT = Op.getValueType();
3681 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3682 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3683 // vmrs are very slow, e.g. cortex-a8.
3686 if (isFloatingPointZero(Op)) {
3690 return ISD::isNormalLoad(N);
3693 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3694 if (isFloatingPointZero(Op))
3695 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3697 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3698 return DAG.getLoad(MVT::i32, SDLoc(Op),
3699 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3700 Ld->isVolatile(), Ld->isNonTemporal(),
3701 Ld->isInvariant(), Ld->getAlignment());
3703 llvm_unreachable("Unknown VFP cmp argument!");
3706 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3707 SDValue &RetVal1, SDValue &RetVal2) {
3710 if (isFloatingPointZero(Op)) {
3711 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3712 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3716 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3717 SDValue Ptr = Ld->getBasePtr();
3718 RetVal1 = DAG.getLoad(MVT::i32, dl,
3719 Ld->getChain(), Ptr,
3720 Ld->getPointerInfo(),
3721 Ld->isVolatile(), Ld->isNonTemporal(),
3722 Ld->isInvariant(), Ld->getAlignment());
3724 EVT PtrType = Ptr.getValueType();
3725 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3726 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3727 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3728 RetVal2 = DAG.getLoad(MVT::i32, dl,
3729 Ld->getChain(), NewPtr,
3730 Ld->getPointerInfo().getWithOffset(4),
3731 Ld->isVolatile(), Ld->isNonTemporal(),
3732 Ld->isInvariant(), NewAlign);
3736 llvm_unreachable("Unknown VFP cmp argument!");
3739 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3740 /// f32 and even f64 comparisons to integer ones.
3742 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3743 SDValue Chain = Op.getOperand(0);
3744 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3745 SDValue LHS = Op.getOperand(2);
3746 SDValue RHS = Op.getOperand(3);
3747 SDValue Dest = Op.getOperand(4);
3750 bool LHSSeenZero = false;
3751 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3752 bool RHSSeenZero = false;
3753 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3754 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3755 // If unsafe fp math optimization is enabled and there are no other uses of
3756 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3757 // to an integer comparison.
3758 if (CC == ISD::SETOEQ)
3760 else if (CC == ISD::SETUNE)
3763 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3765 if (LHS.getValueType() == MVT::f32) {
3766 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3767 bitcastf32Toi32(LHS, DAG), Mask);
3768 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3769 bitcastf32Toi32(RHS, DAG), Mask);
3770 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3771 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3772 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3773 Chain, Dest, ARMcc, CCR, Cmp);
3778 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3779 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3780 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3781 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3782 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3783 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3784 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3785 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3786 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3792 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3793 SDValue Chain = Op.getOperand(0);
3794 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3795 SDValue LHS = Op.getOperand(2);
3796 SDValue RHS = Op.getOperand(3);
3797 SDValue Dest = Op.getOperand(4);
3800 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3801 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3804 // If softenSetCCOperands only returned one value, we should compare it to
3806 if (!RHS.getNode()) {
3807 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3812 if (LHS.getValueType() == MVT::i32) {
3814 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3815 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3816 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3817 Chain, Dest, ARMcc, CCR, Cmp);
3820 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3822 if (getTargetMachine().Options.UnsafeFPMath &&
3823 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3824 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3825 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3826 if (Result.getNode())
3830 ARMCC::CondCodes CondCode, CondCode2;
3831 FPCCToARMCC(CC, CondCode, CondCode2);
3833 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3834 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3835 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3836 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3837 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3838 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3839 if (CondCode2 != ARMCC::AL) {
3840 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3841 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3842 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3847 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3848 SDValue Chain = Op.getOperand(0);
3849 SDValue Table = Op.getOperand(1);
3850 SDValue Index = Op.getOperand(2);
3853 EVT PTy = getPointerTy(DAG.getDataLayout());
3854 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3855 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3856 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3857 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3858 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3859 if (Subtarget->isThumb2()) {
3860 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3861 // which does another jump to the destination. This also makes it easier
3862 // to translate it to TBB / TBH later.
3863 // FIXME: This might not work if the function is extremely large.
3864 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3865 Addr, Op.getOperand(2), JTI);
3867 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3869 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3870 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3871 false, false, false, 0);
3872 Chain = Addr.getValue(1);
3873 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3874 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3877 DAG.getLoad(PTy, dl, Chain, Addr,
3878 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3879 false, false, false, 0);
3880 Chain = Addr.getValue(1);
3881 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3885 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3886 EVT VT = Op.getValueType();
3889 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3890 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3892 return DAG.UnrollVectorOp(Op.getNode());
3895 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3896 "Invalid type for custom lowering!");
3897 if (VT != MVT::v4i16)
3898 return DAG.UnrollVectorOp(Op.getNode());
3900 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3901 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3904 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3905 EVT VT = Op.getValueType();
3907 return LowerVectorFP_TO_INT(Op, DAG);
3908 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3910 if (Op.getOpcode() == ISD::FP_TO_SINT)
3911 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3914 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3916 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3917 /*isSigned*/ false, SDLoc(Op)).first;
3923 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3924 EVT VT = Op.getValueType();
3927 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3928 if (VT.getVectorElementType() == MVT::f32)
3930 return DAG.UnrollVectorOp(Op.getNode());
3933 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3934 "Invalid type for custom lowering!");
3935 if (VT != MVT::v4f32)
3936 return DAG.UnrollVectorOp(Op.getNode());
3940 switch (Op.getOpcode()) {
3941 default: llvm_unreachable("Invalid opcode!");
3942 case ISD::SINT_TO_FP:
3943 CastOpc = ISD::SIGN_EXTEND;
3944 Opc = ISD::SINT_TO_FP;
3946 case ISD::UINT_TO_FP:
3947 CastOpc = ISD::ZERO_EXTEND;
3948 Opc = ISD::UINT_TO_FP;
3952 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3953 return DAG.getNode(Opc, dl, VT, Op);
3956 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3957 EVT VT = Op.getValueType();
3959 return LowerVectorINT_TO_FP(Op, DAG);
3960 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3962 if (Op.getOpcode() == ISD::SINT_TO_FP)
3963 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3966 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3968 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3969 /*isSigned*/ false, SDLoc(Op)).first;
3975 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3976 // Implement fcopysign with a fabs and a conditional fneg.
3977 SDValue Tmp0 = Op.getOperand(0);
3978 SDValue Tmp1 = Op.getOperand(1);
3980 EVT VT = Op.getValueType();
3981 EVT SrcVT = Tmp1.getValueType();
3982 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3983 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3984 bool UseNEON = !InGPR && Subtarget->hasNEON();
3987 // Use VBSL to copy the sign bit.
3988 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3989 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3990 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3991 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3993 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3994 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3995 DAG.getConstant(32, dl, MVT::i32));
3996 else /*if (VT == MVT::f32)*/
3997 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3998 if (SrcVT == MVT::f32) {
3999 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4001 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4002 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4003 DAG.getConstant(32, dl, MVT::i32));
4004 } else if (VT == MVT::f32)
4005 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4006 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4007 DAG.getConstant(32, dl, MVT::i32));
4008 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4009 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4011 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4013 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4014 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4015 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4017 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4018 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4019 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4020 if (VT == MVT::f32) {
4021 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4022 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4023 DAG.getConstant(0, dl, MVT::i32));
4025 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4031 // Bitcast operand 1 to i32.
4032 if (SrcVT == MVT::f64)
4033 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4035 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4037 // Or in the signbit with integer operations.
4038 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4039 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4040 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4041 if (VT == MVT::f32) {
4042 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4043 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4044 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4045 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4048 // f64: Or the high part with signbit and then combine two parts.
4049 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4051 SDValue Lo = Tmp0.getValue(0);
4052 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4053 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4054 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4057 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4058 MachineFunction &MF = DAG.getMachineFunction();
4059 MachineFrameInfo *MFI = MF.getFrameInfo();
4060 MFI->setReturnAddressIsTaken(true);
4062 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4065 EVT VT = Op.getValueType();
4067 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4069 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4070 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4071 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4072 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4073 MachinePointerInfo(), false, false, false, 0);
4076 // Return LR, which contains the return address. Mark it an implicit live-in.
4077 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4078 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4081 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4082 const ARMBaseRegisterInfo &ARI =
4083 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4084 MachineFunction &MF = DAG.getMachineFunction();
4085 MachineFrameInfo *MFI = MF.getFrameInfo();
4086 MFI->setFrameAddressIsTaken(true);
4088 EVT VT = Op.getValueType();
4089 SDLoc dl(Op); // FIXME probably not meaningful
4090 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4091 unsigned FrameReg = ARI.getFrameRegister(MF);
4092 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4094 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4095 MachinePointerInfo(),
4096 false, false, false, 0);
4100 // FIXME? Maybe this could be a TableGen attribute on some registers and
4101 // this table could be generated automatically from RegInfo.
4102 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4103 SelectionDAG &DAG) const {
4104 unsigned Reg = StringSwitch<unsigned>(RegName)
4105 .Case("sp", ARM::SP)
4109 report_fatal_error(Twine("Invalid register name \""
4110 + StringRef(RegName) + "\"."));
4113 // Result is 64 bit value so split into two 32 bit values and return as a
4115 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4116 SelectionDAG &DAG) {
4119 // This function is only supposed to be called for i64 type destination.
4120 assert(N->getValueType(0) == MVT::i64
4121 && "ExpandREAD_REGISTER called for non-i64 type result.");
4123 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4124 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4128 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4130 Results.push_back(Read.getOperand(0));
4133 /// ExpandBITCAST - If the target supports VFP, this function is called to
4134 /// expand a bit convert where either the source or destination type is i64 to
4135 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4136 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4137 /// vectors), since the legalizer won't know what to do with that.
4138 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4141 SDValue Op = N->getOperand(0);
4143 // This function is only supposed to be called for i64 types, either as the
4144 // source or destination of the bit convert.
4145 EVT SrcVT = Op.getValueType();
4146 EVT DstVT = N->getValueType(0);
4147 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4148 "ExpandBITCAST called for non-i64 type");
4150 // Turn i64->f64 into VMOVDRR.
4151 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4152 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153 DAG.getConstant(0, dl, MVT::i32));
4154 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155 DAG.getConstant(1, dl, MVT::i32));
4156 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4157 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4160 // Turn f64->i64 into VMOVRRD.
4161 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4163 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4164 SrcVT.getVectorNumElements() > 1)
4165 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166 DAG.getVTList(MVT::i32, MVT::i32),
4167 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4169 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4170 DAG.getVTList(MVT::i32, MVT::i32), Op);
4171 // Merge the pieces into a single i64 value.
4172 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4178 /// getZeroVector - Returns a vector of specified type with all zero elements.
4179 /// Zero vectors are used to represent vector negation and in those cases
4180 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4181 /// not support i64 elements, so sometimes the zero vectors will need to be
4182 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4184 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4185 assert(VT.isVector() && "Expected a vector type");
4186 // The canonical modified immediate encoding of a zero vector is....0!
4187 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4188 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4189 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4190 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4193 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4194 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4195 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4196 SelectionDAG &DAG) const {
4197 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4198 EVT VT = Op.getValueType();
4199 unsigned VTBits = VT.getSizeInBits();
4201 SDValue ShOpLo = Op.getOperand(0);
4202 SDValue ShOpHi = Op.getOperand(1);
4203 SDValue ShAmt = Op.getOperand(2);
4205 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4207 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4209 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4210 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4211 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4212 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4213 DAG.getConstant(VTBits, dl, MVT::i32));
4214 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4215 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4216 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4218 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4219 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4220 ISD::SETGE, ARMcc, DAG, dl);
4221 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4222 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4225 SDValue Ops[2] = { Lo, Hi };
4226 return DAG.getMergeValues(Ops, dl);
4229 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4232 SelectionDAG &DAG) const {
4233 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234 EVT VT = Op.getValueType();
4235 unsigned VTBits = VT.getSizeInBits();
4237 SDValue ShOpLo = Op.getOperand(0);
4238 SDValue ShOpHi = Op.getOperand(1);
4239 SDValue ShAmt = Op.getOperand(2);
4242 assert(Op.getOpcode() == ISD::SHL_PARTS);
4243 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4244 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4245 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4246 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4247 DAG.getConstant(VTBits, dl, MVT::i32));
4248 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4249 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4251 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4253 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4254 ISD::SETGE, ARMcc, DAG, dl);
4255 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4256 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4259 SDValue Ops[2] = { Lo, Hi };
4260 return DAG.getMergeValues(Ops, dl);
4263 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4264 SelectionDAG &DAG) const {
4265 // The rounding mode is in bits 23:22 of the FPSCR.
4266 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4267 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4268 // so that the shift + and get folded into a bitfield extract.
4270 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4271 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4273 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4274 DAG.getConstant(1U << 22, dl, MVT::i32));
4275 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4276 DAG.getConstant(22, dl, MVT::i32));
4277 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4278 DAG.getConstant(3, dl, MVT::i32));
4281 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4282 const ARMSubtarget *ST) {
4284 EVT VT = N->getValueType(0);
4285 if (VT.isVector()) {
4286 assert(ST->hasNEON());
4288 // Compute the least significant set bit: LSB = X & -X
4289 SDValue X = N->getOperand(0);
4290 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4291 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4293 EVT ElemTy = VT.getVectorElementType();
4295 if (ElemTy == MVT::i8) {
4296 // Compute with: cttz(x) = ctpop(lsb - 1)
4297 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4298 DAG.getTargetConstant(1, dl, ElemTy));
4299 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4300 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4303 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4304 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4305 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4306 unsigned NumBits = ElemTy.getSizeInBits();
4307 SDValue WidthMinus1 =
4308 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4309 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4310 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4311 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4314 // Compute with: cttz(x) = ctpop(lsb - 1)
4316 // Since we can only compute the number of bits in a byte with vcnt.8, we
4317 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4322 if (ElemTy == MVT::i64) {
4323 // Load constant 0xffff'ffff'ffff'ffff to register.
4324 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4325 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4326 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4328 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4329 DAG.getTargetConstant(1, dl, ElemTy));
4330 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4333 // Count #bits with vcnt.8.
4334 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4335 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4336 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4338 // Gather the #bits with vpaddl (pairwise add.)
4339 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4340 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4341 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4343 if (ElemTy == MVT::i16)
4346 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4347 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4348 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4350 if (ElemTy == MVT::i32)
4353 assert(ElemTy == MVT::i64);
4354 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4355 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4360 if (!ST->hasV6T2Ops())
4363 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4364 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4367 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4368 /// for each 16-bit element from operand, repeated. The basic idea is to
4369 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4371 /// Trace for v4i16:
4372 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4373 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4374 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4375 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4376 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4377 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4378 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4379 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4380 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4381 EVT VT = N->getValueType(0);
4384 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4385 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4386 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4387 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4388 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4389 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4392 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4393 /// bit-count for each 16-bit element from the operand. We need slightly
4394 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4395 /// 64/128-bit registers.
4397 /// Trace for v4i16:
4398 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4399 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4400 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4401 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4402 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4403 EVT VT = N->getValueType(0);
4406 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4407 if (VT.is64BitVector()) {
4408 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4409 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4410 DAG.getIntPtrConstant(0, DL));
4412 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4413 BitCounts, DAG.getIntPtrConstant(0, DL));
4414 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4418 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4419 /// bit-count for each 32-bit element from the operand. The idea here is
4420 /// to split the vector into 16-bit elements, leverage the 16-bit count
4421 /// routine, and then combine the results.
4423 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4424 /// input = [v0 v1 ] (vi: 32-bit elements)
4425 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4426 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4427 /// vrev: N0 = [k1 k0 k3 k2 ]
4429 /// N1 =+[k1 k0 k3 k2 ]
4431 /// N2 =+[k1 k3 k0 k2 ]
4433 /// Extended =+[k1 k3 k0 k2 ]
4435 /// Extracted=+[k1 k3 ]
4437 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4438 EVT VT = N->getValueType(0);
4441 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4443 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4444 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4445 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4446 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4447 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4449 if (VT.is64BitVector()) {
4450 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4451 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4452 DAG.getIntPtrConstant(0, DL));
4454 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4455 DAG.getIntPtrConstant(0, DL));
4456 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4460 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4461 const ARMSubtarget *ST) {
4462 EVT VT = N->getValueType(0);
4464 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4465 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4466 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4467 "Unexpected type for custom ctpop lowering");
4469 if (VT.getVectorElementType() == MVT::i32)
4470 return lowerCTPOP32BitElements(N, DAG);
4472 return lowerCTPOP16BitElements(N, DAG);
4475 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4476 const ARMSubtarget *ST) {
4477 EVT VT = N->getValueType(0);
4483 // Lower vector shifts on NEON to use VSHL.
4484 assert(ST->hasNEON() && "unexpected vector shift");
4486 // Left shifts translate directly to the vshiftu intrinsic.
4487 if (N->getOpcode() == ISD::SHL)
4488 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4489 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4491 N->getOperand(0), N->getOperand(1));
4493 assert((N->getOpcode() == ISD::SRA ||
4494 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4496 // NEON uses the same intrinsics for both left and right shifts. For
4497 // right shifts, the shift amounts are negative, so negate the vector of
4499 EVT ShiftVT = N->getOperand(1).getValueType();
4500 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4501 getZeroVector(ShiftVT, DAG, dl),
4503 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4504 Intrinsic::arm_neon_vshifts :
4505 Intrinsic::arm_neon_vshiftu);
4506 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4507 DAG.getConstant(vshiftInt, dl, MVT::i32),
4508 N->getOperand(0), NegatedCount);
4511 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4512 const ARMSubtarget *ST) {
4513 EVT VT = N->getValueType(0);
4516 // We can get here for a node like i32 = ISD::SHL i32, i64
4520 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4521 "Unknown shift to lower!");
4523 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4524 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4525 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4528 // If we are in thumb mode, we don't have RRX.
4529 if (ST->isThumb1Only()) return SDValue();
4531 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4532 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4533 DAG.getConstant(0, dl, MVT::i32));
4534 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4535 DAG.getConstant(1, dl, MVT::i32));
4537 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4538 // captures the result into a carry flag.
4539 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4540 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4542 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4543 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4545 // Merge the pieces into a single i64 value.
4546 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4549 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4550 SDValue TmpOp0, TmpOp1;
4551 bool Invert = false;
4555 SDValue Op0 = Op.getOperand(0);
4556 SDValue Op1 = Op.getOperand(1);
4557 SDValue CC = Op.getOperand(2);
4558 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4559 EVT VT = Op.getValueType();
4560 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4563 if (Op1.getValueType().isFloatingPoint()) {
4564 switch (SetCCOpcode) {
4565 default: llvm_unreachable("Illegal FP comparison");
4567 case ISD::SETNE: Invert = true; // Fallthrough
4569 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4571 case ISD::SETLT: Swap = true; // Fallthrough
4573 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4575 case ISD::SETLE: Swap = true; // Fallthrough
4577 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4578 case ISD::SETUGE: Swap = true; // Fallthrough
4579 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4580 case ISD::SETUGT: Swap = true; // Fallthrough
4581 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4582 case ISD::SETUEQ: Invert = true; // Fallthrough
4584 // Expand this to (OLT | OGT).
4588 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4589 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4591 case ISD::SETUO: Invert = true; // Fallthrough
4593 // Expand this to (OLT | OGE).
4597 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4598 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4602 // Integer comparisons.
4603 switch (SetCCOpcode) {
4604 default: llvm_unreachable("Illegal integer comparison");
4605 case ISD::SETNE: Invert = true;
4606 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4607 case ISD::SETLT: Swap = true;
4608 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4609 case ISD::SETLE: Swap = true;
4610 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4611 case ISD::SETULT: Swap = true;
4612 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4613 case ISD::SETULE: Swap = true;
4614 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4617 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4618 if (Opc == ARMISD::VCEQ) {
4621 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4623 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4626 // Ignore bitconvert.
4627 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4628 AndOp = AndOp.getOperand(0);
4630 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4632 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4633 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4640 std::swap(Op0, Op1);
4642 // If one of the operands is a constant vector zero, attempt to fold the
4643 // comparison to a specialized compare-against-zero form.
4645 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4647 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4648 if (Opc == ARMISD::VCGE)
4649 Opc = ARMISD::VCLEZ;
4650 else if (Opc == ARMISD::VCGT)
4651 Opc = ARMISD::VCLTZ;
4656 if (SingleOp.getNode()) {
4659 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4661 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4663 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4665 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4667 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4669 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4672 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4675 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4678 Result = DAG.getNOT(dl, Result, VT);
4683 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4684 /// valid vector constant for a NEON instruction with a "modified immediate"
4685 /// operand (e.g., VMOV). If so, return the encoded value.
4686 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4687 unsigned SplatBitSize, SelectionDAG &DAG,
4688 SDLoc dl, EVT &VT, bool is128Bits,
4689 NEONModImmType type) {
4690 unsigned OpCmode, Imm;
4692 // SplatBitSize is set to the smallest size that splats the vector, so a
4693 // zero vector will always have SplatBitSize == 8. However, NEON modified
4694 // immediate instructions others than VMOV do not support the 8-bit encoding
4695 // of a zero vector, and the default encoding of zero is supposed to be the
4700 switch (SplatBitSize) {
4702 if (type != VMOVModImm)
4704 // Any 1-byte value is OK. Op=0, Cmode=1110.
4705 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4708 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4712 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4713 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4714 if ((SplatBits & ~0xff) == 0) {
4715 // Value = 0x00nn: Op=x, Cmode=100x.
4720 if ((SplatBits & ~0xff00) == 0) {
4721 // Value = 0xnn00: Op=x, Cmode=101x.
4723 Imm = SplatBits >> 8;
4729 // NEON's 32-bit VMOV supports splat values where:
4730 // * only one byte is nonzero, or
4731 // * the least significant byte is 0xff and the second byte is nonzero, or
4732 // * the least significant 2 bytes are 0xff and the third is nonzero.
4733 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4734 if ((SplatBits & ~0xff) == 0) {
4735 // Value = 0x000000nn: Op=x, Cmode=000x.
4740 if ((SplatBits & ~0xff00) == 0) {
4741 // Value = 0x0000nn00: Op=x, Cmode=001x.
4743 Imm = SplatBits >> 8;
4746 if ((SplatBits & ~0xff0000) == 0) {
4747 // Value = 0x00nn0000: Op=x, Cmode=010x.
4749 Imm = SplatBits >> 16;
4752 if ((SplatBits & ~0xff000000) == 0) {
4753 // Value = 0xnn000000: Op=x, Cmode=011x.
4755 Imm = SplatBits >> 24;
4759 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4760 if (type == OtherModImm) return SDValue();
4762 if ((SplatBits & ~0xffff) == 0 &&
4763 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4764 // Value = 0x0000nnff: Op=x, Cmode=1100.
4766 Imm = SplatBits >> 8;
4770 if ((SplatBits & ~0xffffff) == 0 &&
4771 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4772 // Value = 0x00nnffff: Op=x, Cmode=1101.
4774 Imm = SplatBits >> 16;
4778 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4779 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4780 // VMOV.I32. A (very) minor optimization would be to replicate the value
4781 // and fall through here to test for a valid 64-bit splat. But, then the
4782 // caller would also need to check and handle the change in size.
4786 if (type != VMOVModImm)
4788 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4789 uint64_t BitMask = 0xff;
4791 unsigned ImmMask = 1;
4793 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4794 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4797 } else if ((SplatBits & BitMask) != 0) {
4804 if (DAG.getDataLayout().isBigEndian())
4805 // swap higher and lower 32 bit word
4806 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4808 // Op=1, Cmode=1110.
4810 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4815 llvm_unreachable("unexpected size for isNEONModifiedImm");
4818 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4819 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4822 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4823 const ARMSubtarget *ST) const {
4827 bool IsDouble = Op.getValueType() == MVT::f64;
4828 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4830 // Use the default (constant pool) lowering for double constants when we have
4832 if (IsDouble && Subtarget->isFPOnlySP())
4835 // Try splatting with a VMOV.f32...
4836 APFloat FPVal = CFP->getValueAPF();
4837 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4840 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4841 // We have code in place to select a valid ConstantFP already, no need to
4846 // It's a float and we are trying to use NEON operations where
4847 // possible. Lower it to a splat followed by an extract.
4849 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4850 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4852 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4853 DAG.getConstant(0, DL, MVT::i32));
4856 // The rest of our options are NEON only, make sure that's allowed before
4858 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4862 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4864 // It wouldn't really be worth bothering for doubles except for one very
4865 // important value, which does happen to match: 0.0. So make sure we don't do
4867 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4870 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4871 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4872 VMovVT, false, VMOVModImm);
4873 if (NewVal != SDValue()) {
4875 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4878 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4880 // It's a float: cast and extract a vector element.
4881 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4883 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4884 DAG.getConstant(0, DL, MVT::i32));
4887 // Finally, try a VMVN.i32
4888 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4890 if (NewVal != SDValue()) {
4892 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4895 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4897 // It's a float: cast and extract a vector element.
4898 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4900 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4901 DAG.getConstant(0, DL, MVT::i32));
4907 // check if an VEXT instruction can handle the shuffle mask when the
4908 // vector sources of the shuffle are the same.
4909 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4910 unsigned NumElts = VT.getVectorNumElements();
4912 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4918 // If this is a VEXT shuffle, the immediate value is the index of the first
4919 // element. The other shuffle indices must be the successive elements after
4921 unsigned ExpectedElt = Imm;
4922 for (unsigned i = 1; i < NumElts; ++i) {
4923 // Increment the expected index. If it wraps around, just follow it
4924 // back to index zero and keep going.
4926 if (ExpectedElt == NumElts)
4929 if (M[i] < 0) continue; // ignore UNDEF indices
4930 if (ExpectedElt != static_cast<unsigned>(M[i]))
4938 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4939 bool &ReverseVEXT, unsigned &Imm) {
4940 unsigned NumElts = VT.getVectorNumElements();
4941 ReverseVEXT = false;
4943 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4949 // If this is a VEXT shuffle, the immediate value is the index of the first
4950 // element. The other shuffle indices must be the successive elements after
4952 unsigned ExpectedElt = Imm;
4953 for (unsigned i = 1; i < NumElts; ++i) {
4954 // Increment the expected index. If it wraps around, it may still be
4955 // a VEXT but the source vectors must be swapped.
4957 if (ExpectedElt == NumElts * 2) {
4962 if (M[i] < 0) continue; // ignore UNDEF indices
4963 if (ExpectedElt != static_cast<unsigned>(M[i]))
4967 // Adjust the index value if the source operands will be swapped.
4974 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4975 /// instruction with the specified blocksize. (The order of the elements
4976 /// within each block of the vector is reversed.)
4977 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4978 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4979 "Only possible block sizes for VREV are: 16, 32, 64");
4981 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4985 unsigned NumElts = VT.getVectorNumElements();
4986 unsigned BlockElts = M[0] + 1;
4987 // If the first shuffle index is UNDEF, be optimistic.
4989 BlockElts = BlockSize / EltSz;
4991 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4994 for (unsigned i = 0; i < NumElts; ++i) {
4995 if (M[i] < 0) continue; // ignore UNDEF indices
4996 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5003 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5004 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5005 // range, then 0 is placed into the resulting vector. So pretty much any mask
5006 // of 8 elements can work here.
5007 return VT == MVT::v8i8 && M.size() == 8;
5010 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5011 // checking that pairs of elements in the shuffle mask represent the same index
5012 // in each vector, incrementing the expected index by 2 at each step.
5013 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5014 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5016 // WhichResult gives the offset for each element in the mask based on which
5017 // of the two results it belongs to.
5019 // The transpose can be represented either as:
5020 // result1 = shufflevector v1, v2, result1_shuffle_mask
5021 // result2 = shufflevector v1, v2, result2_shuffle_mask
5022 // where v1/v2 and the shuffle masks have the same number of elements
5023 // (here WhichResult (see below) indicates which result is being checked)
5026 // results = shufflevector v1, v2, shuffle_mask
5027 // where both results are returned in one vector and the shuffle mask has twice
5028 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5029 // want to check the low half and high half of the shuffle mask as if it were
5031 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5032 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5036 unsigned NumElts = VT.getVectorNumElements();
5037 if (M.size() != NumElts && M.size() != NumElts*2)
5040 // If the mask is twice as long as the result then we need to check the upper
5041 // and lower parts of the mask
5042 for (unsigned i = 0; i < M.size(); i += NumElts) {
5043 WhichResult = M[i] == 0 ? 0 : 1;
5044 for (unsigned j = 0; j < NumElts; j += 2) {
5045 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5046 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5051 if (M.size() == NumElts*2)
5057 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5058 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5059 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5060 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5061 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5065 unsigned NumElts = VT.getVectorNumElements();
5066 if (M.size() != NumElts && M.size() != NumElts*2)
5069 for (unsigned i = 0; i < M.size(); i += NumElts) {
5070 WhichResult = M[i] == 0 ? 0 : 1;
5071 for (unsigned j = 0; j < NumElts; j += 2) {
5072 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5073 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5078 if (M.size() == NumElts*2)
5084 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5085 // that the mask elements are either all even and in steps of size 2 or all odd
5086 // and in steps of size 2.
5087 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5088 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5090 // Requires similar checks to that of isVTRNMask with
5091 // respect the how results are returned.
5092 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5093 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5097 unsigned NumElts = VT.getVectorNumElements();
5098 if (M.size() != NumElts && M.size() != NumElts*2)
5101 for (unsigned i = 0; i < M.size(); i += NumElts) {
5102 WhichResult = M[i] == 0 ? 0 : 1;
5103 for (unsigned j = 0; j < NumElts; ++j) {
5104 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5109 if (M.size() == NumElts*2)
5112 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5113 if (VT.is64BitVector() && EltSz == 32)
5119 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5120 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5121 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5122 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5123 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5127 unsigned NumElts = VT.getVectorNumElements();
5128 if (M.size() != NumElts && M.size() != NumElts*2)
5131 unsigned Half = NumElts / 2;
5132 for (unsigned i = 0; i < M.size(); i += NumElts) {
5133 WhichResult = M[i] == 0 ? 0 : 1;
5134 for (unsigned j = 0; j < NumElts; j += Half) {
5135 unsigned Idx = WhichResult;
5136 for (unsigned k = 0; k < Half; ++k) {
5137 int MIdx = M[i + j + k];
5138 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5145 if (M.size() == NumElts*2)
5148 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5149 if (VT.is64BitVector() && EltSz == 32)
5155 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5156 // that pairs of elements of the shufflemask represent the same index in each
5157 // vector incrementing sequentially through the vectors.
5158 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5159 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5161 // Requires similar checks to that of isVTRNMask with respect the how results
5163 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5164 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5168 unsigned NumElts = VT.getVectorNumElements();
5169 if (M.size() != NumElts && M.size() != NumElts*2)
5172 for (unsigned i = 0; i < M.size(); i += NumElts) {
5173 WhichResult = M[i] == 0 ? 0 : 1;
5174 unsigned Idx = WhichResult * NumElts / 2;
5175 for (unsigned j = 0; j < NumElts; j += 2) {
5176 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5177 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5183 if (M.size() == NumElts*2)
5186 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5187 if (VT.is64BitVector() && EltSz == 32)
5193 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5194 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5195 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5196 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5197 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5201 unsigned NumElts = VT.getVectorNumElements();
5202 if (M.size() != NumElts && M.size() != NumElts*2)
5205 for (unsigned i = 0; i < M.size(); i += NumElts) {
5206 WhichResult = M[i] == 0 ? 0 : 1;
5207 unsigned Idx = WhichResult * NumElts / 2;
5208 for (unsigned j = 0; j < NumElts; j += 2) {
5209 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5210 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5216 if (M.size() == NumElts*2)
5219 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5220 if (VT.is64BitVector() && EltSz == 32)
5226 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5227 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5228 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5229 unsigned &WhichResult,
5232 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5233 return ARMISD::VTRN;
5234 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5235 return ARMISD::VUZP;
5236 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5237 return ARMISD::VZIP;
5240 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5241 return ARMISD::VTRN;
5242 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5243 return ARMISD::VUZP;
5244 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5245 return ARMISD::VZIP;
5250 /// \return true if this is a reverse operation on an vector.
5251 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5252 unsigned NumElts = VT.getVectorNumElements();
5253 // Make sure the mask has the right size.
5254 if (NumElts != M.size())
5257 // Look for <15, ..., 3, -1, 1, 0>.
5258 for (unsigned i = 0; i != NumElts; ++i)
5259 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5265 // If N is an integer constant that can be moved into a register in one
5266 // instruction, return an SDValue of such a constant (will become a MOV
5267 // instruction). Otherwise return null.
5268 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5269 const ARMSubtarget *ST, SDLoc dl) {
5271 if (!isa<ConstantSDNode>(N))
5273 Val = cast<ConstantSDNode>(N)->getZExtValue();
5275 if (ST->isThumb1Only()) {
5276 if (Val <= 255 || ~Val <= 255)
5277 return DAG.getConstant(Val, dl, MVT::i32);
5279 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5280 return DAG.getConstant(Val, dl, MVT::i32);
5285 // If this is a case we can't handle, return null and let the default
5286 // expansion code take care of it.
5287 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5288 const ARMSubtarget *ST) const {
5289 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5291 EVT VT = Op.getValueType();
5293 APInt SplatBits, SplatUndef;
5294 unsigned SplatBitSize;
5296 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5297 if (SplatBitSize <= 64) {
5298 // Check if an immediate VMOV works.
5300 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5301 SplatUndef.getZExtValue(), SplatBitSize,
5302 DAG, dl, VmovVT, VT.is128BitVector(),
5304 if (Val.getNode()) {
5305 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5306 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5309 // Try an immediate VMVN.
5310 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5311 Val = isNEONModifiedImm(NegatedImm,
5312 SplatUndef.getZExtValue(), SplatBitSize,
5313 DAG, dl, VmovVT, VT.is128BitVector(),
5315 if (Val.getNode()) {
5316 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5317 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5320 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5321 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5322 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5324 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5325 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5331 // Scan through the operands to see if only one value is used.
5333 // As an optimisation, even if more than one value is used it may be more
5334 // profitable to splat with one value then change some lanes.
5336 // Heuristically we decide to do this if the vector has a "dominant" value,
5337 // defined as splatted to more than half of the lanes.
5338 unsigned NumElts = VT.getVectorNumElements();
5339 bool isOnlyLowElement = true;
5340 bool usesOnlyOneValue = true;
5341 bool hasDominantValue = false;
5342 bool isConstant = true;
5344 // Map of the number of times a particular SDValue appears in the
5346 DenseMap<SDValue, unsigned> ValueCounts;
5348 for (unsigned i = 0; i < NumElts; ++i) {
5349 SDValue V = Op.getOperand(i);
5350 if (V.getOpcode() == ISD::UNDEF)
5353 isOnlyLowElement = false;
5354 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5357 ValueCounts.insert(std::make_pair(V, 0));
5358 unsigned &Count = ValueCounts[V];
5360 // Is this value dominant? (takes up more than half of the lanes)
5361 if (++Count > (NumElts / 2)) {
5362 hasDominantValue = true;
5366 if (ValueCounts.size() != 1)
5367 usesOnlyOneValue = false;
5368 if (!Value.getNode() && ValueCounts.size() > 0)
5369 Value = ValueCounts.begin()->first;
5371 if (ValueCounts.size() == 0)
5372 return DAG.getUNDEF(VT);
5374 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5375 // Keep going if we are hitting this case.
5376 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5377 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5379 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5381 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5382 // i32 and try again.
5383 if (hasDominantValue && EltSize <= 32) {
5387 // If we are VDUPing a value that comes directly from a vector, that will
5388 // cause an unnecessary move to and from a GPR, where instead we could
5389 // just use VDUPLANE. We can only do this if the lane being extracted
5390 // is at a constant index, as the VDUP from lane instructions only have
5391 // constant-index forms.
5392 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5393 isa<ConstantSDNode>(Value->getOperand(1))) {
5394 // We need to create a new undef vector to use for the VDUPLANE if the
5395 // size of the vector from which we get the value is different than the
5396 // size of the vector that we need to create. We will insert the element
5397 // such that the register coalescer will remove unnecessary copies.
5398 if (VT != Value->getOperand(0).getValueType()) {
5399 ConstantSDNode *constIndex;
5400 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5401 assert(constIndex && "The index is not a constant!");
5402 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5403 VT.getVectorNumElements();
5404 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5405 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5406 Value, DAG.getConstant(index, dl, MVT::i32)),
5407 DAG.getConstant(index, dl, MVT::i32));
5409 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5410 Value->getOperand(0), Value->getOperand(1));
5412 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5414 if (!usesOnlyOneValue) {
5415 // The dominant value was splatted as 'N', but we now have to insert
5416 // all differing elements.
5417 for (unsigned I = 0; I < NumElts; ++I) {
5418 if (Op.getOperand(I) == Value)
5420 SmallVector<SDValue, 3> Ops;
5422 Ops.push_back(Op.getOperand(I));
5423 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5424 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5429 if (VT.getVectorElementType().isFloatingPoint()) {
5430 SmallVector<SDValue, 8> Ops;
5431 for (unsigned i = 0; i < NumElts; ++i)
5432 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5434 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5435 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5436 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5438 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5440 if (usesOnlyOneValue) {
5441 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5442 if (isConstant && Val.getNode())
5443 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5447 // If all elements are constants and the case above didn't get hit, fall back
5448 // to the default expansion, which will generate a load from the constant
5453 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5455 SDValue shuffle = ReconstructShuffle(Op, DAG);
5456 if (shuffle != SDValue())
5460 // Vectors with 32- or 64-bit elements can be built by directly assigning
5461 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5462 // will be legalized.
5463 if (EltSize >= 32) {
5464 // Do the expansion with floating-point types, since that is what the VFP
5465 // registers are defined to use, and since i64 is not legal.
5466 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5467 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5468 SmallVector<SDValue, 8> Ops;
5469 for (unsigned i = 0; i < NumElts; ++i)
5470 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5471 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5472 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5475 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5476 // know the default expansion would otherwise fall back on something even
5477 // worse. For a vector with one or two non-undef values, that's
5478 // scalar_to_vector for the elements followed by a shuffle (provided the
5479 // shuffle is valid for the target) and materialization element by element
5480 // on the stack followed by a load for everything else.
5481 if (!isConstant && !usesOnlyOneValue) {
5482 SDValue Vec = DAG.getUNDEF(VT);
5483 for (unsigned i = 0 ; i < NumElts; ++i) {
5484 SDValue V = Op.getOperand(i);
5485 if (V.getOpcode() == ISD::UNDEF)
5487 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5488 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5496 /// getExtFactor - Determine the adjustment factor for the position when
5497 /// generating an "extract from vector registers" instruction.
5498 static unsigned getExtFactor(SDValue &V) {
5499 EVT EltType = V.getValueType().getVectorElementType();
5500 return EltType.getSizeInBits() / 8;
5503 // Gather data to see if the operation can be modelled as a
5504 // shuffle in combination with VEXTs.
5505 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5506 SelectionDAG &DAG) const {
5507 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5509 EVT VT = Op.getValueType();
5510 unsigned NumElts = VT.getVectorNumElements();
5512 struct ShuffleSourceInfo {
5517 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5518 // be compatible with the shuffle we intend to construct. As a result
5519 // ShuffleVec will be some sliding window into the original Vec.
5522 // Code should guarantee that element i in Vec starts at element "WindowBase
5523 // + i * WindowScale in ShuffleVec".
5527 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5528 ShuffleSourceInfo(SDValue Vec)
5529 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5533 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5535 SmallVector<ShuffleSourceInfo, 2> Sources;
5536 for (unsigned i = 0; i < NumElts; ++i) {
5537 SDValue V = Op.getOperand(i);
5538 if (V.getOpcode() == ISD::UNDEF)
5540 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5541 // A shuffle can only come from building a vector from various
5542 // elements of other vectors.
5546 // Add this element source to the list if it's not already there.
5547 SDValue SourceVec = V.getOperand(0);
5548 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5549 if (Source == Sources.end())
5550 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5552 // Update the minimum and maximum lane number seen.
5553 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5554 Source->MinElt = std::min(Source->MinElt, EltNo);
5555 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5558 // Currently only do something sane when at most two source vectors
5560 if (Sources.size() > 2)
5563 // Find out the smallest element size among result and two sources, and use
5564 // it as element size to build the shuffle_vector.
5565 EVT SmallestEltTy = VT.getVectorElementType();
5566 for (auto &Source : Sources) {
5567 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5568 if (SrcEltTy.bitsLT(SmallestEltTy))
5569 SmallestEltTy = SrcEltTy;
5571 unsigned ResMultiplier =
5572 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5573 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5574 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5576 // If the source vector is too wide or too narrow, we may nevertheless be able
5577 // to construct a compatible shuffle either by concatenating it with UNDEF or
5578 // extracting a suitable range of elements.
5579 for (auto &Src : Sources) {
5580 EVT SrcVT = Src.ShuffleVec.getValueType();
5582 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5585 // This stage of the search produces a source with the same element type as
5586 // the original, but with a total width matching the BUILD_VECTOR output.
5587 EVT EltVT = SrcVT.getVectorElementType();
5588 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5589 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5591 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5592 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5594 // We can pad out the smaller vector for free, so if it's part of a
5597 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5598 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5602 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5605 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5606 // Span too large for a VEXT to cope
5610 if (Src.MinElt >= NumSrcElts) {
5611 // The extraction can just take the second half
5613 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5614 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5615 Src.WindowBase = -NumSrcElts;
5616 } else if (Src.MaxElt < NumSrcElts) {
5617 // The extraction can just take the first half
5619 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5620 DAG.getConstant(0, dl, MVT::i32));
5622 // An actual VEXT is needed
5624 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5625 DAG.getConstant(0, dl, MVT::i32));
5627 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5628 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5629 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5631 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5633 DAG.getConstant(Imm, dl, MVT::i32));
5634 Src.WindowBase = -Src.MinElt;
5638 // Another possible incompatibility occurs from the vector element types. We
5639 // can fix this by bitcasting the source vectors to the same type we intend
5641 for (auto &Src : Sources) {
5642 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5643 if (SrcEltTy == SmallestEltTy)
5645 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5646 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5647 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5648 Src.WindowBase *= Src.WindowScale;
5651 // Final sanity check before we try to actually produce a shuffle.
5653 for (auto Src : Sources)
5654 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5657 // The stars all align, our next step is to produce the mask for the shuffle.
5658 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5659 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5660 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5661 SDValue Entry = Op.getOperand(i);
5662 if (Entry.getOpcode() == ISD::UNDEF)
5665 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5666 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5668 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5669 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5671 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5672 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5673 VT.getVectorElementType().getSizeInBits());
5674 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5676 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5677 // starting at the appropriate offset.
5678 int *LaneMask = &Mask[i * ResMultiplier];
5680 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5681 ExtractBase += NumElts * (Src - Sources.begin());
5682 for (int j = 0; j < LanesDefined; ++j)
5683 LaneMask[j] = ExtractBase + j;
5686 // Final check before we try to produce nonsense...
5687 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5690 // We can't handle more than two sources. This should have already
5691 // been checked before this point.
5692 assert(Sources.size() <= 2 && "Too many sources!");
5694 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5695 for (unsigned i = 0; i < Sources.size(); ++i)
5696 ShuffleOps[i] = Sources[i].ShuffleVec;
5698 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5699 ShuffleOps[1], &Mask[0]);
5700 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5703 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5704 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5705 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5706 /// are assumed to be legal.
5708 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5710 if (VT.getVectorNumElements() == 4 &&
5711 (VT.is128BitVector() || VT.is64BitVector())) {
5712 unsigned PFIndexes[4];
5713 for (unsigned i = 0; i != 4; ++i) {
5717 PFIndexes[i] = M[i];
5720 // Compute the index in the perfect shuffle table.
5721 unsigned PFTableIndex =
5722 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5723 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5724 unsigned Cost = (PFEntry >> 30);
5730 bool ReverseVEXT, isV_UNDEF;
5731 unsigned Imm, WhichResult;
5733 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5734 return (EltSize >= 32 ||
5735 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5736 isVREVMask(M, VT, 64) ||
5737 isVREVMask(M, VT, 32) ||
5738 isVREVMask(M, VT, 16) ||
5739 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5740 isVTBLMask(M, VT) ||
5741 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5742 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5745 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5746 /// the specified operations to build the shuffle.
5747 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5748 SDValue RHS, SelectionDAG &DAG,
5750 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5751 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5752 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5755 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5764 OP_VUZPL, // VUZP, left result
5765 OP_VUZPR, // VUZP, right result
5766 OP_VZIPL, // VZIP, left result
5767 OP_VZIPR, // VZIP, right result
5768 OP_VTRNL, // VTRN, left result
5769 OP_VTRNR // VTRN, right result
5772 if (OpNum == OP_COPY) {
5773 if (LHSID == (1*9+2)*9+3) return LHS;
5774 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5778 SDValue OpLHS, OpRHS;
5779 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5780 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5781 EVT VT = OpLHS.getValueType();
5784 default: llvm_unreachable("Unknown shuffle opcode!");
5786 // VREV divides the vector in half and swaps within the half.
5787 if (VT.getVectorElementType() == MVT::i32 ||
5788 VT.getVectorElementType() == MVT::f32)
5789 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5790 // vrev <4 x i16> -> VREV32
5791 if (VT.getVectorElementType() == MVT::i16)
5792 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5793 // vrev <4 x i8> -> VREV16
5794 assert(VT.getVectorElementType() == MVT::i8);
5795 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5800 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5801 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5805 return DAG.getNode(ARMISD::VEXT, dl, VT,
5807 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5810 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5811 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5814 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5815 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5818 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5819 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5823 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5824 ArrayRef<int> ShuffleMask,
5825 SelectionDAG &DAG) {
5826 // Check to see if we can use the VTBL instruction.
5827 SDValue V1 = Op.getOperand(0);
5828 SDValue V2 = Op.getOperand(1);
5831 SmallVector<SDValue, 8> VTBLMask;
5832 for (ArrayRef<int>::iterator
5833 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5834 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5836 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5837 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5838 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5840 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5841 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5844 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5845 SelectionDAG &DAG) {
5847 SDValue OpLHS = Op.getOperand(0);
5848 EVT VT = OpLHS.getValueType();
5850 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5851 "Expect an v8i16/v16i8 type");
5852 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5853 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5854 // extract the first 8 bytes into the top double word and the last 8 bytes
5855 // into the bottom double word. The v8i16 case is similar.
5856 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5857 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5858 DAG.getConstant(ExtractNum, DL, MVT::i32));
5861 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5862 SDValue V1 = Op.getOperand(0);
5863 SDValue V2 = Op.getOperand(1);
5865 EVT VT = Op.getValueType();
5866 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5868 // Convert shuffles that are directly supported on NEON to target-specific
5869 // DAG nodes, instead of keeping them as shuffles and matching them again
5870 // during code selection. This is more efficient and avoids the possibility
5871 // of inconsistencies between legalization and selection.
5872 // FIXME: floating-point vectors should be canonicalized to integer vectors
5873 // of the same time so that they get CSEd properly.
5874 ArrayRef<int> ShuffleMask = SVN->getMask();
5876 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5877 if (EltSize <= 32) {
5878 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5879 int Lane = SVN->getSplatIndex();
5880 // If this is undef splat, generate it via "just" vdup, if possible.
5881 if (Lane == -1) Lane = 0;
5883 // Test if V1 is a SCALAR_TO_VECTOR.
5884 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5885 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5887 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5888 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5890 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5891 !isa<ConstantSDNode>(V1.getOperand(0))) {
5892 bool IsScalarToVector = true;
5893 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5894 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5895 IsScalarToVector = false;
5898 if (IsScalarToVector)
5899 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5901 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5902 DAG.getConstant(Lane, dl, MVT::i32));
5907 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5910 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5911 DAG.getConstant(Imm, dl, MVT::i32));
5914 if (isVREVMask(ShuffleMask, VT, 64))
5915 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5916 if (isVREVMask(ShuffleMask, VT, 32))
5917 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5918 if (isVREVMask(ShuffleMask, VT, 16))
5919 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5921 if (V2->getOpcode() == ISD::UNDEF &&
5922 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5923 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5924 DAG.getConstant(Imm, dl, MVT::i32));
5927 // Check for Neon shuffles that modify both input vectors in place.
5928 // If both results are used, i.e., if there are two shuffles with the same
5929 // source operands and with masks corresponding to both results of one of
5930 // these operations, DAG memoization will ensure that a single node is
5931 // used for both shuffles.
5932 unsigned WhichResult;
5934 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5935 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5938 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5939 .getValue(WhichResult);
5942 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5943 // shuffles that produce a result larger than their operands with:
5944 // shuffle(concat(v1, undef), concat(v2, undef))
5946 // shuffle(concat(v1, v2), undef)
5947 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5949 // This is useful in the general case, but there are special cases where
5950 // native shuffles produce larger results: the two-result ops.
5952 // Look through the concat when lowering them:
5953 // shuffle(concat(v1, v2), undef)
5955 // concat(VZIP(v1, v2):0, :1)
5957 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5958 V2->getOpcode() == ISD::UNDEF) {
5959 SDValue SubV1 = V1->getOperand(0);
5960 SDValue SubV2 = V1->getOperand(1);
5961 EVT SubVT = SubV1.getValueType();
5963 // We expect these to have been canonicalized to -1.
5964 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5965 return i < (int)VT.getVectorNumElements();
5966 }) && "Unexpected shuffle index into UNDEF operand!");
5968 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5969 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5972 assert((WhichResult == 0) &&
5973 "In-place shuffle of concat can only have one result!");
5974 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5976 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5982 // If the shuffle is not directly supported and it has 4 elements, use
5983 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5984 unsigned NumElts = VT.getVectorNumElements();
5986 unsigned PFIndexes[4];
5987 for (unsigned i = 0; i != 4; ++i) {
5988 if (ShuffleMask[i] < 0)
5991 PFIndexes[i] = ShuffleMask[i];
5994 // Compute the index in the perfect shuffle table.
5995 unsigned PFTableIndex =
5996 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5997 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5998 unsigned Cost = (PFEntry >> 30);
6001 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6004 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6005 if (EltSize >= 32) {
6006 // Do the expansion with floating-point types, since that is what the VFP
6007 // registers are defined to use, and since i64 is not legal.
6008 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6009 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6010 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6011 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6012 SmallVector<SDValue, 8> Ops;
6013 for (unsigned i = 0; i < NumElts; ++i) {
6014 if (ShuffleMask[i] < 0)
6015 Ops.push_back(DAG.getUNDEF(EltVT));
6017 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6018 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6019 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6022 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6023 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6026 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6027 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6029 if (VT == MVT::v8i8) {
6030 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6031 if (NewOp.getNode())
6038 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6039 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6040 SDValue Lane = Op.getOperand(2);
6041 if (!isa<ConstantSDNode>(Lane))
6047 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6048 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6049 SDValue Lane = Op.getOperand(1);
6050 if (!isa<ConstantSDNode>(Lane))
6053 SDValue Vec = Op.getOperand(0);
6054 if (Op.getValueType() == MVT::i32 &&
6055 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6057 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6063 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6064 // The only time a CONCAT_VECTORS operation can have legal types is when
6065 // two 64-bit vectors are concatenated to a 128-bit vector.
6066 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6067 "unexpected CONCAT_VECTORS");
6069 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6070 SDValue Op0 = Op.getOperand(0);
6071 SDValue Op1 = Op.getOperand(1);
6072 if (Op0.getOpcode() != ISD::UNDEF)
6073 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6074 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6075 DAG.getIntPtrConstant(0, dl));
6076 if (Op1.getOpcode() != ISD::UNDEF)
6077 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6078 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6079 DAG.getIntPtrConstant(1, dl));
6080 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6083 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6084 /// element has been zero/sign-extended, depending on the isSigned parameter,
6085 /// from an integer type half its size.
6086 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6088 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6089 EVT VT = N->getValueType(0);
6090 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6091 SDNode *BVN = N->getOperand(0).getNode();
6092 if (BVN->getValueType(0) != MVT::v4i32 ||
6093 BVN->getOpcode() != ISD::BUILD_VECTOR)
6095 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6096 unsigned HiElt = 1 - LoElt;
6097 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6098 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6099 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6100 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6101 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6104 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6105 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6108 if (Hi0->isNullValue() && Hi1->isNullValue())
6114 if (N->getOpcode() != ISD::BUILD_VECTOR)
6117 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6118 SDNode *Elt = N->getOperand(i).getNode();
6119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6120 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6121 unsigned HalfSize = EltSize / 2;
6123 if (!isIntN(HalfSize, C->getSExtValue()))
6126 if (!isUIntN(HalfSize, C->getZExtValue()))
6137 /// isSignExtended - Check if a node is a vector value that is sign-extended
6138 /// or a constant BUILD_VECTOR with sign-extended elements.
6139 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6140 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6142 if (isExtendedBUILD_VECTOR(N, DAG, true))
6147 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6148 /// or a constant BUILD_VECTOR with zero-extended elements.
6149 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6150 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6152 if (isExtendedBUILD_VECTOR(N, DAG, false))
6157 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6158 if (OrigVT.getSizeInBits() >= 64)
6161 assert(OrigVT.isSimple() && "Expecting a simple value type");
6163 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6164 switch (OrigSimpleTy) {
6165 default: llvm_unreachable("Unexpected Vector Type");
6174 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6175 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6176 /// We insert the required extension here to get the vector to fill a D register.
6177 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6180 unsigned ExtOpcode) {
6181 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6182 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6183 // 64-bits we need to insert a new extension so that it will be 64-bits.
6184 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6185 if (OrigTy.getSizeInBits() >= 64)
6188 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6189 EVT NewVT = getExtensionTo64Bits(OrigTy);
6191 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6194 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6195 /// does not do any sign/zero extension. If the original vector is less
6196 /// than 64 bits, an appropriate extension will be added after the load to
6197 /// reach a total size of 64 bits. We have to add the extension separately
6198 /// because ARM does not have a sign/zero extending load for vectors.
6199 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6200 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6202 // The load already has the right type.
6203 if (ExtendedTy == LD->getMemoryVT())
6204 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6205 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6206 LD->isNonTemporal(), LD->isInvariant(),
6207 LD->getAlignment());
6209 // We need to create a zextload/sextload. We cannot just create a load
6210 // followed by a zext/zext node because LowerMUL is also run during normal
6211 // operation legalization where we can't create illegal types.
6212 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6213 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6214 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6215 LD->isNonTemporal(), LD->getAlignment());
6218 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6219 /// extending load, or BUILD_VECTOR with extended elements, return the
6220 /// unextended value. The unextended vector should be 64 bits so that it can
6221 /// be used as an operand to a VMULL instruction. If the original vector size
6222 /// before extension is less than 64 bits we add a an extension to resize
6223 /// the vector to 64 bits.
6224 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6225 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6226 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6227 N->getOperand(0)->getValueType(0),
6231 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6232 return SkipLoadExtensionForVMULL(LD, DAG);
6234 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6235 // have been legalized as a BITCAST from v4i32.
6236 if (N->getOpcode() == ISD::BITCAST) {
6237 SDNode *BVN = N->getOperand(0).getNode();
6238 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6239 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6240 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6241 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6242 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6244 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6245 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6246 EVT VT = N->getValueType(0);
6247 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6248 unsigned NumElts = VT.getVectorNumElements();
6249 MVT TruncVT = MVT::getIntegerVT(EltSize);
6250 SmallVector<SDValue, 8> Ops;
6252 for (unsigned i = 0; i != NumElts; ++i) {
6253 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6254 const APInt &CInt = C->getAPIntValue();
6255 // Element types smaller than 32 bits are not legal, so use i32 elements.
6256 // The values are implicitly truncated so sext vs. zext doesn't matter.
6257 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6259 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6260 MVT::getVectorVT(TruncVT, NumElts), Ops);
6263 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6264 unsigned Opcode = N->getOpcode();
6265 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6266 SDNode *N0 = N->getOperand(0).getNode();
6267 SDNode *N1 = N->getOperand(1).getNode();
6268 return N0->hasOneUse() && N1->hasOneUse() &&
6269 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6274 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6275 unsigned Opcode = N->getOpcode();
6276 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6277 SDNode *N0 = N->getOperand(0).getNode();
6278 SDNode *N1 = N->getOperand(1).getNode();
6279 return N0->hasOneUse() && N1->hasOneUse() &&
6280 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6285 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6286 // Multiplications are only custom-lowered for 128-bit vectors so that
6287 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6288 EVT VT = Op.getValueType();
6289 assert(VT.is128BitVector() && VT.isInteger() &&
6290 "unexpected type for custom-lowering ISD::MUL");
6291 SDNode *N0 = Op.getOperand(0).getNode();
6292 SDNode *N1 = Op.getOperand(1).getNode();
6293 unsigned NewOpc = 0;
6295 bool isN0SExt = isSignExtended(N0, DAG);
6296 bool isN1SExt = isSignExtended(N1, DAG);
6297 if (isN0SExt && isN1SExt)
6298 NewOpc = ARMISD::VMULLs;
6300 bool isN0ZExt = isZeroExtended(N0, DAG);
6301 bool isN1ZExt = isZeroExtended(N1, DAG);
6302 if (isN0ZExt && isN1ZExt)
6303 NewOpc = ARMISD::VMULLu;
6304 else if (isN1SExt || isN1ZExt) {
6305 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6306 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6307 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6308 NewOpc = ARMISD::VMULLs;
6310 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6311 NewOpc = ARMISD::VMULLu;
6313 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6315 NewOpc = ARMISD::VMULLu;
6321 if (VT == MVT::v2i64)
6322 // Fall through to expand this. It is not legal.
6325 // Other vector multiplications are legal.
6330 // Legalize to a VMULL instruction.
6333 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6335 Op0 = SkipExtensionForVMULL(N0, DAG);
6336 assert(Op0.getValueType().is64BitVector() &&
6337 Op1.getValueType().is64BitVector() &&
6338 "unexpected types for extended operands to VMULL");
6339 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6342 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6343 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6350 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6351 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6352 EVT Op1VT = Op1.getValueType();
6353 return DAG.getNode(N0->getOpcode(), DL, VT,
6354 DAG.getNode(NewOpc, DL, VT,
6355 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6356 DAG.getNode(NewOpc, DL, VT,
6357 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6361 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6363 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6364 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6365 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6366 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6367 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6368 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6369 // Get reciprocal estimate.
6370 // float4 recip = vrecpeq_f32(yf);
6371 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6372 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6374 // Because char has a smaller range than uchar, we can actually get away
6375 // without any newton steps. This requires that we use a weird bias
6376 // of 0xb000, however (again, this has been exhaustively tested).
6377 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6378 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6379 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6380 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6381 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6382 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6383 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6384 // Convert back to short.
6385 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6386 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6391 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6393 // Convert to float.
6394 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6395 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6396 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6397 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6398 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6399 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6401 // Use reciprocal estimate and one refinement step.
6402 // float4 recip = vrecpeq_f32(yf);
6403 // recip *= vrecpsq_f32(yf, recip);
6404 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6405 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6407 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6408 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6410 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6411 // Because short has a smaller range than ushort, we can actually get away
6412 // with only a single newton step. This requires that we use a weird bias
6413 // of 89, however (again, this has been exhaustively tested).
6414 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6415 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6416 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6417 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6418 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6419 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6420 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6421 // Convert back to integer and return.
6422 // return vmovn_s32(vcvt_s32_f32(result));
6423 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6424 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6428 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6429 EVT VT = Op.getValueType();
6430 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6431 "unexpected type for custom-lowering ISD::SDIV");
6434 SDValue N0 = Op.getOperand(0);
6435 SDValue N1 = Op.getOperand(1);
6438 if (VT == MVT::v8i8) {
6439 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6440 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6442 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6443 DAG.getIntPtrConstant(4, dl));
6444 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6445 DAG.getIntPtrConstant(4, dl));
6446 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6447 DAG.getIntPtrConstant(0, dl));
6448 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6449 DAG.getIntPtrConstant(0, dl));
6451 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6452 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6454 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6455 N0 = LowerCONCAT_VECTORS(N0, DAG);
6457 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6460 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6463 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6464 EVT VT = Op.getValueType();
6465 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6466 "unexpected type for custom-lowering ISD::UDIV");
6469 SDValue N0 = Op.getOperand(0);
6470 SDValue N1 = Op.getOperand(1);
6473 if (VT == MVT::v8i8) {
6474 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6475 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6477 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6478 DAG.getIntPtrConstant(4, dl));
6479 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6480 DAG.getIntPtrConstant(4, dl));
6481 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6482 DAG.getIntPtrConstant(0, dl));
6483 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6484 DAG.getIntPtrConstant(0, dl));
6486 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6487 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6489 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6490 N0 = LowerCONCAT_VECTORS(N0, DAG);
6492 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6493 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6499 // v4i16 sdiv ... Convert to float.
6500 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6501 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6502 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6503 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6504 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6505 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6507 // Use reciprocal estimate and two refinement steps.
6508 // float4 recip = vrecpeq_f32(yf);
6509 // recip *= vrecpsq_f32(yf, recip);
6510 // recip *= vrecpsq_f32(yf, recip);
6511 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6512 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6514 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6515 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6517 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6518 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6519 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6521 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6522 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6523 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6524 // and that it will never cause us to return an answer too large).
6525 // float4 result = as_float4(as_int4(xf*recip) + 2);
6526 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6527 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6528 N1 = DAG.getConstant(2, dl, MVT::i32);
6529 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6530 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6531 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6532 // Convert back to integer and return.
6533 // return vmovn_u32(vcvt_s32_f32(result));
6534 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6535 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6539 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6540 EVT VT = Op.getNode()->getValueType(0);
6541 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6544 bool ExtraOp = false;
6545 switch (Op.getOpcode()) {
6546 default: llvm_unreachable("Invalid code");
6547 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6548 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6549 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6550 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6554 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6556 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6557 Op.getOperand(1), Op.getOperand(2));
6560 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6561 assert(Subtarget->isTargetDarwin());
6563 // For iOS, we want to call an alternative entry point: __sincos_stret,
6564 // return values are passed via sret.
6566 SDValue Arg = Op.getOperand(0);
6567 EVT ArgVT = Arg.getValueType();
6568 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6569 auto PtrVT = getPointerTy(DAG.getDataLayout());
6571 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6573 // Pair of floats / doubles used to pass the result.
6574 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6576 // Create stack object for sret.
6577 auto &DL = DAG.getDataLayout();
6578 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6579 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6580 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6581 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6587 Entry.Ty = RetTy->getPointerTo();
6588 Entry.isSExt = false;
6589 Entry.isZExt = false;
6590 Entry.isSRet = true;
6591 Args.push_back(Entry);
6595 Entry.isSExt = false;
6596 Entry.isZExt = false;
6597 Args.push_back(Entry);
6599 const char *LibcallName = (ArgVT == MVT::f64)
6600 ? "__sincos_stret" : "__sincosf_stret";
6601 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6603 TargetLowering::CallLoweringInfo CLI(DAG);
6604 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6605 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6607 .setDiscardResult();
6609 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6611 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6612 MachinePointerInfo(), false, false, false, 0);
6614 // Address of cos field.
6615 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6616 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6617 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6618 MachinePointerInfo(), false, false, false, 0);
6620 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6621 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6622 LoadSin.getValue(0), LoadCos.getValue(0));
6625 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6626 // Monotonic load/store is legal for all targets
6627 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6630 // Acquire/Release load/store is not legal for targets without a
6631 // dmb or equivalent available.
6635 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6636 SmallVectorImpl<SDValue> &Results,
6638 const ARMSubtarget *Subtarget) {
6640 SDValue Cycles32, OutChain;
6642 if (Subtarget->hasPerfMon()) {
6643 // Under Power Management extensions, the cycle-count is:
6644 // mrc p15, #0, <Rt>, c9, c13, #0
6645 SDValue Ops[] = { N->getOperand(0), // Chain
6646 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6647 DAG.getConstant(15, DL, MVT::i32),
6648 DAG.getConstant(0, DL, MVT::i32),
6649 DAG.getConstant(9, DL, MVT::i32),
6650 DAG.getConstant(13, DL, MVT::i32),
6651 DAG.getConstant(0, DL, MVT::i32)
6654 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6655 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6656 OutChain = Cycles32.getValue(1);
6658 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6659 // there are older ARM CPUs that have implementation-specific ways of
6660 // obtaining this information (FIXME!).
6661 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6662 OutChain = DAG.getEntryNode();
6666 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6667 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6668 Results.push_back(Cycles64);
6669 Results.push_back(OutChain);
6672 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6673 switch (Op.getOpcode()) {
6674 default: llvm_unreachable("Don't know how to custom lower this!");
6675 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6676 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6677 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6678 case ISD::GlobalAddress:
6679 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6680 default: llvm_unreachable("unknown object format");
6682 return LowerGlobalAddressWindows(Op, DAG);
6684 return LowerGlobalAddressELF(Op, DAG);
6686 return LowerGlobalAddressDarwin(Op, DAG);
6688 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6689 case ISD::SELECT: return LowerSELECT(Op, DAG);
6690 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6691 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6692 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6693 case ISD::VASTART: return LowerVASTART(Op, DAG);
6694 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6695 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6696 case ISD::SINT_TO_FP:
6697 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6698 case ISD::FP_TO_SINT:
6699 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6700 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6701 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6702 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6703 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6704 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6705 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6706 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6707 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6709 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6712 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6713 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6714 case ISD::SRL_PARTS:
6715 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6717 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6718 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6719 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6720 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6721 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6722 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6723 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6724 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6725 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6726 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6727 case ISD::MUL: return LowerMUL(Op, DAG);
6728 case ISD::SDIV: return LowerSDIV(Op, DAG);
6729 case ISD::UDIV: return LowerUDIV(Op, DAG);
6733 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6738 return LowerXALUO(Op, DAG);
6739 case ISD::ATOMIC_LOAD:
6740 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6741 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6743 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6744 case ISD::DYNAMIC_STACKALLOC:
6745 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6746 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6747 llvm_unreachable("Don't know how to custom lower this!");
6748 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6749 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6753 /// ReplaceNodeResults - Replace the results of node with an illegal result
6754 /// type with new values built out of custom code.
6755 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6756 SmallVectorImpl<SDValue>&Results,
6757 SelectionDAG &DAG) const {
6759 switch (N->getOpcode()) {
6761 llvm_unreachable("Don't know how to custom expand this!");
6762 case ISD::READ_REGISTER:
6763 ExpandREAD_REGISTER(N, Results, DAG);
6766 Res = ExpandBITCAST(N, DAG);
6770 Res = Expand64BitShift(N, DAG, Subtarget);
6772 case ISD::READCYCLECOUNTER:
6773 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6777 Results.push_back(Res);
6780 //===----------------------------------------------------------------------===//
6781 // ARM Scheduler Hooks
6782 //===----------------------------------------------------------------------===//
6784 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6785 /// registers the function context.
6786 void ARMTargetLowering::
6787 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6788 MachineBasicBlock *DispatchBB, int FI) const {
6789 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6790 DebugLoc dl = MI->getDebugLoc();
6791 MachineFunction *MF = MBB->getParent();
6792 MachineRegisterInfo *MRI = &MF->getRegInfo();
6793 MachineConstantPool *MCP = MF->getConstantPool();
6794 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6795 const Function *F = MF->getFunction();
6797 bool isThumb = Subtarget->isThumb();
6798 bool isThumb2 = Subtarget->isThumb2();
6800 unsigned PCLabelId = AFI->createPICLabelUId();
6801 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6802 ARMConstantPoolValue *CPV =
6803 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6804 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6806 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6807 : &ARM::GPRRegClass;
6809 // Grab constant pool and fixed stack memory operands.
6810 MachineMemOperand *CPMMO =
6811 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6812 MachineMemOperand::MOLoad, 4, 4);
6814 MachineMemOperand *FIMMOSt =
6815 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6816 MachineMemOperand::MOStore, 4, 4);
6818 // Load the address of the dispatch MBB into the jump buffer.
6820 // Incoming value: jbuf
6821 // ldr.n r5, LCPI1_1
6824 // str r5, [$jbuf, #+4] ; &jbuf[1]
6825 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6826 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6827 .addConstantPoolIndex(CPI)
6828 .addMemOperand(CPMMO));
6829 // Set the low bit because of thumb mode.
6830 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6832 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6833 .addReg(NewVReg1, RegState::Kill)
6835 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6836 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6837 .addReg(NewVReg2, RegState::Kill)
6839 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6840 .addReg(NewVReg3, RegState::Kill)
6842 .addImm(36) // &jbuf[1] :: pc
6843 .addMemOperand(FIMMOSt));
6844 } else if (isThumb) {
6845 // Incoming value: jbuf
6846 // ldr.n r1, LCPI1_4
6850 // add r2, $jbuf, #+4 ; &jbuf[1]
6852 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6853 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6854 .addConstantPoolIndex(CPI)
6855 .addMemOperand(CPMMO));
6856 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6857 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6858 .addReg(NewVReg1, RegState::Kill)
6860 // Set the low bit because of thumb mode.
6861 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6862 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6863 .addReg(ARM::CPSR, RegState::Define)
6865 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6866 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6867 .addReg(ARM::CPSR, RegState::Define)
6868 .addReg(NewVReg2, RegState::Kill)
6869 .addReg(NewVReg3, RegState::Kill));
6870 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6871 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6873 .addImm(36); // &jbuf[1] :: pc
6874 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6875 .addReg(NewVReg4, RegState::Kill)
6876 .addReg(NewVReg5, RegState::Kill)
6878 .addMemOperand(FIMMOSt));
6880 // Incoming value: jbuf
6883 // str r1, [$jbuf, #+4] ; &jbuf[1]
6884 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6885 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6886 .addConstantPoolIndex(CPI)
6888 .addMemOperand(CPMMO));
6889 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6890 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6891 .addReg(NewVReg1, RegState::Kill)
6892 .addImm(PCLabelId));
6893 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6894 .addReg(NewVReg2, RegState::Kill)
6896 .addImm(36) // &jbuf[1] :: pc
6897 .addMemOperand(FIMMOSt));
6901 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6902 MachineBasicBlock *MBB) const {
6903 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6904 DebugLoc dl = MI->getDebugLoc();
6905 MachineFunction *MF = MBB->getParent();
6906 MachineRegisterInfo *MRI = &MF->getRegInfo();
6907 MachineFrameInfo *MFI = MF->getFrameInfo();
6908 int FI = MFI->getFunctionContextIndex();
6910 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6911 : &ARM::GPRnopcRegClass;
6913 // Get a mapping of the call site numbers to all of the landing pads they're
6915 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6916 unsigned MaxCSNum = 0;
6917 MachineModuleInfo &MMI = MF->getMMI();
6918 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6920 if (!BB->isLandingPad()) continue;
6922 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6924 for (MachineBasicBlock::iterator
6925 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6926 if (!II->isEHLabel()) continue;
6928 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6929 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6931 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6932 for (SmallVectorImpl<unsigned>::iterator
6933 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6934 CSI != CSE; ++CSI) {
6935 CallSiteNumToLPad[*CSI].push_back(BB);
6936 MaxCSNum = std::max(MaxCSNum, *CSI);
6942 // Get an ordered list of the machine basic blocks for the jump table.
6943 std::vector<MachineBasicBlock*> LPadList;
6944 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6945 LPadList.reserve(CallSiteNumToLPad.size());
6946 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6947 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6948 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6949 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6950 LPadList.push_back(*II);
6951 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6955 assert(!LPadList.empty() &&
6956 "No landing pad destinations for the dispatch jump table!");
6958 // Create the jump table and associated information.
6959 MachineJumpTableInfo *JTI =
6960 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6961 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6962 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6964 // Create the MBBs for the dispatch code.
6966 // Shove the dispatch's address into the return slot in the function context.
6967 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6968 DispatchBB->setIsLandingPad();
6970 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6971 unsigned trap_opcode;
6972 if (Subtarget->isThumb())
6973 trap_opcode = ARM::tTRAP;
6975 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6977 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6978 DispatchBB->addSuccessor(TrapBB);
6980 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6981 DispatchBB->addSuccessor(DispContBB);
6984 MF->insert(MF->end(), DispatchBB);
6985 MF->insert(MF->end(), DispContBB);
6986 MF->insert(MF->end(), TrapBB);
6988 // Insert code into the entry block that creates and registers the function
6990 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6992 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
6993 MachinePointerInfo::getFixedStack(*MF, FI),
6994 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
6996 MachineInstrBuilder MIB;
6997 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6999 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7000 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7002 // Add a register mask with no preserved registers. This results in all
7003 // registers being marked as clobbered.
7004 MIB.addRegMask(RI.getNoPreservedMask());
7006 unsigned NumLPads = LPadList.size();
7007 if (Subtarget->isThumb2()) {
7008 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7009 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7012 .addMemOperand(FIMMOLd));
7014 if (NumLPads < 256) {
7015 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7017 .addImm(LPadList.size()));
7019 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7020 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7021 .addImm(NumLPads & 0xFFFF));
7023 unsigned VReg2 = VReg1;
7024 if ((NumLPads & 0xFFFF0000) != 0) {
7025 VReg2 = MRI->createVirtualRegister(TRC);
7026 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7028 .addImm(NumLPads >> 16));
7031 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7036 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7041 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7042 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7043 .addJumpTableIndex(MJTI));
7045 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7048 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7049 .addReg(NewVReg3, RegState::Kill)
7051 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7053 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7054 .addReg(NewVReg4, RegState::Kill)
7056 .addJumpTableIndex(MJTI);
7057 } else if (Subtarget->isThumb()) {
7058 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7059 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7062 .addMemOperand(FIMMOLd));
7064 if (NumLPads < 256) {
7065 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7069 MachineConstantPool *ConstantPool = MF->getConstantPool();
7070 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7071 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7073 // MachineConstantPool wants an explicit alignment.
7074 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7076 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7077 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7079 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7080 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7081 .addReg(VReg1, RegState::Define)
7082 .addConstantPoolIndex(Idx));
7083 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7088 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7093 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7094 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7095 .addReg(ARM::CPSR, RegState::Define)
7099 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7100 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7101 .addJumpTableIndex(MJTI));
7103 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7104 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7105 .addReg(ARM::CPSR, RegState::Define)
7106 .addReg(NewVReg2, RegState::Kill)
7109 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7110 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7112 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7113 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7114 .addReg(NewVReg4, RegState::Kill)
7116 .addMemOperand(JTMMOLd));
7118 unsigned NewVReg6 = NewVReg5;
7119 if (RelocM == Reloc::PIC_) {
7120 NewVReg6 = MRI->createVirtualRegister(TRC);
7121 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7122 .addReg(ARM::CPSR, RegState::Define)
7123 .addReg(NewVReg5, RegState::Kill)
7127 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7128 .addReg(NewVReg6, RegState::Kill)
7129 .addJumpTableIndex(MJTI);
7131 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7132 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7135 .addMemOperand(FIMMOLd));
7137 if (NumLPads < 256) {
7138 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7141 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7142 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7143 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7144 .addImm(NumLPads & 0xFFFF));
7146 unsigned VReg2 = VReg1;
7147 if ((NumLPads & 0xFFFF0000) != 0) {
7148 VReg2 = MRI->createVirtualRegister(TRC);
7149 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7151 .addImm(NumLPads >> 16));
7154 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7158 MachineConstantPool *ConstantPool = MF->getConstantPool();
7159 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7160 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7162 // MachineConstantPool wants an explicit alignment.
7163 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7165 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7166 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7168 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7169 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7170 .addReg(VReg1, RegState::Define)
7171 .addConstantPoolIndex(Idx)
7173 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7175 .addReg(VReg1, RegState::Kill));
7178 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7183 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7185 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7187 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7188 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7189 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7190 .addJumpTableIndex(MJTI));
7192 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7193 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7194 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7196 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7197 .addReg(NewVReg3, RegState::Kill)
7200 .addMemOperand(JTMMOLd));
7202 if (RelocM == Reloc::PIC_) {
7203 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7204 .addReg(NewVReg5, RegState::Kill)
7206 .addJumpTableIndex(MJTI);
7208 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7209 .addReg(NewVReg5, RegState::Kill)
7210 .addJumpTableIndex(MJTI);
7214 // Add the jump table entries as successors to the MBB.
7215 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7216 for (std::vector<MachineBasicBlock*>::iterator
7217 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7218 MachineBasicBlock *CurMBB = *I;
7219 if (SeenMBBs.insert(CurMBB).second)
7220 DispContBB->addSuccessor(CurMBB);
7223 // N.B. the order the invoke BBs are processed in doesn't matter here.
7224 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7225 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7226 for (MachineBasicBlock *BB : InvokeBBs) {
7228 // Remove the landing pad successor from the invoke block and replace it
7229 // with the new dispatch block.
7230 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7232 while (!Successors.empty()) {
7233 MachineBasicBlock *SMBB = Successors.pop_back_val();
7234 if (SMBB->isLandingPad()) {
7235 BB->removeSuccessor(SMBB);
7236 MBBLPads.push_back(SMBB);
7240 BB->addSuccessor(DispatchBB);
7242 // Find the invoke call and mark all of the callee-saved registers as
7243 // 'implicit defined' so that they're spilled. This prevents code from
7244 // moving instructions to before the EH block, where they will never be
7246 for (MachineBasicBlock::reverse_iterator
7247 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7248 if (!II->isCall()) continue;
7250 DenseMap<unsigned, bool> DefRegs;
7251 for (MachineInstr::mop_iterator
7252 OI = II->operands_begin(), OE = II->operands_end();
7254 if (!OI->isReg()) continue;
7255 DefRegs[OI->getReg()] = true;
7258 MachineInstrBuilder MIB(*MF, &*II);
7260 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7261 unsigned Reg = SavedRegs[i];
7262 if (Subtarget->isThumb2() &&
7263 !ARM::tGPRRegClass.contains(Reg) &&
7264 !ARM::hGPRRegClass.contains(Reg))
7266 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7268 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7271 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7278 // Mark all former landing pads as non-landing pads. The dispatch is the only
7280 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7281 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7282 (*I)->setIsLandingPad(false);
7284 // The instruction is gone now.
7285 MI->eraseFromParent();
7289 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7290 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7291 E = MBB->succ_end(); I != E; ++I)
7294 llvm_unreachable("Expecting a BB with two successors!");
7297 /// Return the load opcode for a given load size. If load size >= 8,
7298 /// neon opcode will be returned.
7299 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7301 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7302 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7304 return LdSize == 4 ? ARM::tLDRi
7305 : LdSize == 2 ? ARM::tLDRHi
7306 : LdSize == 1 ? ARM::tLDRBi : 0;
7308 return LdSize == 4 ? ARM::t2LDR_POST
7309 : LdSize == 2 ? ARM::t2LDRH_POST
7310 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7311 return LdSize == 4 ? ARM::LDR_POST_IMM
7312 : LdSize == 2 ? ARM::LDRH_POST
7313 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7316 /// Return the store opcode for a given store size. If store size >= 8,
7317 /// neon opcode will be returned.
7318 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7320 return StSize == 16 ? ARM::VST1q32wb_fixed
7321 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7323 return StSize == 4 ? ARM::tSTRi
7324 : StSize == 2 ? ARM::tSTRHi
7325 : StSize == 1 ? ARM::tSTRBi : 0;
7327 return StSize == 4 ? ARM::t2STR_POST
7328 : StSize == 2 ? ARM::t2STRH_POST
7329 : StSize == 1 ? ARM::t2STRB_POST : 0;
7330 return StSize == 4 ? ARM::STR_POST_IMM
7331 : StSize == 2 ? ARM::STRH_POST
7332 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7335 /// Emit a post-increment load operation with given size. The instructions
7336 /// will be added to BB at Pos.
7337 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7338 const TargetInstrInfo *TII, DebugLoc dl,
7339 unsigned LdSize, unsigned Data, unsigned AddrIn,
7340 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7341 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7342 assert(LdOpc != 0 && "Should have a load opcode");
7344 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7345 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7347 } else if (IsThumb1) {
7348 // load + update AddrIn
7349 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7350 .addReg(AddrIn).addImm(0));
7351 MachineInstrBuilder MIB =
7352 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7353 MIB = AddDefaultT1CC(MIB);
7354 MIB.addReg(AddrIn).addImm(LdSize);
7355 AddDefaultPred(MIB);
7356 } else if (IsThumb2) {
7357 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7358 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7361 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7362 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7363 .addReg(0).addImm(LdSize));
7367 /// Emit a post-increment store operation with given size. The instructions
7368 /// will be added to BB at Pos.
7369 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7370 const TargetInstrInfo *TII, DebugLoc dl,
7371 unsigned StSize, unsigned Data, unsigned AddrIn,
7372 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7373 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7374 assert(StOpc != 0 && "Should have a store opcode");
7376 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7377 .addReg(AddrIn).addImm(0).addReg(Data));
7378 } else if (IsThumb1) {
7379 // store + update AddrIn
7380 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7381 .addReg(AddrIn).addImm(0));
7382 MachineInstrBuilder MIB =
7383 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7384 MIB = AddDefaultT1CC(MIB);
7385 MIB.addReg(AddrIn).addImm(StSize);
7386 AddDefaultPred(MIB);
7387 } else if (IsThumb2) {
7388 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7389 .addReg(Data).addReg(AddrIn).addImm(StSize));
7391 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7392 .addReg(Data).addReg(AddrIn).addReg(0)
7398 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7399 MachineBasicBlock *BB) const {
7400 // This pseudo instruction has 3 operands: dst, src, size
7401 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7402 // Otherwise, we will generate unrolled scalar copies.
7403 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7404 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7405 MachineFunction::iterator It = BB;
7408 unsigned dest = MI->getOperand(0).getReg();
7409 unsigned src = MI->getOperand(1).getReg();
7410 unsigned SizeVal = MI->getOperand(2).getImm();
7411 unsigned Align = MI->getOperand(3).getImm();
7412 DebugLoc dl = MI->getDebugLoc();
7414 MachineFunction *MF = BB->getParent();
7415 MachineRegisterInfo &MRI = MF->getRegInfo();
7416 unsigned UnitSize = 0;
7417 const TargetRegisterClass *TRC = nullptr;
7418 const TargetRegisterClass *VecTRC = nullptr;
7420 bool IsThumb1 = Subtarget->isThumb1Only();
7421 bool IsThumb2 = Subtarget->isThumb2();
7425 } else if (Align & 2) {
7428 // Check whether we can use NEON instructions.
7429 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7430 Subtarget->hasNEON()) {
7431 if ((Align % 16 == 0) && SizeVal >= 16)
7433 else if ((Align % 8 == 0) && SizeVal >= 8)
7436 // Can't use NEON instructions.
7441 // Select the correct opcode and register class for unit size load/store
7442 bool IsNeon = UnitSize >= 8;
7443 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7445 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7446 : UnitSize == 8 ? &ARM::DPRRegClass
7449 unsigned BytesLeft = SizeVal % UnitSize;
7450 unsigned LoopSize = SizeVal - BytesLeft;
7452 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7453 // Use LDR and STR to copy.
7454 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7455 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7456 unsigned srcIn = src;
7457 unsigned destIn = dest;
7458 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7459 unsigned srcOut = MRI.createVirtualRegister(TRC);
7460 unsigned destOut = MRI.createVirtualRegister(TRC);
7461 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7462 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7463 IsThumb1, IsThumb2);
7464 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7465 IsThumb1, IsThumb2);
7470 // Handle the leftover bytes with LDRB and STRB.
7471 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7472 // [destOut] = STRB_POST(scratch, destIn, 1)
7473 for (unsigned i = 0; i < BytesLeft; i++) {
7474 unsigned srcOut = MRI.createVirtualRegister(TRC);
7475 unsigned destOut = MRI.createVirtualRegister(TRC);
7476 unsigned scratch = MRI.createVirtualRegister(TRC);
7477 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7478 IsThumb1, IsThumb2);
7479 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7480 IsThumb1, IsThumb2);
7484 MI->eraseFromParent(); // The instruction is gone now.
7488 // Expand the pseudo op to a loop.
7491 // movw varEnd, # --> with thumb2
7493 // ldrcp varEnd, idx --> without thumb2
7494 // fallthrough --> loopMBB
7496 // PHI varPhi, varEnd, varLoop
7497 // PHI srcPhi, src, srcLoop
7498 // PHI destPhi, dst, destLoop
7499 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7500 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7501 // subs varLoop, varPhi, #UnitSize
7503 // fallthrough --> exitMBB
7505 // epilogue to handle left-over bytes
7506 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7507 // [destOut] = STRB_POST(scratch, destLoop, 1)
7508 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7509 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7510 MF->insert(It, loopMBB);
7511 MF->insert(It, exitMBB);
7513 // Transfer the remainder of BB and its successor edges to exitMBB.
7514 exitMBB->splice(exitMBB->begin(), BB,
7515 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7516 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7518 // Load an immediate to varEnd.
7519 unsigned varEnd = MRI.createVirtualRegister(TRC);
7520 if (Subtarget->useMovt(*MF)) {
7521 unsigned Vtmp = varEnd;
7522 if ((LoopSize & 0xFFFF0000) != 0)
7523 Vtmp = MRI.createVirtualRegister(TRC);
7524 AddDefaultPred(BuildMI(BB, dl,
7525 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7526 Vtmp).addImm(LoopSize & 0xFFFF));
7528 if ((LoopSize & 0xFFFF0000) != 0)
7529 AddDefaultPred(BuildMI(BB, dl,
7530 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7533 .addImm(LoopSize >> 16));
7535 MachineConstantPool *ConstantPool = MF->getConstantPool();
7536 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7537 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7539 // MachineConstantPool wants an explicit alignment.
7540 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7542 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7543 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7546 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7547 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7549 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7550 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7552 BB->addSuccessor(loopMBB);
7554 // Generate the loop body:
7555 // varPhi = PHI(varLoop, varEnd)
7556 // srcPhi = PHI(srcLoop, src)
7557 // destPhi = PHI(destLoop, dst)
7558 MachineBasicBlock *entryBB = BB;
7560 unsigned varLoop = MRI.createVirtualRegister(TRC);
7561 unsigned varPhi = MRI.createVirtualRegister(TRC);
7562 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7563 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7564 unsigned destLoop = MRI.createVirtualRegister(TRC);
7565 unsigned destPhi = MRI.createVirtualRegister(TRC);
7567 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7568 .addReg(varLoop).addMBB(loopMBB)
7569 .addReg(varEnd).addMBB(entryBB);
7570 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7571 .addReg(srcLoop).addMBB(loopMBB)
7572 .addReg(src).addMBB(entryBB);
7573 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7574 .addReg(destLoop).addMBB(loopMBB)
7575 .addReg(dest).addMBB(entryBB);
7577 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7578 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7579 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7580 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7581 IsThumb1, IsThumb2);
7582 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7583 IsThumb1, IsThumb2);
7585 // Decrement loop variable by UnitSize.
7587 MachineInstrBuilder MIB =
7588 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7589 MIB = AddDefaultT1CC(MIB);
7590 MIB.addReg(varPhi).addImm(UnitSize);
7591 AddDefaultPred(MIB);
7593 MachineInstrBuilder MIB =
7594 BuildMI(*BB, BB->end(), dl,
7595 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7596 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7597 MIB->getOperand(5).setReg(ARM::CPSR);
7598 MIB->getOperand(5).setIsDef(true);
7600 BuildMI(*BB, BB->end(), dl,
7601 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7602 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7604 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7605 BB->addSuccessor(loopMBB);
7606 BB->addSuccessor(exitMBB);
7608 // Add epilogue to handle BytesLeft.
7610 MachineInstr *StartOfExit = exitMBB->begin();
7612 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7613 // [destOut] = STRB_POST(scratch, destLoop, 1)
7614 unsigned srcIn = srcLoop;
7615 unsigned destIn = destLoop;
7616 for (unsigned i = 0; i < BytesLeft; i++) {
7617 unsigned srcOut = MRI.createVirtualRegister(TRC);
7618 unsigned destOut = MRI.createVirtualRegister(TRC);
7619 unsigned scratch = MRI.createVirtualRegister(TRC);
7620 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7621 IsThumb1, IsThumb2);
7622 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7623 IsThumb1, IsThumb2);
7628 MI->eraseFromParent(); // The instruction is gone now.
7633 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7634 MachineBasicBlock *MBB) const {
7635 const TargetMachine &TM = getTargetMachine();
7636 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7637 DebugLoc DL = MI->getDebugLoc();
7639 assert(Subtarget->isTargetWindows() &&
7640 "__chkstk is only supported on Windows");
7641 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7643 // __chkstk takes the number of words to allocate on the stack in R4, and
7644 // returns the stack adjustment in number of bytes in R4. This will not
7645 // clober any other registers (other than the obvious lr).
7647 // Although, technically, IP should be considered a register which may be
7648 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7649 // thumb-2 environment, so there is no interworking required. As a result, we
7650 // do not expect a veneer to be emitted by the linker, clobbering IP.
7652 // Each module receives its own copy of __chkstk, so no import thunk is
7653 // required, again, ensuring that IP is not clobbered.
7655 // Finally, although some linkers may theoretically provide a trampoline for
7656 // out of range calls (which is quite common due to a 32M range limitation of
7657 // branches for Thumb), we can generate the long-call version via
7658 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7661 switch (TM.getCodeModel()) {
7662 case CodeModel::Small:
7663 case CodeModel::Medium:
7664 case CodeModel::Default:
7665 case CodeModel::Kernel:
7666 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7667 .addImm((unsigned)ARMCC::AL).addReg(0)
7668 .addExternalSymbol("__chkstk")
7669 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7670 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7671 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7673 case CodeModel::Large:
7674 case CodeModel::JITDefault: {
7675 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7676 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7678 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7679 .addExternalSymbol("__chkstk");
7680 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7681 .addImm((unsigned)ARMCC::AL).addReg(0)
7682 .addReg(Reg, RegState::Kill)
7683 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7684 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7685 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7690 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7692 .addReg(ARM::SP).addReg(ARM::R4)));
7694 MI->eraseFromParent();
7699 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7700 MachineBasicBlock *BB) const {
7701 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7702 DebugLoc dl = MI->getDebugLoc();
7703 bool isThumb2 = Subtarget->isThumb2();
7704 switch (MI->getOpcode()) {
7707 llvm_unreachable("Unexpected instr type to insert");
7709 // The Thumb2 pre-indexed stores have the same MI operands, they just
7710 // define them differently in the .td files from the isel patterns, so
7711 // they need pseudos.
7712 case ARM::t2STR_preidx:
7713 MI->setDesc(TII->get(ARM::t2STR_PRE));
7715 case ARM::t2STRB_preidx:
7716 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7718 case ARM::t2STRH_preidx:
7719 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7722 case ARM::STRi_preidx:
7723 case ARM::STRBi_preidx: {
7724 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7725 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7726 // Decode the offset.
7727 unsigned Offset = MI->getOperand(4).getImm();
7728 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7729 Offset = ARM_AM::getAM2Offset(Offset);
7733 MachineMemOperand *MMO = *MI->memoperands_begin();
7734 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7735 .addOperand(MI->getOperand(0)) // Rn_wb
7736 .addOperand(MI->getOperand(1)) // Rt
7737 .addOperand(MI->getOperand(2)) // Rn
7738 .addImm(Offset) // offset (skip GPR==zero_reg)
7739 .addOperand(MI->getOperand(5)) // pred
7740 .addOperand(MI->getOperand(6))
7741 .addMemOperand(MMO);
7742 MI->eraseFromParent();
7745 case ARM::STRr_preidx:
7746 case ARM::STRBr_preidx:
7747 case ARM::STRH_preidx: {
7749 switch (MI->getOpcode()) {
7750 default: llvm_unreachable("unexpected opcode!");
7751 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7752 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7753 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7755 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7756 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7757 MIB.addOperand(MI->getOperand(i));
7758 MI->eraseFromParent();
7762 case ARM::tMOVCCr_pseudo: {
7763 // To "insert" a SELECT_CC instruction, we actually have to insert the
7764 // diamond control-flow pattern. The incoming instruction knows the
7765 // destination vreg to set, the condition code register to branch on, the
7766 // true/false values to select between, and a branch opcode to use.
7767 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7768 MachineFunction::iterator It = BB;
7774 // cmpTY ccX, r1, r2
7776 // fallthrough --> copy0MBB
7777 MachineBasicBlock *thisMBB = BB;
7778 MachineFunction *F = BB->getParent();
7779 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7780 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7781 F->insert(It, copy0MBB);
7782 F->insert(It, sinkMBB);
7784 // Transfer the remainder of BB and its successor edges to sinkMBB.
7785 sinkMBB->splice(sinkMBB->begin(), BB,
7786 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7787 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7789 BB->addSuccessor(copy0MBB);
7790 BB->addSuccessor(sinkMBB);
7792 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7793 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7796 // %FalseValue = ...
7797 // # fallthrough to sinkMBB
7800 // Update machine-CFG edges
7801 BB->addSuccessor(sinkMBB);
7804 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7807 BuildMI(*BB, BB->begin(), dl,
7808 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7809 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7810 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7812 MI->eraseFromParent(); // The pseudo instruction is gone now.
7817 case ARM::BCCZi64: {
7818 // If there is an unconditional branch to the other successor, remove it.
7819 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7821 // Compare both parts that make up the double comparison separately for
7823 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7825 unsigned LHS1 = MI->getOperand(1).getReg();
7826 unsigned LHS2 = MI->getOperand(2).getReg();
7828 AddDefaultPred(BuildMI(BB, dl,
7829 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7830 .addReg(LHS1).addImm(0));
7831 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7832 .addReg(LHS2).addImm(0)
7833 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7835 unsigned RHS1 = MI->getOperand(3).getReg();
7836 unsigned RHS2 = MI->getOperand(4).getReg();
7837 AddDefaultPred(BuildMI(BB, dl,
7838 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7839 .addReg(LHS1).addReg(RHS1));
7840 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7841 .addReg(LHS2).addReg(RHS2)
7842 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7845 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7846 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7847 if (MI->getOperand(0).getImm() == ARMCC::NE)
7848 std::swap(destMBB, exitMBB);
7850 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7851 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7853 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7855 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7857 MI->eraseFromParent(); // The pseudo instruction is gone now.
7861 case ARM::Int_eh_sjlj_setjmp:
7862 case ARM::Int_eh_sjlj_setjmp_nofp:
7863 case ARM::tInt_eh_sjlj_setjmp:
7864 case ARM::t2Int_eh_sjlj_setjmp:
7865 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7868 case ARM::Int_eh_sjlj_setup_dispatch:
7869 EmitSjLjDispatchBlock(MI, BB);
7874 // To insert an ABS instruction, we have to insert the
7875 // diamond control-flow pattern. The incoming instruction knows the
7876 // source vreg to test against 0, the destination vreg to set,
7877 // the condition code register to branch on, the
7878 // true/false values to select between, and a branch opcode to use.
7883 // BCC (branch to SinkBB if V0 >= 0)
7884 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7885 // SinkBB: V1 = PHI(V2, V3)
7886 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7887 MachineFunction::iterator BBI = BB;
7889 MachineFunction *Fn = BB->getParent();
7890 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7891 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7892 Fn->insert(BBI, RSBBB);
7893 Fn->insert(BBI, SinkBB);
7895 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7896 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7897 bool ABSSrcKIll = MI->getOperand(1).isKill();
7898 bool isThumb2 = Subtarget->isThumb2();
7899 MachineRegisterInfo &MRI = Fn->getRegInfo();
7900 // In Thumb mode S must not be specified if source register is the SP or
7901 // PC and if destination register is the SP, so restrict register class
7902 unsigned NewRsbDstReg =
7903 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7905 // Transfer the remainder of BB and its successor edges to sinkMBB.
7906 SinkBB->splice(SinkBB->begin(), BB,
7907 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7908 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7910 BB->addSuccessor(RSBBB);
7911 BB->addSuccessor(SinkBB);
7913 // fall through to SinkMBB
7914 RSBBB->addSuccessor(SinkBB);
7916 // insert a cmp at the end of BB
7917 AddDefaultPred(BuildMI(BB, dl,
7918 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7919 .addReg(ABSSrcReg).addImm(0));
7921 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7923 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7924 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7926 // insert rsbri in RSBBB
7927 // Note: BCC and rsbri will be converted into predicated rsbmi
7928 // by if-conversion pass
7929 BuildMI(*RSBBB, RSBBB->begin(), dl,
7930 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7931 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7932 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7934 // insert PHI in SinkBB,
7935 // reuse ABSDstReg to not change uses of ABS instruction
7936 BuildMI(*SinkBB, SinkBB->begin(), dl,
7937 TII->get(ARM::PHI), ABSDstReg)
7938 .addReg(NewRsbDstReg).addMBB(RSBBB)
7939 .addReg(ABSSrcReg).addMBB(BB);
7941 // remove ABS instruction
7942 MI->eraseFromParent();
7944 // return last added BB
7947 case ARM::COPY_STRUCT_BYVAL_I32:
7949 return EmitStructByval(MI, BB);
7950 case ARM::WIN__CHKSTK:
7951 return EmitLowered__chkstk(MI, BB);
7955 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7956 SDNode *Node) const {
7957 const MCInstrDesc *MCID = &MI->getDesc();
7958 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7959 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7960 // operand is still set to noreg. If needed, set the optional operand's
7961 // register to CPSR, and remove the redundant implicit def.
7963 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7965 // Rename pseudo opcodes.
7966 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7968 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7969 MCID = &TII->get(NewOpc);
7971 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7972 "converted opcode should be the same except for cc_out");
7976 // Add the optional cc_out operand
7977 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7979 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7981 // Any ARM instruction that sets the 's' bit should specify an optional
7982 // "cc_out" operand in the last operand position.
7983 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7984 assert(!NewOpc && "Optional cc_out operand required");
7987 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7988 // since we already have an optional CPSR def.
7989 bool definesCPSR = false;
7990 bool deadCPSR = false;
7991 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7993 const MachineOperand &MO = MI->getOperand(i);
7994 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7998 MI->RemoveOperand(i);
8003 assert(!NewOpc && "Optional cc_out operand required");
8006 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8008 assert(!MI->getOperand(ccOutIdx).getReg() &&
8009 "expect uninitialized optional cc_out operand");
8013 // If this instruction was defined with an optional CPSR def and its dag node
8014 // had a live implicit CPSR def, then activate the optional CPSR def.
8015 MachineOperand &MO = MI->getOperand(ccOutIdx);
8016 MO.setReg(ARM::CPSR);
8020 //===----------------------------------------------------------------------===//
8021 // ARM Optimization Hooks
8022 //===----------------------------------------------------------------------===//
8024 // Helper function that checks if N is a null or all ones constant.
8025 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8026 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8029 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8032 // Return true if N is conditionally 0 or all ones.
8033 // Detects these expressions where cc is an i1 value:
8035 // (select cc 0, y) [AllOnes=0]
8036 // (select cc y, 0) [AllOnes=0]
8037 // (zext cc) [AllOnes=0]
8038 // (sext cc) [AllOnes=0/1]
8039 // (select cc -1, y) [AllOnes=1]
8040 // (select cc y, -1) [AllOnes=1]
8042 // Invert is set when N is the null/all ones constant when CC is false.
8043 // OtherOp is set to the alternative value of N.
8044 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8045 SDValue &CC, bool &Invert,
8047 SelectionDAG &DAG) {
8048 switch (N->getOpcode()) {
8049 default: return false;
8051 CC = N->getOperand(0);
8052 SDValue N1 = N->getOperand(1);
8053 SDValue N2 = N->getOperand(2);
8054 if (isZeroOrAllOnes(N1, AllOnes)) {
8059 if (isZeroOrAllOnes(N2, AllOnes)) {
8066 case ISD::ZERO_EXTEND:
8067 // (zext cc) can never be the all ones value.
8071 case ISD::SIGN_EXTEND: {
8073 EVT VT = N->getValueType(0);
8074 CC = N->getOperand(0);
8075 if (CC.getValueType() != MVT::i1)
8079 // When looking for an AllOnes constant, N is an sext, and the 'other'
8081 OtherOp = DAG.getConstant(0, dl, VT);
8082 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8083 // When looking for a 0 constant, N can be zext or sext.
8084 OtherOp = DAG.getConstant(1, dl, VT);
8086 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8093 // Combine a constant select operand into its use:
8095 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8096 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8097 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8098 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8099 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8101 // The transform is rejected if the select doesn't have a constant operand that
8102 // is null, or all ones when AllOnes is set.
8104 // Also recognize sext/zext from i1:
8106 // (add (zext cc), x) -> (select cc (add x, 1), x)
8107 // (add (sext cc), x) -> (select cc (add x, -1), x)
8109 // These transformations eventually create predicated instructions.
8111 // @param N The node to transform.
8112 // @param Slct The N operand that is a select.
8113 // @param OtherOp The other N operand (x above).
8114 // @param DCI Context.
8115 // @param AllOnes Require the select constant to be all ones instead of null.
8116 // @returns The new node, or SDValue() on failure.
8118 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8119 TargetLowering::DAGCombinerInfo &DCI,
8120 bool AllOnes = false) {
8121 SelectionDAG &DAG = DCI.DAG;
8122 EVT VT = N->getValueType(0);
8123 SDValue NonConstantVal;
8126 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8127 NonConstantVal, DAG))
8130 // Slct is now know to be the desired identity constant when CC is true.
8131 SDValue TrueVal = OtherOp;
8132 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8133 OtherOp, NonConstantVal);
8134 // Unless SwapSelectOps says CC should be false.
8136 std::swap(TrueVal, FalseVal);
8138 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8139 CCOp, TrueVal, FalseVal);
8142 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8144 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8145 TargetLowering::DAGCombinerInfo &DCI) {
8146 SDValue N0 = N->getOperand(0);
8147 SDValue N1 = N->getOperand(1);
8148 if (N0.getNode()->hasOneUse()) {
8149 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8150 if (Result.getNode())
8153 if (N1.getNode()->hasOneUse()) {
8154 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8155 if (Result.getNode())
8161 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8162 // (only after legalization).
8163 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8164 TargetLowering::DAGCombinerInfo &DCI,
8165 const ARMSubtarget *Subtarget) {
8167 // Only perform optimization if after legalize, and if NEON is available. We
8168 // also expected both operands to be BUILD_VECTORs.
8169 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8170 || N0.getOpcode() != ISD::BUILD_VECTOR
8171 || N1.getOpcode() != ISD::BUILD_VECTOR)
8174 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8175 EVT VT = N->getValueType(0);
8176 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8179 // Check that the vector operands are of the right form.
8180 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8181 // operands, where N is the size of the formed vector.
8182 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8183 // index such that we have a pair wise add pattern.
8185 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8186 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8188 SDValue Vec = N0->getOperand(0)->getOperand(0);
8189 SDNode *V = Vec.getNode();
8190 unsigned nextIndex = 0;
8192 // For each operands to the ADD which are BUILD_VECTORs,
8193 // check to see if each of their operands are an EXTRACT_VECTOR with
8194 // the same vector and appropriate index.
8195 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8196 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8197 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8199 SDValue ExtVec0 = N0->getOperand(i);
8200 SDValue ExtVec1 = N1->getOperand(i);
8202 // First operand is the vector, verify its the same.
8203 if (V != ExtVec0->getOperand(0).getNode() ||
8204 V != ExtVec1->getOperand(0).getNode())
8207 // Second is the constant, verify its correct.
8208 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8209 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8211 // For the constant, we want to see all the even or all the odd.
8212 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8213 || C1->getZExtValue() != nextIndex+1)
8222 // Create VPADDL node.
8223 SelectionDAG &DAG = DCI.DAG;
8224 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8228 // Build operand list.
8229 SmallVector<SDValue, 8> Ops;
8230 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8231 TLI.getPointerTy(DAG.getDataLayout())));
8233 // Input is the vector.
8236 // Get widened type and narrowed type.
8238 unsigned numElem = VT.getVectorNumElements();
8240 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8241 switch (inputLaneType.getSimpleVT().SimpleTy) {
8242 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8243 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8244 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8246 llvm_unreachable("Invalid vector element type for padd optimization.");
8249 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8250 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8251 return DAG.getNode(ExtOp, dl, VT, tmp);
8254 static SDValue findMUL_LOHI(SDValue V) {
8255 if (V->getOpcode() == ISD::UMUL_LOHI ||
8256 V->getOpcode() == ISD::SMUL_LOHI)
8261 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8262 TargetLowering::DAGCombinerInfo &DCI,
8263 const ARMSubtarget *Subtarget) {
8265 if (Subtarget->isThumb1Only()) return SDValue();
8267 // Only perform the checks after legalize when the pattern is available.
8268 if (DCI.isBeforeLegalize()) return SDValue();
8270 // Look for multiply add opportunities.
8271 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8272 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8273 // a glue link from the first add to the second add.
8274 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8275 // a S/UMLAL instruction.
8278 // / \ [no multiline comment]
8284 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8285 SDValue AddcOp0 = AddcNode->getOperand(0);
8286 SDValue AddcOp1 = AddcNode->getOperand(1);
8288 // Check if the two operands are from the same mul_lohi node.
8289 if (AddcOp0.getNode() == AddcOp1.getNode())
8292 assert(AddcNode->getNumValues() == 2 &&
8293 AddcNode->getValueType(0) == MVT::i32 &&
8294 "Expect ADDC with two result values. First: i32");
8296 // Check that we have a glued ADDC node.
8297 if (AddcNode->getValueType(1) != MVT::Glue)
8300 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8301 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8302 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8303 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8304 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8307 // Look for the glued ADDE.
8308 SDNode* AddeNode = AddcNode->getGluedUser();
8312 // Make sure it is really an ADDE.
8313 if (AddeNode->getOpcode() != ISD::ADDE)
8316 assert(AddeNode->getNumOperands() == 3 &&
8317 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8318 "ADDE node has the wrong inputs");
8320 // Check for the triangle shape.
8321 SDValue AddeOp0 = AddeNode->getOperand(0);
8322 SDValue AddeOp1 = AddeNode->getOperand(1);
8324 // Make sure that the ADDE operands are not coming from the same node.
8325 if (AddeOp0.getNode() == AddeOp1.getNode())
8328 // Find the MUL_LOHI node walking up ADDE's operands.
8329 bool IsLeftOperandMUL = false;
8330 SDValue MULOp = findMUL_LOHI(AddeOp0);
8331 if (MULOp == SDValue())
8332 MULOp = findMUL_LOHI(AddeOp1);
8334 IsLeftOperandMUL = true;
8335 if (MULOp == SDValue())
8338 // Figure out the right opcode.
8339 unsigned Opc = MULOp->getOpcode();
8340 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8342 // Figure out the high and low input values to the MLAL node.
8343 SDValue* HiAdd = nullptr;
8344 SDValue* LoMul = nullptr;
8345 SDValue* LowAdd = nullptr;
8347 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8348 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8351 if (IsLeftOperandMUL)
8357 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8358 // whose low result is fed to the ADDC we are checking.
8360 if (AddcOp0 == MULOp.getValue(0)) {
8364 if (AddcOp1 == MULOp.getValue(0)) {
8372 // Create the merged node.
8373 SelectionDAG &DAG = DCI.DAG;
8375 // Build operand list.
8376 SmallVector<SDValue, 8> Ops;
8377 Ops.push_back(LoMul->getOperand(0));
8378 Ops.push_back(LoMul->getOperand(1));
8379 Ops.push_back(*LowAdd);
8380 Ops.push_back(*HiAdd);
8382 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8383 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8385 // Replace the ADDs' nodes uses by the MLA node's values.
8386 SDValue HiMLALResult(MLALNode.getNode(), 1);
8387 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8389 SDValue LoMLALResult(MLALNode.getNode(), 0);
8390 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8392 // Return original node to notify the driver to stop replacing.
8393 SDValue resNode(AddcNode, 0);
8397 /// PerformADDCCombine - Target-specific dag combine transform from
8398 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8399 static SDValue PerformADDCCombine(SDNode *N,
8400 TargetLowering::DAGCombinerInfo &DCI,
8401 const ARMSubtarget *Subtarget) {
8403 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8407 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8408 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8409 /// called with the default operands, and if that fails, with commuted
8411 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8412 TargetLowering::DAGCombinerInfo &DCI,
8413 const ARMSubtarget *Subtarget){
8415 // Attempt to create vpaddl for this add.
8416 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8417 if (Result.getNode())
8420 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8421 if (N0.getNode()->hasOneUse()) {
8422 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8423 if (Result.getNode()) return Result;
8428 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8430 static SDValue PerformADDCombine(SDNode *N,
8431 TargetLowering::DAGCombinerInfo &DCI,
8432 const ARMSubtarget *Subtarget) {
8433 SDValue N0 = N->getOperand(0);
8434 SDValue N1 = N->getOperand(1);
8436 // First try with the default operand order.
8437 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8438 if (Result.getNode())
8441 // If that didn't work, try again with the operands commuted.
8442 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8445 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8447 static SDValue PerformSUBCombine(SDNode *N,
8448 TargetLowering::DAGCombinerInfo &DCI) {
8449 SDValue N0 = N->getOperand(0);
8450 SDValue N1 = N->getOperand(1);
8452 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8453 if (N1.getNode()->hasOneUse()) {
8454 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8455 if (Result.getNode()) return Result;
8461 /// PerformVMULCombine
8462 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8463 /// special multiplier accumulator forwarding.
8469 // However, for (A + B) * (A + B),
8476 static SDValue PerformVMULCombine(SDNode *N,
8477 TargetLowering::DAGCombinerInfo &DCI,
8478 const ARMSubtarget *Subtarget) {
8479 if (!Subtarget->hasVMLxForwarding())
8482 SelectionDAG &DAG = DCI.DAG;
8483 SDValue N0 = N->getOperand(0);
8484 SDValue N1 = N->getOperand(1);
8485 unsigned Opcode = N0.getOpcode();
8486 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8487 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8488 Opcode = N1.getOpcode();
8489 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8490 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8498 EVT VT = N->getValueType(0);
8500 SDValue N00 = N0->getOperand(0);
8501 SDValue N01 = N0->getOperand(1);
8502 return DAG.getNode(Opcode, DL, VT,
8503 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8504 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8507 static SDValue PerformMULCombine(SDNode *N,
8508 TargetLowering::DAGCombinerInfo &DCI,
8509 const ARMSubtarget *Subtarget) {
8510 SelectionDAG &DAG = DCI.DAG;
8512 if (Subtarget->isThumb1Only())
8515 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8518 EVT VT = N->getValueType(0);
8519 if (VT.is64BitVector() || VT.is128BitVector())
8520 return PerformVMULCombine(N, DCI, Subtarget);
8524 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8528 int64_t MulAmt = C->getSExtValue();
8529 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8531 ShiftAmt = ShiftAmt & (32 - 1);
8532 SDValue V = N->getOperand(0);
8536 MulAmt >>= ShiftAmt;
8539 if (isPowerOf2_32(MulAmt - 1)) {
8540 // (mul x, 2^N + 1) => (add (shl x, N), x)
8541 Res = DAG.getNode(ISD::ADD, DL, VT,
8543 DAG.getNode(ISD::SHL, DL, VT,
8545 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8547 } else if (isPowerOf2_32(MulAmt + 1)) {
8548 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8549 Res = DAG.getNode(ISD::SUB, DL, VT,
8550 DAG.getNode(ISD::SHL, DL, VT,
8552 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8558 uint64_t MulAmtAbs = -MulAmt;
8559 if (isPowerOf2_32(MulAmtAbs + 1)) {
8560 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8561 Res = DAG.getNode(ISD::SUB, DL, VT,
8563 DAG.getNode(ISD::SHL, DL, VT,
8565 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8567 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8568 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8569 Res = DAG.getNode(ISD::ADD, DL, VT,
8571 DAG.getNode(ISD::SHL, DL, VT,
8573 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8575 Res = DAG.getNode(ISD::SUB, DL, VT,
8576 DAG.getConstant(0, DL, MVT::i32), Res);
8583 Res = DAG.getNode(ISD::SHL, DL, VT,
8584 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8586 // Do not add new nodes to DAG combiner worklist.
8587 DCI.CombineTo(N, Res, false);
8591 static SDValue PerformANDCombine(SDNode *N,
8592 TargetLowering::DAGCombinerInfo &DCI,
8593 const ARMSubtarget *Subtarget) {
8595 // Attempt to use immediate-form VBIC
8596 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8598 EVT VT = N->getValueType(0);
8599 SelectionDAG &DAG = DCI.DAG;
8601 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8604 APInt SplatBits, SplatUndef;
8605 unsigned SplatBitSize;
8608 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8609 if (SplatBitSize <= 64) {
8611 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8612 SplatUndef.getZExtValue(), SplatBitSize,
8613 DAG, dl, VbicVT, VT.is128BitVector(),
8615 if (Val.getNode()) {
8617 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8618 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8619 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8624 if (!Subtarget->isThumb1Only()) {
8625 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8626 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8627 if (Result.getNode())
8634 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8635 static SDValue PerformORCombine(SDNode *N,
8636 TargetLowering::DAGCombinerInfo &DCI,
8637 const ARMSubtarget *Subtarget) {
8638 // Attempt to use immediate-form VORR
8639 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8641 EVT VT = N->getValueType(0);
8642 SelectionDAG &DAG = DCI.DAG;
8644 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8647 APInt SplatBits, SplatUndef;
8648 unsigned SplatBitSize;
8650 if (BVN && Subtarget->hasNEON() &&
8651 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8652 if (SplatBitSize <= 64) {
8654 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8655 SplatUndef.getZExtValue(), SplatBitSize,
8656 DAG, dl, VorrVT, VT.is128BitVector(),
8658 if (Val.getNode()) {
8660 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8661 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8662 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8667 if (!Subtarget->isThumb1Only()) {
8668 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8669 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8670 if (Result.getNode())
8674 // The code below optimizes (or (and X, Y), Z).
8675 // The AND operand needs to have a single user to make these optimizations
8677 SDValue N0 = N->getOperand(0);
8678 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8680 SDValue N1 = N->getOperand(1);
8682 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8683 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8684 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8686 unsigned SplatBitSize;
8689 APInt SplatBits0, SplatBits1;
8690 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8691 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8692 // Ensure that the second operand of both ands are constants
8693 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8694 HasAnyUndefs) && !HasAnyUndefs) {
8695 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8696 HasAnyUndefs) && !HasAnyUndefs) {
8697 // Ensure that the bit width of the constants are the same and that
8698 // the splat arguments are logical inverses as per the pattern we
8699 // are trying to simplify.
8700 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8701 SplatBits0 == ~SplatBits1) {
8702 // Canonicalize the vector type to make instruction selection
8704 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8705 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8709 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8715 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8718 // BFI is only available on V6T2+
8719 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8723 // 1) or (and A, mask), val => ARMbfi A, val, mask
8724 // iff (val & mask) == val
8726 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8727 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8728 // && mask == ~mask2
8729 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8730 // && ~mask == mask2
8731 // (i.e., copy a bitfield value into another bitfield of the same width)
8736 SDValue N00 = N0.getOperand(0);
8738 // The value and the mask need to be constants so we can verify this is
8739 // actually a bitfield set. If the mask is 0xffff, we can do better
8740 // via a movt instruction, so don't use BFI in that case.
8741 SDValue MaskOp = N0.getOperand(1);
8742 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8745 unsigned Mask = MaskC->getZExtValue();
8749 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8750 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8752 unsigned Val = N1C->getZExtValue();
8753 if ((Val & ~Mask) != Val)
8756 if (ARM::isBitFieldInvertedMask(Mask)) {
8757 Val >>= countTrailingZeros(~Mask);
8759 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8760 DAG.getConstant(Val, DL, MVT::i32),
8761 DAG.getConstant(Mask, DL, MVT::i32));
8763 // Do not add new nodes to DAG combiner worklist.
8764 DCI.CombineTo(N, Res, false);
8767 } else if (N1.getOpcode() == ISD::AND) {
8768 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8769 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8772 unsigned Mask2 = N11C->getZExtValue();
8774 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8776 if (ARM::isBitFieldInvertedMask(Mask) &&
8778 // The pack halfword instruction works better for masks that fit it,
8779 // so use that when it's available.
8780 if (Subtarget->hasT2ExtractPack() &&
8781 (Mask == 0xffff || Mask == 0xffff0000))
8784 unsigned amt = countTrailingZeros(Mask2);
8785 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8786 DAG.getConstant(amt, DL, MVT::i32));
8787 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8788 DAG.getConstant(Mask, DL, MVT::i32));
8789 // Do not add new nodes to DAG combiner worklist.
8790 DCI.CombineTo(N, Res, false);
8792 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8794 // The pack halfword instruction works better for masks that fit it,
8795 // so use that when it's available.
8796 if (Subtarget->hasT2ExtractPack() &&
8797 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8800 unsigned lsb = countTrailingZeros(Mask);
8801 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8802 DAG.getConstant(lsb, DL, MVT::i32));
8803 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8804 DAG.getConstant(Mask2, DL, MVT::i32));
8805 // Do not add new nodes to DAG combiner worklist.
8806 DCI.CombineTo(N, Res, false);
8811 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8812 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8813 ARM::isBitFieldInvertedMask(~Mask)) {
8814 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8815 // where lsb(mask) == #shamt and masked bits of B are known zero.
8816 SDValue ShAmt = N00.getOperand(1);
8817 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8818 unsigned LSB = countTrailingZeros(Mask);
8822 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8823 DAG.getConstant(~Mask, DL, MVT::i32));
8825 // Do not add new nodes to DAG combiner worklist.
8826 DCI.CombineTo(N, Res, false);
8832 static SDValue PerformXORCombine(SDNode *N,
8833 TargetLowering::DAGCombinerInfo &DCI,
8834 const ARMSubtarget *Subtarget) {
8835 EVT VT = N->getValueType(0);
8836 SelectionDAG &DAG = DCI.DAG;
8838 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8841 if (!Subtarget->isThumb1Only()) {
8842 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8843 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8844 if (Result.getNode())
8851 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8852 /// the bits being cleared by the AND are not demanded by the BFI.
8853 static SDValue PerformBFICombine(SDNode *N,
8854 TargetLowering::DAGCombinerInfo &DCI) {
8855 SDValue N1 = N->getOperand(1);
8856 if (N1.getOpcode() == ISD::AND) {
8857 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8860 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8861 unsigned LSB = countTrailingZeros(~InvMask);
8862 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8864 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8865 "undefined behavior");
8866 unsigned Mask = (1u << Width) - 1;
8867 unsigned Mask2 = N11C->getZExtValue();
8868 if ((Mask & (~Mask2)) == 0)
8869 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8870 N->getOperand(0), N1.getOperand(0),
8876 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8877 /// ARMISD::VMOVRRD.
8878 static SDValue PerformVMOVRRDCombine(SDNode *N,
8879 TargetLowering::DAGCombinerInfo &DCI,
8880 const ARMSubtarget *Subtarget) {
8881 // vmovrrd(vmovdrr x, y) -> x,y
8882 SDValue InDouble = N->getOperand(0);
8883 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8884 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8886 // vmovrrd(load f64) -> (load i32), (load i32)
8887 SDNode *InNode = InDouble.getNode();
8888 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8889 InNode->getValueType(0) == MVT::f64 &&
8890 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8891 !cast<LoadSDNode>(InNode)->isVolatile()) {
8892 // TODO: Should this be done for non-FrameIndex operands?
8893 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8895 SelectionDAG &DAG = DCI.DAG;
8897 SDValue BasePtr = LD->getBasePtr();
8898 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8899 LD->getPointerInfo(), LD->isVolatile(),
8900 LD->isNonTemporal(), LD->isInvariant(),
8901 LD->getAlignment());
8903 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8904 DAG.getConstant(4, DL, MVT::i32));
8905 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8906 LD->getPointerInfo(), LD->isVolatile(),
8907 LD->isNonTemporal(), LD->isInvariant(),
8908 std::min(4U, LD->getAlignment() / 2));
8910 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8911 if (DCI.DAG.getDataLayout().isBigEndian())
8912 std::swap (NewLD1, NewLD2);
8913 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8920 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8921 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8922 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8923 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8924 SDValue Op0 = N->getOperand(0);
8925 SDValue Op1 = N->getOperand(1);
8926 if (Op0.getOpcode() == ISD::BITCAST)
8927 Op0 = Op0.getOperand(0);
8928 if (Op1.getOpcode() == ISD::BITCAST)
8929 Op1 = Op1.getOperand(0);
8930 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8931 Op0.getNode() == Op1.getNode() &&
8932 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8933 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8934 N->getValueType(0), Op0.getOperand(0));
8938 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8939 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8940 /// i64 vector to have f64 elements, since the value can then be loaded
8941 /// directly into a VFP register.
8942 static bool hasNormalLoadOperand(SDNode *N) {
8943 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8944 for (unsigned i = 0; i < NumElts; ++i) {
8945 SDNode *Elt = N->getOperand(i).getNode();
8946 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8952 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8953 /// ISD::BUILD_VECTOR.
8954 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8955 TargetLowering::DAGCombinerInfo &DCI,
8956 const ARMSubtarget *Subtarget) {
8957 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8958 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8959 // into a pair of GPRs, which is fine when the value is used as a scalar,
8960 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8961 SelectionDAG &DAG = DCI.DAG;
8962 if (N->getNumOperands() == 2) {
8963 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8968 // Load i64 elements as f64 values so that type legalization does not split
8969 // them up into i32 values.
8970 EVT VT = N->getValueType(0);
8971 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8974 SmallVector<SDValue, 8> Ops;
8975 unsigned NumElts = VT.getVectorNumElements();
8976 for (unsigned i = 0; i < NumElts; ++i) {
8977 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8979 // Make the DAGCombiner fold the bitcast.
8980 DCI.AddToWorklist(V.getNode());
8982 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8983 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8984 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8987 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8989 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8990 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8991 // At that time, we may have inserted bitcasts from integer to float.
8992 // If these bitcasts have survived DAGCombine, change the lowering of this
8993 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8994 // force to use floating point types.
8996 // Make sure we can change the type of the vector.
8997 // This is possible iff:
8998 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8999 // 1.1. Vector is used only once.
9000 // 1.2. Use is a bit convert to an integer type.
9001 // 2. The size of its operands are 32-bits (64-bits are not legal).
9002 EVT VT = N->getValueType(0);
9003 EVT EltVT = VT.getVectorElementType();
9005 // Check 1.1. and 2.
9006 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9009 // By construction, the input type must be float.
9010 assert(EltVT == MVT::f32 && "Unexpected type!");
9013 SDNode *Use = *N->use_begin();
9014 if (Use->getOpcode() != ISD::BITCAST ||
9015 Use->getValueType(0).isFloatingPoint())
9018 // Check profitability.
9019 // Model is, if more than half of the relevant operands are bitcast from
9020 // i32, turn the build_vector into a sequence of insert_vector_elt.
9021 // Relevant operands are everything that is not statically
9022 // (i.e., at compile time) bitcasted.
9023 unsigned NumOfBitCastedElts = 0;
9024 unsigned NumElts = VT.getVectorNumElements();
9025 unsigned NumOfRelevantElts = NumElts;
9026 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9027 SDValue Elt = N->getOperand(Idx);
9028 if (Elt->getOpcode() == ISD::BITCAST) {
9029 // Assume only bit cast to i32 will go away.
9030 if (Elt->getOperand(0).getValueType() == MVT::i32)
9031 ++NumOfBitCastedElts;
9032 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9033 // Constants are statically casted, thus do not count them as
9034 // relevant operands.
9035 --NumOfRelevantElts;
9038 // Check if more than half of the elements require a non-free bitcast.
9039 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9042 SelectionDAG &DAG = DCI.DAG;
9043 // Create the new vector type.
9044 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9045 // Check if the type is legal.
9046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9047 if (!TLI.isTypeLegal(VecVT))
9051 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9052 // => BITCAST INSERT_VECTOR_ELT
9053 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9055 SDValue Vec = DAG.getUNDEF(VecVT);
9057 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9058 SDValue V = N->getOperand(Idx);
9059 if (V.getOpcode() == ISD::UNDEF)
9061 if (V.getOpcode() == ISD::BITCAST &&
9062 V->getOperand(0).getValueType() == MVT::i32)
9063 // Fold obvious case.
9064 V = V.getOperand(0);
9066 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9067 // Make the DAGCombiner fold the bitcasts.
9068 DCI.AddToWorklist(V.getNode());
9070 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9071 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9073 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9074 // Make the DAGCombiner fold the bitcasts.
9075 DCI.AddToWorklist(Vec.getNode());
9079 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9080 /// ISD::INSERT_VECTOR_ELT.
9081 static SDValue PerformInsertEltCombine(SDNode *N,
9082 TargetLowering::DAGCombinerInfo &DCI) {
9083 // Bitcast an i64 load inserted into a vector to f64.
9084 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9085 EVT VT = N->getValueType(0);
9086 SDNode *Elt = N->getOperand(1).getNode();
9087 if (VT.getVectorElementType() != MVT::i64 ||
9088 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9091 SelectionDAG &DAG = DCI.DAG;
9093 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9094 VT.getVectorNumElements());
9095 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9096 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9097 // Make the DAGCombiner fold the bitcasts.
9098 DCI.AddToWorklist(Vec.getNode());
9099 DCI.AddToWorklist(V.getNode());
9100 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9101 Vec, V, N->getOperand(2));
9102 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9105 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9106 /// ISD::VECTOR_SHUFFLE.
9107 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9108 // The LLVM shufflevector instruction does not require the shuffle mask
9109 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9110 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9111 // operands do not match the mask length, they are extended by concatenating
9112 // them with undef vectors. That is probably the right thing for other
9113 // targets, but for NEON it is better to concatenate two double-register
9114 // size vector operands into a single quad-register size vector. Do that
9115 // transformation here:
9116 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9117 // shuffle(concat(v1, v2), undef)
9118 SDValue Op0 = N->getOperand(0);
9119 SDValue Op1 = N->getOperand(1);
9120 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9121 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9122 Op0.getNumOperands() != 2 ||
9123 Op1.getNumOperands() != 2)
9125 SDValue Concat0Op1 = Op0.getOperand(1);
9126 SDValue Concat1Op1 = Op1.getOperand(1);
9127 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9128 Concat1Op1.getOpcode() != ISD::UNDEF)
9130 // Skip the transformation if any of the types are illegal.
9131 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9132 EVT VT = N->getValueType(0);
9133 if (!TLI.isTypeLegal(VT) ||
9134 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9135 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9138 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9139 Op0.getOperand(0), Op1.getOperand(0));
9140 // Translate the shuffle mask.
9141 SmallVector<int, 16> NewMask;
9142 unsigned NumElts = VT.getVectorNumElements();
9143 unsigned HalfElts = NumElts/2;
9144 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9145 for (unsigned n = 0; n < NumElts; ++n) {
9146 int MaskElt = SVN->getMaskElt(n);
9148 if (MaskElt < (int)HalfElts)
9150 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9151 NewElt = HalfElts + MaskElt - NumElts;
9152 NewMask.push_back(NewElt);
9154 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9155 DAG.getUNDEF(VT), NewMask.data());
9158 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9159 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9160 /// base address updates.
9161 /// For generic load/stores, the memory type is assumed to be a vector.
9162 /// The caller is assumed to have checked legality.
9163 static SDValue CombineBaseUpdate(SDNode *N,
9164 TargetLowering::DAGCombinerInfo &DCI) {
9165 SelectionDAG &DAG = DCI.DAG;
9166 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9167 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9168 const bool isStore = N->getOpcode() == ISD::STORE;
9169 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9170 SDValue Addr = N->getOperand(AddrOpIdx);
9171 MemSDNode *MemN = cast<MemSDNode>(N);
9174 // Search for a use of the address operand that is an increment.
9175 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9176 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9178 if (User->getOpcode() != ISD::ADD ||
9179 UI.getUse().getResNo() != Addr.getResNo())
9182 // Check that the add is independent of the load/store. Otherwise, folding
9183 // it would create a cycle.
9184 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9187 // Find the new opcode for the updating load/store.
9188 bool isLoadOp = true;
9189 bool isLaneOp = false;
9190 unsigned NewOpc = 0;
9191 unsigned NumVecs = 0;
9193 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9195 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9196 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9198 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9200 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9202 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9204 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9205 NumVecs = 2; isLaneOp = true; break;
9206 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9207 NumVecs = 3; isLaneOp = true; break;
9208 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9209 NumVecs = 4; isLaneOp = true; break;
9210 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9211 NumVecs = 1; isLoadOp = false; break;
9212 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9213 NumVecs = 2; isLoadOp = false; break;
9214 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9215 NumVecs = 3; isLoadOp = false; break;
9216 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9217 NumVecs = 4; isLoadOp = false; break;
9218 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9219 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9220 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9221 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9222 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9223 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9227 switch (N->getOpcode()) {
9228 default: llvm_unreachable("unexpected opcode for Neon base update");
9229 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9230 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9231 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9232 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9233 NumVecs = 1; isLaneOp = false; break;
9234 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9235 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9239 // Find the size of memory referenced by the load/store.
9242 VecTy = N->getValueType(0);
9243 } else if (isIntrinsic) {
9244 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9246 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9247 VecTy = N->getOperand(1).getValueType();
9250 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9252 NumBytes /= VecTy.getVectorNumElements();
9254 // If the increment is a constant, it must match the memory ref size.
9255 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9256 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9257 uint64_t IncVal = CInc->getZExtValue();
9258 if (IncVal != NumBytes)
9260 } else if (NumBytes >= 3 * 16) {
9261 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9262 // separate instructions that make it harder to use a non-constant update.
9266 // OK, we found an ADD we can fold into the base update.
9267 // Now, create a _UPD node, taking care of not breaking alignment.
9269 EVT AlignedVecTy = VecTy;
9270 unsigned Alignment = MemN->getAlignment();
9272 // If this is a less-than-standard-aligned load/store, change the type to
9273 // match the standard alignment.
9274 // The alignment is overlooked when selecting _UPD variants; and it's
9275 // easier to introduce bitcasts here than fix that.
9276 // There are 3 ways to get to this base-update combine:
9277 // - intrinsics: they are assumed to be properly aligned (to the standard
9278 // alignment of the memory type), so we don't need to do anything.
9279 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9280 // intrinsics, so, likewise, there's nothing to do.
9281 // - generic load/store instructions: the alignment is specified as an
9282 // explicit operand, rather than implicitly as the standard alignment
9283 // of the memory type (like the intrisics). We need to change the
9284 // memory type to match the explicit alignment. That way, we don't
9285 // generate non-standard-aligned ARMISD::VLDx nodes.
9286 if (isa<LSBaseSDNode>(N)) {
9289 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9290 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9291 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9292 assert(!isLaneOp && "Unexpected generic load/store lane.");
9293 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9294 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9296 // Don't set an explicit alignment on regular load/stores that we want
9297 // to transform to VLD/VST 1_UPD nodes.
9298 // This matches the behavior of regular load/stores, which only get an
9299 // explicit alignment if the MMO alignment is larger than the standard
9300 // alignment of the memory type.
9301 // Intrinsics, however, always get an explicit alignment, set to the
9302 // alignment of the MMO.
9306 // Create the new updating load/store node.
9307 // First, create an SDVTList for the new updating node's results.
9309 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9311 for (n = 0; n < NumResultVecs; ++n)
9312 Tys[n] = AlignedVecTy;
9313 Tys[n++] = MVT::i32;
9314 Tys[n] = MVT::Other;
9315 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9317 // Then, gather the new node's operands.
9318 SmallVector<SDValue, 8> Ops;
9319 Ops.push_back(N->getOperand(0)); // incoming chain
9320 Ops.push_back(N->getOperand(AddrOpIdx));
9323 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9324 // Try to match the intrinsic's signature
9325 Ops.push_back(StN->getValue());
9327 // Loads (and of course intrinsics) match the intrinsics' signature,
9328 // so just add all but the alignment operand.
9329 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9330 Ops.push_back(N->getOperand(i));
9333 // For all node types, the alignment operand is always the last one.
9334 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9336 // If this is a non-standard-aligned STORE, the penultimate operand is the
9337 // stored value. Bitcast it to the aligned type.
9338 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9339 SDValue &StVal = Ops[Ops.size()-2];
9340 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9343 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9345 MemN->getMemOperand());
9348 SmallVector<SDValue, 5> NewResults;
9349 for (unsigned i = 0; i < NumResultVecs; ++i)
9350 NewResults.push_back(SDValue(UpdN.getNode(), i));
9352 // If this is an non-standard-aligned LOAD, the first result is the loaded
9353 // value. Bitcast it to the expected result type.
9354 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9355 SDValue &LdVal = NewResults[0];
9356 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9359 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9360 DCI.CombineTo(N, NewResults);
9361 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9368 static SDValue PerformVLDCombine(SDNode *N,
9369 TargetLowering::DAGCombinerInfo &DCI) {
9370 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9373 return CombineBaseUpdate(N, DCI);
9376 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9377 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9378 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9380 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9381 SelectionDAG &DAG = DCI.DAG;
9382 EVT VT = N->getValueType(0);
9383 // vldN-dup instructions only support 64-bit vectors for N > 1.
9384 if (!VT.is64BitVector())
9387 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9388 SDNode *VLD = N->getOperand(0).getNode();
9389 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9391 unsigned NumVecs = 0;
9392 unsigned NewOpc = 0;
9393 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9394 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9396 NewOpc = ARMISD::VLD2DUP;
9397 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9399 NewOpc = ARMISD::VLD3DUP;
9400 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9402 NewOpc = ARMISD::VLD4DUP;
9407 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9408 // numbers match the load.
9409 unsigned VLDLaneNo =
9410 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9411 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9413 // Ignore uses of the chain result.
9414 if (UI.getUse().getResNo() == NumVecs)
9417 if (User->getOpcode() != ARMISD::VDUPLANE ||
9418 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9422 // Create the vldN-dup node.
9425 for (n = 0; n < NumVecs; ++n)
9427 Tys[n] = MVT::Other;
9428 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9429 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9430 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9431 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9432 Ops, VLDMemInt->getMemoryVT(),
9433 VLDMemInt->getMemOperand());
9436 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9438 unsigned ResNo = UI.getUse().getResNo();
9439 // Ignore uses of the chain result.
9440 if (ResNo == NumVecs)
9443 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9446 // Now the vldN-lane intrinsic is dead except for its chain result.
9447 // Update uses of the chain.
9448 std::vector<SDValue> VLDDupResults;
9449 for (unsigned n = 0; n < NumVecs; ++n)
9450 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9451 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9452 DCI.CombineTo(VLD, VLDDupResults);
9457 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9458 /// ARMISD::VDUPLANE.
9459 static SDValue PerformVDUPLANECombine(SDNode *N,
9460 TargetLowering::DAGCombinerInfo &DCI) {
9461 SDValue Op = N->getOperand(0);
9463 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9464 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9465 if (CombineVLDDUP(N, DCI))
9466 return SDValue(N, 0);
9468 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9469 // redundant. Ignore bit_converts for now; element sizes are checked below.
9470 while (Op.getOpcode() == ISD::BITCAST)
9471 Op = Op.getOperand(0);
9472 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9475 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9476 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9477 // The canonical VMOV for a zero vector uses a 32-bit element size.
9478 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9480 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9482 EVT VT = N->getValueType(0);
9483 if (EltSize > VT.getVectorElementType().getSizeInBits())
9486 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9489 static SDValue PerformLOADCombine(SDNode *N,
9490 TargetLowering::DAGCombinerInfo &DCI) {
9491 EVT VT = N->getValueType(0);
9493 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9494 if (ISD::isNormalLoad(N) && VT.isVector() &&
9495 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9496 return CombineBaseUpdate(N, DCI);
9501 /// PerformSTORECombine - Target-specific dag combine xforms for
9503 static SDValue PerformSTORECombine(SDNode *N,
9504 TargetLowering::DAGCombinerInfo &DCI) {
9505 StoreSDNode *St = cast<StoreSDNode>(N);
9506 if (St->isVolatile())
9509 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9510 // pack all of the elements in one place. Next, store to memory in fewer
9512 SDValue StVal = St->getValue();
9513 EVT VT = StVal.getValueType();
9514 if (St->isTruncatingStore() && VT.isVector()) {
9515 SelectionDAG &DAG = DCI.DAG;
9516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9517 EVT StVT = St->getMemoryVT();
9518 unsigned NumElems = VT.getVectorNumElements();
9519 assert(StVT != VT && "Cannot truncate to the same type");
9520 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9521 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9523 // From, To sizes and ElemCount must be pow of two
9524 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9526 // We are going to use the original vector elt for storing.
9527 // Accumulated smaller vector elements must be a multiple of the store size.
9528 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9530 unsigned SizeRatio = FromEltSz / ToEltSz;
9531 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9533 // Create a type on which we perform the shuffle.
9534 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9535 NumElems*SizeRatio);
9536 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9539 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9540 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9541 for (unsigned i = 0; i < NumElems; ++i)
9542 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9543 ? (i + 1) * SizeRatio - 1
9546 // Can't shuffle using an illegal type.
9547 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9549 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9550 DAG.getUNDEF(WideVec.getValueType()),
9552 // At this point all of the data is stored at the bottom of the
9553 // register. We now need to save it to mem.
9555 // Find the largest store unit
9556 MVT StoreType = MVT::i8;
9557 for (MVT Tp : MVT::integer_valuetypes()) {
9558 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9561 // Didn't find a legal store type.
9562 if (!TLI.isTypeLegal(StoreType))
9565 // Bitcast the original vector into a vector of store-size units
9566 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9567 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9568 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9569 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9570 SmallVector<SDValue, 8> Chains;
9571 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9572 TLI.getPointerTy(DAG.getDataLayout()));
9573 SDValue BasePtr = St->getBasePtr();
9575 // Perform one or more big stores into memory.
9576 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9577 for (unsigned I = 0; I < E; I++) {
9578 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9579 StoreType, ShuffWide,
9580 DAG.getIntPtrConstant(I, DL));
9581 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9582 St->getPointerInfo(), St->isVolatile(),
9583 St->isNonTemporal(), St->getAlignment());
9584 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9586 Chains.push_back(Ch);
9588 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9591 if (!ISD::isNormalStore(St))
9594 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9595 // ARM stores of arguments in the same cache line.
9596 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9597 StVal.getNode()->hasOneUse()) {
9598 SelectionDAG &DAG = DCI.DAG;
9599 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9601 SDValue BasePtr = St->getBasePtr();
9602 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9603 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9604 BasePtr, St->getPointerInfo(), St->isVolatile(),
9605 St->isNonTemporal(), St->getAlignment());
9607 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9608 DAG.getConstant(4, DL, MVT::i32));
9609 return DAG.getStore(NewST1.getValue(0), DL,
9610 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9611 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9612 St->isNonTemporal(),
9613 std::min(4U, St->getAlignment() / 2));
9616 if (StVal.getValueType() == MVT::i64 &&
9617 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9619 // Bitcast an i64 store extracted from a vector to f64.
9620 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9621 SelectionDAG &DAG = DCI.DAG;
9623 SDValue IntVec = StVal.getOperand(0);
9624 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9625 IntVec.getValueType().getVectorNumElements());
9626 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9627 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9628 Vec, StVal.getOperand(1));
9630 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9631 // Make the DAGCombiner fold the bitcasts.
9632 DCI.AddToWorklist(Vec.getNode());
9633 DCI.AddToWorklist(ExtElt.getNode());
9634 DCI.AddToWorklist(V.getNode());
9635 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9636 St->getPointerInfo(), St->isVolatile(),
9637 St->isNonTemporal(), St->getAlignment(),
9641 // If this is a legal vector store, try to combine it into a VST1_UPD.
9642 if (ISD::isNormalStore(N) && VT.isVector() &&
9643 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9644 return CombineBaseUpdate(N, DCI);
9649 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9650 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9651 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9655 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9657 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9662 APFloat APF = C->getValueAPF();
9663 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9664 != APFloat::opOK || !isExact)
9667 c0 = (I == 0) ? cN : c0;
9668 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9675 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9676 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9677 /// when the VMUL has a constant operand that is a power of 2.
9679 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9680 /// vmul.f32 d16, d17, d16
9681 /// vcvt.s32.f32 d16, d16
9683 /// vcvt.s32.f32 d16, d16, #3
9684 static SDValue PerformVCVTCombine(SDNode *N,
9685 TargetLowering::DAGCombinerInfo &DCI,
9686 const ARMSubtarget *Subtarget) {
9687 SelectionDAG &DAG = DCI.DAG;
9688 SDValue Op = N->getOperand(0);
9690 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9691 Op.getOpcode() != ISD::FMUL)
9695 SDValue N0 = Op->getOperand(0);
9696 SDValue ConstVec = Op->getOperand(1);
9697 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9699 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9700 !isConstVecPow2(ConstVec, isSigned, C))
9703 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9704 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9705 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9706 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9708 // These instructions only exist converting from f32 to i32. We can handle
9709 // smaller integers by generating an extra truncate, but larger ones would
9710 // be lossy. We also can't handle more then 4 lanes, since these intructions
9711 // only support v2i32/v4i32 types.
9716 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9717 Intrinsic::arm_neon_vcvtfp2fxu;
9718 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9719 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9720 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9722 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9724 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9725 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9730 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9731 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9732 /// when the VDIV has a constant operand that is a power of 2.
9734 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9735 /// vcvt.f32.s32 d16, d16
9736 /// vdiv.f32 d16, d17, d16
9738 /// vcvt.f32.s32 d16, d16, #3
9739 static SDValue PerformVDIVCombine(SDNode *N,
9740 TargetLowering::DAGCombinerInfo &DCI,
9741 const ARMSubtarget *Subtarget) {
9742 SelectionDAG &DAG = DCI.DAG;
9743 SDValue Op = N->getOperand(0);
9744 unsigned OpOpcode = Op.getNode()->getOpcode();
9746 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9747 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9751 SDValue ConstVec = N->getOperand(1);
9752 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9754 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9755 !isConstVecPow2(ConstVec, isSigned, C))
9758 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9759 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9760 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9761 // These instructions only exist converting from i32 to f32. We can handle
9762 // smaller integers by generating an extra extend, but larger ones would
9768 SDValue ConvInput = Op.getOperand(0);
9769 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9770 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9771 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9772 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9775 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9776 Intrinsic::arm_neon_vcvtfxu2fp;
9777 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9779 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9780 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9783 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9784 /// operand of a vector shift operation, where all the elements of the
9785 /// build_vector must have the same constant integer value.
9786 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9787 // Ignore bit_converts.
9788 while (Op.getOpcode() == ISD::BITCAST)
9789 Op = Op.getOperand(0);
9790 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9791 APInt SplatBits, SplatUndef;
9792 unsigned SplatBitSize;
9794 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9795 HasAnyUndefs, ElementBits) ||
9796 SplatBitSize > ElementBits)
9798 Cnt = SplatBits.getSExtValue();
9802 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9803 /// operand of a vector shift left operation. That value must be in the range:
9804 /// 0 <= Value < ElementBits for a left shift; or
9805 /// 0 <= Value <= ElementBits for a long left shift.
9806 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9807 assert(VT.isVector() && "vector shift count is not a vector type");
9808 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9809 if (! getVShiftImm(Op, ElementBits, Cnt))
9811 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9814 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9815 /// operand of a vector shift right operation. For a shift opcode, the value
9816 /// is positive, but for an intrinsic the value count must be negative. The
9817 /// absolute value must be in the range:
9818 /// 1 <= |Value| <= ElementBits for a right shift; or
9819 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9820 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9822 assert(VT.isVector() && "vector shift count is not a vector type");
9823 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9824 if (! getVShiftImm(Op, ElementBits, Cnt))
9827 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9828 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9835 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9836 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9837 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9840 // Don't do anything for most intrinsics.
9843 case Intrinsic::arm_neon_vabds:
9844 if (!N->getValueType(0).isInteger())
9846 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9847 N->getOperand(1), N->getOperand(2));
9848 case Intrinsic::arm_neon_vabdu:
9849 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9850 N->getOperand(1), N->getOperand(2));
9852 // Vector shifts: check for immediate versions and lower them.
9853 // Note: This is done during DAG combining instead of DAG legalizing because
9854 // the build_vectors for 64-bit vector element shift counts are generally
9855 // not legal, and it is hard to see their values after they get legalized to
9856 // loads from a constant pool.
9857 case Intrinsic::arm_neon_vshifts:
9858 case Intrinsic::arm_neon_vshiftu:
9859 case Intrinsic::arm_neon_vrshifts:
9860 case Intrinsic::arm_neon_vrshiftu:
9861 case Intrinsic::arm_neon_vrshiftn:
9862 case Intrinsic::arm_neon_vqshifts:
9863 case Intrinsic::arm_neon_vqshiftu:
9864 case Intrinsic::arm_neon_vqshiftsu:
9865 case Intrinsic::arm_neon_vqshiftns:
9866 case Intrinsic::arm_neon_vqshiftnu:
9867 case Intrinsic::arm_neon_vqshiftnsu:
9868 case Intrinsic::arm_neon_vqrshiftns:
9869 case Intrinsic::arm_neon_vqrshiftnu:
9870 case Intrinsic::arm_neon_vqrshiftnsu: {
9871 EVT VT = N->getOperand(1).getValueType();
9873 unsigned VShiftOpc = 0;
9876 case Intrinsic::arm_neon_vshifts:
9877 case Intrinsic::arm_neon_vshiftu:
9878 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9879 VShiftOpc = ARMISD::VSHL;
9882 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9883 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9884 ARMISD::VSHRs : ARMISD::VSHRu);
9889 case Intrinsic::arm_neon_vrshifts:
9890 case Intrinsic::arm_neon_vrshiftu:
9891 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9895 case Intrinsic::arm_neon_vqshifts:
9896 case Intrinsic::arm_neon_vqshiftu:
9897 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9901 case Intrinsic::arm_neon_vqshiftsu:
9902 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9904 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9906 case Intrinsic::arm_neon_vrshiftn:
9907 case Intrinsic::arm_neon_vqshiftns:
9908 case Intrinsic::arm_neon_vqshiftnu:
9909 case Intrinsic::arm_neon_vqshiftnsu:
9910 case Intrinsic::arm_neon_vqrshiftns:
9911 case Intrinsic::arm_neon_vqrshiftnu:
9912 case Intrinsic::arm_neon_vqrshiftnsu:
9913 // Narrowing shifts require an immediate right shift.
9914 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9916 llvm_unreachable("invalid shift count for narrowing vector shift "
9920 llvm_unreachable("unhandled vector shift");
9924 case Intrinsic::arm_neon_vshifts:
9925 case Intrinsic::arm_neon_vshiftu:
9926 // Opcode already set above.
9928 case Intrinsic::arm_neon_vrshifts:
9929 VShiftOpc = ARMISD::VRSHRs; break;
9930 case Intrinsic::arm_neon_vrshiftu:
9931 VShiftOpc = ARMISD::VRSHRu; break;
9932 case Intrinsic::arm_neon_vrshiftn:
9933 VShiftOpc = ARMISD::VRSHRN; break;
9934 case Intrinsic::arm_neon_vqshifts:
9935 VShiftOpc = ARMISD::VQSHLs; break;
9936 case Intrinsic::arm_neon_vqshiftu:
9937 VShiftOpc = ARMISD::VQSHLu; break;
9938 case Intrinsic::arm_neon_vqshiftsu:
9939 VShiftOpc = ARMISD::VQSHLsu; break;
9940 case Intrinsic::arm_neon_vqshiftns:
9941 VShiftOpc = ARMISD::VQSHRNs; break;
9942 case Intrinsic::arm_neon_vqshiftnu:
9943 VShiftOpc = ARMISD::VQSHRNu; break;
9944 case Intrinsic::arm_neon_vqshiftnsu:
9945 VShiftOpc = ARMISD::VQSHRNsu; break;
9946 case Intrinsic::arm_neon_vqrshiftns:
9947 VShiftOpc = ARMISD::VQRSHRNs; break;
9948 case Intrinsic::arm_neon_vqrshiftnu:
9949 VShiftOpc = ARMISD::VQRSHRNu; break;
9950 case Intrinsic::arm_neon_vqrshiftnsu:
9951 VShiftOpc = ARMISD::VQRSHRNsu; break;
9955 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9956 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9959 case Intrinsic::arm_neon_vshiftins: {
9960 EVT VT = N->getOperand(1).getValueType();
9962 unsigned VShiftOpc = 0;
9964 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9965 VShiftOpc = ARMISD::VSLI;
9966 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9967 VShiftOpc = ARMISD::VSRI;
9969 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9973 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9974 N->getOperand(1), N->getOperand(2),
9975 DAG.getConstant(Cnt, dl, MVT::i32));
9978 case Intrinsic::arm_neon_vqrshifts:
9979 case Intrinsic::arm_neon_vqrshiftu:
9980 // No immediate versions of these to check for.
9987 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9988 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9989 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9990 /// vector element shift counts are generally not legal, and it is hard to see
9991 /// their values after they get legalized to loads from a constant pool.
9992 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9993 const ARMSubtarget *ST) {
9994 EVT VT = N->getValueType(0);
9995 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9996 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9997 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9998 SDValue N1 = N->getOperand(1);
9999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10000 SDValue N0 = N->getOperand(0);
10001 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10002 DAG.MaskedValueIsZero(N0.getOperand(0),
10003 APInt::getHighBitsSet(32, 16)))
10004 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10008 // Nothing to be done for scalar shifts.
10009 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10010 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10013 assert(ST->hasNEON() && "unexpected vector shift");
10016 switch (N->getOpcode()) {
10017 default: llvm_unreachable("unexpected shift opcode");
10020 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10022 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10023 DAG.getConstant(Cnt, dl, MVT::i32));
10029 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10030 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10031 ARMISD::VSHRs : ARMISD::VSHRu);
10033 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10034 DAG.getConstant(Cnt, dl, MVT::i32));
10040 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10041 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10042 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10043 const ARMSubtarget *ST) {
10044 SDValue N0 = N->getOperand(0);
10046 // Check for sign- and zero-extensions of vector extract operations of 8-
10047 // and 16-bit vector elements. NEON supports these directly. They are
10048 // handled during DAG combining because type legalization will promote them
10049 // to 32-bit types and it is messy to recognize the operations after that.
10050 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10051 SDValue Vec = N0.getOperand(0);
10052 SDValue Lane = N0.getOperand(1);
10053 EVT VT = N->getValueType(0);
10054 EVT EltVT = N0.getValueType();
10055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10057 if (VT == MVT::i32 &&
10058 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10059 TLI.isTypeLegal(Vec.getValueType()) &&
10060 isa<ConstantSDNode>(Lane)) {
10063 switch (N->getOpcode()) {
10064 default: llvm_unreachable("unexpected opcode");
10065 case ISD::SIGN_EXTEND:
10066 Opc = ARMISD::VGETLANEs;
10068 case ISD::ZERO_EXTEND:
10069 case ISD::ANY_EXTEND:
10070 Opc = ARMISD::VGETLANEu;
10073 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10080 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10082 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10083 SDValue Cmp = N->getOperand(4);
10084 if (Cmp.getOpcode() != ARMISD::CMPZ)
10085 // Only looking at EQ and NE cases.
10088 EVT VT = N->getValueType(0);
10090 SDValue LHS = Cmp.getOperand(0);
10091 SDValue RHS = Cmp.getOperand(1);
10092 SDValue FalseVal = N->getOperand(0);
10093 SDValue TrueVal = N->getOperand(1);
10094 SDValue ARMcc = N->getOperand(2);
10095 ARMCC::CondCodes CC =
10096 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10114 /// FIXME: Turn this into a target neutral optimization?
10116 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10117 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10118 N->getOperand(3), Cmp);
10119 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10121 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10122 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10123 N->getOperand(3), NewCmp);
10126 if (Res.getNode()) {
10127 APInt KnownZero, KnownOne;
10128 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10129 // Capture demanded bits information that would be otherwise lost.
10130 if (KnownZero == 0xfffffffe)
10131 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10132 DAG.getValueType(MVT::i1));
10133 else if (KnownZero == 0xffffff00)
10134 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10135 DAG.getValueType(MVT::i8));
10136 else if (KnownZero == 0xffff0000)
10137 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10138 DAG.getValueType(MVT::i16));
10144 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10145 DAGCombinerInfo &DCI) const {
10146 switch (N->getOpcode()) {
10148 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10149 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10150 case ISD::SUB: return PerformSUBCombine(N, DCI);
10151 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10152 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10153 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10154 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10155 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10156 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10157 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10158 case ISD::STORE: return PerformSTORECombine(N, DCI);
10159 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10160 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10161 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10162 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10163 case ISD::FP_TO_SINT:
10164 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10165 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10166 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10169 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10170 case ISD::SIGN_EXTEND:
10171 case ISD::ZERO_EXTEND:
10172 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10173 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10174 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10175 case ARMISD::VLD2DUP:
10176 case ARMISD::VLD3DUP:
10177 case ARMISD::VLD4DUP:
10178 return PerformVLDCombine(N, DCI);
10179 case ARMISD::BUILD_VECTOR:
10180 return PerformARMBUILD_VECTORCombine(N, DCI);
10181 case ISD::INTRINSIC_VOID:
10182 case ISD::INTRINSIC_W_CHAIN:
10183 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10184 case Intrinsic::arm_neon_vld1:
10185 case Intrinsic::arm_neon_vld2:
10186 case Intrinsic::arm_neon_vld3:
10187 case Intrinsic::arm_neon_vld4:
10188 case Intrinsic::arm_neon_vld2lane:
10189 case Intrinsic::arm_neon_vld3lane:
10190 case Intrinsic::arm_neon_vld4lane:
10191 case Intrinsic::arm_neon_vst1:
10192 case Intrinsic::arm_neon_vst2:
10193 case Intrinsic::arm_neon_vst3:
10194 case Intrinsic::arm_neon_vst4:
10195 case Intrinsic::arm_neon_vst2lane:
10196 case Intrinsic::arm_neon_vst3lane:
10197 case Intrinsic::arm_neon_vst4lane:
10198 return PerformVLDCombine(N, DCI);
10206 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10208 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10211 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10214 bool *Fast) const {
10215 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10216 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10218 switch (VT.getSimpleVT().SimpleTy) {
10224 // Unaligned access can use (for example) LRDB, LRDH, LDR
10225 if (AllowsUnaligned) {
10227 *Fast = Subtarget->hasV7Ops();
10234 // For any little-endian targets with neon, we can support unaligned ld/st
10235 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10236 // A big-endian target may also explicitly support unaligned accesses
10237 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10247 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10248 unsigned AlignCheck) {
10249 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10250 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10253 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10254 unsigned DstAlign, unsigned SrcAlign,
10255 bool IsMemset, bool ZeroMemset,
10257 MachineFunction &MF) const {
10258 const Function *F = MF.getFunction();
10260 // See if we can use NEON instructions for this...
10261 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10262 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10265 (memOpAlign(SrcAlign, DstAlign, 16) ||
10266 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10268 } else if (Size >= 8 &&
10269 (memOpAlign(SrcAlign, DstAlign, 8) ||
10270 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10276 // Lowering to i32/i16 if the size permits.
10279 else if (Size >= 2)
10282 // Let the target-independent logic figure it out.
10286 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10287 if (Val.getOpcode() != ISD::LOAD)
10290 EVT VT1 = Val.getValueType();
10291 if (!VT1.isSimple() || !VT1.isInteger() ||
10292 !VT2.isSimple() || !VT2.isInteger())
10295 switch (VT1.getSimpleVT().SimpleTy) {
10300 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10307 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10308 EVT VT = ExtVal.getValueType();
10310 if (!isTypeLegal(VT))
10313 // Don't create a loadext if we can fold the extension into a wide/long
10315 // If there's more than one user instruction, the loadext is desirable no
10316 // matter what. There can be two uses by the same instruction.
10317 if (ExtVal->use_empty() ||
10318 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10321 SDNode *U = *ExtVal->use_begin();
10322 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10323 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10329 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10330 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10333 if (!isTypeLegal(EVT::getEVT(Ty1)))
10336 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10338 // Assuming the caller doesn't have a zeroext or signext return parameter,
10339 // truncation all the way down to i1 is valid.
10344 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10348 unsigned Scale = 1;
10349 switch (VT.getSimpleVT().SimpleTy) {
10350 default: return false;
10365 if ((V & (Scale - 1)) != 0)
10368 return V == (V & ((1LL << 5) - 1));
10371 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10372 const ARMSubtarget *Subtarget) {
10373 bool isNeg = false;
10379 switch (VT.getSimpleVT().SimpleTy) {
10380 default: return false;
10385 // + imm12 or - imm8
10387 return V == (V & ((1LL << 8) - 1));
10388 return V == (V & ((1LL << 12) - 1));
10391 // Same as ARM mode. FIXME: NEON?
10392 if (!Subtarget->hasVFP2())
10397 return V == (V & ((1LL << 8) - 1));
10401 /// isLegalAddressImmediate - Return true if the integer value can be used
10402 /// as the offset of the target addressing mode for load / store of the
10404 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10405 const ARMSubtarget *Subtarget) {
10409 if (!VT.isSimple())
10412 if (Subtarget->isThumb1Only())
10413 return isLegalT1AddressImmediate(V, VT);
10414 else if (Subtarget->isThumb2())
10415 return isLegalT2AddressImmediate(V, VT, Subtarget);
10420 switch (VT.getSimpleVT().SimpleTy) {
10421 default: return false;
10426 return V == (V & ((1LL << 12) - 1));
10429 return V == (V & ((1LL << 8) - 1));
10432 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10437 return V == (V & ((1LL << 8) - 1));
10441 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10443 int Scale = AM.Scale;
10447 switch (VT.getSimpleVT().SimpleTy) {
10448 default: return false;
10456 Scale = Scale & ~1;
10457 return Scale == 2 || Scale == 4 || Scale == 8;
10460 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10464 // Note, we allow "void" uses (basically, uses that aren't loads or
10465 // stores), because arm allows folding a scale into many arithmetic
10466 // operations. This should be made more precise and revisited later.
10468 // Allow r << imm, but the imm has to be a multiple of two.
10469 if (Scale & 1) return false;
10470 return isPowerOf2_32(Scale);
10474 /// isLegalAddressingMode - Return true if the addressing mode represented
10475 /// by AM is legal for this target, for a load/store of the specified type.
10476 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10477 const AddrMode &AM, Type *Ty,
10478 unsigned AS) const {
10479 EVT VT = getValueType(DL, Ty, true);
10480 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10483 // Can never fold addr of global into load/store.
10487 switch (AM.Scale) {
10488 case 0: // no scale reg, must be "r+i" or "r", or "i".
10491 if (Subtarget->isThumb1Only())
10495 // ARM doesn't support any R+R*scale+imm addr modes.
10499 if (!VT.isSimple())
10502 if (Subtarget->isThumb2())
10503 return isLegalT2ScaledAddressingMode(AM, VT);
10505 int Scale = AM.Scale;
10506 switch (VT.getSimpleVT().SimpleTy) {
10507 default: return false;
10511 if (Scale < 0) Scale = -Scale;
10515 return isPowerOf2_32(Scale & ~1);
10519 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10524 // Note, we allow "void" uses (basically, uses that aren't loads or
10525 // stores), because arm allows folding a scale into many arithmetic
10526 // operations. This should be made more precise and revisited later.
10528 // Allow r << imm, but the imm has to be a multiple of two.
10529 if (Scale & 1) return false;
10530 return isPowerOf2_32(Scale);
10536 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10537 /// icmp immediate, that is the target has icmp instructions which can compare
10538 /// a register against the immediate without having to materialize the
10539 /// immediate into a register.
10540 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10541 // Thumb2 and ARM modes can use cmn for negative immediates.
10542 if (!Subtarget->isThumb())
10543 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10544 if (Subtarget->isThumb2())
10545 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10546 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10547 return Imm >= 0 && Imm <= 255;
10550 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10551 /// *or sub* immediate, that is the target has add or sub instructions which can
10552 /// add a register with the immediate without having to materialize the
10553 /// immediate into a register.
10554 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10555 // Same encoding for add/sub, just flip the sign.
10556 int64_t AbsImm = std::abs(Imm);
10557 if (!Subtarget->isThumb())
10558 return ARM_AM::getSOImmVal(AbsImm) != -1;
10559 if (Subtarget->isThumb2())
10560 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10561 // Thumb1 only has 8-bit unsigned immediate.
10562 return AbsImm >= 0 && AbsImm <= 255;
10565 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10566 bool isSEXTLoad, SDValue &Base,
10567 SDValue &Offset, bool &isInc,
10568 SelectionDAG &DAG) {
10569 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10572 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10573 // AddressingMode 3
10574 Base = Ptr->getOperand(0);
10575 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10576 int RHSC = (int)RHS->getZExtValue();
10577 if (RHSC < 0 && RHSC > -256) {
10578 assert(Ptr->getOpcode() == ISD::ADD);
10580 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10584 isInc = (Ptr->getOpcode() == ISD::ADD);
10585 Offset = Ptr->getOperand(1);
10587 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10588 // AddressingMode 2
10589 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10590 int RHSC = (int)RHS->getZExtValue();
10591 if (RHSC < 0 && RHSC > -0x1000) {
10592 assert(Ptr->getOpcode() == ISD::ADD);
10594 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10595 Base = Ptr->getOperand(0);
10600 if (Ptr->getOpcode() == ISD::ADD) {
10602 ARM_AM::ShiftOpc ShOpcVal=
10603 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10604 if (ShOpcVal != ARM_AM::no_shift) {
10605 Base = Ptr->getOperand(1);
10606 Offset = Ptr->getOperand(0);
10608 Base = Ptr->getOperand(0);
10609 Offset = Ptr->getOperand(1);
10614 isInc = (Ptr->getOpcode() == ISD::ADD);
10615 Base = Ptr->getOperand(0);
10616 Offset = Ptr->getOperand(1);
10620 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10624 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10625 bool isSEXTLoad, SDValue &Base,
10626 SDValue &Offset, bool &isInc,
10627 SelectionDAG &DAG) {
10628 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10631 Base = Ptr->getOperand(0);
10632 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10633 int RHSC = (int)RHS->getZExtValue();
10634 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10635 assert(Ptr->getOpcode() == ISD::ADD);
10637 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10639 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10640 isInc = Ptr->getOpcode() == ISD::ADD;
10641 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10649 /// getPreIndexedAddressParts - returns true by value, base pointer and
10650 /// offset pointer and addressing mode by reference if the node's address
10651 /// can be legally represented as pre-indexed load / store address.
10653 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10655 ISD::MemIndexedMode &AM,
10656 SelectionDAG &DAG) const {
10657 if (Subtarget->isThumb1Only())
10662 bool isSEXTLoad = false;
10663 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10664 Ptr = LD->getBasePtr();
10665 VT = LD->getMemoryVT();
10666 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10667 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10668 Ptr = ST->getBasePtr();
10669 VT = ST->getMemoryVT();
10674 bool isLegal = false;
10675 if (Subtarget->isThumb2())
10676 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10677 Offset, isInc, DAG);
10679 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10680 Offset, isInc, DAG);
10684 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10688 /// getPostIndexedAddressParts - returns true by value, base pointer and
10689 /// offset pointer and addressing mode by reference if this node can be
10690 /// combined with a load / store to form a post-indexed load / store.
10691 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10694 ISD::MemIndexedMode &AM,
10695 SelectionDAG &DAG) const {
10696 if (Subtarget->isThumb1Only())
10701 bool isSEXTLoad = false;
10702 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10703 VT = LD->getMemoryVT();
10704 Ptr = LD->getBasePtr();
10705 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10706 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10707 VT = ST->getMemoryVT();
10708 Ptr = ST->getBasePtr();
10713 bool isLegal = false;
10714 if (Subtarget->isThumb2())
10715 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10718 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10724 // Swap base ptr and offset to catch more post-index load / store when
10725 // it's legal. In Thumb2 mode, offset must be an immediate.
10726 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10727 !Subtarget->isThumb2())
10728 std::swap(Base, Offset);
10730 // Post-indexed load / store update the base pointer.
10735 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10739 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10742 const SelectionDAG &DAG,
10743 unsigned Depth) const {
10744 unsigned BitWidth = KnownOne.getBitWidth();
10745 KnownZero = KnownOne = APInt(BitWidth, 0);
10746 switch (Op.getOpcode()) {
10752 // These nodes' second result is a boolean
10753 if (Op.getResNo() == 0)
10755 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10757 case ARMISD::CMOV: {
10758 // Bits are known zero/one if known on the LHS and RHS.
10759 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10760 if (KnownZero == 0 && KnownOne == 0) return;
10762 APInt KnownZeroRHS, KnownOneRHS;
10763 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10764 KnownZero &= KnownZeroRHS;
10765 KnownOne &= KnownOneRHS;
10768 case ISD::INTRINSIC_W_CHAIN: {
10769 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10770 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10773 case Intrinsic::arm_ldaex:
10774 case Intrinsic::arm_ldrex: {
10775 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10776 unsigned MemBits = VT.getScalarType().getSizeInBits();
10777 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10785 //===----------------------------------------------------------------------===//
10786 // ARM Inline Assembly Support
10787 //===----------------------------------------------------------------------===//
10789 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10790 // Looking for "rev" which is V6+.
10791 if (!Subtarget->hasV6Ops())
10794 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10795 std::string AsmStr = IA->getAsmString();
10796 SmallVector<StringRef, 4> AsmPieces;
10797 SplitString(AsmStr, AsmPieces, ";\n");
10799 switch (AsmPieces.size()) {
10800 default: return false;
10802 AsmStr = AsmPieces[0];
10804 SplitString(AsmStr, AsmPieces, " \t,");
10807 if (AsmPieces.size() == 3 &&
10808 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10809 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10810 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10811 if (Ty && Ty->getBitWidth() == 32)
10812 return IntrinsicLowering::LowerToByteSwap(CI);
10820 /// getConstraintType - Given a constraint letter, return the type of
10821 /// constraint it is for this target.
10822 ARMTargetLowering::ConstraintType
10823 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10824 if (Constraint.size() == 1) {
10825 switch (Constraint[0]) {
10827 case 'l': return C_RegisterClass;
10828 case 'w': return C_RegisterClass;
10829 case 'h': return C_RegisterClass;
10830 case 'x': return C_RegisterClass;
10831 case 't': return C_RegisterClass;
10832 case 'j': return C_Other; // Constant for movw.
10833 // An address with a single base register. Due to the way we
10834 // currently handle addresses it is the same as an 'r' memory constraint.
10835 case 'Q': return C_Memory;
10837 } else if (Constraint.size() == 2) {
10838 switch (Constraint[0]) {
10840 // All 'U+' constraints are addresses.
10841 case 'U': return C_Memory;
10844 return TargetLowering::getConstraintType(Constraint);
10847 /// Examine constraint type and operand type and determine a weight value.
10848 /// This object must already have been set up with the operand type
10849 /// and the current alternative constraint selected.
10850 TargetLowering::ConstraintWeight
10851 ARMTargetLowering::getSingleConstraintMatchWeight(
10852 AsmOperandInfo &info, const char *constraint) const {
10853 ConstraintWeight weight = CW_Invalid;
10854 Value *CallOperandVal = info.CallOperandVal;
10855 // If we don't have a value, we can't do a match,
10856 // but allow it at the lowest weight.
10857 if (!CallOperandVal)
10859 Type *type = CallOperandVal->getType();
10860 // Look at the constraint type.
10861 switch (*constraint) {
10863 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10866 if (type->isIntegerTy()) {
10867 if (Subtarget->isThumb())
10868 weight = CW_SpecificReg;
10870 weight = CW_Register;
10874 if (type->isFloatingPointTy())
10875 weight = CW_Register;
10881 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10882 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10883 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10884 if (Constraint.size() == 1) {
10885 // GCC ARM Constraint Letters
10886 switch (Constraint[0]) {
10887 case 'l': // Low regs or general regs.
10888 if (Subtarget->isThumb())
10889 return RCPair(0U, &ARM::tGPRRegClass);
10890 return RCPair(0U, &ARM::GPRRegClass);
10891 case 'h': // High regs or no regs.
10892 if (Subtarget->isThumb())
10893 return RCPair(0U, &ARM::hGPRRegClass);
10896 if (Subtarget->isThumb1Only())
10897 return RCPair(0U, &ARM::tGPRRegClass);
10898 return RCPair(0U, &ARM::GPRRegClass);
10900 if (VT == MVT::Other)
10902 if (VT == MVT::f32)
10903 return RCPair(0U, &ARM::SPRRegClass);
10904 if (VT.getSizeInBits() == 64)
10905 return RCPair(0U, &ARM::DPRRegClass);
10906 if (VT.getSizeInBits() == 128)
10907 return RCPair(0U, &ARM::QPRRegClass);
10910 if (VT == MVT::Other)
10912 if (VT == MVT::f32)
10913 return RCPair(0U, &ARM::SPR_8RegClass);
10914 if (VT.getSizeInBits() == 64)
10915 return RCPair(0U, &ARM::DPR_8RegClass);
10916 if (VT.getSizeInBits() == 128)
10917 return RCPair(0U, &ARM::QPR_8RegClass);
10920 if (VT == MVT::f32)
10921 return RCPair(0U, &ARM::SPRRegClass);
10925 if (StringRef("{cc}").equals_lower(Constraint))
10926 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10928 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10931 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10932 /// vector. If it is invalid, don't add anything to Ops.
10933 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10934 std::string &Constraint,
10935 std::vector<SDValue>&Ops,
10936 SelectionDAG &DAG) const {
10939 // Currently only support length 1 constraints.
10940 if (Constraint.length() != 1) return;
10942 char ConstraintLetter = Constraint[0];
10943 switch (ConstraintLetter) {
10946 case 'I': case 'J': case 'K': case 'L':
10947 case 'M': case 'N': case 'O':
10948 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10952 int64_t CVal64 = C->getSExtValue();
10953 int CVal = (int) CVal64;
10954 // None of these constraints allow values larger than 32 bits. Check
10955 // that the value fits in an int.
10956 if (CVal != CVal64)
10959 switch (ConstraintLetter) {
10961 // Constant suitable for movw, must be between 0 and
10963 if (Subtarget->hasV6T2Ops())
10964 if (CVal >= 0 && CVal <= 65535)
10968 if (Subtarget->isThumb1Only()) {
10969 // This must be a constant between 0 and 255, for ADD
10971 if (CVal >= 0 && CVal <= 255)
10973 } else if (Subtarget->isThumb2()) {
10974 // A constant that can be used as an immediate value in a
10975 // data-processing instruction.
10976 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10979 // A constant that can be used as an immediate value in a
10980 // data-processing instruction.
10981 if (ARM_AM::getSOImmVal(CVal) != -1)
10987 if (Subtarget->isThumb()) { // FIXME thumb2
10988 // This must be a constant between -255 and -1, for negated ADD
10989 // immediates. This can be used in GCC with an "n" modifier that
10990 // prints the negated value, for use with SUB instructions. It is
10991 // not useful otherwise but is implemented for compatibility.
10992 if (CVal >= -255 && CVal <= -1)
10995 // This must be a constant between -4095 and 4095. It is not clear
10996 // what this constraint is intended for. Implemented for
10997 // compatibility with GCC.
10998 if (CVal >= -4095 && CVal <= 4095)
11004 if (Subtarget->isThumb1Only()) {
11005 // A 32-bit value where only one byte has a nonzero value. Exclude
11006 // zero to match GCC. This constraint is used by GCC internally for
11007 // constants that can be loaded with a move/shift combination.
11008 // It is not useful otherwise but is implemented for compatibility.
11009 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11011 } else if (Subtarget->isThumb2()) {
11012 // A constant whose bitwise inverse can be used as an immediate
11013 // value in a data-processing instruction. This can be used in GCC
11014 // with a "B" modifier that prints the inverted value, for use with
11015 // BIC and MVN instructions. It is not useful otherwise but is
11016 // implemented for compatibility.
11017 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11020 // A constant whose bitwise inverse can be used as an immediate
11021 // value in a data-processing instruction. This can be used in GCC
11022 // with a "B" modifier that prints the inverted value, for use with
11023 // BIC and MVN instructions. It is not useful otherwise but is
11024 // implemented for compatibility.
11025 if (ARM_AM::getSOImmVal(~CVal) != -1)
11031 if (Subtarget->isThumb1Only()) {
11032 // This must be a constant between -7 and 7,
11033 // for 3-operand ADD/SUB immediate instructions.
11034 if (CVal >= -7 && CVal < 7)
11036 } else if (Subtarget->isThumb2()) {
11037 // A constant whose negation can be used as an immediate value in a
11038 // data-processing instruction. This can be used in GCC with an "n"
11039 // modifier that prints the negated value, for use with SUB
11040 // instructions. It is not useful otherwise but is implemented for
11042 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11045 // A constant whose negation can be used as an immediate value in a
11046 // data-processing instruction. This can be used in GCC with an "n"
11047 // modifier that prints the negated value, for use with SUB
11048 // instructions. It is not useful otherwise but is implemented for
11050 if (ARM_AM::getSOImmVal(-CVal) != -1)
11056 if (Subtarget->isThumb()) { // FIXME thumb2
11057 // This must be a multiple of 4 between 0 and 1020, for
11058 // ADD sp + immediate.
11059 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11062 // A power of two or a constant between 0 and 32. This is used in
11063 // GCC for the shift amount on shifted register operands, but it is
11064 // useful in general for any shift amounts.
11065 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11071 if (Subtarget->isThumb()) { // FIXME thumb2
11072 // This must be a constant between 0 and 31, for shift amounts.
11073 if (CVal >= 0 && CVal <= 31)
11079 if (Subtarget->isThumb()) { // FIXME thumb2
11080 // This must be a multiple of 4 between -508 and 508, for
11081 // ADD/SUB sp = sp + immediate.
11082 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11087 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11091 if (Result.getNode()) {
11092 Ops.push_back(Result);
11095 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11098 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11099 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11100 "Register-based DivRem lowering only");
11101 unsigned Opcode = Op->getOpcode();
11102 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11103 "Invalid opcode for Div/Rem lowering");
11104 bool isSigned = (Opcode == ISD::SDIVREM);
11105 EVT VT = Op->getValueType(0);
11106 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11109 switch (VT.getSimpleVT().SimpleTy) {
11110 default: llvm_unreachable("Unexpected request for libcall!");
11111 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11112 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11113 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11114 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11117 SDValue InChain = DAG.getEntryNode();
11119 TargetLowering::ArgListTy Args;
11120 TargetLowering::ArgListEntry Entry;
11121 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11122 EVT ArgVT = Op->getOperand(i).getValueType();
11123 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11124 Entry.Node = Op->getOperand(i);
11126 Entry.isSExt = isSigned;
11127 Entry.isZExt = !isSigned;
11128 Args.push_back(Entry);
11131 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11132 getPointerTy(DAG.getDataLayout()));
11134 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11137 TargetLowering::CallLoweringInfo CLI(DAG);
11138 CLI.setDebugLoc(dl).setChain(InChain)
11139 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11140 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11142 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11143 return CallInfo.first;
11147 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11148 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11152 SDValue Chain = Op.getOperand(0);
11153 SDValue Size = Op.getOperand(1);
11155 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11156 DAG.getConstant(2, DL, MVT::i32));
11159 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11160 Flag = Chain.getValue(1);
11162 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11163 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11165 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11166 Chain = NewSP.getValue(1);
11168 SDValue Ops[2] = { NewSP, Chain };
11169 return DAG.getMergeValues(Ops, DL);
11172 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11173 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11174 "Unexpected type for custom-lowering FP_EXTEND");
11177 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11179 SDValue SrcVal = Op.getOperand(0);
11180 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11181 /*isSigned*/ false, SDLoc(Op)).first;
11184 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11185 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11186 Subtarget->isFPOnlySP() &&
11187 "Unexpected type for custom-lowering FP_ROUND");
11190 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11192 SDValue SrcVal = Op.getOperand(0);
11193 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11194 /*isSigned*/ false, SDLoc(Op)).first;
11198 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11199 // The ARM target isn't yet aware of offsets.
11203 bool ARM::isBitFieldInvertedMask(unsigned v) {
11204 if (v == 0xffffffff)
11207 // there can be 1's on either or both "outsides", all the "inside"
11208 // bits must be 0's
11209 return isShiftedMask_32(~v);
11212 /// isFPImmLegal - Returns true if the target can instruction select the
11213 /// specified FP immediate natively. If false, the legalizer will
11214 /// materialize the FP immediate as a load from a constant pool.
11215 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11216 if (!Subtarget->hasVFP3())
11218 if (VT == MVT::f32)
11219 return ARM_AM::getFP32Imm(Imm) != -1;
11220 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11221 return ARM_AM::getFP64Imm(Imm) != -1;
11225 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11226 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11227 /// specified in the intrinsic calls.
11228 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11230 unsigned Intrinsic) const {
11231 switch (Intrinsic) {
11232 case Intrinsic::arm_neon_vld1:
11233 case Intrinsic::arm_neon_vld2:
11234 case Intrinsic::arm_neon_vld3:
11235 case Intrinsic::arm_neon_vld4:
11236 case Intrinsic::arm_neon_vld2lane:
11237 case Intrinsic::arm_neon_vld3lane:
11238 case Intrinsic::arm_neon_vld4lane: {
11239 Info.opc = ISD::INTRINSIC_W_CHAIN;
11240 // Conservatively set memVT to the entire set of vectors loaded.
11241 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11242 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11243 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11244 Info.ptrVal = I.getArgOperand(0);
11246 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11247 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11248 Info.vol = false; // volatile loads with NEON intrinsics not supported
11249 Info.readMem = true;
11250 Info.writeMem = false;
11253 case Intrinsic::arm_neon_vst1:
11254 case Intrinsic::arm_neon_vst2:
11255 case Intrinsic::arm_neon_vst3:
11256 case Intrinsic::arm_neon_vst4:
11257 case Intrinsic::arm_neon_vst2lane:
11258 case Intrinsic::arm_neon_vst3lane:
11259 case Intrinsic::arm_neon_vst4lane: {
11260 Info.opc = ISD::INTRINSIC_VOID;
11261 // Conservatively set memVT to the entire set of vectors stored.
11262 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11263 unsigned NumElts = 0;
11264 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11265 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11266 if (!ArgTy->isVectorTy())
11268 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11270 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11271 Info.ptrVal = I.getArgOperand(0);
11273 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11274 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11275 Info.vol = false; // volatile stores with NEON intrinsics not supported
11276 Info.readMem = false;
11277 Info.writeMem = true;
11280 case Intrinsic::arm_ldaex:
11281 case Intrinsic::arm_ldrex: {
11282 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11283 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11284 Info.opc = ISD::INTRINSIC_W_CHAIN;
11285 Info.memVT = MVT::getVT(PtrTy->getElementType());
11286 Info.ptrVal = I.getArgOperand(0);
11288 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11290 Info.readMem = true;
11291 Info.writeMem = false;
11294 case Intrinsic::arm_stlex:
11295 case Intrinsic::arm_strex: {
11296 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11297 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11298 Info.opc = ISD::INTRINSIC_W_CHAIN;
11299 Info.memVT = MVT::getVT(PtrTy->getElementType());
11300 Info.ptrVal = I.getArgOperand(1);
11302 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11304 Info.readMem = false;
11305 Info.writeMem = true;
11308 case Intrinsic::arm_stlexd:
11309 case Intrinsic::arm_strexd: {
11310 Info.opc = ISD::INTRINSIC_W_CHAIN;
11311 Info.memVT = MVT::i64;
11312 Info.ptrVal = I.getArgOperand(2);
11316 Info.readMem = false;
11317 Info.writeMem = true;
11320 case Intrinsic::arm_ldaexd:
11321 case Intrinsic::arm_ldrexd: {
11322 Info.opc = ISD::INTRINSIC_W_CHAIN;
11323 Info.memVT = MVT::i64;
11324 Info.ptrVal = I.getArgOperand(0);
11328 Info.readMem = true;
11329 Info.writeMem = false;
11339 /// \brief Returns true if it is beneficial to convert a load of a constant
11340 /// to just the constant itself.
11341 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11343 assert(Ty->isIntegerTy());
11345 unsigned Bits = Ty->getPrimitiveSizeInBits();
11346 if (Bits == 0 || Bits > 32)
11351 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11353 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11354 ARM_MB::MemBOpt Domain) const {
11355 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11357 // First, if the target has no DMB, see what fallback we can use.
11358 if (!Subtarget->hasDataBarrier()) {
11359 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11360 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11362 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11363 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11364 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11365 Builder.getInt32(0), Builder.getInt32(7),
11366 Builder.getInt32(10), Builder.getInt32(5)};
11367 return Builder.CreateCall(MCR, args);
11369 // Instead of using barriers, atomic accesses on these subtargets use
11371 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11374 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11375 // Only a full system barrier exists in the M-class architectures.
11376 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11377 Constant *CDomain = Builder.getInt32(Domain);
11378 return Builder.CreateCall(DMB, CDomain);
11382 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11383 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11384 AtomicOrdering Ord, bool IsStore,
11385 bool IsLoad) const {
11386 if (!getInsertFencesForAtomic())
11392 llvm_unreachable("Invalid fence: unordered/non-atomic");
11395 return nullptr; // Nothing to do
11396 case SequentiallyConsistent:
11398 return nullptr; // Nothing to do
11401 case AcquireRelease:
11402 if (Subtarget->isSwift())
11403 return makeDMB(Builder, ARM_MB::ISHST);
11404 // FIXME: add a comment with a link to documentation justifying this.
11406 return makeDMB(Builder, ARM_MB::ISH);
11408 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11411 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11412 AtomicOrdering Ord, bool IsStore,
11413 bool IsLoad) const {
11414 if (!getInsertFencesForAtomic())
11420 llvm_unreachable("Invalid fence: unordered/not-atomic");
11423 return nullptr; // Nothing to do
11425 case AcquireRelease:
11426 case SequentiallyConsistent:
11427 return makeDMB(Builder, ARM_MB::ISH);
11429 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11432 // Loads and stores less than 64-bits are already atomic; ones above that
11433 // are doomed anyway, so defer to the default libcall and blame the OS when
11434 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11435 // anything for those.
11436 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11437 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11438 return (Size == 64) && !Subtarget->isMClass();
11441 // Loads and stores less than 64-bits are already atomic; ones above that
11442 // are doomed anyway, so defer to the default libcall and blame the OS when
11443 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11444 // anything for those.
11445 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11446 // guarantee, see DDI0406C ARM architecture reference manual,
11447 // sections A8.8.72-74 LDRD)
11448 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11449 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11450 return (Size == 64) && !Subtarget->isMClass();
11453 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11454 // and up to 64 bits on the non-M profiles
11455 TargetLoweringBase::AtomicRMWExpansionKind
11456 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11457 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11458 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11459 ? AtomicRMWExpansionKind::LLSC
11460 : AtomicRMWExpansionKind::None;
11463 // This has so far only been implemented for MachO.
11464 bool ARMTargetLowering::useLoadStackGuardNode() const {
11465 return Subtarget->isTargetMachO();
11468 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11469 unsigned &Cost) const {
11470 // If we do not have NEON, vector types are not natively supported.
11471 if (!Subtarget->hasNEON())
11474 // Floating point values and vector values map to the same register file.
11475 // Therefore, although we could do a store extract of a vector type, this is
11476 // better to leave at float as we have more freedom in the addressing mode for
11478 if (VectorTy->isFPOrFPVectorTy())
11481 // If the index is unknown at compile time, this is very expensive to lower
11482 // and it is not possible to combine the store with the extract.
11483 if (!isa<ConstantInt>(Idx))
11486 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11487 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11488 // We can do a store + vector extract on any vector that fits perfectly in a D
11490 if (BitWidth == 64 || BitWidth == 128) {
11497 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11498 AtomicOrdering Ord) const {
11499 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11500 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11501 bool IsAcquire = isAtLeastAcquire(Ord);
11503 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11504 // intrinsic must return {i32, i32} and we have to recombine them into a
11505 // single i64 here.
11506 if (ValTy->getPrimitiveSizeInBits() == 64) {
11507 Intrinsic::ID Int =
11508 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11509 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11511 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11512 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11514 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11515 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11516 if (!Subtarget->isLittle())
11517 std::swap (Lo, Hi);
11518 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11519 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11520 return Builder.CreateOr(
11521 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11524 Type *Tys[] = { Addr->getType() };
11525 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11526 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11528 return Builder.CreateTruncOrBitCast(
11529 Builder.CreateCall(Ldrex, Addr),
11530 cast<PointerType>(Addr->getType())->getElementType());
11533 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11535 AtomicOrdering Ord) const {
11536 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11537 bool IsRelease = isAtLeastRelease(Ord);
11539 // Since the intrinsics must have legal type, the i64 intrinsics take two
11540 // parameters: "i32, i32". We must marshal Val into the appropriate form
11541 // before the call.
11542 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11543 Intrinsic::ID Int =
11544 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11545 Function *Strex = Intrinsic::getDeclaration(M, Int);
11546 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11548 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11549 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11550 if (!Subtarget->isLittle())
11551 std::swap (Lo, Hi);
11552 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11553 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11556 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11557 Type *Tys[] = { Addr->getType() };
11558 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11560 return Builder.CreateCall(
11561 Strex, {Builder.CreateZExtOrBitCast(
11562 Val, Strex->getFunctionType()->getParamType(0)),
11566 /// \brief Lower an interleaved load into a vldN intrinsic.
11568 /// E.g. Lower an interleaved load (Factor = 2):
11569 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11570 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11571 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11574 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11575 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11576 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11577 bool ARMTargetLowering::lowerInterleavedLoad(
11578 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11579 ArrayRef<unsigned> Indices, unsigned Factor) const {
11580 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11581 "Invalid interleave factor");
11582 assert(!Shuffles.empty() && "Empty shufflevector input");
11583 assert(Shuffles.size() == Indices.size() &&
11584 "Unmatched number of shufflevectors and indices");
11586 VectorType *VecTy = Shuffles[0]->getType();
11587 Type *EltTy = VecTy->getVectorElementType();
11589 const DataLayout &DL = LI->getModule()->getDataLayout();
11590 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11591 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11593 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11594 // support i64/f64 element).
11595 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11598 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11599 // load integer vectors first and then convert to pointer vectors.
11600 if (EltTy->isPointerTy())
11602 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11604 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11605 Intrinsic::arm_neon_vld3,
11606 Intrinsic::arm_neon_vld4};
11608 Function *VldnFunc =
11609 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11611 IRBuilder<> Builder(LI);
11612 SmallVector<Value *, 2> Ops;
11614 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11615 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11616 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11618 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11620 // Replace uses of each shufflevector with the corresponding vector loaded
11622 for (unsigned i = 0; i < Shuffles.size(); i++) {
11623 ShuffleVectorInst *SV = Shuffles[i];
11624 unsigned Index = Indices[i];
11626 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11628 // Convert the integer vector to pointer vector if the element is pointer.
11629 if (EltTy->isPointerTy())
11630 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11632 SV->replaceAllUsesWith(SubVec);
11638 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11640 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11641 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11642 unsigned NumElts) {
11643 SmallVector<Constant *, 16> Mask;
11644 for (unsigned i = 0; i < NumElts; i++)
11645 Mask.push_back(Builder.getInt32(Start + i));
11647 return ConstantVector::get(Mask);
11650 /// \brief Lower an interleaved store into a vstN intrinsic.
11652 /// E.g. Lower an interleaved store (Factor = 3):
11653 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11654 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11655 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11658 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11659 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11660 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11661 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11663 /// Note that the new shufflevectors will be removed and we'll only generate one
11664 /// vst3 instruction in CodeGen.
11665 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11666 ShuffleVectorInst *SVI,
11667 unsigned Factor) const {
11668 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11669 "Invalid interleave factor");
11671 VectorType *VecTy = SVI->getType();
11672 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11673 "Invalid interleaved store");
11675 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11676 Type *EltTy = VecTy->getVectorElementType();
11677 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11679 const DataLayout &DL = SI->getModule()->getDataLayout();
11680 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11681 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11683 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11684 // doesn't support i64/f64 element).
11685 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11688 Value *Op0 = SVI->getOperand(0);
11689 Value *Op1 = SVI->getOperand(1);
11690 IRBuilder<> Builder(SI);
11692 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11693 // vectors to integer vectors.
11694 if (EltTy->isPointerTy()) {
11695 Type *IntTy = DL.getIntPtrType(EltTy);
11697 // Convert to the corresponding integer vector.
11699 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11700 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11701 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11703 SubVecTy = VectorType::get(IntTy, NumSubElts);
11706 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11707 Intrinsic::arm_neon_vst3,
11708 Intrinsic::arm_neon_vst4};
11709 Function *VstNFunc = Intrinsic::getDeclaration(
11710 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11712 SmallVector<Value *, 6> Ops;
11714 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11715 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11717 // Split the shufflevector operands into sub vectors for the new vstN call.
11718 for (unsigned i = 0; i < Factor; i++)
11719 Ops.push_back(Builder.CreateShuffleVector(
11720 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11722 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11723 Builder.CreateCall(VstNFunc, Ops);
11735 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11736 uint64_t &Members) {
11737 if (auto *ST = dyn_cast<StructType>(Ty)) {
11738 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11739 uint64_t SubMembers = 0;
11740 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11742 Members += SubMembers;
11744 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11745 uint64_t SubMembers = 0;
11746 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11748 Members += SubMembers * AT->getNumElements();
11749 } else if (Ty->isFloatTy()) {
11750 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11754 } else if (Ty->isDoubleTy()) {
11755 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11759 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11766 return VT->getBitWidth() == 64;
11768 return VT->getBitWidth() == 128;
11770 switch (VT->getBitWidth()) {
11783 return (Members > 0 && Members <= 4);
11786 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11787 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11788 /// passing according to AAPCS rules.
11789 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11790 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11791 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11792 CallingConv::ARM_AAPCS_VFP)
11795 HABaseType Base = HA_UNKNOWN;
11796 uint64_t Members = 0;
11797 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11798 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11800 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11801 return IsHA || IsIntArray;