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 (CmpVT.getVectorElementType() == MVT::i64)
4564 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4565 // but it's possible that our operands are 64-bit but our result is 32-bit.
4566 // Bail in this case.
4569 if (Op1.getValueType().isFloatingPoint()) {
4570 switch (SetCCOpcode) {
4571 default: llvm_unreachable("Illegal FP comparison");
4573 case ISD::SETNE: Invert = true; // Fallthrough
4575 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4577 case ISD::SETLT: Swap = true; // Fallthrough
4579 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4581 case ISD::SETLE: Swap = true; // Fallthrough
4583 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4584 case ISD::SETUGE: Swap = true; // Fallthrough
4585 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4586 case ISD::SETUGT: Swap = true; // Fallthrough
4587 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4588 case ISD::SETUEQ: Invert = true; // Fallthrough
4590 // Expand this to (OLT | OGT).
4594 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4595 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4597 case ISD::SETUO: Invert = true; // Fallthrough
4599 // Expand this to (OLT | OGE).
4603 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4604 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4608 // Integer comparisons.
4609 switch (SetCCOpcode) {
4610 default: llvm_unreachable("Illegal integer comparison");
4611 case ISD::SETNE: Invert = true;
4612 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4613 case ISD::SETLT: Swap = true;
4614 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4615 case ISD::SETLE: Swap = true;
4616 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4617 case ISD::SETULT: Swap = true;
4618 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4619 case ISD::SETULE: Swap = true;
4620 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4623 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4624 if (Opc == ARMISD::VCEQ) {
4627 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4629 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4632 // Ignore bitconvert.
4633 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4634 AndOp = AndOp.getOperand(0);
4636 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4638 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4639 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4646 std::swap(Op0, Op1);
4648 // If one of the operands is a constant vector zero, attempt to fold the
4649 // comparison to a specialized compare-against-zero form.
4651 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4653 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4654 if (Opc == ARMISD::VCGE)
4655 Opc = ARMISD::VCLEZ;
4656 else if (Opc == ARMISD::VCGT)
4657 Opc = ARMISD::VCLTZ;
4662 if (SingleOp.getNode()) {
4665 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4667 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4669 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4671 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4673 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4675 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4678 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4681 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4684 Result = DAG.getNOT(dl, Result, VT);
4689 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4690 /// valid vector constant for a NEON instruction with a "modified immediate"
4691 /// operand (e.g., VMOV). If so, return the encoded value.
4692 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4693 unsigned SplatBitSize, SelectionDAG &DAG,
4694 SDLoc dl, EVT &VT, bool is128Bits,
4695 NEONModImmType type) {
4696 unsigned OpCmode, Imm;
4698 // SplatBitSize is set to the smallest size that splats the vector, so a
4699 // zero vector will always have SplatBitSize == 8. However, NEON modified
4700 // immediate instructions others than VMOV do not support the 8-bit encoding
4701 // of a zero vector, and the default encoding of zero is supposed to be the
4706 switch (SplatBitSize) {
4708 if (type != VMOVModImm)
4710 // Any 1-byte value is OK. Op=0, Cmode=1110.
4711 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4714 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4718 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4719 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4720 if ((SplatBits & ~0xff) == 0) {
4721 // Value = 0x00nn: Op=x, Cmode=100x.
4726 if ((SplatBits & ~0xff00) == 0) {
4727 // Value = 0xnn00: Op=x, Cmode=101x.
4729 Imm = SplatBits >> 8;
4735 // NEON's 32-bit VMOV supports splat values where:
4736 // * only one byte is nonzero, or
4737 // * the least significant byte is 0xff and the second byte is nonzero, or
4738 // * the least significant 2 bytes are 0xff and the third is nonzero.
4739 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4740 if ((SplatBits & ~0xff) == 0) {
4741 // Value = 0x000000nn: Op=x, Cmode=000x.
4746 if ((SplatBits & ~0xff00) == 0) {
4747 // Value = 0x0000nn00: Op=x, Cmode=001x.
4749 Imm = SplatBits >> 8;
4752 if ((SplatBits & ~0xff0000) == 0) {
4753 // Value = 0x00nn0000: Op=x, Cmode=010x.
4755 Imm = SplatBits >> 16;
4758 if ((SplatBits & ~0xff000000) == 0) {
4759 // Value = 0xnn000000: Op=x, Cmode=011x.
4761 Imm = SplatBits >> 24;
4765 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4766 if (type == OtherModImm) return SDValue();
4768 if ((SplatBits & ~0xffff) == 0 &&
4769 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4770 // Value = 0x0000nnff: Op=x, Cmode=1100.
4772 Imm = SplatBits >> 8;
4776 if ((SplatBits & ~0xffffff) == 0 &&
4777 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4778 // Value = 0x00nnffff: Op=x, Cmode=1101.
4780 Imm = SplatBits >> 16;
4784 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4785 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4786 // VMOV.I32. A (very) minor optimization would be to replicate the value
4787 // and fall through here to test for a valid 64-bit splat. But, then the
4788 // caller would also need to check and handle the change in size.
4792 if (type != VMOVModImm)
4794 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4795 uint64_t BitMask = 0xff;
4797 unsigned ImmMask = 1;
4799 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4800 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4803 } else if ((SplatBits & BitMask) != 0) {
4810 if (DAG.getDataLayout().isBigEndian())
4811 // swap higher and lower 32 bit word
4812 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4814 // Op=1, Cmode=1110.
4816 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4821 llvm_unreachable("unexpected size for isNEONModifiedImm");
4824 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4825 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4828 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4829 const ARMSubtarget *ST) const {
4833 bool IsDouble = Op.getValueType() == MVT::f64;
4834 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4836 // Use the default (constant pool) lowering for double constants when we have
4838 if (IsDouble && Subtarget->isFPOnlySP())
4841 // Try splatting with a VMOV.f32...
4842 APFloat FPVal = CFP->getValueAPF();
4843 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4846 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4847 // We have code in place to select a valid ConstantFP already, no need to
4852 // It's a float and we are trying to use NEON operations where
4853 // possible. Lower it to a splat followed by an extract.
4855 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4856 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4858 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4859 DAG.getConstant(0, DL, MVT::i32));
4862 // The rest of our options are NEON only, make sure that's allowed before
4864 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4868 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4870 // It wouldn't really be worth bothering for doubles except for one very
4871 // important value, which does happen to match: 0.0. So make sure we don't do
4873 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4876 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4877 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4878 VMovVT, false, VMOVModImm);
4879 if (NewVal != SDValue()) {
4881 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4884 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4886 // It's a float: cast and extract a vector element.
4887 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4889 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4890 DAG.getConstant(0, DL, MVT::i32));
4893 // Finally, try a VMVN.i32
4894 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4896 if (NewVal != SDValue()) {
4898 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4901 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4903 // It's a float: cast and extract a vector element.
4904 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4906 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4907 DAG.getConstant(0, DL, MVT::i32));
4913 // check if an VEXT instruction can handle the shuffle mask when the
4914 // vector sources of the shuffle are the same.
4915 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4916 unsigned NumElts = VT.getVectorNumElements();
4918 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4924 // If this is a VEXT shuffle, the immediate value is the index of the first
4925 // element. The other shuffle indices must be the successive elements after
4927 unsigned ExpectedElt = Imm;
4928 for (unsigned i = 1; i < NumElts; ++i) {
4929 // Increment the expected index. If it wraps around, just follow it
4930 // back to index zero and keep going.
4932 if (ExpectedElt == NumElts)
4935 if (M[i] < 0) continue; // ignore UNDEF indices
4936 if (ExpectedElt != static_cast<unsigned>(M[i]))
4944 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4945 bool &ReverseVEXT, unsigned &Imm) {
4946 unsigned NumElts = VT.getVectorNumElements();
4947 ReverseVEXT = false;
4949 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4955 // If this is a VEXT shuffle, the immediate value is the index of the first
4956 // element. The other shuffle indices must be the successive elements after
4958 unsigned ExpectedElt = Imm;
4959 for (unsigned i = 1; i < NumElts; ++i) {
4960 // Increment the expected index. If it wraps around, it may still be
4961 // a VEXT but the source vectors must be swapped.
4963 if (ExpectedElt == NumElts * 2) {
4968 if (M[i] < 0) continue; // ignore UNDEF indices
4969 if (ExpectedElt != static_cast<unsigned>(M[i]))
4973 // Adjust the index value if the source operands will be swapped.
4980 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4981 /// instruction with the specified blocksize. (The order of the elements
4982 /// within each block of the vector is reversed.)
4983 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4984 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4985 "Only possible block sizes for VREV are: 16, 32, 64");
4987 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4991 unsigned NumElts = VT.getVectorNumElements();
4992 unsigned BlockElts = M[0] + 1;
4993 // If the first shuffle index is UNDEF, be optimistic.
4995 BlockElts = BlockSize / EltSz;
4997 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5000 for (unsigned i = 0; i < NumElts; ++i) {
5001 if (M[i] < 0) continue; // ignore UNDEF indices
5002 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5009 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5010 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5011 // range, then 0 is placed into the resulting vector. So pretty much any mask
5012 // of 8 elements can work here.
5013 return VT == MVT::v8i8 && M.size() == 8;
5016 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5017 // checking that pairs of elements in the shuffle mask represent the same index
5018 // in each vector, incrementing the expected index by 2 at each step.
5019 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5020 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5022 // WhichResult gives the offset for each element in the mask based on which
5023 // of the two results it belongs to.
5025 // The transpose can be represented either as:
5026 // result1 = shufflevector v1, v2, result1_shuffle_mask
5027 // result2 = shufflevector v1, v2, result2_shuffle_mask
5028 // where v1/v2 and the shuffle masks have the same number of elements
5029 // (here WhichResult (see below) indicates which result is being checked)
5032 // results = shufflevector v1, v2, shuffle_mask
5033 // where both results are returned in one vector and the shuffle mask has twice
5034 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5035 // want to check the low half and high half of the shuffle mask as if it were
5037 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5038 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5042 unsigned NumElts = VT.getVectorNumElements();
5043 if (M.size() != NumElts && M.size() != NumElts*2)
5046 // If the mask is twice as long as the result then we need to check the upper
5047 // and lower parts of the mask
5048 for (unsigned i = 0; i < M.size(); i += NumElts) {
5049 WhichResult = M[i] == 0 ? 0 : 1;
5050 for (unsigned j = 0; j < NumElts; j += 2) {
5051 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5052 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5057 if (M.size() == NumElts*2)
5063 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5064 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5065 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5066 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5067 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5071 unsigned NumElts = VT.getVectorNumElements();
5072 if (M.size() != NumElts && M.size() != NumElts*2)
5075 for (unsigned i = 0; i < M.size(); i += NumElts) {
5076 WhichResult = M[i] == 0 ? 0 : 1;
5077 for (unsigned j = 0; j < NumElts; j += 2) {
5078 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5079 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5084 if (M.size() == NumElts*2)
5090 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5091 // that the mask elements are either all even and in steps of size 2 or all odd
5092 // and in steps of size 2.
5093 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5094 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5096 // Requires similar checks to that of isVTRNMask with
5097 // respect the how results are returned.
5098 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5099 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5103 unsigned NumElts = VT.getVectorNumElements();
5104 if (M.size() != NumElts && M.size() != NumElts*2)
5107 for (unsigned i = 0; i < M.size(); i += NumElts) {
5108 WhichResult = M[i] == 0 ? 0 : 1;
5109 for (unsigned j = 0; j < NumElts; ++j) {
5110 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5115 if (M.size() == NumElts*2)
5118 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5119 if (VT.is64BitVector() && EltSz == 32)
5125 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5126 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5127 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5128 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5129 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5133 unsigned NumElts = VT.getVectorNumElements();
5134 if (M.size() != NumElts && M.size() != NumElts*2)
5137 unsigned Half = NumElts / 2;
5138 for (unsigned i = 0; i < M.size(); i += NumElts) {
5139 WhichResult = M[i] == 0 ? 0 : 1;
5140 for (unsigned j = 0; j < NumElts; j += Half) {
5141 unsigned Idx = WhichResult;
5142 for (unsigned k = 0; k < Half; ++k) {
5143 int MIdx = M[i + j + k];
5144 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5151 if (M.size() == NumElts*2)
5154 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5155 if (VT.is64BitVector() && EltSz == 32)
5161 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5162 // that pairs of elements of the shufflemask represent the same index in each
5163 // vector incrementing sequentially through the vectors.
5164 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5165 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5167 // Requires similar checks to that of isVTRNMask with respect the how results
5169 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5170 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5174 unsigned NumElts = VT.getVectorNumElements();
5175 if (M.size() != NumElts && M.size() != NumElts*2)
5178 for (unsigned i = 0; i < M.size(); i += NumElts) {
5179 WhichResult = M[i] == 0 ? 0 : 1;
5180 unsigned Idx = WhichResult * NumElts / 2;
5181 for (unsigned j = 0; j < NumElts; j += 2) {
5182 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5183 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5189 if (M.size() == NumElts*2)
5192 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5193 if (VT.is64BitVector() && EltSz == 32)
5199 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5200 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5201 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5202 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5203 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5207 unsigned NumElts = VT.getVectorNumElements();
5208 if (M.size() != NumElts && M.size() != NumElts*2)
5211 for (unsigned i = 0; i < M.size(); i += NumElts) {
5212 WhichResult = M[i] == 0 ? 0 : 1;
5213 unsigned Idx = WhichResult * NumElts / 2;
5214 for (unsigned j = 0; j < NumElts; j += 2) {
5215 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5216 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5222 if (M.size() == NumElts*2)
5225 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5226 if (VT.is64BitVector() && EltSz == 32)
5232 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5233 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5234 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5235 unsigned &WhichResult,
5238 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5239 return ARMISD::VTRN;
5240 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5241 return ARMISD::VUZP;
5242 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5243 return ARMISD::VZIP;
5246 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5247 return ARMISD::VTRN;
5248 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5249 return ARMISD::VUZP;
5250 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5251 return ARMISD::VZIP;
5256 /// \return true if this is a reverse operation on an vector.
5257 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5258 unsigned NumElts = VT.getVectorNumElements();
5259 // Make sure the mask has the right size.
5260 if (NumElts != M.size())
5263 // Look for <15, ..., 3, -1, 1, 0>.
5264 for (unsigned i = 0; i != NumElts; ++i)
5265 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5271 // If N is an integer constant that can be moved into a register in one
5272 // instruction, return an SDValue of such a constant (will become a MOV
5273 // instruction). Otherwise return null.
5274 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5275 const ARMSubtarget *ST, SDLoc dl) {
5277 if (!isa<ConstantSDNode>(N))
5279 Val = cast<ConstantSDNode>(N)->getZExtValue();
5281 if (ST->isThumb1Only()) {
5282 if (Val <= 255 || ~Val <= 255)
5283 return DAG.getConstant(Val, dl, MVT::i32);
5285 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5286 return DAG.getConstant(Val, dl, MVT::i32);
5291 // If this is a case we can't handle, return null and let the default
5292 // expansion code take care of it.
5293 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5294 const ARMSubtarget *ST) const {
5295 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5297 EVT VT = Op.getValueType();
5299 APInt SplatBits, SplatUndef;
5300 unsigned SplatBitSize;
5302 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5303 if (SplatBitSize <= 64) {
5304 // Check if an immediate VMOV works.
5306 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5307 SplatUndef.getZExtValue(), SplatBitSize,
5308 DAG, dl, VmovVT, VT.is128BitVector(),
5310 if (Val.getNode()) {
5311 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5312 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5315 // Try an immediate VMVN.
5316 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5317 Val = isNEONModifiedImm(NegatedImm,
5318 SplatUndef.getZExtValue(), SplatBitSize,
5319 DAG, dl, VmovVT, VT.is128BitVector(),
5321 if (Val.getNode()) {
5322 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5323 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5326 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5327 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5328 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5330 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5331 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5337 // Scan through the operands to see if only one value is used.
5339 // As an optimisation, even if more than one value is used it may be more
5340 // profitable to splat with one value then change some lanes.
5342 // Heuristically we decide to do this if the vector has a "dominant" value,
5343 // defined as splatted to more than half of the lanes.
5344 unsigned NumElts = VT.getVectorNumElements();
5345 bool isOnlyLowElement = true;
5346 bool usesOnlyOneValue = true;
5347 bool hasDominantValue = false;
5348 bool isConstant = true;
5350 // Map of the number of times a particular SDValue appears in the
5352 DenseMap<SDValue, unsigned> ValueCounts;
5354 for (unsigned i = 0; i < NumElts; ++i) {
5355 SDValue V = Op.getOperand(i);
5356 if (V.getOpcode() == ISD::UNDEF)
5359 isOnlyLowElement = false;
5360 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5363 ValueCounts.insert(std::make_pair(V, 0));
5364 unsigned &Count = ValueCounts[V];
5366 // Is this value dominant? (takes up more than half of the lanes)
5367 if (++Count > (NumElts / 2)) {
5368 hasDominantValue = true;
5372 if (ValueCounts.size() != 1)
5373 usesOnlyOneValue = false;
5374 if (!Value.getNode() && ValueCounts.size() > 0)
5375 Value = ValueCounts.begin()->first;
5377 if (ValueCounts.size() == 0)
5378 return DAG.getUNDEF(VT);
5380 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5381 // Keep going if we are hitting this case.
5382 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5383 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5385 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5387 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5388 // i32 and try again.
5389 if (hasDominantValue && EltSize <= 32) {
5393 // If we are VDUPing a value that comes directly from a vector, that will
5394 // cause an unnecessary move to and from a GPR, where instead we could
5395 // just use VDUPLANE. We can only do this if the lane being extracted
5396 // is at a constant index, as the VDUP from lane instructions only have
5397 // constant-index forms.
5398 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5399 isa<ConstantSDNode>(Value->getOperand(1))) {
5400 // We need to create a new undef vector to use for the VDUPLANE if the
5401 // size of the vector from which we get the value is different than the
5402 // size of the vector that we need to create. We will insert the element
5403 // such that the register coalescer will remove unnecessary copies.
5404 if (VT != Value->getOperand(0).getValueType()) {
5405 ConstantSDNode *constIndex;
5406 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5407 assert(constIndex && "The index is not a constant!");
5408 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5409 VT.getVectorNumElements();
5410 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5411 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5412 Value, DAG.getConstant(index, dl, MVT::i32)),
5413 DAG.getConstant(index, dl, MVT::i32));
5415 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5416 Value->getOperand(0), Value->getOperand(1));
5418 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5420 if (!usesOnlyOneValue) {
5421 // The dominant value was splatted as 'N', but we now have to insert
5422 // all differing elements.
5423 for (unsigned I = 0; I < NumElts; ++I) {
5424 if (Op.getOperand(I) == Value)
5426 SmallVector<SDValue, 3> Ops;
5428 Ops.push_back(Op.getOperand(I));
5429 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5430 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5435 if (VT.getVectorElementType().isFloatingPoint()) {
5436 SmallVector<SDValue, 8> Ops;
5437 for (unsigned i = 0; i < NumElts; ++i)
5438 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5440 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5441 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5442 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5444 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5446 if (usesOnlyOneValue) {
5447 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5448 if (isConstant && Val.getNode())
5449 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5453 // If all elements are constants and the case above didn't get hit, fall back
5454 // to the default expansion, which will generate a load from the constant
5459 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5461 SDValue shuffle = ReconstructShuffle(Op, DAG);
5462 if (shuffle != SDValue())
5466 // Vectors with 32- or 64-bit elements can be built by directly assigning
5467 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5468 // will be legalized.
5469 if (EltSize >= 32) {
5470 // Do the expansion with floating-point types, since that is what the VFP
5471 // registers are defined to use, and since i64 is not legal.
5472 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5473 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5474 SmallVector<SDValue, 8> Ops;
5475 for (unsigned i = 0; i < NumElts; ++i)
5476 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5477 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5478 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5481 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5482 // know the default expansion would otherwise fall back on something even
5483 // worse. For a vector with one or two non-undef values, that's
5484 // scalar_to_vector for the elements followed by a shuffle (provided the
5485 // shuffle is valid for the target) and materialization element by element
5486 // on the stack followed by a load for everything else.
5487 if (!isConstant && !usesOnlyOneValue) {
5488 SDValue Vec = DAG.getUNDEF(VT);
5489 for (unsigned i = 0 ; i < NumElts; ++i) {
5490 SDValue V = Op.getOperand(i);
5491 if (V.getOpcode() == ISD::UNDEF)
5493 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5494 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5502 /// getExtFactor - Determine the adjustment factor for the position when
5503 /// generating an "extract from vector registers" instruction.
5504 static unsigned getExtFactor(SDValue &V) {
5505 EVT EltType = V.getValueType().getVectorElementType();
5506 return EltType.getSizeInBits() / 8;
5509 // Gather data to see if the operation can be modelled as a
5510 // shuffle in combination with VEXTs.
5511 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5512 SelectionDAG &DAG) const {
5513 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5515 EVT VT = Op.getValueType();
5516 unsigned NumElts = VT.getVectorNumElements();
5518 struct ShuffleSourceInfo {
5523 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5524 // be compatible with the shuffle we intend to construct. As a result
5525 // ShuffleVec will be some sliding window into the original Vec.
5528 // Code should guarantee that element i in Vec starts at element "WindowBase
5529 // + i * WindowScale in ShuffleVec".
5533 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5534 ShuffleSourceInfo(SDValue Vec)
5535 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5539 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5541 SmallVector<ShuffleSourceInfo, 2> Sources;
5542 for (unsigned i = 0; i < NumElts; ++i) {
5543 SDValue V = Op.getOperand(i);
5544 if (V.getOpcode() == ISD::UNDEF)
5546 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5547 // A shuffle can only come from building a vector from various
5548 // elements of other vectors.
5552 // Add this element source to the list if it's not already there.
5553 SDValue SourceVec = V.getOperand(0);
5554 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5555 if (Source == Sources.end())
5556 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5558 // Update the minimum and maximum lane number seen.
5559 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5560 Source->MinElt = std::min(Source->MinElt, EltNo);
5561 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5564 // Currently only do something sane when at most two source vectors
5566 if (Sources.size() > 2)
5569 // Find out the smallest element size among result and two sources, and use
5570 // it as element size to build the shuffle_vector.
5571 EVT SmallestEltTy = VT.getVectorElementType();
5572 for (auto &Source : Sources) {
5573 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5574 if (SrcEltTy.bitsLT(SmallestEltTy))
5575 SmallestEltTy = SrcEltTy;
5577 unsigned ResMultiplier =
5578 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5579 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5580 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5582 // If the source vector is too wide or too narrow, we may nevertheless be able
5583 // to construct a compatible shuffle either by concatenating it with UNDEF or
5584 // extracting a suitable range of elements.
5585 for (auto &Src : Sources) {
5586 EVT SrcVT = Src.ShuffleVec.getValueType();
5588 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5591 // This stage of the search produces a source with the same element type as
5592 // the original, but with a total width matching the BUILD_VECTOR output.
5593 EVT EltVT = SrcVT.getVectorElementType();
5594 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5595 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5597 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5598 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5600 // We can pad out the smaller vector for free, so if it's part of a
5603 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5604 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5608 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5611 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5612 // Span too large for a VEXT to cope
5616 if (Src.MinElt >= NumSrcElts) {
5617 // The extraction can just take the second half
5619 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5620 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5621 Src.WindowBase = -NumSrcElts;
5622 } else if (Src.MaxElt < NumSrcElts) {
5623 // The extraction can just take the first half
5625 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5626 DAG.getConstant(0, dl, MVT::i32));
5628 // An actual VEXT is needed
5630 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5631 DAG.getConstant(0, dl, MVT::i32));
5633 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5634 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5635 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5637 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5639 DAG.getConstant(Imm, dl, MVT::i32));
5640 Src.WindowBase = -Src.MinElt;
5644 // Another possible incompatibility occurs from the vector element types. We
5645 // can fix this by bitcasting the source vectors to the same type we intend
5647 for (auto &Src : Sources) {
5648 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5649 if (SrcEltTy == SmallestEltTy)
5651 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5652 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5653 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5654 Src.WindowBase *= Src.WindowScale;
5657 // Final sanity check before we try to actually produce a shuffle.
5659 for (auto Src : Sources)
5660 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5663 // The stars all align, our next step is to produce the mask for the shuffle.
5664 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5665 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5666 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5667 SDValue Entry = Op.getOperand(i);
5668 if (Entry.getOpcode() == ISD::UNDEF)
5671 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5672 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5674 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5675 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5677 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5678 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5679 VT.getVectorElementType().getSizeInBits());
5680 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5682 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5683 // starting at the appropriate offset.
5684 int *LaneMask = &Mask[i * ResMultiplier];
5686 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5687 ExtractBase += NumElts * (Src - Sources.begin());
5688 for (int j = 0; j < LanesDefined; ++j)
5689 LaneMask[j] = ExtractBase + j;
5692 // Final check before we try to produce nonsense...
5693 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5696 // We can't handle more than two sources. This should have already
5697 // been checked before this point.
5698 assert(Sources.size() <= 2 && "Too many sources!");
5700 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5701 for (unsigned i = 0; i < Sources.size(); ++i)
5702 ShuffleOps[i] = Sources[i].ShuffleVec;
5704 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5705 ShuffleOps[1], &Mask[0]);
5706 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5709 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5710 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5711 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5712 /// are assumed to be legal.
5714 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5716 if (VT.getVectorNumElements() == 4 &&
5717 (VT.is128BitVector() || VT.is64BitVector())) {
5718 unsigned PFIndexes[4];
5719 for (unsigned i = 0; i != 4; ++i) {
5723 PFIndexes[i] = M[i];
5726 // Compute the index in the perfect shuffle table.
5727 unsigned PFTableIndex =
5728 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5729 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5730 unsigned Cost = (PFEntry >> 30);
5736 bool ReverseVEXT, isV_UNDEF;
5737 unsigned Imm, WhichResult;
5739 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5740 return (EltSize >= 32 ||
5741 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5742 isVREVMask(M, VT, 64) ||
5743 isVREVMask(M, VT, 32) ||
5744 isVREVMask(M, VT, 16) ||
5745 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5746 isVTBLMask(M, VT) ||
5747 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5748 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5751 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5752 /// the specified operations to build the shuffle.
5753 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5754 SDValue RHS, SelectionDAG &DAG,
5756 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5757 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5758 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5761 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5770 OP_VUZPL, // VUZP, left result
5771 OP_VUZPR, // VUZP, right result
5772 OP_VZIPL, // VZIP, left result
5773 OP_VZIPR, // VZIP, right result
5774 OP_VTRNL, // VTRN, left result
5775 OP_VTRNR // VTRN, right result
5778 if (OpNum == OP_COPY) {
5779 if (LHSID == (1*9+2)*9+3) return LHS;
5780 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5784 SDValue OpLHS, OpRHS;
5785 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5786 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5787 EVT VT = OpLHS.getValueType();
5790 default: llvm_unreachable("Unknown shuffle opcode!");
5792 // VREV divides the vector in half and swaps within the half.
5793 if (VT.getVectorElementType() == MVT::i32 ||
5794 VT.getVectorElementType() == MVT::f32)
5795 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5796 // vrev <4 x i16> -> VREV32
5797 if (VT.getVectorElementType() == MVT::i16)
5798 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5799 // vrev <4 x i8> -> VREV16
5800 assert(VT.getVectorElementType() == MVT::i8);
5801 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5806 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5807 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5811 return DAG.getNode(ARMISD::VEXT, dl, VT,
5813 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5816 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5817 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5820 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5821 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5824 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5825 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5829 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5830 ArrayRef<int> ShuffleMask,
5831 SelectionDAG &DAG) {
5832 // Check to see if we can use the VTBL instruction.
5833 SDValue V1 = Op.getOperand(0);
5834 SDValue V2 = Op.getOperand(1);
5837 SmallVector<SDValue, 8> VTBLMask;
5838 for (ArrayRef<int>::iterator
5839 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5840 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5842 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5843 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5844 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5846 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5847 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5850 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5851 SelectionDAG &DAG) {
5853 SDValue OpLHS = Op.getOperand(0);
5854 EVT VT = OpLHS.getValueType();
5856 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5857 "Expect an v8i16/v16i8 type");
5858 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5859 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5860 // extract the first 8 bytes into the top double word and the last 8 bytes
5861 // into the bottom double word. The v8i16 case is similar.
5862 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5863 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5864 DAG.getConstant(ExtractNum, DL, MVT::i32));
5867 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5868 SDValue V1 = Op.getOperand(0);
5869 SDValue V2 = Op.getOperand(1);
5871 EVT VT = Op.getValueType();
5872 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5874 // Convert shuffles that are directly supported on NEON to target-specific
5875 // DAG nodes, instead of keeping them as shuffles and matching them again
5876 // during code selection. This is more efficient and avoids the possibility
5877 // of inconsistencies between legalization and selection.
5878 // FIXME: floating-point vectors should be canonicalized to integer vectors
5879 // of the same time so that they get CSEd properly.
5880 ArrayRef<int> ShuffleMask = SVN->getMask();
5882 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5883 if (EltSize <= 32) {
5884 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5885 int Lane = SVN->getSplatIndex();
5886 // If this is undef splat, generate it via "just" vdup, if possible.
5887 if (Lane == -1) Lane = 0;
5889 // Test if V1 is a SCALAR_TO_VECTOR.
5890 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5891 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5893 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5894 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5896 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5897 !isa<ConstantSDNode>(V1.getOperand(0))) {
5898 bool IsScalarToVector = true;
5899 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5900 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5901 IsScalarToVector = false;
5904 if (IsScalarToVector)
5905 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5907 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5908 DAG.getConstant(Lane, dl, MVT::i32));
5913 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5916 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5917 DAG.getConstant(Imm, dl, MVT::i32));
5920 if (isVREVMask(ShuffleMask, VT, 64))
5921 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5922 if (isVREVMask(ShuffleMask, VT, 32))
5923 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5924 if (isVREVMask(ShuffleMask, VT, 16))
5925 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5927 if (V2->getOpcode() == ISD::UNDEF &&
5928 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5929 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5930 DAG.getConstant(Imm, dl, MVT::i32));
5933 // Check for Neon shuffles that modify both input vectors in place.
5934 // If both results are used, i.e., if there are two shuffles with the same
5935 // source operands and with masks corresponding to both results of one of
5936 // these operations, DAG memoization will ensure that a single node is
5937 // used for both shuffles.
5938 unsigned WhichResult;
5940 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5941 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5944 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5945 .getValue(WhichResult);
5948 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5949 // shuffles that produce a result larger than their operands with:
5950 // shuffle(concat(v1, undef), concat(v2, undef))
5952 // shuffle(concat(v1, v2), undef)
5953 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5955 // This is useful in the general case, but there are special cases where
5956 // native shuffles produce larger results: the two-result ops.
5958 // Look through the concat when lowering them:
5959 // shuffle(concat(v1, v2), undef)
5961 // concat(VZIP(v1, v2):0, :1)
5963 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5964 V2->getOpcode() == ISD::UNDEF) {
5965 SDValue SubV1 = V1->getOperand(0);
5966 SDValue SubV2 = V1->getOperand(1);
5967 EVT SubVT = SubV1.getValueType();
5969 // We expect these to have been canonicalized to -1.
5970 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5971 return i < (int)VT.getVectorNumElements();
5972 }) && "Unexpected shuffle index into UNDEF operand!");
5974 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5975 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5978 assert((WhichResult == 0) &&
5979 "In-place shuffle of concat can only have one result!");
5980 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5982 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5988 // If the shuffle is not directly supported and it has 4 elements, use
5989 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5990 unsigned NumElts = VT.getVectorNumElements();
5992 unsigned PFIndexes[4];
5993 for (unsigned i = 0; i != 4; ++i) {
5994 if (ShuffleMask[i] < 0)
5997 PFIndexes[i] = ShuffleMask[i];
6000 // Compute the index in the perfect shuffle table.
6001 unsigned PFTableIndex =
6002 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6003 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6004 unsigned Cost = (PFEntry >> 30);
6007 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6010 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6011 if (EltSize >= 32) {
6012 // Do the expansion with floating-point types, since that is what the VFP
6013 // registers are defined to use, and since i64 is not legal.
6014 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6015 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6016 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6017 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6018 SmallVector<SDValue, 8> Ops;
6019 for (unsigned i = 0; i < NumElts; ++i) {
6020 if (ShuffleMask[i] < 0)
6021 Ops.push_back(DAG.getUNDEF(EltVT));
6023 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6024 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6025 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6028 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6029 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6032 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6033 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6035 if (VT == MVT::v8i8) {
6036 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6037 if (NewOp.getNode())
6044 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6045 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6046 SDValue Lane = Op.getOperand(2);
6047 if (!isa<ConstantSDNode>(Lane))
6053 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6054 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6055 SDValue Lane = Op.getOperand(1);
6056 if (!isa<ConstantSDNode>(Lane))
6059 SDValue Vec = Op.getOperand(0);
6060 if (Op.getValueType() == MVT::i32 &&
6061 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6063 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6069 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6070 // The only time a CONCAT_VECTORS operation can have legal types is when
6071 // two 64-bit vectors are concatenated to a 128-bit vector.
6072 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6073 "unexpected CONCAT_VECTORS");
6075 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6076 SDValue Op0 = Op.getOperand(0);
6077 SDValue Op1 = Op.getOperand(1);
6078 if (Op0.getOpcode() != ISD::UNDEF)
6079 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6080 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6081 DAG.getIntPtrConstant(0, dl));
6082 if (Op1.getOpcode() != ISD::UNDEF)
6083 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6084 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6085 DAG.getIntPtrConstant(1, dl));
6086 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6089 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6090 /// element has been zero/sign-extended, depending on the isSigned parameter,
6091 /// from an integer type half its size.
6092 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6094 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6095 EVT VT = N->getValueType(0);
6096 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6097 SDNode *BVN = N->getOperand(0).getNode();
6098 if (BVN->getValueType(0) != MVT::v4i32 ||
6099 BVN->getOpcode() != ISD::BUILD_VECTOR)
6101 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6102 unsigned HiElt = 1 - LoElt;
6103 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6104 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6105 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6106 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6107 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6110 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6111 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6114 if (Hi0->isNullValue() && Hi1->isNullValue())
6120 if (N->getOpcode() != ISD::BUILD_VECTOR)
6123 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6124 SDNode *Elt = N->getOperand(i).getNode();
6125 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6126 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6127 unsigned HalfSize = EltSize / 2;
6129 if (!isIntN(HalfSize, C->getSExtValue()))
6132 if (!isUIntN(HalfSize, C->getZExtValue()))
6143 /// isSignExtended - Check if a node is a vector value that is sign-extended
6144 /// or a constant BUILD_VECTOR with sign-extended elements.
6145 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6146 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6148 if (isExtendedBUILD_VECTOR(N, DAG, true))
6153 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6154 /// or a constant BUILD_VECTOR with zero-extended elements.
6155 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6156 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6158 if (isExtendedBUILD_VECTOR(N, DAG, false))
6163 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6164 if (OrigVT.getSizeInBits() >= 64)
6167 assert(OrigVT.isSimple() && "Expecting a simple value type");
6169 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6170 switch (OrigSimpleTy) {
6171 default: llvm_unreachable("Unexpected Vector Type");
6180 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6181 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6182 /// We insert the required extension here to get the vector to fill a D register.
6183 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6186 unsigned ExtOpcode) {
6187 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6188 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6189 // 64-bits we need to insert a new extension so that it will be 64-bits.
6190 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6191 if (OrigTy.getSizeInBits() >= 64)
6194 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6195 EVT NewVT = getExtensionTo64Bits(OrigTy);
6197 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6200 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6201 /// does not do any sign/zero extension. If the original vector is less
6202 /// than 64 bits, an appropriate extension will be added after the load to
6203 /// reach a total size of 64 bits. We have to add the extension separately
6204 /// because ARM does not have a sign/zero extending load for vectors.
6205 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6206 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6208 // The load already has the right type.
6209 if (ExtendedTy == LD->getMemoryVT())
6210 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6211 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6212 LD->isNonTemporal(), LD->isInvariant(),
6213 LD->getAlignment());
6215 // We need to create a zextload/sextload. We cannot just create a load
6216 // followed by a zext/zext node because LowerMUL is also run during normal
6217 // operation legalization where we can't create illegal types.
6218 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6219 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6220 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6221 LD->isNonTemporal(), LD->getAlignment());
6224 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6225 /// extending load, or BUILD_VECTOR with extended elements, return the
6226 /// unextended value. The unextended vector should be 64 bits so that it can
6227 /// be used as an operand to a VMULL instruction. If the original vector size
6228 /// before extension is less than 64 bits we add a an extension to resize
6229 /// the vector to 64 bits.
6230 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6231 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6232 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6233 N->getOperand(0)->getValueType(0),
6237 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6238 return SkipLoadExtensionForVMULL(LD, DAG);
6240 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6241 // have been legalized as a BITCAST from v4i32.
6242 if (N->getOpcode() == ISD::BITCAST) {
6243 SDNode *BVN = N->getOperand(0).getNode();
6244 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6245 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6246 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6247 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6248 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6250 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6251 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6252 EVT VT = N->getValueType(0);
6253 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6254 unsigned NumElts = VT.getVectorNumElements();
6255 MVT TruncVT = MVT::getIntegerVT(EltSize);
6256 SmallVector<SDValue, 8> Ops;
6258 for (unsigned i = 0; i != NumElts; ++i) {
6259 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6260 const APInt &CInt = C->getAPIntValue();
6261 // Element types smaller than 32 bits are not legal, so use i32 elements.
6262 // The values are implicitly truncated so sext vs. zext doesn't matter.
6263 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6265 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6266 MVT::getVectorVT(TruncVT, NumElts), Ops);
6269 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6270 unsigned Opcode = N->getOpcode();
6271 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6272 SDNode *N0 = N->getOperand(0).getNode();
6273 SDNode *N1 = N->getOperand(1).getNode();
6274 return N0->hasOneUse() && N1->hasOneUse() &&
6275 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6280 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6281 unsigned Opcode = N->getOpcode();
6282 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6283 SDNode *N0 = N->getOperand(0).getNode();
6284 SDNode *N1 = N->getOperand(1).getNode();
6285 return N0->hasOneUse() && N1->hasOneUse() &&
6286 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6291 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6292 // Multiplications are only custom-lowered for 128-bit vectors so that
6293 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6294 EVT VT = Op.getValueType();
6295 assert(VT.is128BitVector() && VT.isInteger() &&
6296 "unexpected type for custom-lowering ISD::MUL");
6297 SDNode *N0 = Op.getOperand(0).getNode();
6298 SDNode *N1 = Op.getOperand(1).getNode();
6299 unsigned NewOpc = 0;
6301 bool isN0SExt = isSignExtended(N0, DAG);
6302 bool isN1SExt = isSignExtended(N1, DAG);
6303 if (isN0SExt && isN1SExt)
6304 NewOpc = ARMISD::VMULLs;
6306 bool isN0ZExt = isZeroExtended(N0, DAG);
6307 bool isN1ZExt = isZeroExtended(N1, DAG);
6308 if (isN0ZExt && isN1ZExt)
6309 NewOpc = ARMISD::VMULLu;
6310 else if (isN1SExt || isN1ZExt) {
6311 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6312 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6313 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6314 NewOpc = ARMISD::VMULLs;
6316 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6317 NewOpc = ARMISD::VMULLu;
6319 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6321 NewOpc = ARMISD::VMULLu;
6327 if (VT == MVT::v2i64)
6328 // Fall through to expand this. It is not legal.
6331 // Other vector multiplications are legal.
6336 // Legalize to a VMULL instruction.
6339 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6341 Op0 = SkipExtensionForVMULL(N0, DAG);
6342 assert(Op0.getValueType().is64BitVector() &&
6343 Op1.getValueType().is64BitVector() &&
6344 "unexpected types for extended operands to VMULL");
6345 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6348 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6349 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6356 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6357 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6358 EVT Op1VT = Op1.getValueType();
6359 return DAG.getNode(N0->getOpcode(), DL, VT,
6360 DAG.getNode(NewOpc, DL, VT,
6361 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6362 DAG.getNode(NewOpc, DL, VT,
6363 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6367 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6369 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6370 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6371 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6372 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6373 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6374 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6375 // Get reciprocal estimate.
6376 // float4 recip = vrecpeq_f32(yf);
6377 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6378 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6380 // Because char has a smaller range than uchar, we can actually get away
6381 // without any newton steps. This requires that we use a weird bias
6382 // of 0xb000, however (again, this has been exhaustively tested).
6383 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6384 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6385 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6386 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6387 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6388 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6389 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6390 // Convert back to short.
6391 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6392 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6397 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6399 // Convert to float.
6400 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6401 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6402 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6403 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6404 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6405 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6407 // Use reciprocal estimate and one refinement step.
6408 // float4 recip = vrecpeq_f32(yf);
6409 // recip *= vrecpsq_f32(yf, recip);
6410 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6411 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6413 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6414 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6416 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6417 // Because short has a smaller range than ushort, we can actually get away
6418 // with only a single newton step. This requires that we use a weird bias
6419 // of 89, however (again, this has been exhaustively tested).
6420 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6421 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6422 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6423 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6424 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6425 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6426 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6427 // Convert back to integer and return.
6428 // return vmovn_s32(vcvt_s32_f32(result));
6429 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6430 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6434 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6435 EVT VT = Op.getValueType();
6436 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6437 "unexpected type for custom-lowering ISD::SDIV");
6440 SDValue N0 = Op.getOperand(0);
6441 SDValue N1 = Op.getOperand(1);
6444 if (VT == MVT::v8i8) {
6445 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6446 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6448 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6449 DAG.getIntPtrConstant(4, dl));
6450 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6451 DAG.getIntPtrConstant(4, dl));
6452 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6453 DAG.getIntPtrConstant(0, dl));
6454 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6455 DAG.getIntPtrConstant(0, dl));
6457 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6458 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6460 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6461 N0 = LowerCONCAT_VECTORS(N0, DAG);
6463 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6466 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6469 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6470 EVT VT = Op.getValueType();
6471 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6472 "unexpected type for custom-lowering ISD::UDIV");
6475 SDValue N0 = Op.getOperand(0);
6476 SDValue N1 = Op.getOperand(1);
6479 if (VT == MVT::v8i8) {
6480 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6481 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6483 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6484 DAG.getIntPtrConstant(4, dl));
6485 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6486 DAG.getIntPtrConstant(4, dl));
6487 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6488 DAG.getIntPtrConstant(0, dl));
6489 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6490 DAG.getIntPtrConstant(0, dl));
6492 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6493 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6495 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6496 N0 = LowerCONCAT_VECTORS(N0, DAG);
6498 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6499 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6505 // v4i16 sdiv ... Convert to float.
6506 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6507 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6508 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6509 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6510 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6511 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6513 // Use reciprocal estimate and two refinement steps.
6514 // float4 recip = vrecpeq_f32(yf);
6515 // recip *= vrecpsq_f32(yf, recip);
6516 // recip *= vrecpsq_f32(yf, recip);
6517 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6518 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6520 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6521 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6523 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6524 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6525 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6527 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6528 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6529 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6530 // and that it will never cause us to return an answer too large).
6531 // float4 result = as_float4(as_int4(xf*recip) + 2);
6532 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6533 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6534 N1 = DAG.getConstant(2, dl, MVT::i32);
6535 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6536 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6537 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6538 // Convert back to integer and return.
6539 // return vmovn_u32(vcvt_s32_f32(result));
6540 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6541 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6545 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6546 EVT VT = Op.getNode()->getValueType(0);
6547 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6550 bool ExtraOp = false;
6551 switch (Op.getOpcode()) {
6552 default: llvm_unreachable("Invalid code");
6553 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6554 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6555 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6556 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6560 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6562 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6563 Op.getOperand(1), Op.getOperand(2));
6566 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6567 assert(Subtarget->isTargetDarwin());
6569 // For iOS, we want to call an alternative entry point: __sincos_stret,
6570 // return values are passed via sret.
6572 SDValue Arg = Op.getOperand(0);
6573 EVT ArgVT = Arg.getValueType();
6574 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6575 auto PtrVT = getPointerTy(DAG.getDataLayout());
6577 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6579 // Pair of floats / doubles used to pass the result.
6580 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6582 // Create stack object for sret.
6583 auto &DL = DAG.getDataLayout();
6584 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6585 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6586 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6587 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6593 Entry.Ty = RetTy->getPointerTo();
6594 Entry.isSExt = false;
6595 Entry.isZExt = false;
6596 Entry.isSRet = true;
6597 Args.push_back(Entry);
6601 Entry.isSExt = false;
6602 Entry.isZExt = false;
6603 Args.push_back(Entry);
6605 const char *LibcallName = (ArgVT == MVT::f64)
6606 ? "__sincos_stret" : "__sincosf_stret";
6607 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6609 TargetLowering::CallLoweringInfo CLI(DAG);
6610 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6611 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6613 .setDiscardResult();
6615 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6617 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6618 MachinePointerInfo(), false, false, false, 0);
6620 // Address of cos field.
6621 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6622 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6623 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6624 MachinePointerInfo(), false, false, false, 0);
6626 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6627 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6628 LoadSin.getValue(0), LoadCos.getValue(0));
6631 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6632 // Monotonic load/store is legal for all targets
6633 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6636 // Acquire/Release load/store is not legal for targets without a
6637 // dmb or equivalent available.
6641 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6642 SmallVectorImpl<SDValue> &Results,
6644 const ARMSubtarget *Subtarget) {
6646 SDValue Cycles32, OutChain;
6648 if (Subtarget->hasPerfMon()) {
6649 // Under Power Management extensions, the cycle-count is:
6650 // mrc p15, #0, <Rt>, c9, c13, #0
6651 SDValue Ops[] = { N->getOperand(0), // Chain
6652 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6653 DAG.getConstant(15, DL, MVT::i32),
6654 DAG.getConstant(0, DL, MVT::i32),
6655 DAG.getConstant(9, DL, MVT::i32),
6656 DAG.getConstant(13, DL, MVT::i32),
6657 DAG.getConstant(0, DL, MVT::i32)
6660 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6661 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6662 OutChain = Cycles32.getValue(1);
6664 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6665 // there are older ARM CPUs that have implementation-specific ways of
6666 // obtaining this information (FIXME!).
6667 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6668 OutChain = DAG.getEntryNode();
6672 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6673 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6674 Results.push_back(Cycles64);
6675 Results.push_back(OutChain);
6678 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6679 switch (Op.getOpcode()) {
6680 default: llvm_unreachable("Don't know how to custom lower this!");
6681 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6682 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6683 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6684 case ISD::GlobalAddress:
6685 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6686 default: llvm_unreachable("unknown object format");
6688 return LowerGlobalAddressWindows(Op, DAG);
6690 return LowerGlobalAddressELF(Op, DAG);
6692 return LowerGlobalAddressDarwin(Op, DAG);
6694 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6695 case ISD::SELECT: return LowerSELECT(Op, DAG);
6696 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6697 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6698 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6699 case ISD::VASTART: return LowerVASTART(Op, DAG);
6700 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6701 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6702 case ISD::SINT_TO_FP:
6703 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6704 case ISD::FP_TO_SINT:
6705 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6706 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6707 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6708 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6709 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6710 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6711 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6712 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6713 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6715 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6718 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6719 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6720 case ISD::SRL_PARTS:
6721 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6723 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6724 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6725 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6726 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6727 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6728 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6729 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6730 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6731 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6732 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6733 case ISD::MUL: return LowerMUL(Op, DAG);
6734 case ISD::SDIV: return LowerSDIV(Op, DAG);
6735 case ISD::UDIV: return LowerUDIV(Op, DAG);
6739 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6744 return LowerXALUO(Op, DAG);
6745 case ISD::ATOMIC_LOAD:
6746 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6747 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6749 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6750 case ISD::DYNAMIC_STACKALLOC:
6751 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6752 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6753 llvm_unreachable("Don't know how to custom lower this!");
6754 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6755 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6759 /// ReplaceNodeResults - Replace the results of node with an illegal result
6760 /// type with new values built out of custom code.
6761 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6762 SmallVectorImpl<SDValue>&Results,
6763 SelectionDAG &DAG) const {
6765 switch (N->getOpcode()) {
6767 llvm_unreachable("Don't know how to custom expand this!");
6768 case ISD::READ_REGISTER:
6769 ExpandREAD_REGISTER(N, Results, DAG);
6772 Res = ExpandBITCAST(N, DAG);
6776 Res = Expand64BitShift(N, DAG, Subtarget);
6778 case ISD::READCYCLECOUNTER:
6779 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6783 Results.push_back(Res);
6786 //===----------------------------------------------------------------------===//
6787 // ARM Scheduler Hooks
6788 //===----------------------------------------------------------------------===//
6790 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6791 /// registers the function context.
6792 void ARMTargetLowering::
6793 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6794 MachineBasicBlock *DispatchBB, int FI) const {
6795 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6796 DebugLoc dl = MI->getDebugLoc();
6797 MachineFunction *MF = MBB->getParent();
6798 MachineRegisterInfo *MRI = &MF->getRegInfo();
6799 MachineConstantPool *MCP = MF->getConstantPool();
6800 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6801 const Function *F = MF->getFunction();
6803 bool isThumb = Subtarget->isThumb();
6804 bool isThumb2 = Subtarget->isThumb2();
6806 unsigned PCLabelId = AFI->createPICLabelUId();
6807 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6808 ARMConstantPoolValue *CPV =
6809 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6810 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6812 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6813 : &ARM::GPRRegClass;
6815 // Grab constant pool and fixed stack memory operands.
6816 MachineMemOperand *CPMMO =
6817 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6818 MachineMemOperand::MOLoad, 4, 4);
6820 MachineMemOperand *FIMMOSt =
6821 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6822 MachineMemOperand::MOStore, 4, 4);
6824 // Load the address of the dispatch MBB into the jump buffer.
6826 // Incoming value: jbuf
6827 // ldr.n r5, LCPI1_1
6830 // str r5, [$jbuf, #+4] ; &jbuf[1]
6831 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6832 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6833 .addConstantPoolIndex(CPI)
6834 .addMemOperand(CPMMO));
6835 // Set the low bit because of thumb mode.
6836 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6838 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6839 .addReg(NewVReg1, RegState::Kill)
6841 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6842 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6843 .addReg(NewVReg2, RegState::Kill)
6845 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6846 .addReg(NewVReg3, RegState::Kill)
6848 .addImm(36) // &jbuf[1] :: pc
6849 .addMemOperand(FIMMOSt));
6850 } else if (isThumb) {
6851 // Incoming value: jbuf
6852 // ldr.n r1, LCPI1_4
6856 // add r2, $jbuf, #+4 ; &jbuf[1]
6858 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6859 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6860 .addConstantPoolIndex(CPI)
6861 .addMemOperand(CPMMO));
6862 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6863 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6864 .addReg(NewVReg1, RegState::Kill)
6866 // Set the low bit because of thumb mode.
6867 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6868 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6869 .addReg(ARM::CPSR, RegState::Define)
6871 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6872 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6873 .addReg(ARM::CPSR, RegState::Define)
6874 .addReg(NewVReg2, RegState::Kill)
6875 .addReg(NewVReg3, RegState::Kill));
6876 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6877 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6879 .addImm(36); // &jbuf[1] :: pc
6880 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6881 .addReg(NewVReg4, RegState::Kill)
6882 .addReg(NewVReg5, RegState::Kill)
6884 .addMemOperand(FIMMOSt));
6886 // Incoming value: jbuf
6889 // str r1, [$jbuf, #+4] ; &jbuf[1]
6890 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6891 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6892 .addConstantPoolIndex(CPI)
6894 .addMemOperand(CPMMO));
6895 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6896 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6897 .addReg(NewVReg1, RegState::Kill)
6898 .addImm(PCLabelId));
6899 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6900 .addReg(NewVReg2, RegState::Kill)
6902 .addImm(36) // &jbuf[1] :: pc
6903 .addMemOperand(FIMMOSt));
6907 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6908 MachineBasicBlock *MBB) const {
6909 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6910 DebugLoc dl = MI->getDebugLoc();
6911 MachineFunction *MF = MBB->getParent();
6912 MachineRegisterInfo *MRI = &MF->getRegInfo();
6913 MachineFrameInfo *MFI = MF->getFrameInfo();
6914 int FI = MFI->getFunctionContextIndex();
6916 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6917 : &ARM::GPRnopcRegClass;
6919 // Get a mapping of the call site numbers to all of the landing pads they're
6921 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6922 unsigned MaxCSNum = 0;
6923 MachineModuleInfo &MMI = MF->getMMI();
6924 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6926 if (!BB->isLandingPad()) continue;
6928 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6930 for (MachineBasicBlock::iterator
6931 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6932 if (!II->isEHLabel()) continue;
6934 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6935 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6937 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6938 for (SmallVectorImpl<unsigned>::iterator
6939 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6940 CSI != CSE; ++CSI) {
6941 CallSiteNumToLPad[*CSI].push_back(BB);
6942 MaxCSNum = std::max(MaxCSNum, *CSI);
6948 // Get an ordered list of the machine basic blocks for the jump table.
6949 std::vector<MachineBasicBlock*> LPadList;
6950 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6951 LPadList.reserve(CallSiteNumToLPad.size());
6952 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6953 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6954 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6955 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6956 LPadList.push_back(*II);
6957 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6961 assert(!LPadList.empty() &&
6962 "No landing pad destinations for the dispatch jump table!");
6964 // Create the jump table and associated information.
6965 MachineJumpTableInfo *JTI =
6966 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6967 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6968 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6970 // Create the MBBs for the dispatch code.
6972 // Shove the dispatch's address into the return slot in the function context.
6973 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6974 DispatchBB->setIsLandingPad();
6976 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6977 unsigned trap_opcode;
6978 if (Subtarget->isThumb())
6979 trap_opcode = ARM::tTRAP;
6981 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6983 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6984 DispatchBB->addSuccessor(TrapBB);
6986 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6987 DispatchBB->addSuccessor(DispContBB);
6990 MF->insert(MF->end(), DispatchBB);
6991 MF->insert(MF->end(), DispContBB);
6992 MF->insert(MF->end(), TrapBB);
6994 // Insert code into the entry block that creates and registers the function
6996 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6998 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
6999 MachinePointerInfo::getFixedStack(*MF, FI),
7000 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7002 MachineInstrBuilder MIB;
7003 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7005 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7006 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7008 // Add a register mask with no preserved registers. This results in all
7009 // registers being marked as clobbered.
7010 MIB.addRegMask(RI.getNoPreservedMask());
7012 unsigned NumLPads = LPadList.size();
7013 if (Subtarget->isThumb2()) {
7014 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7015 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7018 .addMemOperand(FIMMOLd));
7020 if (NumLPads < 256) {
7021 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7023 .addImm(LPadList.size()));
7025 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7026 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7027 .addImm(NumLPads & 0xFFFF));
7029 unsigned VReg2 = VReg1;
7030 if ((NumLPads & 0xFFFF0000) != 0) {
7031 VReg2 = MRI->createVirtualRegister(TRC);
7032 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7034 .addImm(NumLPads >> 16));
7037 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7042 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7047 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7048 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7049 .addJumpTableIndex(MJTI));
7051 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7054 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7055 .addReg(NewVReg3, RegState::Kill)
7057 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7059 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7060 .addReg(NewVReg4, RegState::Kill)
7062 .addJumpTableIndex(MJTI);
7063 } else if (Subtarget->isThumb()) {
7064 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7065 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7068 .addMemOperand(FIMMOLd));
7070 if (NumLPads < 256) {
7071 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7075 MachineConstantPool *ConstantPool = MF->getConstantPool();
7076 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7077 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7079 // MachineConstantPool wants an explicit alignment.
7080 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7082 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7083 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7085 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7086 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7087 .addReg(VReg1, RegState::Define)
7088 .addConstantPoolIndex(Idx));
7089 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7094 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7099 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7100 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7101 .addReg(ARM::CPSR, RegState::Define)
7105 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7106 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7107 .addJumpTableIndex(MJTI));
7109 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7110 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7111 .addReg(ARM::CPSR, RegState::Define)
7112 .addReg(NewVReg2, RegState::Kill)
7115 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7116 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7118 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7119 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7120 .addReg(NewVReg4, RegState::Kill)
7122 .addMemOperand(JTMMOLd));
7124 unsigned NewVReg6 = NewVReg5;
7125 if (RelocM == Reloc::PIC_) {
7126 NewVReg6 = MRI->createVirtualRegister(TRC);
7127 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7128 .addReg(ARM::CPSR, RegState::Define)
7129 .addReg(NewVReg5, RegState::Kill)
7133 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7134 .addReg(NewVReg6, RegState::Kill)
7135 .addJumpTableIndex(MJTI);
7137 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7138 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7141 .addMemOperand(FIMMOLd));
7143 if (NumLPads < 256) {
7144 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7147 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7148 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7149 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7150 .addImm(NumLPads & 0xFFFF));
7152 unsigned VReg2 = VReg1;
7153 if ((NumLPads & 0xFFFF0000) != 0) {
7154 VReg2 = MRI->createVirtualRegister(TRC);
7155 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7157 .addImm(NumLPads >> 16));
7160 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7164 MachineConstantPool *ConstantPool = MF->getConstantPool();
7165 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7166 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7168 // MachineConstantPool wants an explicit alignment.
7169 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7171 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7172 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7174 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7175 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7176 .addReg(VReg1, RegState::Define)
7177 .addConstantPoolIndex(Idx)
7179 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7181 .addReg(VReg1, RegState::Kill));
7184 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7189 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7191 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7193 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7194 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7195 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7196 .addJumpTableIndex(MJTI));
7198 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7199 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7200 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7202 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7203 .addReg(NewVReg3, RegState::Kill)
7206 .addMemOperand(JTMMOLd));
7208 if (RelocM == Reloc::PIC_) {
7209 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7210 .addReg(NewVReg5, RegState::Kill)
7212 .addJumpTableIndex(MJTI);
7214 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7215 .addReg(NewVReg5, RegState::Kill)
7216 .addJumpTableIndex(MJTI);
7220 // Add the jump table entries as successors to the MBB.
7221 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7222 for (std::vector<MachineBasicBlock*>::iterator
7223 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7224 MachineBasicBlock *CurMBB = *I;
7225 if (SeenMBBs.insert(CurMBB).second)
7226 DispContBB->addSuccessor(CurMBB);
7229 // N.B. the order the invoke BBs are processed in doesn't matter here.
7230 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7231 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7232 for (MachineBasicBlock *BB : InvokeBBs) {
7234 // Remove the landing pad successor from the invoke block and replace it
7235 // with the new dispatch block.
7236 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7238 while (!Successors.empty()) {
7239 MachineBasicBlock *SMBB = Successors.pop_back_val();
7240 if (SMBB->isLandingPad()) {
7241 BB->removeSuccessor(SMBB);
7242 MBBLPads.push_back(SMBB);
7246 BB->addSuccessor(DispatchBB);
7248 // Find the invoke call and mark all of the callee-saved registers as
7249 // 'implicit defined' so that they're spilled. This prevents code from
7250 // moving instructions to before the EH block, where they will never be
7252 for (MachineBasicBlock::reverse_iterator
7253 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7254 if (!II->isCall()) continue;
7256 DenseMap<unsigned, bool> DefRegs;
7257 for (MachineInstr::mop_iterator
7258 OI = II->operands_begin(), OE = II->operands_end();
7260 if (!OI->isReg()) continue;
7261 DefRegs[OI->getReg()] = true;
7264 MachineInstrBuilder MIB(*MF, &*II);
7266 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7267 unsigned Reg = SavedRegs[i];
7268 if (Subtarget->isThumb2() &&
7269 !ARM::tGPRRegClass.contains(Reg) &&
7270 !ARM::hGPRRegClass.contains(Reg))
7272 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7274 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7277 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7284 // Mark all former landing pads as non-landing pads. The dispatch is the only
7286 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7287 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7288 (*I)->setIsLandingPad(false);
7290 // The instruction is gone now.
7291 MI->eraseFromParent();
7295 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7296 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7297 E = MBB->succ_end(); I != E; ++I)
7300 llvm_unreachable("Expecting a BB with two successors!");
7303 /// Return the load opcode for a given load size. If load size >= 8,
7304 /// neon opcode will be returned.
7305 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7307 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7308 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7310 return LdSize == 4 ? ARM::tLDRi
7311 : LdSize == 2 ? ARM::tLDRHi
7312 : LdSize == 1 ? ARM::tLDRBi : 0;
7314 return LdSize == 4 ? ARM::t2LDR_POST
7315 : LdSize == 2 ? ARM::t2LDRH_POST
7316 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7317 return LdSize == 4 ? ARM::LDR_POST_IMM
7318 : LdSize == 2 ? ARM::LDRH_POST
7319 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7322 /// Return the store opcode for a given store size. If store size >= 8,
7323 /// neon opcode will be returned.
7324 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7326 return StSize == 16 ? ARM::VST1q32wb_fixed
7327 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7329 return StSize == 4 ? ARM::tSTRi
7330 : StSize == 2 ? ARM::tSTRHi
7331 : StSize == 1 ? ARM::tSTRBi : 0;
7333 return StSize == 4 ? ARM::t2STR_POST
7334 : StSize == 2 ? ARM::t2STRH_POST
7335 : StSize == 1 ? ARM::t2STRB_POST : 0;
7336 return StSize == 4 ? ARM::STR_POST_IMM
7337 : StSize == 2 ? ARM::STRH_POST
7338 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7341 /// Emit a post-increment load operation with given size. The instructions
7342 /// will be added to BB at Pos.
7343 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7344 const TargetInstrInfo *TII, DebugLoc dl,
7345 unsigned LdSize, unsigned Data, unsigned AddrIn,
7346 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7347 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7348 assert(LdOpc != 0 && "Should have a load opcode");
7350 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7351 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7353 } else if (IsThumb1) {
7354 // load + update AddrIn
7355 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7356 .addReg(AddrIn).addImm(0));
7357 MachineInstrBuilder MIB =
7358 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7359 MIB = AddDefaultT1CC(MIB);
7360 MIB.addReg(AddrIn).addImm(LdSize);
7361 AddDefaultPred(MIB);
7362 } else if (IsThumb2) {
7363 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7364 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7367 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7368 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7369 .addReg(0).addImm(LdSize));
7373 /// Emit a post-increment store operation with given size. The instructions
7374 /// will be added to BB at Pos.
7375 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7376 const TargetInstrInfo *TII, DebugLoc dl,
7377 unsigned StSize, unsigned Data, unsigned AddrIn,
7378 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7379 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7380 assert(StOpc != 0 && "Should have a store opcode");
7382 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7383 .addReg(AddrIn).addImm(0).addReg(Data));
7384 } else if (IsThumb1) {
7385 // store + update AddrIn
7386 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7387 .addReg(AddrIn).addImm(0));
7388 MachineInstrBuilder MIB =
7389 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7390 MIB = AddDefaultT1CC(MIB);
7391 MIB.addReg(AddrIn).addImm(StSize);
7392 AddDefaultPred(MIB);
7393 } else if (IsThumb2) {
7394 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7395 .addReg(Data).addReg(AddrIn).addImm(StSize));
7397 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7398 .addReg(Data).addReg(AddrIn).addReg(0)
7404 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7405 MachineBasicBlock *BB) const {
7406 // This pseudo instruction has 3 operands: dst, src, size
7407 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7408 // Otherwise, we will generate unrolled scalar copies.
7409 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7410 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7411 MachineFunction::iterator It = BB;
7414 unsigned dest = MI->getOperand(0).getReg();
7415 unsigned src = MI->getOperand(1).getReg();
7416 unsigned SizeVal = MI->getOperand(2).getImm();
7417 unsigned Align = MI->getOperand(3).getImm();
7418 DebugLoc dl = MI->getDebugLoc();
7420 MachineFunction *MF = BB->getParent();
7421 MachineRegisterInfo &MRI = MF->getRegInfo();
7422 unsigned UnitSize = 0;
7423 const TargetRegisterClass *TRC = nullptr;
7424 const TargetRegisterClass *VecTRC = nullptr;
7426 bool IsThumb1 = Subtarget->isThumb1Only();
7427 bool IsThumb2 = Subtarget->isThumb2();
7431 } else if (Align & 2) {
7434 // Check whether we can use NEON instructions.
7435 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7436 Subtarget->hasNEON()) {
7437 if ((Align % 16 == 0) && SizeVal >= 16)
7439 else if ((Align % 8 == 0) && SizeVal >= 8)
7442 // Can't use NEON instructions.
7447 // Select the correct opcode and register class for unit size load/store
7448 bool IsNeon = UnitSize >= 8;
7449 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7451 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7452 : UnitSize == 8 ? &ARM::DPRRegClass
7455 unsigned BytesLeft = SizeVal % UnitSize;
7456 unsigned LoopSize = SizeVal - BytesLeft;
7458 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7459 // Use LDR and STR to copy.
7460 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7461 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7462 unsigned srcIn = src;
7463 unsigned destIn = dest;
7464 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7465 unsigned srcOut = MRI.createVirtualRegister(TRC);
7466 unsigned destOut = MRI.createVirtualRegister(TRC);
7467 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7468 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7469 IsThumb1, IsThumb2);
7470 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7471 IsThumb1, IsThumb2);
7476 // Handle the leftover bytes with LDRB and STRB.
7477 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7478 // [destOut] = STRB_POST(scratch, destIn, 1)
7479 for (unsigned i = 0; i < BytesLeft; i++) {
7480 unsigned srcOut = MRI.createVirtualRegister(TRC);
7481 unsigned destOut = MRI.createVirtualRegister(TRC);
7482 unsigned scratch = MRI.createVirtualRegister(TRC);
7483 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7484 IsThumb1, IsThumb2);
7485 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7486 IsThumb1, IsThumb2);
7490 MI->eraseFromParent(); // The instruction is gone now.
7494 // Expand the pseudo op to a loop.
7497 // movw varEnd, # --> with thumb2
7499 // ldrcp varEnd, idx --> without thumb2
7500 // fallthrough --> loopMBB
7502 // PHI varPhi, varEnd, varLoop
7503 // PHI srcPhi, src, srcLoop
7504 // PHI destPhi, dst, destLoop
7505 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7506 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7507 // subs varLoop, varPhi, #UnitSize
7509 // fallthrough --> exitMBB
7511 // epilogue to handle left-over bytes
7512 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7513 // [destOut] = STRB_POST(scratch, destLoop, 1)
7514 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7515 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7516 MF->insert(It, loopMBB);
7517 MF->insert(It, exitMBB);
7519 // Transfer the remainder of BB and its successor edges to exitMBB.
7520 exitMBB->splice(exitMBB->begin(), BB,
7521 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7522 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7524 // Load an immediate to varEnd.
7525 unsigned varEnd = MRI.createVirtualRegister(TRC);
7526 if (Subtarget->useMovt(*MF)) {
7527 unsigned Vtmp = varEnd;
7528 if ((LoopSize & 0xFFFF0000) != 0)
7529 Vtmp = MRI.createVirtualRegister(TRC);
7530 AddDefaultPred(BuildMI(BB, dl,
7531 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7532 Vtmp).addImm(LoopSize & 0xFFFF));
7534 if ((LoopSize & 0xFFFF0000) != 0)
7535 AddDefaultPred(BuildMI(BB, dl,
7536 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7539 .addImm(LoopSize >> 16));
7541 MachineConstantPool *ConstantPool = MF->getConstantPool();
7542 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7543 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7545 // MachineConstantPool wants an explicit alignment.
7546 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7548 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7549 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7552 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7553 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7555 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7556 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7558 BB->addSuccessor(loopMBB);
7560 // Generate the loop body:
7561 // varPhi = PHI(varLoop, varEnd)
7562 // srcPhi = PHI(srcLoop, src)
7563 // destPhi = PHI(destLoop, dst)
7564 MachineBasicBlock *entryBB = BB;
7566 unsigned varLoop = MRI.createVirtualRegister(TRC);
7567 unsigned varPhi = MRI.createVirtualRegister(TRC);
7568 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7569 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7570 unsigned destLoop = MRI.createVirtualRegister(TRC);
7571 unsigned destPhi = MRI.createVirtualRegister(TRC);
7573 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7574 .addReg(varLoop).addMBB(loopMBB)
7575 .addReg(varEnd).addMBB(entryBB);
7576 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7577 .addReg(srcLoop).addMBB(loopMBB)
7578 .addReg(src).addMBB(entryBB);
7579 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7580 .addReg(destLoop).addMBB(loopMBB)
7581 .addReg(dest).addMBB(entryBB);
7583 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7584 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7585 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7586 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7587 IsThumb1, IsThumb2);
7588 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7589 IsThumb1, IsThumb2);
7591 // Decrement loop variable by UnitSize.
7593 MachineInstrBuilder MIB =
7594 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7595 MIB = AddDefaultT1CC(MIB);
7596 MIB.addReg(varPhi).addImm(UnitSize);
7597 AddDefaultPred(MIB);
7599 MachineInstrBuilder MIB =
7600 BuildMI(*BB, BB->end(), dl,
7601 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7602 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7603 MIB->getOperand(5).setReg(ARM::CPSR);
7604 MIB->getOperand(5).setIsDef(true);
7606 BuildMI(*BB, BB->end(), dl,
7607 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7608 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7610 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7611 BB->addSuccessor(loopMBB);
7612 BB->addSuccessor(exitMBB);
7614 // Add epilogue to handle BytesLeft.
7616 MachineInstr *StartOfExit = exitMBB->begin();
7618 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7619 // [destOut] = STRB_POST(scratch, destLoop, 1)
7620 unsigned srcIn = srcLoop;
7621 unsigned destIn = destLoop;
7622 for (unsigned i = 0; i < BytesLeft; i++) {
7623 unsigned srcOut = MRI.createVirtualRegister(TRC);
7624 unsigned destOut = MRI.createVirtualRegister(TRC);
7625 unsigned scratch = MRI.createVirtualRegister(TRC);
7626 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7627 IsThumb1, IsThumb2);
7628 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7629 IsThumb1, IsThumb2);
7634 MI->eraseFromParent(); // The instruction is gone now.
7639 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7640 MachineBasicBlock *MBB) const {
7641 const TargetMachine &TM = getTargetMachine();
7642 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7643 DebugLoc DL = MI->getDebugLoc();
7645 assert(Subtarget->isTargetWindows() &&
7646 "__chkstk is only supported on Windows");
7647 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7649 // __chkstk takes the number of words to allocate on the stack in R4, and
7650 // returns the stack adjustment in number of bytes in R4. This will not
7651 // clober any other registers (other than the obvious lr).
7653 // Although, technically, IP should be considered a register which may be
7654 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7655 // thumb-2 environment, so there is no interworking required. As a result, we
7656 // do not expect a veneer to be emitted by the linker, clobbering IP.
7658 // Each module receives its own copy of __chkstk, so no import thunk is
7659 // required, again, ensuring that IP is not clobbered.
7661 // Finally, although some linkers may theoretically provide a trampoline for
7662 // out of range calls (which is quite common due to a 32M range limitation of
7663 // branches for Thumb), we can generate the long-call version via
7664 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7667 switch (TM.getCodeModel()) {
7668 case CodeModel::Small:
7669 case CodeModel::Medium:
7670 case CodeModel::Default:
7671 case CodeModel::Kernel:
7672 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7673 .addImm((unsigned)ARMCC::AL).addReg(0)
7674 .addExternalSymbol("__chkstk")
7675 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7676 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7677 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7679 case CodeModel::Large:
7680 case CodeModel::JITDefault: {
7681 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7682 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7684 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7685 .addExternalSymbol("__chkstk");
7686 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7687 .addImm((unsigned)ARMCC::AL).addReg(0)
7688 .addReg(Reg, RegState::Kill)
7689 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7690 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7691 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7696 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7698 .addReg(ARM::SP).addReg(ARM::R4)));
7700 MI->eraseFromParent();
7705 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7706 MachineBasicBlock *BB) const {
7707 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7708 DebugLoc dl = MI->getDebugLoc();
7709 bool isThumb2 = Subtarget->isThumb2();
7710 switch (MI->getOpcode()) {
7713 llvm_unreachable("Unexpected instr type to insert");
7715 // The Thumb2 pre-indexed stores have the same MI operands, they just
7716 // define them differently in the .td files from the isel patterns, so
7717 // they need pseudos.
7718 case ARM::t2STR_preidx:
7719 MI->setDesc(TII->get(ARM::t2STR_PRE));
7721 case ARM::t2STRB_preidx:
7722 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7724 case ARM::t2STRH_preidx:
7725 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7728 case ARM::STRi_preidx:
7729 case ARM::STRBi_preidx: {
7730 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7731 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7732 // Decode the offset.
7733 unsigned Offset = MI->getOperand(4).getImm();
7734 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7735 Offset = ARM_AM::getAM2Offset(Offset);
7739 MachineMemOperand *MMO = *MI->memoperands_begin();
7740 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7741 .addOperand(MI->getOperand(0)) // Rn_wb
7742 .addOperand(MI->getOperand(1)) // Rt
7743 .addOperand(MI->getOperand(2)) // Rn
7744 .addImm(Offset) // offset (skip GPR==zero_reg)
7745 .addOperand(MI->getOperand(5)) // pred
7746 .addOperand(MI->getOperand(6))
7747 .addMemOperand(MMO);
7748 MI->eraseFromParent();
7751 case ARM::STRr_preidx:
7752 case ARM::STRBr_preidx:
7753 case ARM::STRH_preidx: {
7755 switch (MI->getOpcode()) {
7756 default: llvm_unreachable("unexpected opcode!");
7757 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7758 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7759 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7761 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7762 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7763 MIB.addOperand(MI->getOperand(i));
7764 MI->eraseFromParent();
7768 case ARM::tMOVCCr_pseudo: {
7769 // To "insert" a SELECT_CC instruction, we actually have to insert the
7770 // diamond control-flow pattern. The incoming instruction knows the
7771 // destination vreg to set, the condition code register to branch on, the
7772 // true/false values to select between, and a branch opcode to use.
7773 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7774 MachineFunction::iterator It = BB;
7780 // cmpTY ccX, r1, r2
7782 // fallthrough --> copy0MBB
7783 MachineBasicBlock *thisMBB = BB;
7784 MachineFunction *F = BB->getParent();
7785 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7786 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7787 F->insert(It, copy0MBB);
7788 F->insert(It, sinkMBB);
7790 // Transfer the remainder of BB and its successor edges to sinkMBB.
7791 sinkMBB->splice(sinkMBB->begin(), BB,
7792 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7793 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7795 BB->addSuccessor(copy0MBB);
7796 BB->addSuccessor(sinkMBB);
7798 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7799 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7802 // %FalseValue = ...
7803 // # fallthrough to sinkMBB
7806 // Update machine-CFG edges
7807 BB->addSuccessor(sinkMBB);
7810 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7813 BuildMI(*BB, BB->begin(), dl,
7814 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7815 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7816 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7818 MI->eraseFromParent(); // The pseudo instruction is gone now.
7823 case ARM::BCCZi64: {
7824 // If there is an unconditional branch to the other successor, remove it.
7825 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7827 // Compare both parts that make up the double comparison separately for
7829 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7831 unsigned LHS1 = MI->getOperand(1).getReg();
7832 unsigned LHS2 = MI->getOperand(2).getReg();
7834 AddDefaultPred(BuildMI(BB, dl,
7835 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7836 .addReg(LHS1).addImm(0));
7837 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7838 .addReg(LHS2).addImm(0)
7839 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7841 unsigned RHS1 = MI->getOperand(3).getReg();
7842 unsigned RHS2 = MI->getOperand(4).getReg();
7843 AddDefaultPred(BuildMI(BB, dl,
7844 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7845 .addReg(LHS1).addReg(RHS1));
7846 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7847 .addReg(LHS2).addReg(RHS2)
7848 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7851 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7852 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7853 if (MI->getOperand(0).getImm() == ARMCC::NE)
7854 std::swap(destMBB, exitMBB);
7856 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7857 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7859 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7861 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7863 MI->eraseFromParent(); // The pseudo instruction is gone now.
7867 case ARM::Int_eh_sjlj_setjmp:
7868 case ARM::Int_eh_sjlj_setjmp_nofp:
7869 case ARM::tInt_eh_sjlj_setjmp:
7870 case ARM::t2Int_eh_sjlj_setjmp:
7871 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7874 case ARM::Int_eh_sjlj_setup_dispatch:
7875 EmitSjLjDispatchBlock(MI, BB);
7880 // To insert an ABS instruction, we have to insert the
7881 // diamond control-flow pattern. The incoming instruction knows the
7882 // source vreg to test against 0, the destination vreg to set,
7883 // the condition code register to branch on, the
7884 // true/false values to select between, and a branch opcode to use.
7889 // BCC (branch to SinkBB if V0 >= 0)
7890 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7891 // SinkBB: V1 = PHI(V2, V3)
7892 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7893 MachineFunction::iterator BBI = BB;
7895 MachineFunction *Fn = BB->getParent();
7896 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7897 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7898 Fn->insert(BBI, RSBBB);
7899 Fn->insert(BBI, SinkBB);
7901 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7902 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7903 bool ABSSrcKIll = MI->getOperand(1).isKill();
7904 bool isThumb2 = Subtarget->isThumb2();
7905 MachineRegisterInfo &MRI = Fn->getRegInfo();
7906 // In Thumb mode S must not be specified if source register is the SP or
7907 // PC and if destination register is the SP, so restrict register class
7908 unsigned NewRsbDstReg =
7909 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7911 // Transfer the remainder of BB and its successor edges to sinkMBB.
7912 SinkBB->splice(SinkBB->begin(), BB,
7913 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7914 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7916 BB->addSuccessor(RSBBB);
7917 BB->addSuccessor(SinkBB);
7919 // fall through to SinkMBB
7920 RSBBB->addSuccessor(SinkBB);
7922 // insert a cmp at the end of BB
7923 AddDefaultPred(BuildMI(BB, dl,
7924 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7925 .addReg(ABSSrcReg).addImm(0));
7927 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7929 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7930 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7932 // insert rsbri in RSBBB
7933 // Note: BCC and rsbri will be converted into predicated rsbmi
7934 // by if-conversion pass
7935 BuildMI(*RSBBB, RSBBB->begin(), dl,
7936 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7937 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7938 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7940 // insert PHI in SinkBB,
7941 // reuse ABSDstReg to not change uses of ABS instruction
7942 BuildMI(*SinkBB, SinkBB->begin(), dl,
7943 TII->get(ARM::PHI), ABSDstReg)
7944 .addReg(NewRsbDstReg).addMBB(RSBBB)
7945 .addReg(ABSSrcReg).addMBB(BB);
7947 // remove ABS instruction
7948 MI->eraseFromParent();
7950 // return last added BB
7953 case ARM::COPY_STRUCT_BYVAL_I32:
7955 return EmitStructByval(MI, BB);
7956 case ARM::WIN__CHKSTK:
7957 return EmitLowered__chkstk(MI, BB);
7961 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7962 SDNode *Node) const {
7963 const MCInstrDesc *MCID = &MI->getDesc();
7964 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7965 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7966 // operand is still set to noreg. If needed, set the optional operand's
7967 // register to CPSR, and remove the redundant implicit def.
7969 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7971 // Rename pseudo opcodes.
7972 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7974 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7975 MCID = &TII->get(NewOpc);
7977 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7978 "converted opcode should be the same except for cc_out");
7982 // Add the optional cc_out operand
7983 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7985 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7987 // Any ARM instruction that sets the 's' bit should specify an optional
7988 // "cc_out" operand in the last operand position.
7989 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7990 assert(!NewOpc && "Optional cc_out operand required");
7993 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7994 // since we already have an optional CPSR def.
7995 bool definesCPSR = false;
7996 bool deadCPSR = false;
7997 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7999 const MachineOperand &MO = MI->getOperand(i);
8000 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8004 MI->RemoveOperand(i);
8009 assert(!NewOpc && "Optional cc_out operand required");
8012 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8014 assert(!MI->getOperand(ccOutIdx).getReg() &&
8015 "expect uninitialized optional cc_out operand");
8019 // If this instruction was defined with an optional CPSR def and its dag node
8020 // had a live implicit CPSR def, then activate the optional CPSR def.
8021 MachineOperand &MO = MI->getOperand(ccOutIdx);
8022 MO.setReg(ARM::CPSR);
8026 //===----------------------------------------------------------------------===//
8027 // ARM Optimization Hooks
8028 //===----------------------------------------------------------------------===//
8030 // Helper function that checks if N is a null or all ones constant.
8031 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8032 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8035 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8038 // Return true if N is conditionally 0 or all ones.
8039 // Detects these expressions where cc is an i1 value:
8041 // (select cc 0, y) [AllOnes=0]
8042 // (select cc y, 0) [AllOnes=0]
8043 // (zext cc) [AllOnes=0]
8044 // (sext cc) [AllOnes=0/1]
8045 // (select cc -1, y) [AllOnes=1]
8046 // (select cc y, -1) [AllOnes=1]
8048 // Invert is set when N is the null/all ones constant when CC is false.
8049 // OtherOp is set to the alternative value of N.
8050 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8051 SDValue &CC, bool &Invert,
8053 SelectionDAG &DAG) {
8054 switch (N->getOpcode()) {
8055 default: return false;
8057 CC = N->getOperand(0);
8058 SDValue N1 = N->getOperand(1);
8059 SDValue N2 = N->getOperand(2);
8060 if (isZeroOrAllOnes(N1, AllOnes)) {
8065 if (isZeroOrAllOnes(N2, AllOnes)) {
8072 case ISD::ZERO_EXTEND:
8073 // (zext cc) can never be the all ones value.
8077 case ISD::SIGN_EXTEND: {
8079 EVT VT = N->getValueType(0);
8080 CC = N->getOperand(0);
8081 if (CC.getValueType() != MVT::i1)
8085 // When looking for an AllOnes constant, N is an sext, and the 'other'
8087 OtherOp = DAG.getConstant(0, dl, VT);
8088 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8089 // When looking for a 0 constant, N can be zext or sext.
8090 OtherOp = DAG.getConstant(1, dl, VT);
8092 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8099 // Combine a constant select operand into its use:
8101 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8102 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8103 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8104 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8105 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8107 // The transform is rejected if the select doesn't have a constant operand that
8108 // is null, or all ones when AllOnes is set.
8110 // Also recognize sext/zext from i1:
8112 // (add (zext cc), x) -> (select cc (add x, 1), x)
8113 // (add (sext cc), x) -> (select cc (add x, -1), x)
8115 // These transformations eventually create predicated instructions.
8117 // @param N The node to transform.
8118 // @param Slct The N operand that is a select.
8119 // @param OtherOp The other N operand (x above).
8120 // @param DCI Context.
8121 // @param AllOnes Require the select constant to be all ones instead of null.
8122 // @returns The new node, or SDValue() on failure.
8124 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8125 TargetLowering::DAGCombinerInfo &DCI,
8126 bool AllOnes = false) {
8127 SelectionDAG &DAG = DCI.DAG;
8128 EVT VT = N->getValueType(0);
8129 SDValue NonConstantVal;
8132 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8133 NonConstantVal, DAG))
8136 // Slct is now know to be the desired identity constant when CC is true.
8137 SDValue TrueVal = OtherOp;
8138 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8139 OtherOp, NonConstantVal);
8140 // Unless SwapSelectOps says CC should be false.
8142 std::swap(TrueVal, FalseVal);
8144 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8145 CCOp, TrueVal, FalseVal);
8148 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8150 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8151 TargetLowering::DAGCombinerInfo &DCI) {
8152 SDValue N0 = N->getOperand(0);
8153 SDValue N1 = N->getOperand(1);
8154 if (N0.getNode()->hasOneUse()) {
8155 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8156 if (Result.getNode())
8159 if (N1.getNode()->hasOneUse()) {
8160 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8161 if (Result.getNode())
8167 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8168 // (only after legalization).
8169 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8170 TargetLowering::DAGCombinerInfo &DCI,
8171 const ARMSubtarget *Subtarget) {
8173 // Only perform optimization if after legalize, and if NEON is available. We
8174 // also expected both operands to be BUILD_VECTORs.
8175 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8176 || N0.getOpcode() != ISD::BUILD_VECTOR
8177 || N1.getOpcode() != ISD::BUILD_VECTOR)
8180 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8181 EVT VT = N->getValueType(0);
8182 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8185 // Check that the vector operands are of the right form.
8186 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8187 // operands, where N is the size of the formed vector.
8188 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8189 // index such that we have a pair wise add pattern.
8191 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8192 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8194 SDValue Vec = N0->getOperand(0)->getOperand(0);
8195 SDNode *V = Vec.getNode();
8196 unsigned nextIndex = 0;
8198 // For each operands to the ADD which are BUILD_VECTORs,
8199 // check to see if each of their operands are an EXTRACT_VECTOR with
8200 // the same vector and appropriate index.
8201 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8202 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8203 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8205 SDValue ExtVec0 = N0->getOperand(i);
8206 SDValue ExtVec1 = N1->getOperand(i);
8208 // First operand is the vector, verify its the same.
8209 if (V != ExtVec0->getOperand(0).getNode() ||
8210 V != ExtVec1->getOperand(0).getNode())
8213 // Second is the constant, verify its correct.
8214 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8215 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8217 // For the constant, we want to see all the even or all the odd.
8218 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8219 || C1->getZExtValue() != nextIndex+1)
8228 // Create VPADDL node.
8229 SelectionDAG &DAG = DCI.DAG;
8230 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8234 // Build operand list.
8235 SmallVector<SDValue, 8> Ops;
8236 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8237 TLI.getPointerTy(DAG.getDataLayout())));
8239 // Input is the vector.
8242 // Get widened type and narrowed type.
8244 unsigned numElem = VT.getVectorNumElements();
8246 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8247 switch (inputLaneType.getSimpleVT().SimpleTy) {
8248 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8249 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8250 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8252 llvm_unreachable("Invalid vector element type for padd optimization.");
8255 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8256 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8257 return DAG.getNode(ExtOp, dl, VT, tmp);
8260 static SDValue findMUL_LOHI(SDValue V) {
8261 if (V->getOpcode() == ISD::UMUL_LOHI ||
8262 V->getOpcode() == ISD::SMUL_LOHI)
8267 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8268 TargetLowering::DAGCombinerInfo &DCI,
8269 const ARMSubtarget *Subtarget) {
8271 if (Subtarget->isThumb1Only()) return SDValue();
8273 // Only perform the checks after legalize when the pattern is available.
8274 if (DCI.isBeforeLegalize()) return SDValue();
8276 // Look for multiply add opportunities.
8277 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8278 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8279 // a glue link from the first add to the second add.
8280 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8281 // a S/UMLAL instruction.
8284 // / \ [no multiline comment]
8290 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8291 SDValue AddcOp0 = AddcNode->getOperand(0);
8292 SDValue AddcOp1 = AddcNode->getOperand(1);
8294 // Check if the two operands are from the same mul_lohi node.
8295 if (AddcOp0.getNode() == AddcOp1.getNode())
8298 assert(AddcNode->getNumValues() == 2 &&
8299 AddcNode->getValueType(0) == MVT::i32 &&
8300 "Expect ADDC with two result values. First: i32");
8302 // Check that we have a glued ADDC node.
8303 if (AddcNode->getValueType(1) != MVT::Glue)
8306 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8307 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8308 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8309 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8310 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8313 // Look for the glued ADDE.
8314 SDNode* AddeNode = AddcNode->getGluedUser();
8318 // Make sure it is really an ADDE.
8319 if (AddeNode->getOpcode() != ISD::ADDE)
8322 assert(AddeNode->getNumOperands() == 3 &&
8323 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8324 "ADDE node has the wrong inputs");
8326 // Check for the triangle shape.
8327 SDValue AddeOp0 = AddeNode->getOperand(0);
8328 SDValue AddeOp1 = AddeNode->getOperand(1);
8330 // Make sure that the ADDE operands are not coming from the same node.
8331 if (AddeOp0.getNode() == AddeOp1.getNode())
8334 // Find the MUL_LOHI node walking up ADDE's operands.
8335 bool IsLeftOperandMUL = false;
8336 SDValue MULOp = findMUL_LOHI(AddeOp0);
8337 if (MULOp == SDValue())
8338 MULOp = findMUL_LOHI(AddeOp1);
8340 IsLeftOperandMUL = true;
8341 if (MULOp == SDValue())
8344 // Figure out the right opcode.
8345 unsigned Opc = MULOp->getOpcode();
8346 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8348 // Figure out the high and low input values to the MLAL node.
8349 SDValue* HiAdd = nullptr;
8350 SDValue* LoMul = nullptr;
8351 SDValue* LowAdd = nullptr;
8353 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8354 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8357 if (IsLeftOperandMUL)
8363 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8364 // whose low result is fed to the ADDC we are checking.
8366 if (AddcOp0 == MULOp.getValue(0)) {
8370 if (AddcOp1 == MULOp.getValue(0)) {
8378 // Create the merged node.
8379 SelectionDAG &DAG = DCI.DAG;
8381 // Build operand list.
8382 SmallVector<SDValue, 8> Ops;
8383 Ops.push_back(LoMul->getOperand(0));
8384 Ops.push_back(LoMul->getOperand(1));
8385 Ops.push_back(*LowAdd);
8386 Ops.push_back(*HiAdd);
8388 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8389 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8391 // Replace the ADDs' nodes uses by the MLA node's values.
8392 SDValue HiMLALResult(MLALNode.getNode(), 1);
8393 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8395 SDValue LoMLALResult(MLALNode.getNode(), 0);
8396 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8398 // Return original node to notify the driver to stop replacing.
8399 SDValue resNode(AddcNode, 0);
8403 /// PerformADDCCombine - Target-specific dag combine transform from
8404 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8405 static SDValue PerformADDCCombine(SDNode *N,
8406 TargetLowering::DAGCombinerInfo &DCI,
8407 const ARMSubtarget *Subtarget) {
8409 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8413 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8414 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8415 /// called with the default operands, and if that fails, with commuted
8417 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8418 TargetLowering::DAGCombinerInfo &DCI,
8419 const ARMSubtarget *Subtarget){
8421 // Attempt to create vpaddl for this add.
8422 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8423 if (Result.getNode())
8426 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8427 if (N0.getNode()->hasOneUse()) {
8428 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8429 if (Result.getNode()) return Result;
8434 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8436 static SDValue PerformADDCombine(SDNode *N,
8437 TargetLowering::DAGCombinerInfo &DCI,
8438 const ARMSubtarget *Subtarget) {
8439 SDValue N0 = N->getOperand(0);
8440 SDValue N1 = N->getOperand(1);
8442 // First try with the default operand order.
8443 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8444 if (Result.getNode())
8447 // If that didn't work, try again with the operands commuted.
8448 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8451 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8453 static SDValue PerformSUBCombine(SDNode *N,
8454 TargetLowering::DAGCombinerInfo &DCI) {
8455 SDValue N0 = N->getOperand(0);
8456 SDValue N1 = N->getOperand(1);
8458 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8459 if (N1.getNode()->hasOneUse()) {
8460 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8461 if (Result.getNode()) return Result;
8467 /// PerformVMULCombine
8468 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8469 /// special multiplier accumulator forwarding.
8475 // However, for (A + B) * (A + B),
8482 static SDValue PerformVMULCombine(SDNode *N,
8483 TargetLowering::DAGCombinerInfo &DCI,
8484 const ARMSubtarget *Subtarget) {
8485 if (!Subtarget->hasVMLxForwarding())
8488 SelectionDAG &DAG = DCI.DAG;
8489 SDValue N0 = N->getOperand(0);
8490 SDValue N1 = N->getOperand(1);
8491 unsigned Opcode = N0.getOpcode();
8492 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8493 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8494 Opcode = N1.getOpcode();
8495 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8496 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8504 EVT VT = N->getValueType(0);
8506 SDValue N00 = N0->getOperand(0);
8507 SDValue N01 = N0->getOperand(1);
8508 return DAG.getNode(Opcode, DL, VT,
8509 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8510 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8513 static SDValue PerformMULCombine(SDNode *N,
8514 TargetLowering::DAGCombinerInfo &DCI,
8515 const ARMSubtarget *Subtarget) {
8516 SelectionDAG &DAG = DCI.DAG;
8518 if (Subtarget->isThumb1Only())
8521 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8524 EVT VT = N->getValueType(0);
8525 if (VT.is64BitVector() || VT.is128BitVector())
8526 return PerformVMULCombine(N, DCI, Subtarget);
8530 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8534 int64_t MulAmt = C->getSExtValue();
8535 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8537 ShiftAmt = ShiftAmt & (32 - 1);
8538 SDValue V = N->getOperand(0);
8542 MulAmt >>= ShiftAmt;
8545 if (isPowerOf2_32(MulAmt - 1)) {
8546 // (mul x, 2^N + 1) => (add (shl x, N), x)
8547 Res = DAG.getNode(ISD::ADD, DL, VT,
8549 DAG.getNode(ISD::SHL, DL, VT,
8551 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8553 } else if (isPowerOf2_32(MulAmt + 1)) {
8554 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8555 Res = DAG.getNode(ISD::SUB, DL, VT,
8556 DAG.getNode(ISD::SHL, DL, VT,
8558 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8564 uint64_t MulAmtAbs = -MulAmt;
8565 if (isPowerOf2_32(MulAmtAbs + 1)) {
8566 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8567 Res = DAG.getNode(ISD::SUB, DL, VT,
8569 DAG.getNode(ISD::SHL, DL, VT,
8571 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8573 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8574 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8575 Res = DAG.getNode(ISD::ADD, DL, VT,
8577 DAG.getNode(ISD::SHL, DL, VT,
8579 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8581 Res = DAG.getNode(ISD::SUB, DL, VT,
8582 DAG.getConstant(0, DL, MVT::i32), Res);
8589 Res = DAG.getNode(ISD::SHL, DL, VT,
8590 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8592 // Do not add new nodes to DAG combiner worklist.
8593 DCI.CombineTo(N, Res, false);
8597 static SDValue PerformANDCombine(SDNode *N,
8598 TargetLowering::DAGCombinerInfo &DCI,
8599 const ARMSubtarget *Subtarget) {
8601 // Attempt to use immediate-form VBIC
8602 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8604 EVT VT = N->getValueType(0);
8605 SelectionDAG &DAG = DCI.DAG;
8607 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8610 APInt SplatBits, SplatUndef;
8611 unsigned SplatBitSize;
8614 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8615 if (SplatBitSize <= 64) {
8617 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8618 SplatUndef.getZExtValue(), SplatBitSize,
8619 DAG, dl, VbicVT, VT.is128BitVector(),
8621 if (Val.getNode()) {
8623 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8624 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8625 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8630 if (!Subtarget->isThumb1Only()) {
8631 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8632 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8633 if (Result.getNode())
8640 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8641 static SDValue PerformORCombine(SDNode *N,
8642 TargetLowering::DAGCombinerInfo &DCI,
8643 const ARMSubtarget *Subtarget) {
8644 // Attempt to use immediate-form VORR
8645 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8647 EVT VT = N->getValueType(0);
8648 SelectionDAG &DAG = DCI.DAG;
8650 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8653 APInt SplatBits, SplatUndef;
8654 unsigned SplatBitSize;
8656 if (BVN && Subtarget->hasNEON() &&
8657 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8658 if (SplatBitSize <= 64) {
8660 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8661 SplatUndef.getZExtValue(), SplatBitSize,
8662 DAG, dl, VorrVT, VT.is128BitVector(),
8664 if (Val.getNode()) {
8666 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8667 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8668 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8673 if (!Subtarget->isThumb1Only()) {
8674 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8675 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8676 if (Result.getNode())
8680 // The code below optimizes (or (and X, Y), Z).
8681 // The AND operand needs to have a single user to make these optimizations
8683 SDValue N0 = N->getOperand(0);
8684 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8686 SDValue N1 = N->getOperand(1);
8688 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8689 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8690 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8692 unsigned SplatBitSize;
8695 APInt SplatBits0, SplatBits1;
8696 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8697 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8698 // Ensure that the second operand of both ands are constants
8699 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8700 HasAnyUndefs) && !HasAnyUndefs) {
8701 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8702 HasAnyUndefs) && !HasAnyUndefs) {
8703 // Ensure that the bit width of the constants are the same and that
8704 // the splat arguments are logical inverses as per the pattern we
8705 // are trying to simplify.
8706 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8707 SplatBits0 == ~SplatBits1) {
8708 // Canonicalize the vector type to make instruction selection
8710 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8711 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8715 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8721 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8724 // BFI is only available on V6T2+
8725 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8729 // 1) or (and A, mask), val => ARMbfi A, val, mask
8730 // iff (val & mask) == val
8732 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8733 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8734 // && mask == ~mask2
8735 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8736 // && ~mask == mask2
8737 // (i.e., copy a bitfield value into another bitfield of the same width)
8742 SDValue N00 = N0.getOperand(0);
8744 // The value and the mask need to be constants so we can verify this is
8745 // actually a bitfield set. If the mask is 0xffff, we can do better
8746 // via a movt instruction, so don't use BFI in that case.
8747 SDValue MaskOp = N0.getOperand(1);
8748 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8751 unsigned Mask = MaskC->getZExtValue();
8755 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8756 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8758 unsigned Val = N1C->getZExtValue();
8759 if ((Val & ~Mask) != Val)
8762 if (ARM::isBitFieldInvertedMask(Mask)) {
8763 Val >>= countTrailingZeros(~Mask);
8765 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8766 DAG.getConstant(Val, DL, MVT::i32),
8767 DAG.getConstant(Mask, DL, MVT::i32));
8769 // Do not add new nodes to DAG combiner worklist.
8770 DCI.CombineTo(N, Res, false);
8773 } else if (N1.getOpcode() == ISD::AND) {
8774 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8775 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8778 unsigned Mask2 = N11C->getZExtValue();
8780 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8782 if (ARM::isBitFieldInvertedMask(Mask) &&
8784 // The pack halfword instruction works better for masks that fit it,
8785 // so use that when it's available.
8786 if (Subtarget->hasT2ExtractPack() &&
8787 (Mask == 0xffff || Mask == 0xffff0000))
8790 unsigned amt = countTrailingZeros(Mask2);
8791 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8792 DAG.getConstant(amt, DL, MVT::i32));
8793 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8794 DAG.getConstant(Mask, DL, MVT::i32));
8795 // Do not add new nodes to DAG combiner worklist.
8796 DCI.CombineTo(N, Res, false);
8798 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8800 // The pack halfword instruction works better for masks that fit it,
8801 // so use that when it's available.
8802 if (Subtarget->hasT2ExtractPack() &&
8803 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8806 unsigned lsb = countTrailingZeros(Mask);
8807 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8808 DAG.getConstant(lsb, DL, MVT::i32));
8809 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8810 DAG.getConstant(Mask2, DL, MVT::i32));
8811 // Do not add new nodes to DAG combiner worklist.
8812 DCI.CombineTo(N, Res, false);
8817 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8818 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8819 ARM::isBitFieldInvertedMask(~Mask)) {
8820 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8821 // where lsb(mask) == #shamt and masked bits of B are known zero.
8822 SDValue ShAmt = N00.getOperand(1);
8823 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8824 unsigned LSB = countTrailingZeros(Mask);
8828 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8829 DAG.getConstant(~Mask, DL, MVT::i32));
8831 // Do not add new nodes to DAG combiner worklist.
8832 DCI.CombineTo(N, Res, false);
8838 static SDValue PerformXORCombine(SDNode *N,
8839 TargetLowering::DAGCombinerInfo &DCI,
8840 const ARMSubtarget *Subtarget) {
8841 EVT VT = N->getValueType(0);
8842 SelectionDAG &DAG = DCI.DAG;
8844 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8847 if (!Subtarget->isThumb1Only()) {
8848 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8849 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8850 if (Result.getNode())
8857 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8858 /// the bits being cleared by the AND are not demanded by the BFI.
8859 static SDValue PerformBFICombine(SDNode *N,
8860 TargetLowering::DAGCombinerInfo &DCI) {
8861 SDValue N1 = N->getOperand(1);
8862 if (N1.getOpcode() == ISD::AND) {
8863 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8866 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8867 unsigned LSB = countTrailingZeros(~InvMask);
8868 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8870 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8871 "undefined behavior");
8872 unsigned Mask = (1u << Width) - 1;
8873 unsigned Mask2 = N11C->getZExtValue();
8874 if ((Mask & (~Mask2)) == 0)
8875 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8876 N->getOperand(0), N1.getOperand(0),
8882 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8883 /// ARMISD::VMOVRRD.
8884 static SDValue PerformVMOVRRDCombine(SDNode *N,
8885 TargetLowering::DAGCombinerInfo &DCI,
8886 const ARMSubtarget *Subtarget) {
8887 // vmovrrd(vmovdrr x, y) -> x,y
8888 SDValue InDouble = N->getOperand(0);
8889 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8890 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8892 // vmovrrd(load f64) -> (load i32), (load i32)
8893 SDNode *InNode = InDouble.getNode();
8894 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8895 InNode->getValueType(0) == MVT::f64 &&
8896 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8897 !cast<LoadSDNode>(InNode)->isVolatile()) {
8898 // TODO: Should this be done for non-FrameIndex operands?
8899 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8901 SelectionDAG &DAG = DCI.DAG;
8903 SDValue BasePtr = LD->getBasePtr();
8904 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8905 LD->getPointerInfo(), LD->isVolatile(),
8906 LD->isNonTemporal(), LD->isInvariant(),
8907 LD->getAlignment());
8909 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8910 DAG.getConstant(4, DL, MVT::i32));
8911 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8912 LD->getPointerInfo(), LD->isVolatile(),
8913 LD->isNonTemporal(), LD->isInvariant(),
8914 std::min(4U, LD->getAlignment() / 2));
8916 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8917 if (DCI.DAG.getDataLayout().isBigEndian())
8918 std::swap (NewLD1, NewLD2);
8919 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8926 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8927 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8928 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8929 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8930 SDValue Op0 = N->getOperand(0);
8931 SDValue Op1 = N->getOperand(1);
8932 if (Op0.getOpcode() == ISD::BITCAST)
8933 Op0 = Op0.getOperand(0);
8934 if (Op1.getOpcode() == ISD::BITCAST)
8935 Op1 = Op1.getOperand(0);
8936 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8937 Op0.getNode() == Op1.getNode() &&
8938 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8939 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8940 N->getValueType(0), Op0.getOperand(0));
8944 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8945 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8946 /// i64 vector to have f64 elements, since the value can then be loaded
8947 /// directly into a VFP register.
8948 static bool hasNormalLoadOperand(SDNode *N) {
8949 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8950 for (unsigned i = 0; i < NumElts; ++i) {
8951 SDNode *Elt = N->getOperand(i).getNode();
8952 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8958 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8959 /// ISD::BUILD_VECTOR.
8960 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8961 TargetLowering::DAGCombinerInfo &DCI,
8962 const ARMSubtarget *Subtarget) {
8963 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8964 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8965 // into a pair of GPRs, which is fine when the value is used as a scalar,
8966 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8967 SelectionDAG &DAG = DCI.DAG;
8968 if (N->getNumOperands() == 2) {
8969 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8974 // Load i64 elements as f64 values so that type legalization does not split
8975 // them up into i32 values.
8976 EVT VT = N->getValueType(0);
8977 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8980 SmallVector<SDValue, 8> Ops;
8981 unsigned NumElts = VT.getVectorNumElements();
8982 for (unsigned i = 0; i < NumElts; ++i) {
8983 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8985 // Make the DAGCombiner fold the bitcast.
8986 DCI.AddToWorklist(V.getNode());
8988 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8989 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8990 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8993 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8995 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8996 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8997 // At that time, we may have inserted bitcasts from integer to float.
8998 // If these bitcasts have survived DAGCombine, change the lowering of this
8999 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9000 // force to use floating point types.
9002 // Make sure we can change the type of the vector.
9003 // This is possible iff:
9004 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9005 // 1.1. Vector is used only once.
9006 // 1.2. Use is a bit convert to an integer type.
9007 // 2. The size of its operands are 32-bits (64-bits are not legal).
9008 EVT VT = N->getValueType(0);
9009 EVT EltVT = VT.getVectorElementType();
9011 // Check 1.1. and 2.
9012 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9015 // By construction, the input type must be float.
9016 assert(EltVT == MVT::f32 && "Unexpected type!");
9019 SDNode *Use = *N->use_begin();
9020 if (Use->getOpcode() != ISD::BITCAST ||
9021 Use->getValueType(0).isFloatingPoint())
9024 // Check profitability.
9025 // Model is, if more than half of the relevant operands are bitcast from
9026 // i32, turn the build_vector into a sequence of insert_vector_elt.
9027 // Relevant operands are everything that is not statically
9028 // (i.e., at compile time) bitcasted.
9029 unsigned NumOfBitCastedElts = 0;
9030 unsigned NumElts = VT.getVectorNumElements();
9031 unsigned NumOfRelevantElts = NumElts;
9032 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9033 SDValue Elt = N->getOperand(Idx);
9034 if (Elt->getOpcode() == ISD::BITCAST) {
9035 // Assume only bit cast to i32 will go away.
9036 if (Elt->getOperand(0).getValueType() == MVT::i32)
9037 ++NumOfBitCastedElts;
9038 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9039 // Constants are statically casted, thus do not count them as
9040 // relevant operands.
9041 --NumOfRelevantElts;
9044 // Check if more than half of the elements require a non-free bitcast.
9045 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9048 SelectionDAG &DAG = DCI.DAG;
9049 // Create the new vector type.
9050 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9051 // Check if the type is legal.
9052 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9053 if (!TLI.isTypeLegal(VecVT))
9057 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9058 // => BITCAST INSERT_VECTOR_ELT
9059 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9061 SDValue Vec = DAG.getUNDEF(VecVT);
9063 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9064 SDValue V = N->getOperand(Idx);
9065 if (V.getOpcode() == ISD::UNDEF)
9067 if (V.getOpcode() == ISD::BITCAST &&
9068 V->getOperand(0).getValueType() == MVT::i32)
9069 // Fold obvious case.
9070 V = V.getOperand(0);
9072 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9073 // Make the DAGCombiner fold the bitcasts.
9074 DCI.AddToWorklist(V.getNode());
9076 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9077 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9079 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9080 // Make the DAGCombiner fold the bitcasts.
9081 DCI.AddToWorklist(Vec.getNode());
9085 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9086 /// ISD::INSERT_VECTOR_ELT.
9087 static SDValue PerformInsertEltCombine(SDNode *N,
9088 TargetLowering::DAGCombinerInfo &DCI) {
9089 // Bitcast an i64 load inserted into a vector to f64.
9090 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9091 EVT VT = N->getValueType(0);
9092 SDNode *Elt = N->getOperand(1).getNode();
9093 if (VT.getVectorElementType() != MVT::i64 ||
9094 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9097 SelectionDAG &DAG = DCI.DAG;
9099 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9100 VT.getVectorNumElements());
9101 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9102 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9103 // Make the DAGCombiner fold the bitcasts.
9104 DCI.AddToWorklist(Vec.getNode());
9105 DCI.AddToWorklist(V.getNode());
9106 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9107 Vec, V, N->getOperand(2));
9108 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9111 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9112 /// ISD::VECTOR_SHUFFLE.
9113 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9114 // The LLVM shufflevector instruction does not require the shuffle mask
9115 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9116 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9117 // operands do not match the mask length, they are extended by concatenating
9118 // them with undef vectors. That is probably the right thing for other
9119 // targets, but for NEON it is better to concatenate two double-register
9120 // size vector operands into a single quad-register size vector. Do that
9121 // transformation here:
9122 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9123 // shuffle(concat(v1, v2), undef)
9124 SDValue Op0 = N->getOperand(0);
9125 SDValue Op1 = N->getOperand(1);
9126 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9127 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9128 Op0.getNumOperands() != 2 ||
9129 Op1.getNumOperands() != 2)
9131 SDValue Concat0Op1 = Op0.getOperand(1);
9132 SDValue Concat1Op1 = Op1.getOperand(1);
9133 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9134 Concat1Op1.getOpcode() != ISD::UNDEF)
9136 // Skip the transformation if any of the types are illegal.
9137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9138 EVT VT = N->getValueType(0);
9139 if (!TLI.isTypeLegal(VT) ||
9140 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9141 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9144 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9145 Op0.getOperand(0), Op1.getOperand(0));
9146 // Translate the shuffle mask.
9147 SmallVector<int, 16> NewMask;
9148 unsigned NumElts = VT.getVectorNumElements();
9149 unsigned HalfElts = NumElts/2;
9150 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9151 for (unsigned n = 0; n < NumElts; ++n) {
9152 int MaskElt = SVN->getMaskElt(n);
9154 if (MaskElt < (int)HalfElts)
9156 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9157 NewElt = HalfElts + MaskElt - NumElts;
9158 NewMask.push_back(NewElt);
9160 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9161 DAG.getUNDEF(VT), NewMask.data());
9164 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9165 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9166 /// base address updates.
9167 /// For generic load/stores, the memory type is assumed to be a vector.
9168 /// The caller is assumed to have checked legality.
9169 static SDValue CombineBaseUpdate(SDNode *N,
9170 TargetLowering::DAGCombinerInfo &DCI) {
9171 SelectionDAG &DAG = DCI.DAG;
9172 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9173 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9174 const bool isStore = N->getOpcode() == ISD::STORE;
9175 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9176 SDValue Addr = N->getOperand(AddrOpIdx);
9177 MemSDNode *MemN = cast<MemSDNode>(N);
9180 // Search for a use of the address operand that is an increment.
9181 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9182 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9184 if (User->getOpcode() != ISD::ADD ||
9185 UI.getUse().getResNo() != Addr.getResNo())
9188 // Check that the add is independent of the load/store. Otherwise, folding
9189 // it would create a cycle.
9190 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9193 // Find the new opcode for the updating load/store.
9194 bool isLoadOp = true;
9195 bool isLaneOp = false;
9196 unsigned NewOpc = 0;
9197 unsigned NumVecs = 0;
9199 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9201 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9202 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9204 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9206 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9208 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9210 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9211 NumVecs = 2; isLaneOp = true; break;
9212 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9213 NumVecs = 3; isLaneOp = true; break;
9214 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9215 NumVecs = 4; isLaneOp = true; break;
9216 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9217 NumVecs = 1; isLoadOp = false; break;
9218 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9219 NumVecs = 2; isLoadOp = false; break;
9220 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9221 NumVecs = 3; isLoadOp = false; break;
9222 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9223 NumVecs = 4; isLoadOp = false; break;
9224 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9225 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9226 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9227 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9228 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9229 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9233 switch (N->getOpcode()) {
9234 default: llvm_unreachable("unexpected opcode for Neon base update");
9235 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9236 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9237 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9238 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9239 NumVecs = 1; isLaneOp = false; break;
9240 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9241 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9245 // Find the size of memory referenced by the load/store.
9248 VecTy = N->getValueType(0);
9249 } else if (isIntrinsic) {
9250 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9252 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9253 VecTy = N->getOperand(1).getValueType();
9256 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9258 NumBytes /= VecTy.getVectorNumElements();
9260 // If the increment is a constant, it must match the memory ref size.
9261 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9262 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9263 uint64_t IncVal = CInc->getZExtValue();
9264 if (IncVal != NumBytes)
9266 } else if (NumBytes >= 3 * 16) {
9267 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9268 // separate instructions that make it harder to use a non-constant update.
9272 // OK, we found an ADD we can fold into the base update.
9273 // Now, create a _UPD node, taking care of not breaking alignment.
9275 EVT AlignedVecTy = VecTy;
9276 unsigned Alignment = MemN->getAlignment();
9278 // If this is a less-than-standard-aligned load/store, change the type to
9279 // match the standard alignment.
9280 // The alignment is overlooked when selecting _UPD variants; and it's
9281 // easier to introduce bitcasts here than fix that.
9282 // There are 3 ways to get to this base-update combine:
9283 // - intrinsics: they are assumed to be properly aligned (to the standard
9284 // alignment of the memory type), so we don't need to do anything.
9285 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9286 // intrinsics, so, likewise, there's nothing to do.
9287 // - generic load/store instructions: the alignment is specified as an
9288 // explicit operand, rather than implicitly as the standard alignment
9289 // of the memory type (like the intrisics). We need to change the
9290 // memory type to match the explicit alignment. That way, we don't
9291 // generate non-standard-aligned ARMISD::VLDx nodes.
9292 if (isa<LSBaseSDNode>(N)) {
9295 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9296 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9297 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9298 assert(!isLaneOp && "Unexpected generic load/store lane.");
9299 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9300 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9302 // Don't set an explicit alignment on regular load/stores that we want
9303 // to transform to VLD/VST 1_UPD nodes.
9304 // This matches the behavior of regular load/stores, which only get an
9305 // explicit alignment if the MMO alignment is larger than the standard
9306 // alignment of the memory type.
9307 // Intrinsics, however, always get an explicit alignment, set to the
9308 // alignment of the MMO.
9312 // Create the new updating load/store node.
9313 // First, create an SDVTList for the new updating node's results.
9315 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9317 for (n = 0; n < NumResultVecs; ++n)
9318 Tys[n] = AlignedVecTy;
9319 Tys[n++] = MVT::i32;
9320 Tys[n] = MVT::Other;
9321 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9323 // Then, gather the new node's operands.
9324 SmallVector<SDValue, 8> Ops;
9325 Ops.push_back(N->getOperand(0)); // incoming chain
9326 Ops.push_back(N->getOperand(AddrOpIdx));
9329 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9330 // Try to match the intrinsic's signature
9331 Ops.push_back(StN->getValue());
9333 // Loads (and of course intrinsics) match the intrinsics' signature,
9334 // so just add all but the alignment operand.
9335 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9336 Ops.push_back(N->getOperand(i));
9339 // For all node types, the alignment operand is always the last one.
9340 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9342 // If this is a non-standard-aligned STORE, the penultimate operand is the
9343 // stored value. Bitcast it to the aligned type.
9344 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9345 SDValue &StVal = Ops[Ops.size()-2];
9346 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9349 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9351 MemN->getMemOperand());
9354 SmallVector<SDValue, 5> NewResults;
9355 for (unsigned i = 0; i < NumResultVecs; ++i)
9356 NewResults.push_back(SDValue(UpdN.getNode(), i));
9358 // If this is an non-standard-aligned LOAD, the first result is the loaded
9359 // value. Bitcast it to the expected result type.
9360 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9361 SDValue &LdVal = NewResults[0];
9362 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9365 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9366 DCI.CombineTo(N, NewResults);
9367 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9374 static SDValue PerformVLDCombine(SDNode *N,
9375 TargetLowering::DAGCombinerInfo &DCI) {
9376 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9379 return CombineBaseUpdate(N, DCI);
9382 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9383 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9384 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9386 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9387 SelectionDAG &DAG = DCI.DAG;
9388 EVT VT = N->getValueType(0);
9389 // vldN-dup instructions only support 64-bit vectors for N > 1.
9390 if (!VT.is64BitVector())
9393 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9394 SDNode *VLD = N->getOperand(0).getNode();
9395 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9397 unsigned NumVecs = 0;
9398 unsigned NewOpc = 0;
9399 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9400 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9402 NewOpc = ARMISD::VLD2DUP;
9403 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9405 NewOpc = ARMISD::VLD3DUP;
9406 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9408 NewOpc = ARMISD::VLD4DUP;
9413 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9414 // numbers match the load.
9415 unsigned VLDLaneNo =
9416 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9417 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9419 // Ignore uses of the chain result.
9420 if (UI.getUse().getResNo() == NumVecs)
9423 if (User->getOpcode() != ARMISD::VDUPLANE ||
9424 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9428 // Create the vldN-dup node.
9431 for (n = 0; n < NumVecs; ++n)
9433 Tys[n] = MVT::Other;
9434 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9435 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9436 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9437 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9438 Ops, VLDMemInt->getMemoryVT(),
9439 VLDMemInt->getMemOperand());
9442 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9444 unsigned ResNo = UI.getUse().getResNo();
9445 // Ignore uses of the chain result.
9446 if (ResNo == NumVecs)
9449 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9452 // Now the vldN-lane intrinsic is dead except for its chain result.
9453 // Update uses of the chain.
9454 std::vector<SDValue> VLDDupResults;
9455 for (unsigned n = 0; n < NumVecs; ++n)
9456 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9457 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9458 DCI.CombineTo(VLD, VLDDupResults);
9463 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9464 /// ARMISD::VDUPLANE.
9465 static SDValue PerformVDUPLANECombine(SDNode *N,
9466 TargetLowering::DAGCombinerInfo &DCI) {
9467 SDValue Op = N->getOperand(0);
9469 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9470 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9471 if (CombineVLDDUP(N, DCI))
9472 return SDValue(N, 0);
9474 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9475 // redundant. Ignore bit_converts for now; element sizes are checked below.
9476 while (Op.getOpcode() == ISD::BITCAST)
9477 Op = Op.getOperand(0);
9478 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9481 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9482 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9483 // The canonical VMOV for a zero vector uses a 32-bit element size.
9484 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9486 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9488 EVT VT = N->getValueType(0);
9489 if (EltSize > VT.getVectorElementType().getSizeInBits())
9492 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9495 static SDValue PerformLOADCombine(SDNode *N,
9496 TargetLowering::DAGCombinerInfo &DCI) {
9497 EVT VT = N->getValueType(0);
9499 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9500 if (ISD::isNormalLoad(N) && VT.isVector() &&
9501 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9502 return CombineBaseUpdate(N, DCI);
9507 /// PerformSTORECombine - Target-specific dag combine xforms for
9509 static SDValue PerformSTORECombine(SDNode *N,
9510 TargetLowering::DAGCombinerInfo &DCI) {
9511 StoreSDNode *St = cast<StoreSDNode>(N);
9512 if (St->isVolatile())
9515 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9516 // pack all of the elements in one place. Next, store to memory in fewer
9518 SDValue StVal = St->getValue();
9519 EVT VT = StVal.getValueType();
9520 if (St->isTruncatingStore() && VT.isVector()) {
9521 SelectionDAG &DAG = DCI.DAG;
9522 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9523 EVT StVT = St->getMemoryVT();
9524 unsigned NumElems = VT.getVectorNumElements();
9525 assert(StVT != VT && "Cannot truncate to the same type");
9526 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9527 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9529 // From, To sizes and ElemCount must be pow of two
9530 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9532 // We are going to use the original vector elt for storing.
9533 // Accumulated smaller vector elements must be a multiple of the store size.
9534 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9536 unsigned SizeRatio = FromEltSz / ToEltSz;
9537 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9539 // Create a type on which we perform the shuffle.
9540 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9541 NumElems*SizeRatio);
9542 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9545 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9546 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9547 for (unsigned i = 0; i < NumElems; ++i)
9548 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9549 ? (i + 1) * SizeRatio - 1
9552 // Can't shuffle using an illegal type.
9553 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9555 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9556 DAG.getUNDEF(WideVec.getValueType()),
9558 // At this point all of the data is stored at the bottom of the
9559 // register. We now need to save it to mem.
9561 // Find the largest store unit
9562 MVT StoreType = MVT::i8;
9563 for (MVT Tp : MVT::integer_valuetypes()) {
9564 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9567 // Didn't find a legal store type.
9568 if (!TLI.isTypeLegal(StoreType))
9571 // Bitcast the original vector into a vector of store-size units
9572 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9573 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9574 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9575 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9576 SmallVector<SDValue, 8> Chains;
9577 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9578 TLI.getPointerTy(DAG.getDataLayout()));
9579 SDValue BasePtr = St->getBasePtr();
9581 // Perform one or more big stores into memory.
9582 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9583 for (unsigned I = 0; I < E; I++) {
9584 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9585 StoreType, ShuffWide,
9586 DAG.getIntPtrConstant(I, DL));
9587 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9588 St->getPointerInfo(), St->isVolatile(),
9589 St->isNonTemporal(), St->getAlignment());
9590 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9592 Chains.push_back(Ch);
9594 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9597 if (!ISD::isNormalStore(St))
9600 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9601 // ARM stores of arguments in the same cache line.
9602 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9603 StVal.getNode()->hasOneUse()) {
9604 SelectionDAG &DAG = DCI.DAG;
9605 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9607 SDValue BasePtr = St->getBasePtr();
9608 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9609 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9610 BasePtr, St->getPointerInfo(), St->isVolatile(),
9611 St->isNonTemporal(), St->getAlignment());
9613 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9614 DAG.getConstant(4, DL, MVT::i32));
9615 return DAG.getStore(NewST1.getValue(0), DL,
9616 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9617 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9618 St->isNonTemporal(),
9619 std::min(4U, St->getAlignment() / 2));
9622 if (StVal.getValueType() == MVT::i64 &&
9623 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9625 // Bitcast an i64 store extracted from a vector to f64.
9626 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9627 SelectionDAG &DAG = DCI.DAG;
9629 SDValue IntVec = StVal.getOperand(0);
9630 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9631 IntVec.getValueType().getVectorNumElements());
9632 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9633 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9634 Vec, StVal.getOperand(1));
9636 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9637 // Make the DAGCombiner fold the bitcasts.
9638 DCI.AddToWorklist(Vec.getNode());
9639 DCI.AddToWorklist(ExtElt.getNode());
9640 DCI.AddToWorklist(V.getNode());
9641 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9642 St->getPointerInfo(), St->isVolatile(),
9643 St->isNonTemporal(), St->getAlignment(),
9647 // If this is a legal vector store, try to combine it into a VST1_UPD.
9648 if (ISD::isNormalStore(N) && VT.isVector() &&
9649 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9650 return CombineBaseUpdate(N, DCI);
9655 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9656 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9657 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9661 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9663 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9668 APFloat APF = C->getValueAPF();
9669 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9670 != APFloat::opOK || !isExact)
9673 c0 = (I == 0) ? cN : c0;
9674 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9681 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9682 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9683 /// when the VMUL has a constant operand that is a power of 2.
9685 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9686 /// vmul.f32 d16, d17, d16
9687 /// vcvt.s32.f32 d16, d16
9689 /// vcvt.s32.f32 d16, d16, #3
9690 static SDValue PerformVCVTCombine(SDNode *N,
9691 TargetLowering::DAGCombinerInfo &DCI,
9692 const ARMSubtarget *Subtarget) {
9693 SelectionDAG &DAG = DCI.DAG;
9694 SDValue Op = N->getOperand(0);
9696 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9697 Op.getOpcode() != ISD::FMUL)
9701 SDValue N0 = Op->getOperand(0);
9702 SDValue ConstVec = Op->getOperand(1);
9703 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9705 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9706 !isConstVecPow2(ConstVec, isSigned, C))
9709 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9710 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9711 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9712 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9714 // These instructions only exist converting from f32 to i32. We can handle
9715 // smaller integers by generating an extra truncate, but larger ones would
9716 // be lossy. We also can't handle more then 4 lanes, since these intructions
9717 // only support v2i32/v4i32 types.
9722 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9723 Intrinsic::arm_neon_vcvtfp2fxu;
9724 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9725 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9726 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9728 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9730 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9731 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9736 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9737 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9738 /// when the VDIV has a constant operand that is a power of 2.
9740 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9741 /// vcvt.f32.s32 d16, d16
9742 /// vdiv.f32 d16, d17, d16
9744 /// vcvt.f32.s32 d16, d16, #3
9745 static SDValue PerformVDIVCombine(SDNode *N,
9746 TargetLowering::DAGCombinerInfo &DCI,
9747 const ARMSubtarget *Subtarget) {
9748 SelectionDAG &DAG = DCI.DAG;
9749 SDValue Op = N->getOperand(0);
9750 unsigned OpOpcode = Op.getNode()->getOpcode();
9752 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9753 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9757 SDValue ConstVec = N->getOperand(1);
9758 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9760 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9761 !isConstVecPow2(ConstVec, isSigned, C))
9764 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9765 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9766 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9767 // These instructions only exist converting from i32 to f32. We can handle
9768 // smaller integers by generating an extra extend, but larger ones would
9774 SDValue ConvInput = Op.getOperand(0);
9775 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9776 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9777 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9778 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9781 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9782 Intrinsic::arm_neon_vcvtfxu2fp;
9783 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9785 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9786 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9789 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9790 /// operand of a vector shift operation, where all the elements of the
9791 /// build_vector must have the same constant integer value.
9792 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9793 // Ignore bit_converts.
9794 while (Op.getOpcode() == ISD::BITCAST)
9795 Op = Op.getOperand(0);
9796 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9797 APInt SplatBits, SplatUndef;
9798 unsigned SplatBitSize;
9800 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9801 HasAnyUndefs, ElementBits) ||
9802 SplatBitSize > ElementBits)
9804 Cnt = SplatBits.getSExtValue();
9808 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9809 /// operand of a vector shift left operation. That value must be in the range:
9810 /// 0 <= Value < ElementBits for a left shift; or
9811 /// 0 <= Value <= ElementBits for a long left shift.
9812 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9813 assert(VT.isVector() && "vector shift count is not a vector type");
9814 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9815 if (! getVShiftImm(Op, ElementBits, Cnt))
9817 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9820 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9821 /// operand of a vector shift right operation. For a shift opcode, the value
9822 /// is positive, but for an intrinsic the value count must be negative. The
9823 /// absolute value must be in the range:
9824 /// 1 <= |Value| <= ElementBits for a right shift; or
9825 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9826 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9828 assert(VT.isVector() && "vector shift count is not a vector type");
9829 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9830 if (! getVShiftImm(Op, ElementBits, Cnt))
9833 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9834 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9841 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9842 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9843 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9846 // Don't do anything for most intrinsics.
9849 case Intrinsic::arm_neon_vabds:
9850 if (!N->getValueType(0).isInteger())
9852 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9853 N->getOperand(1), N->getOperand(2));
9854 case Intrinsic::arm_neon_vabdu:
9855 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9856 N->getOperand(1), N->getOperand(2));
9858 // Vector shifts: check for immediate versions and lower them.
9859 // Note: This is done during DAG combining instead of DAG legalizing because
9860 // the build_vectors for 64-bit vector element shift counts are generally
9861 // not legal, and it is hard to see their values after they get legalized to
9862 // loads from a constant pool.
9863 case Intrinsic::arm_neon_vshifts:
9864 case Intrinsic::arm_neon_vshiftu:
9865 case Intrinsic::arm_neon_vrshifts:
9866 case Intrinsic::arm_neon_vrshiftu:
9867 case Intrinsic::arm_neon_vrshiftn:
9868 case Intrinsic::arm_neon_vqshifts:
9869 case Intrinsic::arm_neon_vqshiftu:
9870 case Intrinsic::arm_neon_vqshiftsu:
9871 case Intrinsic::arm_neon_vqshiftns:
9872 case Intrinsic::arm_neon_vqshiftnu:
9873 case Intrinsic::arm_neon_vqshiftnsu:
9874 case Intrinsic::arm_neon_vqrshiftns:
9875 case Intrinsic::arm_neon_vqrshiftnu:
9876 case Intrinsic::arm_neon_vqrshiftnsu: {
9877 EVT VT = N->getOperand(1).getValueType();
9879 unsigned VShiftOpc = 0;
9882 case Intrinsic::arm_neon_vshifts:
9883 case Intrinsic::arm_neon_vshiftu:
9884 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9885 VShiftOpc = ARMISD::VSHL;
9888 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9889 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9890 ARMISD::VSHRs : ARMISD::VSHRu);
9895 case Intrinsic::arm_neon_vrshifts:
9896 case Intrinsic::arm_neon_vrshiftu:
9897 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9901 case Intrinsic::arm_neon_vqshifts:
9902 case Intrinsic::arm_neon_vqshiftu:
9903 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9907 case Intrinsic::arm_neon_vqshiftsu:
9908 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9910 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9912 case Intrinsic::arm_neon_vrshiftn:
9913 case Intrinsic::arm_neon_vqshiftns:
9914 case Intrinsic::arm_neon_vqshiftnu:
9915 case Intrinsic::arm_neon_vqshiftnsu:
9916 case Intrinsic::arm_neon_vqrshiftns:
9917 case Intrinsic::arm_neon_vqrshiftnu:
9918 case Intrinsic::arm_neon_vqrshiftnsu:
9919 // Narrowing shifts require an immediate right shift.
9920 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9922 llvm_unreachable("invalid shift count for narrowing vector shift "
9926 llvm_unreachable("unhandled vector shift");
9930 case Intrinsic::arm_neon_vshifts:
9931 case Intrinsic::arm_neon_vshiftu:
9932 // Opcode already set above.
9934 case Intrinsic::arm_neon_vrshifts:
9935 VShiftOpc = ARMISD::VRSHRs; break;
9936 case Intrinsic::arm_neon_vrshiftu:
9937 VShiftOpc = ARMISD::VRSHRu; break;
9938 case Intrinsic::arm_neon_vrshiftn:
9939 VShiftOpc = ARMISD::VRSHRN; break;
9940 case Intrinsic::arm_neon_vqshifts:
9941 VShiftOpc = ARMISD::VQSHLs; break;
9942 case Intrinsic::arm_neon_vqshiftu:
9943 VShiftOpc = ARMISD::VQSHLu; break;
9944 case Intrinsic::arm_neon_vqshiftsu:
9945 VShiftOpc = ARMISD::VQSHLsu; break;
9946 case Intrinsic::arm_neon_vqshiftns:
9947 VShiftOpc = ARMISD::VQSHRNs; break;
9948 case Intrinsic::arm_neon_vqshiftnu:
9949 VShiftOpc = ARMISD::VQSHRNu; break;
9950 case Intrinsic::arm_neon_vqshiftnsu:
9951 VShiftOpc = ARMISD::VQSHRNsu; break;
9952 case Intrinsic::arm_neon_vqrshiftns:
9953 VShiftOpc = ARMISD::VQRSHRNs; break;
9954 case Intrinsic::arm_neon_vqrshiftnu:
9955 VShiftOpc = ARMISD::VQRSHRNu; break;
9956 case Intrinsic::arm_neon_vqrshiftnsu:
9957 VShiftOpc = ARMISD::VQRSHRNsu; break;
9961 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9962 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9965 case Intrinsic::arm_neon_vshiftins: {
9966 EVT VT = N->getOperand(1).getValueType();
9968 unsigned VShiftOpc = 0;
9970 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9971 VShiftOpc = ARMISD::VSLI;
9972 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9973 VShiftOpc = ARMISD::VSRI;
9975 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9979 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9980 N->getOperand(1), N->getOperand(2),
9981 DAG.getConstant(Cnt, dl, MVT::i32));
9984 case Intrinsic::arm_neon_vqrshifts:
9985 case Intrinsic::arm_neon_vqrshiftu:
9986 // No immediate versions of these to check for.
9993 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9994 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9995 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9996 /// vector element shift counts are generally not legal, and it is hard to see
9997 /// their values after they get legalized to loads from a constant pool.
9998 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9999 const ARMSubtarget *ST) {
10000 EVT VT = N->getValueType(0);
10001 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10002 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10003 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10004 SDValue N1 = N->getOperand(1);
10005 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10006 SDValue N0 = N->getOperand(0);
10007 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10008 DAG.MaskedValueIsZero(N0.getOperand(0),
10009 APInt::getHighBitsSet(32, 16)))
10010 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10014 // Nothing to be done for scalar shifts.
10015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10016 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10019 assert(ST->hasNEON() && "unexpected vector shift");
10022 switch (N->getOpcode()) {
10023 default: llvm_unreachable("unexpected shift opcode");
10026 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10028 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10029 DAG.getConstant(Cnt, dl, MVT::i32));
10035 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10036 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10037 ARMISD::VSHRs : ARMISD::VSHRu);
10039 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10040 DAG.getConstant(Cnt, dl, MVT::i32));
10046 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10047 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10048 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10049 const ARMSubtarget *ST) {
10050 SDValue N0 = N->getOperand(0);
10052 // Check for sign- and zero-extensions of vector extract operations of 8-
10053 // and 16-bit vector elements. NEON supports these directly. They are
10054 // handled during DAG combining because type legalization will promote them
10055 // to 32-bit types and it is messy to recognize the operations after that.
10056 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10057 SDValue Vec = N0.getOperand(0);
10058 SDValue Lane = N0.getOperand(1);
10059 EVT VT = N->getValueType(0);
10060 EVT EltVT = N0.getValueType();
10061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10063 if (VT == MVT::i32 &&
10064 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10065 TLI.isTypeLegal(Vec.getValueType()) &&
10066 isa<ConstantSDNode>(Lane)) {
10069 switch (N->getOpcode()) {
10070 default: llvm_unreachable("unexpected opcode");
10071 case ISD::SIGN_EXTEND:
10072 Opc = ARMISD::VGETLANEs;
10074 case ISD::ZERO_EXTEND:
10075 case ISD::ANY_EXTEND:
10076 Opc = ARMISD::VGETLANEu;
10079 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10086 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10088 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10089 SDValue Cmp = N->getOperand(4);
10090 if (Cmp.getOpcode() != ARMISD::CMPZ)
10091 // Only looking at EQ and NE cases.
10094 EVT VT = N->getValueType(0);
10096 SDValue LHS = Cmp.getOperand(0);
10097 SDValue RHS = Cmp.getOperand(1);
10098 SDValue FalseVal = N->getOperand(0);
10099 SDValue TrueVal = N->getOperand(1);
10100 SDValue ARMcc = N->getOperand(2);
10101 ARMCC::CondCodes CC =
10102 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10120 /// FIXME: Turn this into a target neutral optimization?
10122 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10123 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10124 N->getOperand(3), Cmp);
10125 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10127 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10128 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10129 N->getOperand(3), NewCmp);
10132 if (Res.getNode()) {
10133 APInt KnownZero, KnownOne;
10134 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10135 // Capture demanded bits information that would be otherwise lost.
10136 if (KnownZero == 0xfffffffe)
10137 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10138 DAG.getValueType(MVT::i1));
10139 else if (KnownZero == 0xffffff00)
10140 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10141 DAG.getValueType(MVT::i8));
10142 else if (KnownZero == 0xffff0000)
10143 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10144 DAG.getValueType(MVT::i16));
10150 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10151 DAGCombinerInfo &DCI) const {
10152 switch (N->getOpcode()) {
10154 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10155 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10156 case ISD::SUB: return PerformSUBCombine(N, DCI);
10157 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10158 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10159 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10160 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10161 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10162 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10163 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10164 case ISD::STORE: return PerformSTORECombine(N, DCI);
10165 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10166 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10167 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10168 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10169 case ISD::FP_TO_SINT:
10170 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10171 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10172 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10175 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10176 case ISD::SIGN_EXTEND:
10177 case ISD::ZERO_EXTEND:
10178 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10179 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10180 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10181 case ARMISD::VLD2DUP:
10182 case ARMISD::VLD3DUP:
10183 case ARMISD::VLD4DUP:
10184 return PerformVLDCombine(N, DCI);
10185 case ARMISD::BUILD_VECTOR:
10186 return PerformARMBUILD_VECTORCombine(N, DCI);
10187 case ISD::INTRINSIC_VOID:
10188 case ISD::INTRINSIC_W_CHAIN:
10189 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10190 case Intrinsic::arm_neon_vld1:
10191 case Intrinsic::arm_neon_vld2:
10192 case Intrinsic::arm_neon_vld3:
10193 case Intrinsic::arm_neon_vld4:
10194 case Intrinsic::arm_neon_vld2lane:
10195 case Intrinsic::arm_neon_vld3lane:
10196 case Intrinsic::arm_neon_vld4lane:
10197 case Intrinsic::arm_neon_vst1:
10198 case Intrinsic::arm_neon_vst2:
10199 case Intrinsic::arm_neon_vst3:
10200 case Intrinsic::arm_neon_vst4:
10201 case Intrinsic::arm_neon_vst2lane:
10202 case Intrinsic::arm_neon_vst3lane:
10203 case Intrinsic::arm_neon_vst4lane:
10204 return PerformVLDCombine(N, DCI);
10212 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10214 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10217 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10220 bool *Fast) const {
10221 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10222 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10224 switch (VT.getSimpleVT().SimpleTy) {
10230 // Unaligned access can use (for example) LRDB, LRDH, LDR
10231 if (AllowsUnaligned) {
10233 *Fast = Subtarget->hasV7Ops();
10240 // For any little-endian targets with neon, we can support unaligned ld/st
10241 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10242 // A big-endian target may also explicitly support unaligned accesses
10243 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10253 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10254 unsigned AlignCheck) {
10255 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10256 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10259 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10260 unsigned DstAlign, unsigned SrcAlign,
10261 bool IsMemset, bool ZeroMemset,
10263 MachineFunction &MF) const {
10264 const Function *F = MF.getFunction();
10266 // See if we can use NEON instructions for this...
10267 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10268 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10271 (memOpAlign(SrcAlign, DstAlign, 16) ||
10272 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10274 } else if (Size >= 8 &&
10275 (memOpAlign(SrcAlign, DstAlign, 8) ||
10276 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10282 // Lowering to i32/i16 if the size permits.
10285 else if (Size >= 2)
10288 // Let the target-independent logic figure it out.
10292 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10293 if (Val.getOpcode() != ISD::LOAD)
10296 EVT VT1 = Val.getValueType();
10297 if (!VT1.isSimple() || !VT1.isInteger() ||
10298 !VT2.isSimple() || !VT2.isInteger())
10301 switch (VT1.getSimpleVT().SimpleTy) {
10306 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10313 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10314 EVT VT = ExtVal.getValueType();
10316 if (!isTypeLegal(VT))
10319 // Don't create a loadext if we can fold the extension into a wide/long
10321 // If there's more than one user instruction, the loadext is desirable no
10322 // matter what. There can be two uses by the same instruction.
10323 if (ExtVal->use_empty() ||
10324 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10327 SDNode *U = *ExtVal->use_begin();
10328 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10329 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10335 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10336 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10339 if (!isTypeLegal(EVT::getEVT(Ty1)))
10342 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10344 // Assuming the caller doesn't have a zeroext or signext return parameter,
10345 // truncation all the way down to i1 is valid.
10350 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10354 unsigned Scale = 1;
10355 switch (VT.getSimpleVT().SimpleTy) {
10356 default: return false;
10371 if ((V & (Scale - 1)) != 0)
10374 return V == (V & ((1LL << 5) - 1));
10377 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10378 const ARMSubtarget *Subtarget) {
10379 bool isNeg = false;
10385 switch (VT.getSimpleVT().SimpleTy) {
10386 default: return false;
10391 // + imm12 or - imm8
10393 return V == (V & ((1LL << 8) - 1));
10394 return V == (V & ((1LL << 12) - 1));
10397 // Same as ARM mode. FIXME: NEON?
10398 if (!Subtarget->hasVFP2())
10403 return V == (V & ((1LL << 8) - 1));
10407 /// isLegalAddressImmediate - Return true if the integer value can be used
10408 /// as the offset of the target addressing mode for load / store of the
10410 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10411 const ARMSubtarget *Subtarget) {
10415 if (!VT.isSimple())
10418 if (Subtarget->isThumb1Only())
10419 return isLegalT1AddressImmediate(V, VT);
10420 else if (Subtarget->isThumb2())
10421 return isLegalT2AddressImmediate(V, VT, Subtarget);
10426 switch (VT.getSimpleVT().SimpleTy) {
10427 default: return false;
10432 return V == (V & ((1LL << 12) - 1));
10435 return V == (V & ((1LL << 8) - 1));
10438 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10443 return V == (V & ((1LL << 8) - 1));
10447 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10449 int Scale = AM.Scale;
10453 switch (VT.getSimpleVT().SimpleTy) {
10454 default: return false;
10462 Scale = Scale & ~1;
10463 return Scale == 2 || Scale == 4 || Scale == 8;
10466 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10470 // Note, we allow "void" uses (basically, uses that aren't loads or
10471 // stores), because arm allows folding a scale into many arithmetic
10472 // operations. This should be made more precise and revisited later.
10474 // Allow r << imm, but the imm has to be a multiple of two.
10475 if (Scale & 1) return false;
10476 return isPowerOf2_32(Scale);
10480 /// isLegalAddressingMode - Return true if the addressing mode represented
10481 /// by AM is legal for this target, for a load/store of the specified type.
10482 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10483 const AddrMode &AM, Type *Ty,
10484 unsigned AS) const {
10485 EVT VT = getValueType(DL, Ty, true);
10486 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10489 // Can never fold addr of global into load/store.
10493 switch (AM.Scale) {
10494 case 0: // no scale reg, must be "r+i" or "r", or "i".
10497 if (Subtarget->isThumb1Only())
10501 // ARM doesn't support any R+R*scale+imm addr modes.
10505 if (!VT.isSimple())
10508 if (Subtarget->isThumb2())
10509 return isLegalT2ScaledAddressingMode(AM, VT);
10511 int Scale = AM.Scale;
10512 switch (VT.getSimpleVT().SimpleTy) {
10513 default: return false;
10517 if (Scale < 0) Scale = -Scale;
10521 return isPowerOf2_32(Scale & ~1);
10525 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10530 // Note, we allow "void" uses (basically, uses that aren't loads or
10531 // stores), because arm allows folding a scale into many arithmetic
10532 // operations. This should be made more precise and revisited later.
10534 // Allow r << imm, but the imm has to be a multiple of two.
10535 if (Scale & 1) return false;
10536 return isPowerOf2_32(Scale);
10542 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10543 /// icmp immediate, that is the target has icmp instructions which can compare
10544 /// a register against the immediate without having to materialize the
10545 /// immediate into a register.
10546 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10547 // Thumb2 and ARM modes can use cmn for negative immediates.
10548 if (!Subtarget->isThumb())
10549 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10550 if (Subtarget->isThumb2())
10551 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10552 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10553 return Imm >= 0 && Imm <= 255;
10556 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10557 /// *or sub* immediate, that is the target has add or sub instructions which can
10558 /// add a register with the immediate without having to materialize the
10559 /// immediate into a register.
10560 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10561 // Same encoding for add/sub, just flip the sign.
10562 int64_t AbsImm = std::abs(Imm);
10563 if (!Subtarget->isThumb())
10564 return ARM_AM::getSOImmVal(AbsImm) != -1;
10565 if (Subtarget->isThumb2())
10566 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10567 // Thumb1 only has 8-bit unsigned immediate.
10568 return AbsImm >= 0 && AbsImm <= 255;
10571 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10572 bool isSEXTLoad, SDValue &Base,
10573 SDValue &Offset, bool &isInc,
10574 SelectionDAG &DAG) {
10575 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10578 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10579 // AddressingMode 3
10580 Base = Ptr->getOperand(0);
10581 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10582 int RHSC = (int)RHS->getZExtValue();
10583 if (RHSC < 0 && RHSC > -256) {
10584 assert(Ptr->getOpcode() == ISD::ADD);
10586 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10590 isInc = (Ptr->getOpcode() == ISD::ADD);
10591 Offset = Ptr->getOperand(1);
10593 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10594 // AddressingMode 2
10595 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10596 int RHSC = (int)RHS->getZExtValue();
10597 if (RHSC < 0 && RHSC > -0x1000) {
10598 assert(Ptr->getOpcode() == ISD::ADD);
10600 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10601 Base = Ptr->getOperand(0);
10606 if (Ptr->getOpcode() == ISD::ADD) {
10608 ARM_AM::ShiftOpc ShOpcVal=
10609 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10610 if (ShOpcVal != ARM_AM::no_shift) {
10611 Base = Ptr->getOperand(1);
10612 Offset = Ptr->getOperand(0);
10614 Base = Ptr->getOperand(0);
10615 Offset = Ptr->getOperand(1);
10620 isInc = (Ptr->getOpcode() == ISD::ADD);
10621 Base = Ptr->getOperand(0);
10622 Offset = Ptr->getOperand(1);
10626 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10630 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10631 bool isSEXTLoad, SDValue &Base,
10632 SDValue &Offset, bool &isInc,
10633 SelectionDAG &DAG) {
10634 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10637 Base = Ptr->getOperand(0);
10638 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10639 int RHSC = (int)RHS->getZExtValue();
10640 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10641 assert(Ptr->getOpcode() == ISD::ADD);
10643 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10645 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10646 isInc = Ptr->getOpcode() == ISD::ADD;
10647 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10655 /// getPreIndexedAddressParts - returns true by value, base pointer and
10656 /// offset pointer and addressing mode by reference if the node's address
10657 /// can be legally represented as pre-indexed load / store address.
10659 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10661 ISD::MemIndexedMode &AM,
10662 SelectionDAG &DAG) const {
10663 if (Subtarget->isThumb1Only())
10668 bool isSEXTLoad = false;
10669 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10670 Ptr = LD->getBasePtr();
10671 VT = LD->getMemoryVT();
10672 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10673 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10674 Ptr = ST->getBasePtr();
10675 VT = ST->getMemoryVT();
10680 bool isLegal = false;
10681 if (Subtarget->isThumb2())
10682 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10683 Offset, isInc, DAG);
10685 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10686 Offset, isInc, DAG);
10690 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10694 /// getPostIndexedAddressParts - returns true by value, base pointer and
10695 /// offset pointer and addressing mode by reference if this node can be
10696 /// combined with a load / store to form a post-indexed load / store.
10697 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10700 ISD::MemIndexedMode &AM,
10701 SelectionDAG &DAG) const {
10702 if (Subtarget->isThumb1Only())
10707 bool isSEXTLoad = false;
10708 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10709 VT = LD->getMemoryVT();
10710 Ptr = LD->getBasePtr();
10711 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10712 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10713 VT = ST->getMemoryVT();
10714 Ptr = ST->getBasePtr();
10719 bool isLegal = false;
10720 if (Subtarget->isThumb2())
10721 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10724 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10730 // Swap base ptr and offset to catch more post-index load / store when
10731 // it's legal. In Thumb2 mode, offset must be an immediate.
10732 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10733 !Subtarget->isThumb2())
10734 std::swap(Base, Offset);
10736 // Post-indexed load / store update the base pointer.
10741 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10745 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10748 const SelectionDAG &DAG,
10749 unsigned Depth) const {
10750 unsigned BitWidth = KnownOne.getBitWidth();
10751 KnownZero = KnownOne = APInt(BitWidth, 0);
10752 switch (Op.getOpcode()) {
10758 // These nodes' second result is a boolean
10759 if (Op.getResNo() == 0)
10761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10763 case ARMISD::CMOV: {
10764 // Bits are known zero/one if known on the LHS and RHS.
10765 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10766 if (KnownZero == 0 && KnownOne == 0) return;
10768 APInt KnownZeroRHS, KnownOneRHS;
10769 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10770 KnownZero &= KnownZeroRHS;
10771 KnownOne &= KnownOneRHS;
10774 case ISD::INTRINSIC_W_CHAIN: {
10775 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10776 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10779 case Intrinsic::arm_ldaex:
10780 case Intrinsic::arm_ldrex: {
10781 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10782 unsigned MemBits = VT.getScalarType().getSizeInBits();
10783 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10791 //===----------------------------------------------------------------------===//
10792 // ARM Inline Assembly Support
10793 //===----------------------------------------------------------------------===//
10795 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10796 // Looking for "rev" which is V6+.
10797 if (!Subtarget->hasV6Ops())
10800 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10801 std::string AsmStr = IA->getAsmString();
10802 SmallVector<StringRef, 4> AsmPieces;
10803 SplitString(AsmStr, AsmPieces, ";\n");
10805 switch (AsmPieces.size()) {
10806 default: return false;
10808 AsmStr = AsmPieces[0];
10810 SplitString(AsmStr, AsmPieces, " \t,");
10813 if (AsmPieces.size() == 3 &&
10814 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10815 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10816 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10817 if (Ty && Ty->getBitWidth() == 32)
10818 return IntrinsicLowering::LowerToByteSwap(CI);
10826 /// getConstraintType - Given a constraint letter, return the type of
10827 /// constraint it is for this target.
10828 ARMTargetLowering::ConstraintType
10829 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10830 if (Constraint.size() == 1) {
10831 switch (Constraint[0]) {
10833 case 'l': return C_RegisterClass;
10834 case 'w': return C_RegisterClass;
10835 case 'h': return C_RegisterClass;
10836 case 'x': return C_RegisterClass;
10837 case 't': return C_RegisterClass;
10838 case 'j': return C_Other; // Constant for movw.
10839 // An address with a single base register. Due to the way we
10840 // currently handle addresses it is the same as an 'r' memory constraint.
10841 case 'Q': return C_Memory;
10843 } else if (Constraint.size() == 2) {
10844 switch (Constraint[0]) {
10846 // All 'U+' constraints are addresses.
10847 case 'U': return C_Memory;
10850 return TargetLowering::getConstraintType(Constraint);
10853 /// Examine constraint type and operand type and determine a weight value.
10854 /// This object must already have been set up with the operand type
10855 /// and the current alternative constraint selected.
10856 TargetLowering::ConstraintWeight
10857 ARMTargetLowering::getSingleConstraintMatchWeight(
10858 AsmOperandInfo &info, const char *constraint) const {
10859 ConstraintWeight weight = CW_Invalid;
10860 Value *CallOperandVal = info.CallOperandVal;
10861 // If we don't have a value, we can't do a match,
10862 // but allow it at the lowest weight.
10863 if (!CallOperandVal)
10865 Type *type = CallOperandVal->getType();
10866 // Look at the constraint type.
10867 switch (*constraint) {
10869 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10872 if (type->isIntegerTy()) {
10873 if (Subtarget->isThumb())
10874 weight = CW_SpecificReg;
10876 weight = CW_Register;
10880 if (type->isFloatingPointTy())
10881 weight = CW_Register;
10887 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10888 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10889 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10890 if (Constraint.size() == 1) {
10891 // GCC ARM Constraint Letters
10892 switch (Constraint[0]) {
10893 case 'l': // Low regs or general regs.
10894 if (Subtarget->isThumb())
10895 return RCPair(0U, &ARM::tGPRRegClass);
10896 return RCPair(0U, &ARM::GPRRegClass);
10897 case 'h': // High regs or no regs.
10898 if (Subtarget->isThumb())
10899 return RCPair(0U, &ARM::hGPRRegClass);
10902 if (Subtarget->isThumb1Only())
10903 return RCPair(0U, &ARM::tGPRRegClass);
10904 return RCPair(0U, &ARM::GPRRegClass);
10906 if (VT == MVT::Other)
10908 if (VT == MVT::f32)
10909 return RCPair(0U, &ARM::SPRRegClass);
10910 if (VT.getSizeInBits() == 64)
10911 return RCPair(0U, &ARM::DPRRegClass);
10912 if (VT.getSizeInBits() == 128)
10913 return RCPair(0U, &ARM::QPRRegClass);
10916 if (VT == MVT::Other)
10918 if (VT == MVT::f32)
10919 return RCPair(0U, &ARM::SPR_8RegClass);
10920 if (VT.getSizeInBits() == 64)
10921 return RCPair(0U, &ARM::DPR_8RegClass);
10922 if (VT.getSizeInBits() == 128)
10923 return RCPair(0U, &ARM::QPR_8RegClass);
10926 if (VT == MVT::f32)
10927 return RCPair(0U, &ARM::SPRRegClass);
10931 if (StringRef("{cc}").equals_lower(Constraint))
10932 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10934 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10937 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10938 /// vector. If it is invalid, don't add anything to Ops.
10939 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10940 std::string &Constraint,
10941 std::vector<SDValue>&Ops,
10942 SelectionDAG &DAG) const {
10945 // Currently only support length 1 constraints.
10946 if (Constraint.length() != 1) return;
10948 char ConstraintLetter = Constraint[0];
10949 switch (ConstraintLetter) {
10952 case 'I': case 'J': case 'K': case 'L':
10953 case 'M': case 'N': case 'O':
10954 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10958 int64_t CVal64 = C->getSExtValue();
10959 int CVal = (int) CVal64;
10960 // None of these constraints allow values larger than 32 bits. Check
10961 // that the value fits in an int.
10962 if (CVal != CVal64)
10965 switch (ConstraintLetter) {
10967 // Constant suitable for movw, must be between 0 and
10969 if (Subtarget->hasV6T2Ops())
10970 if (CVal >= 0 && CVal <= 65535)
10974 if (Subtarget->isThumb1Only()) {
10975 // This must be a constant between 0 and 255, for ADD
10977 if (CVal >= 0 && CVal <= 255)
10979 } else if (Subtarget->isThumb2()) {
10980 // A constant that can be used as an immediate value in a
10981 // data-processing instruction.
10982 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10985 // A constant that can be used as an immediate value in a
10986 // data-processing instruction.
10987 if (ARM_AM::getSOImmVal(CVal) != -1)
10993 if (Subtarget->isThumb()) { // FIXME thumb2
10994 // This must be a constant between -255 and -1, for negated ADD
10995 // immediates. This can be used in GCC with an "n" modifier that
10996 // prints the negated value, for use with SUB instructions. It is
10997 // not useful otherwise but is implemented for compatibility.
10998 if (CVal >= -255 && CVal <= -1)
11001 // This must be a constant between -4095 and 4095. It is not clear
11002 // what this constraint is intended for. Implemented for
11003 // compatibility with GCC.
11004 if (CVal >= -4095 && CVal <= 4095)
11010 if (Subtarget->isThumb1Only()) {
11011 // A 32-bit value where only one byte has a nonzero value. Exclude
11012 // zero to match GCC. This constraint is used by GCC internally for
11013 // constants that can be loaded with a move/shift combination.
11014 // It is not useful otherwise but is implemented for compatibility.
11015 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11017 } else if (Subtarget->isThumb2()) {
11018 // A constant whose bitwise inverse can be used as an immediate
11019 // value in a data-processing instruction. This can be used in GCC
11020 // with a "B" modifier that prints the inverted value, for use with
11021 // BIC and MVN instructions. It is not useful otherwise but is
11022 // implemented for compatibility.
11023 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11026 // A constant whose bitwise inverse can be used as an immediate
11027 // value in a data-processing instruction. This can be used in GCC
11028 // with a "B" modifier that prints the inverted value, for use with
11029 // BIC and MVN instructions. It is not useful otherwise but is
11030 // implemented for compatibility.
11031 if (ARM_AM::getSOImmVal(~CVal) != -1)
11037 if (Subtarget->isThumb1Only()) {
11038 // This must be a constant between -7 and 7,
11039 // for 3-operand ADD/SUB immediate instructions.
11040 if (CVal >= -7 && CVal < 7)
11042 } else if (Subtarget->isThumb2()) {
11043 // A constant whose negation can be used as an immediate value in a
11044 // data-processing instruction. This can be used in GCC with an "n"
11045 // modifier that prints the negated value, for use with SUB
11046 // instructions. It is not useful otherwise but is implemented for
11048 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11051 // A constant whose negation can be used as an immediate value in a
11052 // data-processing instruction. This can be used in GCC with an "n"
11053 // modifier that prints the negated value, for use with SUB
11054 // instructions. It is not useful otherwise but is implemented for
11056 if (ARM_AM::getSOImmVal(-CVal) != -1)
11062 if (Subtarget->isThumb()) { // FIXME thumb2
11063 // This must be a multiple of 4 between 0 and 1020, for
11064 // ADD sp + immediate.
11065 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11068 // A power of two or a constant between 0 and 32. This is used in
11069 // GCC for the shift amount on shifted register operands, but it is
11070 // useful in general for any shift amounts.
11071 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11077 if (Subtarget->isThumb()) { // FIXME thumb2
11078 // This must be a constant between 0 and 31, for shift amounts.
11079 if (CVal >= 0 && CVal <= 31)
11085 if (Subtarget->isThumb()) { // FIXME thumb2
11086 // This must be a multiple of 4 between -508 and 508, for
11087 // ADD/SUB sp = sp + immediate.
11088 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11093 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11097 if (Result.getNode()) {
11098 Ops.push_back(Result);
11101 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11104 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11105 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11106 "Register-based DivRem lowering only");
11107 unsigned Opcode = Op->getOpcode();
11108 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11109 "Invalid opcode for Div/Rem lowering");
11110 bool isSigned = (Opcode == ISD::SDIVREM);
11111 EVT VT = Op->getValueType(0);
11112 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11115 switch (VT.getSimpleVT().SimpleTy) {
11116 default: llvm_unreachable("Unexpected request for libcall!");
11117 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11118 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11119 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11120 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11123 SDValue InChain = DAG.getEntryNode();
11125 TargetLowering::ArgListTy Args;
11126 TargetLowering::ArgListEntry Entry;
11127 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11128 EVT ArgVT = Op->getOperand(i).getValueType();
11129 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11130 Entry.Node = Op->getOperand(i);
11132 Entry.isSExt = isSigned;
11133 Entry.isZExt = !isSigned;
11134 Args.push_back(Entry);
11137 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11138 getPointerTy(DAG.getDataLayout()));
11140 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11143 TargetLowering::CallLoweringInfo CLI(DAG);
11144 CLI.setDebugLoc(dl).setChain(InChain)
11145 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11146 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11148 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11149 return CallInfo.first;
11153 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11154 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11158 SDValue Chain = Op.getOperand(0);
11159 SDValue Size = Op.getOperand(1);
11161 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11162 DAG.getConstant(2, DL, MVT::i32));
11165 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11166 Flag = Chain.getValue(1);
11168 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11169 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11171 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11172 Chain = NewSP.getValue(1);
11174 SDValue Ops[2] = { NewSP, Chain };
11175 return DAG.getMergeValues(Ops, DL);
11178 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11179 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11180 "Unexpected type for custom-lowering FP_EXTEND");
11183 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11185 SDValue SrcVal = Op.getOperand(0);
11186 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11187 /*isSigned*/ false, SDLoc(Op)).first;
11190 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11191 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11192 Subtarget->isFPOnlySP() &&
11193 "Unexpected type for custom-lowering FP_ROUND");
11196 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11198 SDValue SrcVal = Op.getOperand(0);
11199 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11200 /*isSigned*/ false, SDLoc(Op)).first;
11204 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11205 // The ARM target isn't yet aware of offsets.
11209 bool ARM::isBitFieldInvertedMask(unsigned v) {
11210 if (v == 0xffffffff)
11213 // there can be 1's on either or both "outsides", all the "inside"
11214 // bits must be 0's
11215 return isShiftedMask_32(~v);
11218 /// isFPImmLegal - Returns true if the target can instruction select the
11219 /// specified FP immediate natively. If false, the legalizer will
11220 /// materialize the FP immediate as a load from a constant pool.
11221 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11222 if (!Subtarget->hasVFP3())
11224 if (VT == MVT::f32)
11225 return ARM_AM::getFP32Imm(Imm) != -1;
11226 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11227 return ARM_AM::getFP64Imm(Imm) != -1;
11231 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11232 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11233 /// specified in the intrinsic calls.
11234 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11236 unsigned Intrinsic) const {
11237 switch (Intrinsic) {
11238 case Intrinsic::arm_neon_vld1:
11239 case Intrinsic::arm_neon_vld2:
11240 case Intrinsic::arm_neon_vld3:
11241 case Intrinsic::arm_neon_vld4:
11242 case Intrinsic::arm_neon_vld2lane:
11243 case Intrinsic::arm_neon_vld3lane:
11244 case Intrinsic::arm_neon_vld4lane: {
11245 Info.opc = ISD::INTRINSIC_W_CHAIN;
11246 // Conservatively set memVT to the entire set of vectors loaded.
11247 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11248 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11249 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11250 Info.ptrVal = I.getArgOperand(0);
11252 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11253 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11254 Info.vol = false; // volatile loads with NEON intrinsics not supported
11255 Info.readMem = true;
11256 Info.writeMem = false;
11259 case Intrinsic::arm_neon_vst1:
11260 case Intrinsic::arm_neon_vst2:
11261 case Intrinsic::arm_neon_vst3:
11262 case Intrinsic::arm_neon_vst4:
11263 case Intrinsic::arm_neon_vst2lane:
11264 case Intrinsic::arm_neon_vst3lane:
11265 case Intrinsic::arm_neon_vst4lane: {
11266 Info.opc = ISD::INTRINSIC_VOID;
11267 // Conservatively set memVT to the entire set of vectors stored.
11268 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11269 unsigned NumElts = 0;
11270 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11271 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11272 if (!ArgTy->isVectorTy())
11274 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11276 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11277 Info.ptrVal = I.getArgOperand(0);
11279 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11280 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11281 Info.vol = false; // volatile stores with NEON intrinsics not supported
11282 Info.readMem = false;
11283 Info.writeMem = true;
11286 case Intrinsic::arm_ldaex:
11287 case Intrinsic::arm_ldrex: {
11288 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11289 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11290 Info.opc = ISD::INTRINSIC_W_CHAIN;
11291 Info.memVT = MVT::getVT(PtrTy->getElementType());
11292 Info.ptrVal = I.getArgOperand(0);
11294 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11296 Info.readMem = true;
11297 Info.writeMem = false;
11300 case Intrinsic::arm_stlex:
11301 case Intrinsic::arm_strex: {
11302 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11303 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11304 Info.opc = ISD::INTRINSIC_W_CHAIN;
11305 Info.memVT = MVT::getVT(PtrTy->getElementType());
11306 Info.ptrVal = I.getArgOperand(1);
11308 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11310 Info.readMem = false;
11311 Info.writeMem = true;
11314 case Intrinsic::arm_stlexd:
11315 case Intrinsic::arm_strexd: {
11316 Info.opc = ISD::INTRINSIC_W_CHAIN;
11317 Info.memVT = MVT::i64;
11318 Info.ptrVal = I.getArgOperand(2);
11322 Info.readMem = false;
11323 Info.writeMem = true;
11326 case Intrinsic::arm_ldaexd:
11327 case Intrinsic::arm_ldrexd: {
11328 Info.opc = ISD::INTRINSIC_W_CHAIN;
11329 Info.memVT = MVT::i64;
11330 Info.ptrVal = I.getArgOperand(0);
11334 Info.readMem = true;
11335 Info.writeMem = false;
11345 /// \brief Returns true if it is beneficial to convert a load of a constant
11346 /// to just the constant itself.
11347 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11349 assert(Ty->isIntegerTy());
11351 unsigned Bits = Ty->getPrimitiveSizeInBits();
11352 if (Bits == 0 || Bits > 32)
11357 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11359 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11360 ARM_MB::MemBOpt Domain) const {
11361 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11363 // First, if the target has no DMB, see what fallback we can use.
11364 if (!Subtarget->hasDataBarrier()) {
11365 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11366 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11368 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11369 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11370 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11371 Builder.getInt32(0), Builder.getInt32(7),
11372 Builder.getInt32(10), Builder.getInt32(5)};
11373 return Builder.CreateCall(MCR, args);
11375 // Instead of using barriers, atomic accesses on these subtargets use
11377 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11380 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11381 // Only a full system barrier exists in the M-class architectures.
11382 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11383 Constant *CDomain = Builder.getInt32(Domain);
11384 return Builder.CreateCall(DMB, CDomain);
11388 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11389 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11390 AtomicOrdering Ord, bool IsStore,
11391 bool IsLoad) const {
11392 if (!getInsertFencesForAtomic())
11398 llvm_unreachable("Invalid fence: unordered/non-atomic");
11401 return nullptr; // Nothing to do
11402 case SequentiallyConsistent:
11404 return nullptr; // Nothing to do
11407 case AcquireRelease:
11408 if (Subtarget->isSwift())
11409 return makeDMB(Builder, ARM_MB::ISHST);
11410 // FIXME: add a comment with a link to documentation justifying this.
11412 return makeDMB(Builder, ARM_MB::ISH);
11414 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11417 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11418 AtomicOrdering Ord, bool IsStore,
11419 bool IsLoad) const {
11420 if (!getInsertFencesForAtomic())
11426 llvm_unreachable("Invalid fence: unordered/not-atomic");
11429 return nullptr; // Nothing to do
11431 case AcquireRelease:
11432 case SequentiallyConsistent:
11433 return makeDMB(Builder, ARM_MB::ISH);
11435 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11438 // Loads and stores less than 64-bits are already atomic; ones above that
11439 // are doomed anyway, so defer to the default libcall and blame the OS when
11440 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11441 // anything for those.
11442 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11443 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11444 return (Size == 64) && !Subtarget->isMClass();
11447 // Loads and stores less than 64-bits are already atomic; ones above that
11448 // are doomed anyway, so defer to the default libcall and blame the OS when
11449 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11450 // anything for those.
11451 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11452 // guarantee, see DDI0406C ARM architecture reference manual,
11453 // sections A8.8.72-74 LDRD)
11454 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11455 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11456 return (Size == 64) && !Subtarget->isMClass();
11459 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11460 // and up to 64 bits on the non-M profiles
11461 TargetLoweringBase::AtomicRMWExpansionKind
11462 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11463 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11464 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11465 ? AtomicRMWExpansionKind::LLSC
11466 : AtomicRMWExpansionKind::None;
11469 // This has so far only been implemented for MachO.
11470 bool ARMTargetLowering::useLoadStackGuardNode() const {
11471 return Subtarget->isTargetMachO();
11474 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11475 unsigned &Cost) const {
11476 // If we do not have NEON, vector types are not natively supported.
11477 if (!Subtarget->hasNEON())
11480 // Floating point values and vector values map to the same register file.
11481 // Therefore, although we could do a store extract of a vector type, this is
11482 // better to leave at float as we have more freedom in the addressing mode for
11484 if (VectorTy->isFPOrFPVectorTy())
11487 // If the index is unknown at compile time, this is very expensive to lower
11488 // and it is not possible to combine the store with the extract.
11489 if (!isa<ConstantInt>(Idx))
11492 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11493 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11494 // We can do a store + vector extract on any vector that fits perfectly in a D
11496 if (BitWidth == 64 || BitWidth == 128) {
11503 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11504 AtomicOrdering Ord) const {
11505 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11506 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11507 bool IsAcquire = isAtLeastAcquire(Ord);
11509 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11510 // intrinsic must return {i32, i32} and we have to recombine them into a
11511 // single i64 here.
11512 if (ValTy->getPrimitiveSizeInBits() == 64) {
11513 Intrinsic::ID Int =
11514 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11515 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11517 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11518 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11520 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11521 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11522 if (!Subtarget->isLittle())
11523 std::swap (Lo, Hi);
11524 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11525 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11526 return Builder.CreateOr(
11527 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11530 Type *Tys[] = { Addr->getType() };
11531 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11532 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11534 return Builder.CreateTruncOrBitCast(
11535 Builder.CreateCall(Ldrex, Addr),
11536 cast<PointerType>(Addr->getType())->getElementType());
11539 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11541 AtomicOrdering Ord) const {
11542 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11543 bool IsRelease = isAtLeastRelease(Ord);
11545 // Since the intrinsics must have legal type, the i64 intrinsics take two
11546 // parameters: "i32, i32". We must marshal Val into the appropriate form
11547 // before the call.
11548 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11549 Intrinsic::ID Int =
11550 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11551 Function *Strex = Intrinsic::getDeclaration(M, Int);
11552 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11554 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11555 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11556 if (!Subtarget->isLittle())
11557 std::swap (Lo, Hi);
11558 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11559 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11562 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11563 Type *Tys[] = { Addr->getType() };
11564 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11566 return Builder.CreateCall(
11567 Strex, {Builder.CreateZExtOrBitCast(
11568 Val, Strex->getFunctionType()->getParamType(0)),
11572 /// \brief Lower an interleaved load into a vldN intrinsic.
11574 /// E.g. Lower an interleaved load (Factor = 2):
11575 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11576 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11577 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11580 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11581 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11582 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11583 bool ARMTargetLowering::lowerInterleavedLoad(
11584 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11585 ArrayRef<unsigned> Indices, unsigned Factor) const {
11586 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11587 "Invalid interleave factor");
11588 assert(!Shuffles.empty() && "Empty shufflevector input");
11589 assert(Shuffles.size() == Indices.size() &&
11590 "Unmatched number of shufflevectors and indices");
11592 VectorType *VecTy = Shuffles[0]->getType();
11593 Type *EltTy = VecTy->getVectorElementType();
11595 const DataLayout &DL = LI->getModule()->getDataLayout();
11596 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11597 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11599 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11600 // support i64/f64 element).
11601 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11604 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11605 // load integer vectors first and then convert to pointer vectors.
11606 if (EltTy->isPointerTy())
11608 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11610 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11611 Intrinsic::arm_neon_vld3,
11612 Intrinsic::arm_neon_vld4};
11614 Function *VldnFunc =
11615 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11617 IRBuilder<> Builder(LI);
11618 SmallVector<Value *, 2> Ops;
11620 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11621 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11622 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11624 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11626 // Replace uses of each shufflevector with the corresponding vector loaded
11628 for (unsigned i = 0; i < Shuffles.size(); i++) {
11629 ShuffleVectorInst *SV = Shuffles[i];
11630 unsigned Index = Indices[i];
11632 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11634 // Convert the integer vector to pointer vector if the element is pointer.
11635 if (EltTy->isPointerTy())
11636 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11638 SV->replaceAllUsesWith(SubVec);
11644 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11646 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11647 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11648 unsigned NumElts) {
11649 SmallVector<Constant *, 16> Mask;
11650 for (unsigned i = 0; i < NumElts; i++)
11651 Mask.push_back(Builder.getInt32(Start + i));
11653 return ConstantVector::get(Mask);
11656 /// \brief Lower an interleaved store into a vstN intrinsic.
11658 /// E.g. Lower an interleaved store (Factor = 3):
11659 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11660 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11661 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11664 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11665 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11666 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11667 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11669 /// Note that the new shufflevectors will be removed and we'll only generate one
11670 /// vst3 instruction in CodeGen.
11671 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11672 ShuffleVectorInst *SVI,
11673 unsigned Factor) const {
11674 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11675 "Invalid interleave factor");
11677 VectorType *VecTy = SVI->getType();
11678 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11679 "Invalid interleaved store");
11681 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11682 Type *EltTy = VecTy->getVectorElementType();
11683 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11685 const DataLayout &DL = SI->getModule()->getDataLayout();
11686 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11687 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11689 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11690 // doesn't support i64/f64 element).
11691 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11694 Value *Op0 = SVI->getOperand(0);
11695 Value *Op1 = SVI->getOperand(1);
11696 IRBuilder<> Builder(SI);
11698 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11699 // vectors to integer vectors.
11700 if (EltTy->isPointerTy()) {
11701 Type *IntTy = DL.getIntPtrType(EltTy);
11703 // Convert to the corresponding integer vector.
11705 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11706 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11707 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11709 SubVecTy = VectorType::get(IntTy, NumSubElts);
11712 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11713 Intrinsic::arm_neon_vst3,
11714 Intrinsic::arm_neon_vst4};
11715 Function *VstNFunc = Intrinsic::getDeclaration(
11716 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11718 SmallVector<Value *, 6> Ops;
11720 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11721 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11723 // Split the shufflevector operands into sub vectors for the new vstN call.
11724 for (unsigned i = 0; i < Factor; i++)
11725 Ops.push_back(Builder.CreateShuffleVector(
11726 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11728 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11729 Builder.CreateCall(VstNFunc, Ops);
11741 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11742 uint64_t &Members) {
11743 if (auto *ST = dyn_cast<StructType>(Ty)) {
11744 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11745 uint64_t SubMembers = 0;
11746 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11748 Members += SubMembers;
11750 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11751 uint64_t SubMembers = 0;
11752 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11754 Members += SubMembers * AT->getNumElements();
11755 } else if (Ty->isFloatTy()) {
11756 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11760 } else if (Ty->isDoubleTy()) {
11761 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11765 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11772 return VT->getBitWidth() == 64;
11774 return VT->getBitWidth() == 128;
11776 switch (VT->getBitWidth()) {
11789 return (Members > 0 && Members <= 4);
11792 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11793 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11794 /// passing according to AAPCS rules.
11795 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11796 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11797 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11798 CallingConv::ARM_AAPCS_VFP)
11801 HABaseType Base = HA_UNKNOWN;
11802 uint64_t Members = 0;
11803 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11804 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11806 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11807 return IsHA || IsIntArray;