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 setOperationAction(ISD::SREM, MVT::i32, Expand);
742 setOperationAction(ISD::UREM, MVT::i32, Expand);
743 // Register based DivRem for AEABI (RTABI 4.2)
744 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
745 setOperationAction(ISD::SREM, MVT::i64, Custom);
746 setOperationAction(ISD::UREM, MVT::i64, Custom);
748 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
749 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
750 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
751 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
752 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
753 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
754 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
755 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
757 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
758 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
759 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
760 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
761 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
762 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
763 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
764 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
766 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
767 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
769 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
770 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
773 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
774 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
775 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
776 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
777 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
779 setOperationAction(ISD::TRAP, MVT::Other, Legal);
781 // Use the default implementation.
782 setOperationAction(ISD::VASTART, MVT::Other, Custom);
783 setOperationAction(ISD::VAARG, MVT::Other, Expand);
784 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
785 setOperationAction(ISD::VAEND, MVT::Other, Expand);
786 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
787 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
789 if (!Subtarget->isTargetMachO()) {
790 // Non-MachO platforms may return values in these registers via the
791 // personality function.
792 setExceptionPointerRegister(ARM::R0);
793 setExceptionSelectorRegister(ARM::R1);
796 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
797 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
799 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
801 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
802 // the default expansion. If we are targeting a single threaded system,
803 // then set them all for expand so we can lower them later into their
805 if (TM.Options.ThreadModel == ThreadModel::Single)
806 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
807 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
808 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
809 // to ldrex/strex loops already.
810 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
812 // On v8, we have particularly efficient implementations of atomic fences
813 // if they can be combined with nearby atomic loads and stores.
814 if (!Subtarget->hasV8Ops()) {
815 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
816 setInsertFencesForAtomic(true);
819 // If there's anything we can use as a barrier, go through custom lowering
821 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
822 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
824 // Set them all for expansion, which will force libcalls.
825 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
826 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
827 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
828 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
829 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
830 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
831 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
832 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
833 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
834 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
835 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
836 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
837 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
838 // Unordered/Monotonic case.
839 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
840 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
843 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
845 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
846 if (!Subtarget->hasV6Ops()) {
847 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
848 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
850 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
852 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
853 !Subtarget->isThumb1Only()) {
854 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
855 // iff target supports vfp2.
856 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
857 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
860 // We want to custom lower some of our intrinsics.
861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
862 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
863 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
864 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
865 if (Subtarget->isTargetDarwin())
866 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
868 setOperationAction(ISD::SETCC, MVT::i32, Expand);
869 setOperationAction(ISD::SETCC, MVT::f32, Expand);
870 setOperationAction(ISD::SETCC, MVT::f64, Expand);
871 setOperationAction(ISD::SELECT, MVT::i32, Custom);
872 setOperationAction(ISD::SELECT, MVT::f32, Custom);
873 setOperationAction(ISD::SELECT, MVT::f64, Custom);
874 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
875 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
876 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
878 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
879 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
880 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
881 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
882 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
884 // We don't support sin/cos/fmod/copysign/pow
885 setOperationAction(ISD::FSIN, MVT::f64, Expand);
886 setOperationAction(ISD::FSIN, MVT::f32, Expand);
887 setOperationAction(ISD::FCOS, MVT::f32, Expand);
888 setOperationAction(ISD::FCOS, MVT::f64, Expand);
889 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
890 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
891 setOperationAction(ISD::FREM, MVT::f64, Expand);
892 setOperationAction(ISD::FREM, MVT::f32, Expand);
893 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
894 !Subtarget->isThumb1Only()) {
895 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
896 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
898 setOperationAction(ISD::FPOW, MVT::f64, Expand);
899 setOperationAction(ISD::FPOW, MVT::f32, Expand);
901 if (!Subtarget->hasVFP4()) {
902 setOperationAction(ISD::FMA, MVT::f64, Expand);
903 setOperationAction(ISD::FMA, MVT::f32, Expand);
906 // Various VFP goodness
907 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
908 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
909 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
910 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
911 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
914 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
915 if (!Subtarget->hasFP16()) {
916 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
917 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
921 // Combine sin / cos into one node or libcall if possible.
922 if (Subtarget->hasSinCos()) {
923 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
924 setLibcallName(RTLIB::SINCOS_F64, "sincos");
925 if (Subtarget->getTargetTriple().isiOS()) {
926 // For iOS, we don't want to the normal expansion of a libcall to
927 // sincos. We want to issue a libcall to __sincos_stret.
928 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
929 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
933 // FP-ARMv8 implements a lot of rounding-like FP operations.
934 if (Subtarget->hasFPARMv8()) {
935 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
936 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
937 setOperationAction(ISD::FROUND, MVT::f32, Legal);
938 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
939 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
940 setOperationAction(ISD::FRINT, MVT::f32, Legal);
941 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
942 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
943 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
944 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
945 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
946 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
948 if (!Subtarget->isFPOnlySP()) {
949 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
950 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
951 setOperationAction(ISD::FROUND, MVT::f64, Legal);
952 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
953 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
954 setOperationAction(ISD::FRINT, MVT::f64, Legal);
955 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
956 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
960 if (Subtarget->hasNEON()) {
961 // vmin and vmax aren't available in a scalar form, so we use
962 // a NEON instruction with an undef lane instead.
963 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
964 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
965 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
966 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
967 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
968 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
971 // We have target-specific dag combine patterns for the following nodes:
972 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
973 setTargetDAGCombine(ISD::ADD);
974 setTargetDAGCombine(ISD::SUB);
975 setTargetDAGCombine(ISD::MUL);
976 setTargetDAGCombine(ISD::AND);
977 setTargetDAGCombine(ISD::OR);
978 setTargetDAGCombine(ISD::XOR);
980 if (Subtarget->hasV6Ops())
981 setTargetDAGCombine(ISD::SRL);
983 setStackPointerRegisterToSaveRestore(ARM::SP);
985 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
986 !Subtarget->hasVFP2())
987 setSchedulingPreference(Sched::RegPressure);
989 setSchedulingPreference(Sched::Hybrid);
991 //// temporary - rewrite interface to use type
992 MaxStoresPerMemset = 8;
993 MaxStoresPerMemsetOptSize = 4;
994 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
995 MaxStoresPerMemcpyOptSize = 2;
996 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
997 MaxStoresPerMemmoveOptSize = 2;
999 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1000 // are at least 4 bytes aligned.
1001 setMinStackArgumentAlignment(4);
1003 // Prefer likely predicted branches to selects on out-of-order cores.
1004 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1006 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1009 bool ARMTargetLowering::useSoftFloat() const {
1010 return Subtarget->useSoftFloat();
1013 // FIXME: It might make sense to define the representative register class as the
1014 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1015 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1016 // SPR's representative would be DPR_VFP2. This should work well if register
1017 // pressure tracking were modified such that a register use would increment the
1018 // pressure of the register class's representative and all of it's super
1019 // classes' representatives transitively. We have not implemented this because
1020 // of the difficulty prior to coalescing of modeling operand register classes
1021 // due to the common occurrence of cross class copies and subregister insertions
1023 std::pair<const TargetRegisterClass *, uint8_t>
1024 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1026 const TargetRegisterClass *RRC = nullptr;
1028 switch (VT.SimpleTy) {
1030 return TargetLowering::findRepresentativeClass(TRI, VT);
1031 // Use DPR as representative register class for all floating point
1032 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1033 // the cost is 1 for both f32 and f64.
1034 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1035 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1036 RRC = &ARM::DPRRegClass;
1037 // When NEON is used for SP, only half of the register file is available
1038 // because operations that define both SP and DP results will be constrained
1039 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1040 // coalescing by double-counting the SP regs. See the FIXME above.
1041 if (Subtarget->useNEONForSinglePrecisionFP())
1044 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1045 case MVT::v4f32: case MVT::v2f64:
1046 RRC = &ARM::DPRRegClass;
1050 RRC = &ARM::DPRRegClass;
1054 RRC = &ARM::DPRRegClass;
1058 return std::make_pair(RRC, Cost);
1061 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1062 switch ((ARMISD::NodeType)Opcode) {
1063 case ARMISD::FIRST_NUMBER: break;
1064 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1065 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1066 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1067 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1068 case ARMISD::CALL: return "ARMISD::CALL";
1069 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1070 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1071 case ARMISD::tCALL: return "ARMISD::tCALL";
1072 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1073 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1074 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1075 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1076 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1077 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1078 case ARMISD::CMP: return "ARMISD::CMP";
1079 case ARMISD::CMN: return "ARMISD::CMN";
1080 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1081 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1082 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1083 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1084 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1086 case ARMISD::CMOV: return "ARMISD::CMOV";
1088 case ARMISD::RBIT: return "ARMISD::RBIT";
1090 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1091 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1092 case ARMISD::RRX: return "ARMISD::RRX";
1094 case ARMISD::ADDC: return "ARMISD::ADDC";
1095 case ARMISD::ADDE: return "ARMISD::ADDE";
1096 case ARMISD::SUBC: return "ARMISD::SUBC";
1097 case ARMISD::SUBE: return "ARMISD::SUBE";
1099 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1100 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1102 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1103 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1104 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1106 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1108 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1110 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1112 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1114 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1116 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1118 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1119 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1120 case ARMISD::VCGE: return "ARMISD::VCGE";
1121 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1122 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1123 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1124 case ARMISD::VCGT: return "ARMISD::VCGT";
1125 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1126 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1127 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1128 case ARMISD::VTST: return "ARMISD::VTST";
1130 case ARMISD::VSHL: return "ARMISD::VSHL";
1131 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1132 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1133 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1134 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1135 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1136 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1137 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1138 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1139 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1140 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1141 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1142 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1143 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1144 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1145 case ARMISD::VSLI: return "ARMISD::VSLI";
1146 case ARMISD::VSRI: return "ARMISD::VSRI";
1147 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1148 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1149 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1150 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1151 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1152 case ARMISD::VDUP: return "ARMISD::VDUP";
1153 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1154 case ARMISD::VEXT: return "ARMISD::VEXT";
1155 case ARMISD::VREV64: return "ARMISD::VREV64";
1156 case ARMISD::VREV32: return "ARMISD::VREV32";
1157 case ARMISD::VREV16: return "ARMISD::VREV16";
1158 case ARMISD::VZIP: return "ARMISD::VZIP";
1159 case ARMISD::VUZP: return "ARMISD::VUZP";
1160 case ARMISD::VTRN: return "ARMISD::VTRN";
1161 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1162 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1163 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1164 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1165 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1166 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1167 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1168 case ARMISD::BFI: return "ARMISD::BFI";
1169 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1170 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1171 case ARMISD::VBSL: return "ARMISD::VBSL";
1172 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1173 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1174 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1175 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1176 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1177 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1178 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1179 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1180 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1181 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1182 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1183 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1184 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1185 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1186 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1187 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1188 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1189 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1190 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1191 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1196 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1199 return getPointerTy(DL);
1200 return VT.changeVectorElementTypeToInteger();
1203 /// getRegClassFor - Return the register class that should be used for the
1204 /// specified value type.
1205 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1206 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1207 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1208 // load / store 4 to 8 consecutive D registers.
1209 if (Subtarget->hasNEON()) {
1210 if (VT == MVT::v4i64)
1211 return &ARM::QQPRRegClass;
1212 if (VT == MVT::v8i64)
1213 return &ARM::QQQQPRRegClass;
1215 return TargetLowering::getRegClassFor(VT);
1218 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1219 // source/dest is aligned and the copy size is large enough. We therefore want
1220 // to align such objects passed to memory intrinsics.
1221 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1222 unsigned &PrefAlign) const {
1223 if (!isa<MemIntrinsic>(CI))
1226 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1227 // cycle faster than 4-byte aligned LDM.
1228 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1232 // Create a fast isel object.
1234 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1235 const TargetLibraryInfo *libInfo) const {
1236 return ARM::createFastISel(funcInfo, libInfo);
1239 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1240 unsigned NumVals = N->getNumValues();
1242 return Sched::RegPressure;
1244 for (unsigned i = 0; i != NumVals; ++i) {
1245 EVT VT = N->getValueType(i);
1246 if (VT == MVT::Glue || VT == MVT::Other)
1248 if (VT.isFloatingPoint() || VT.isVector())
1252 if (!N->isMachineOpcode())
1253 return Sched::RegPressure;
1255 // Load are scheduled for latency even if there instruction itinerary
1256 // is not available.
1257 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1258 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1260 if (MCID.getNumDefs() == 0)
1261 return Sched::RegPressure;
1262 if (!Itins->isEmpty() &&
1263 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1266 return Sched::RegPressure;
1269 //===----------------------------------------------------------------------===//
1271 //===----------------------------------------------------------------------===//
1273 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1274 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1276 default: llvm_unreachable("Unknown condition code!");
1277 case ISD::SETNE: return ARMCC::NE;
1278 case ISD::SETEQ: return ARMCC::EQ;
1279 case ISD::SETGT: return ARMCC::GT;
1280 case ISD::SETGE: return ARMCC::GE;
1281 case ISD::SETLT: return ARMCC::LT;
1282 case ISD::SETLE: return ARMCC::LE;
1283 case ISD::SETUGT: return ARMCC::HI;
1284 case ISD::SETUGE: return ARMCC::HS;
1285 case ISD::SETULT: return ARMCC::LO;
1286 case ISD::SETULE: return ARMCC::LS;
1290 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1291 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1292 ARMCC::CondCodes &CondCode2) {
1293 CondCode2 = ARMCC::AL;
1295 default: llvm_unreachable("Unknown FP condition!");
1297 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1299 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1301 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1302 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1303 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1304 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1305 case ISD::SETO: CondCode = ARMCC::VC; break;
1306 case ISD::SETUO: CondCode = ARMCC::VS; break;
1307 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1308 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1309 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1311 case ISD::SETULT: CondCode = ARMCC::LT; break;
1313 case ISD::SETULE: CondCode = ARMCC::LE; break;
1315 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1319 //===----------------------------------------------------------------------===//
1320 // Calling Convention Implementation
1321 //===----------------------------------------------------------------------===//
1323 #include "ARMGenCallingConv.inc"
1325 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1326 /// account presence of floating point hardware and calling convention
1327 /// limitations, such as support for variadic functions.
1329 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1330 bool isVarArg) const {
1333 llvm_unreachable("Unsupported calling convention");
1334 case CallingConv::ARM_AAPCS:
1335 case CallingConv::ARM_APCS:
1336 case CallingConv::GHC:
1338 case CallingConv::ARM_AAPCS_VFP:
1339 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1340 case CallingConv::C:
1341 if (!Subtarget->isAAPCS_ABI())
1342 return CallingConv::ARM_APCS;
1343 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1344 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1346 return CallingConv::ARM_AAPCS_VFP;
1348 return CallingConv::ARM_AAPCS;
1349 case CallingConv::Fast:
1350 if (!Subtarget->isAAPCS_ABI()) {
1351 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1352 return CallingConv::Fast;
1353 return CallingConv::ARM_APCS;
1354 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1355 return CallingConv::ARM_AAPCS_VFP;
1357 return CallingConv::ARM_AAPCS;
1361 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1362 /// CallingConvention.
1363 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1365 bool isVarArg) const {
1366 switch (getEffectiveCallingConv(CC, isVarArg)) {
1368 llvm_unreachable("Unsupported calling convention");
1369 case CallingConv::ARM_APCS:
1370 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1371 case CallingConv::ARM_AAPCS:
1372 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1373 case CallingConv::ARM_AAPCS_VFP:
1374 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1375 case CallingConv::Fast:
1376 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1377 case CallingConv::GHC:
1378 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1382 /// LowerCallResult - Lower the result values of a call into the
1383 /// appropriate copies out of appropriate physical registers.
1385 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1386 CallingConv::ID CallConv, bool isVarArg,
1387 const SmallVectorImpl<ISD::InputArg> &Ins,
1388 SDLoc dl, SelectionDAG &DAG,
1389 SmallVectorImpl<SDValue> &InVals,
1390 bool isThisReturn, SDValue ThisVal) const {
1392 // Assign locations to each value returned by this call.
1393 SmallVector<CCValAssign, 16> RVLocs;
1394 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1395 *DAG.getContext(), Call);
1396 CCInfo.AnalyzeCallResult(Ins,
1397 CCAssignFnForNode(CallConv, /* Return*/ true,
1400 // Copy all of the result registers out of their specified physreg.
1401 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1402 CCValAssign VA = RVLocs[i];
1404 // Pass 'this' value directly from the argument to return value, to avoid
1405 // reg unit interference
1406 if (i == 0 && isThisReturn) {
1407 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1408 "unexpected return calling convention register assignment");
1409 InVals.push_back(ThisVal);
1414 if (VA.needsCustom()) {
1415 // Handle f64 or half of a v2f64.
1416 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1418 Chain = Lo.getValue(1);
1419 InFlag = Lo.getValue(2);
1420 VA = RVLocs[++i]; // skip ahead to next loc
1421 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1423 Chain = Hi.getValue(1);
1424 InFlag = Hi.getValue(2);
1425 if (!Subtarget->isLittle())
1427 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1429 if (VA.getLocVT() == MVT::v2f64) {
1430 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1431 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1432 DAG.getConstant(0, dl, MVT::i32));
1434 VA = RVLocs[++i]; // skip ahead to next loc
1435 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1436 Chain = Lo.getValue(1);
1437 InFlag = Lo.getValue(2);
1438 VA = RVLocs[++i]; // skip ahead to next loc
1439 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1440 Chain = Hi.getValue(1);
1441 InFlag = Hi.getValue(2);
1442 if (!Subtarget->isLittle())
1444 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1445 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1446 DAG.getConstant(1, dl, MVT::i32));
1449 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1451 Chain = Val.getValue(1);
1452 InFlag = Val.getValue(2);
1455 switch (VA.getLocInfo()) {
1456 default: llvm_unreachable("Unknown loc info!");
1457 case CCValAssign::Full: break;
1458 case CCValAssign::BCvt:
1459 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1463 InVals.push_back(Val);
1469 /// LowerMemOpCallTo - Store the argument to the stack.
1471 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1472 SDValue StackPtr, SDValue Arg,
1473 SDLoc dl, SelectionDAG &DAG,
1474 const CCValAssign &VA,
1475 ISD::ArgFlagsTy Flags) const {
1476 unsigned LocMemOffset = VA.getLocMemOffset();
1477 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1478 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1480 return DAG.getStore(
1481 Chain, dl, Arg, PtrOff,
1482 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1486 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1487 SDValue Chain, SDValue &Arg,
1488 RegsToPassVector &RegsToPass,
1489 CCValAssign &VA, CCValAssign &NextVA,
1491 SmallVectorImpl<SDValue> &MemOpChains,
1492 ISD::ArgFlagsTy Flags) const {
1494 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1495 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1496 unsigned id = Subtarget->isLittle() ? 0 : 1;
1497 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1499 if (NextVA.isRegLoc())
1500 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1502 assert(NextVA.isMemLoc());
1503 if (!StackPtr.getNode())
1504 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1505 getPointerTy(DAG.getDataLayout()));
1507 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1513 /// LowerCall - Lowering a call into a callseq_start <-
1514 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1517 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1518 SmallVectorImpl<SDValue> &InVals) const {
1519 SelectionDAG &DAG = CLI.DAG;
1521 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1522 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1523 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1524 SDValue Chain = CLI.Chain;
1525 SDValue Callee = CLI.Callee;
1526 bool &isTailCall = CLI.IsTailCall;
1527 CallingConv::ID CallConv = CLI.CallConv;
1528 bool doesNotRet = CLI.DoesNotReturn;
1529 bool isVarArg = CLI.IsVarArg;
1531 MachineFunction &MF = DAG.getMachineFunction();
1532 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1533 bool isThisReturn = false;
1534 bool isSibCall = false;
1535 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1537 // Disable tail calls if they're not supported.
1538 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1542 // Check if it's really possible to do a tail call.
1543 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1544 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1545 Outs, OutVals, Ins, DAG);
1546 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1547 report_fatal_error("failed to perform tail call elimination on a call "
1548 "site marked musttail");
1549 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1550 // detected sibcalls.
1557 // Analyze operands of the call, assigning locations to each operand.
1558 SmallVector<CCValAssign, 16> ArgLocs;
1559 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1560 *DAG.getContext(), Call);
1561 CCInfo.AnalyzeCallOperands(Outs,
1562 CCAssignFnForNode(CallConv, /* Return*/ false,
1565 // Get a count of how many bytes are to be pushed on the stack.
1566 unsigned NumBytes = CCInfo.getNextStackOffset();
1568 // For tail calls, memory operands are available in our caller's stack.
1572 // Adjust the stack pointer for the new arguments...
1573 // These operations are automatically eliminated by the prolog/epilog pass
1575 Chain = DAG.getCALLSEQ_START(Chain,
1576 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1579 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1581 RegsToPassVector RegsToPass;
1582 SmallVector<SDValue, 8> MemOpChains;
1584 // Walk the register/memloc assignments, inserting copies/loads. In the case
1585 // of tail call optimization, arguments are handled later.
1586 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1588 ++i, ++realArgIdx) {
1589 CCValAssign &VA = ArgLocs[i];
1590 SDValue Arg = OutVals[realArgIdx];
1591 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1592 bool isByVal = Flags.isByVal();
1594 // Promote the value if needed.
1595 switch (VA.getLocInfo()) {
1596 default: llvm_unreachable("Unknown loc info!");
1597 case CCValAssign::Full: break;
1598 case CCValAssign::SExt:
1599 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1601 case CCValAssign::ZExt:
1602 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1604 case CCValAssign::AExt:
1605 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1607 case CCValAssign::BCvt:
1608 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1612 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1613 if (VA.needsCustom()) {
1614 if (VA.getLocVT() == MVT::v2f64) {
1615 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1616 DAG.getConstant(0, dl, MVT::i32));
1617 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1618 DAG.getConstant(1, dl, MVT::i32));
1620 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1621 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1623 VA = ArgLocs[++i]; // skip ahead to next loc
1624 if (VA.isRegLoc()) {
1625 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1626 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1628 assert(VA.isMemLoc());
1630 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1631 dl, DAG, VA, Flags));
1634 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1635 StackPtr, MemOpChains, Flags);
1637 } else if (VA.isRegLoc()) {
1638 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1639 assert(VA.getLocVT() == MVT::i32 &&
1640 "unexpected calling convention register assignment");
1641 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1642 "unexpected use of 'returned'");
1643 isThisReturn = true;
1645 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1646 } else if (isByVal) {
1647 assert(VA.isMemLoc());
1648 unsigned offset = 0;
1650 // True if this byval aggregate will be split between registers
1652 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1653 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1655 if (CurByValIdx < ByValArgsCount) {
1657 unsigned RegBegin, RegEnd;
1658 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1661 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1663 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1664 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1665 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1666 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1667 MachinePointerInfo(),
1668 false, false, false,
1669 DAG.InferPtrAlignment(AddArg));
1670 MemOpChains.push_back(Load.getValue(1));
1671 RegsToPass.push_back(std::make_pair(j, Load));
1674 // If parameter size outsides register area, "offset" value
1675 // helps us to calculate stack slot for remained part properly.
1676 offset = RegEnd - RegBegin;
1678 CCInfo.nextInRegsParam();
1681 if (Flags.getByValSize() > 4*offset) {
1682 auto PtrVT = getPointerTy(DAG.getDataLayout());
1683 unsigned LocMemOffset = VA.getLocMemOffset();
1684 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1685 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1686 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1687 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1688 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1690 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1693 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1694 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1695 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1698 } else if (!isSibCall) {
1699 assert(VA.isMemLoc());
1701 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1702 dl, DAG, VA, Flags));
1706 if (!MemOpChains.empty())
1707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1709 // Build a sequence of copy-to-reg nodes chained together with token chain
1710 // and flag operands which copy the outgoing args into the appropriate regs.
1712 // Tail call byval lowering might overwrite argument registers so in case of
1713 // tail call optimization the copies to registers are lowered later.
1715 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1716 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1717 RegsToPass[i].second, InFlag);
1718 InFlag = Chain.getValue(1);
1721 // For tail calls lower the arguments to the 'real' stack slot.
1723 // Force all the incoming stack arguments to be loaded from the stack
1724 // before any new outgoing arguments are stored to the stack, because the
1725 // outgoing stack slots may alias the incoming argument stack slots, and
1726 // the alias isn't otherwise explicit. This is slightly more conservative
1727 // than necessary, because it means that each store effectively depends
1728 // on every argument instead of just those arguments it would clobber.
1730 // Do not flag preceding copytoreg stuff together with the following stuff.
1732 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1733 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1734 RegsToPass[i].second, InFlag);
1735 InFlag = Chain.getValue(1);
1740 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1741 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1742 // node so that legalize doesn't hack it.
1743 bool isDirect = false;
1744 bool isARMFunc = false;
1745 bool isLocalARMFunc = false;
1746 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1747 auto PtrVt = getPointerTy(DAG.getDataLayout());
1749 if (Subtarget->genLongCalls()) {
1750 assert((Subtarget->isTargetWindows() ||
1751 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1752 "long-calls with non-static relocation model!");
1753 // Handle a global address or an external symbol. If it's not one of
1754 // those, the target's already in a register, so we don't need to do
1756 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1757 const GlobalValue *GV = G->getGlobal();
1758 // Create a constant pool entry for the callee address
1759 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1760 ARMConstantPoolValue *CPV =
1761 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1763 // Get the address of the callee into a register
1764 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1765 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1766 Callee = DAG.getLoad(
1767 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1768 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1770 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1771 const char *Sym = S->getSymbol();
1773 // Create a constant pool entry for the callee address
1774 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1775 ARMConstantPoolValue *CPV =
1776 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1777 ARMPCLabelIndex, 0);
1778 // Get the address of the callee into a register
1779 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1780 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1781 Callee = DAG.getLoad(
1782 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1783 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1786 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1787 const GlobalValue *GV = G->getGlobal();
1789 bool isDef = GV->isStrongDefinitionForLinker();
1790 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1791 getTargetMachine().getRelocationModel() != Reloc::Static;
1792 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1793 // ARM call to a local ARM function is predicable.
1794 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1795 // tBX takes a register source operand.
1796 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1797 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1798 Callee = DAG.getNode(
1799 ARMISD::WrapperPIC, dl, PtrVt,
1800 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1801 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1802 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1803 false, false, true, 0);
1804 } else if (Subtarget->isTargetCOFF()) {
1805 assert(Subtarget->isTargetWindows() &&
1806 "Windows is the only supported COFF target");
1807 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1808 ? ARMII::MO_DLLIMPORT
1809 : ARMII::MO_NO_FLAG;
1811 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1812 if (GV->hasDLLImportStorageClass())
1814 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1815 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1816 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1817 false, false, false, 0);
1819 // On ELF targets for PIC code, direct calls should go through the PLT
1820 unsigned OpFlags = 0;
1821 if (Subtarget->isTargetELF() &&
1822 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1823 OpFlags = ARMII::MO_PLT;
1824 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1826 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1828 bool isStub = Subtarget->isTargetMachO() &&
1829 getTargetMachine().getRelocationModel() != Reloc::Static;
1830 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1831 // tBX takes a register source operand.
1832 const char *Sym = S->getSymbol();
1833 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1834 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1835 ARMConstantPoolValue *CPV =
1836 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1837 ARMPCLabelIndex, 4);
1838 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1839 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1840 Callee = DAG.getLoad(
1841 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1842 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1844 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1845 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1847 unsigned OpFlags = 0;
1848 // On ELF targets for PIC code, direct calls should go through the PLT
1849 if (Subtarget->isTargetELF() &&
1850 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1851 OpFlags = ARMII::MO_PLT;
1852 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1856 // FIXME: handle tail calls differently.
1858 if (Subtarget->isThumb()) {
1859 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1860 CallOpc = ARMISD::CALL_NOLINK;
1862 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1864 if (!isDirect && !Subtarget->hasV5TOps())
1865 CallOpc = ARMISD::CALL_NOLINK;
1866 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1867 // Emit regular call when code size is the priority
1868 !MF.getFunction()->optForMinSize())
1869 // "mov lr, pc; b _foo" to avoid confusing the RSP
1870 CallOpc = ARMISD::CALL_NOLINK;
1872 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1875 std::vector<SDValue> Ops;
1876 Ops.push_back(Chain);
1877 Ops.push_back(Callee);
1879 // Add argument registers to the end of the list so that they are known live
1881 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1882 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1883 RegsToPass[i].second.getValueType()));
1885 // Add a register mask operand representing the call-preserved registers.
1887 const uint32_t *Mask;
1888 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1890 // For 'this' returns, use the R0-preserving mask if applicable
1891 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1893 // Set isThisReturn to false if the calling convention is not one that
1894 // allows 'returned' to be modeled in this way, so LowerCallResult does
1895 // not try to pass 'this' straight through
1896 isThisReturn = false;
1897 Mask = ARI->getCallPreservedMask(MF, CallConv);
1900 Mask = ARI->getCallPreservedMask(MF, CallConv);
1902 assert(Mask && "Missing call preserved mask for calling convention");
1903 Ops.push_back(DAG.getRegisterMask(Mask));
1906 if (InFlag.getNode())
1907 Ops.push_back(InFlag);
1909 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1911 MF.getFrameInfo()->setHasTailCall();
1912 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1915 // Returns a chain and a flag for retval copy to use.
1916 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1917 InFlag = Chain.getValue(1);
1919 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1920 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1922 InFlag = Chain.getValue(1);
1924 // Handle result values, copying them out of physregs into vregs that we
1926 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1927 InVals, isThisReturn,
1928 isThisReturn ? OutVals[0] : SDValue());
1931 /// HandleByVal - Every parameter *after* a byval parameter is passed
1932 /// on the stack. Remember the next parameter register to allocate,
1933 /// and then confiscate the rest of the parameter registers to insure
1935 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1936 unsigned Align) const {
1937 assert((State->getCallOrPrologue() == Prologue ||
1938 State->getCallOrPrologue() == Call) &&
1939 "unhandled ParmContext");
1941 // Byval (as with any stack) slots are always at least 4 byte aligned.
1942 Align = std::max(Align, 4U);
1944 unsigned Reg = State->AllocateReg(GPRArgRegs);
1948 unsigned AlignInRegs = Align / 4;
1949 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1950 for (unsigned i = 0; i < Waste; ++i)
1951 Reg = State->AllocateReg(GPRArgRegs);
1956 unsigned Excess = 4 * (ARM::R4 - Reg);
1958 // Special case when NSAA != SP and parameter size greater than size of
1959 // all remained GPR regs. In that case we can't split parameter, we must
1960 // send it to stack. We also must set NCRN to R4, so waste all
1961 // remained registers.
1962 const unsigned NSAAOffset = State->getNextStackOffset();
1963 if (NSAAOffset != 0 && Size > Excess) {
1964 while (State->AllocateReg(GPRArgRegs))
1969 // First register for byval parameter is the first register that wasn't
1970 // allocated before this method call, so it would be "reg".
1971 // If parameter is small enough to be saved in range [reg, r4), then
1972 // the end (first after last) register would be reg + param-size-in-regs,
1973 // else parameter would be splitted between registers and stack,
1974 // end register would be r4 in this case.
1975 unsigned ByValRegBegin = Reg;
1976 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1977 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1978 // Note, first register is allocated in the beginning of function already,
1979 // allocate remained amount of registers we need.
1980 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1981 State->AllocateReg(GPRArgRegs);
1982 // A byval parameter that is split between registers and memory needs its
1983 // size truncated here.
1984 // In the case where the entire structure fits in registers, we set the
1985 // size in memory to zero.
1986 Size = std::max<int>(Size - Excess, 0);
1989 /// MatchingStackOffset - Return true if the given stack call argument is
1990 /// already available in the same position (relatively) of the caller's
1991 /// incoming argument stack.
1993 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1994 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1995 const TargetInstrInfo *TII) {
1996 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1998 if (Arg.getOpcode() == ISD::CopyFromReg) {
1999 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2000 if (!TargetRegisterInfo::isVirtualRegister(VR))
2002 MachineInstr *Def = MRI->getVRegDef(VR);
2005 if (!Flags.isByVal()) {
2006 if (!TII->isLoadFromStackSlot(Def, FI))
2011 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2012 if (Flags.isByVal())
2013 // ByVal argument is passed in as a pointer but it's now being
2014 // dereferenced. e.g.
2015 // define @foo(%struct.X* %A) {
2016 // tail call @bar(%struct.X* byval %A)
2019 SDValue Ptr = Ld->getBasePtr();
2020 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2023 FI = FINode->getIndex();
2027 assert(FI != INT_MAX);
2028 if (!MFI->isFixedObjectIndex(FI))
2030 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2033 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2034 /// for tail call optimization. Targets which want to do tail call
2035 /// optimization should implement this function.
2037 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2038 CallingConv::ID CalleeCC,
2040 bool isCalleeStructRet,
2041 bool isCallerStructRet,
2042 const SmallVectorImpl<ISD::OutputArg> &Outs,
2043 const SmallVectorImpl<SDValue> &OutVals,
2044 const SmallVectorImpl<ISD::InputArg> &Ins,
2045 SelectionDAG& DAG) const {
2046 const Function *CallerF = DAG.getMachineFunction().getFunction();
2047 CallingConv::ID CallerCC = CallerF->getCallingConv();
2048 bool CCMatch = CallerCC == CalleeCC;
2050 // Look for obvious safe cases to perform tail call optimization that do not
2051 // require ABI changes. This is what gcc calls sibcall.
2053 // Do not sibcall optimize vararg calls unless the call site is not passing
2055 if (isVarArg && !Outs.empty())
2058 // Exception-handling functions need a special set of instructions to indicate
2059 // a return to the hardware. Tail-calling another function would probably
2061 if (CallerF->hasFnAttribute("interrupt"))
2064 // Also avoid sibcall optimization if either caller or callee uses struct
2065 // return semantics.
2066 if (isCalleeStructRet || isCallerStructRet)
2069 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2070 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2071 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2072 // support in the assembler and linker to be used. This would need to be
2073 // fixed to fully support tail calls in Thumb1.
2075 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2076 // LR. This means if we need to reload LR, it takes an extra instructions,
2077 // which outweighs the value of the tail call; but here we don't know yet
2078 // whether LR is going to be used. Probably the right approach is to
2079 // generate the tail call here and turn it back into CALL/RET in
2080 // emitEpilogue if LR is used.
2082 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2083 // but we need to make sure there are enough registers; the only valid
2084 // registers are the 4 used for parameters. We don't currently do this
2086 if (Subtarget->isThumb1Only())
2089 // Externally-defined functions with weak linkage should not be
2090 // tail-called on ARM when the OS does not support dynamic
2091 // pre-emption of symbols, as the AAELF spec requires normal calls
2092 // to undefined weak functions to be replaced with a NOP or jump to the
2093 // next instruction. The behaviour of branch instructions in this
2094 // situation (as used for tail calls) is implementation-defined, so we
2095 // cannot rely on the linker replacing the tail call with a return.
2096 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2097 const GlobalValue *GV = G->getGlobal();
2098 const Triple &TT = getTargetMachine().getTargetTriple();
2099 if (GV->hasExternalWeakLinkage() &&
2100 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2104 // If the calling conventions do not match, then we'd better make sure the
2105 // results are returned in the same way as what the caller expects.
2107 SmallVector<CCValAssign, 16> RVLocs1;
2108 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2109 *DAG.getContext(), Call);
2110 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2112 SmallVector<CCValAssign, 16> RVLocs2;
2113 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2114 *DAG.getContext(), Call);
2115 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2117 if (RVLocs1.size() != RVLocs2.size())
2119 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2120 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2122 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2124 if (RVLocs1[i].isRegLoc()) {
2125 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2128 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2134 // If Caller's vararg or byval argument has been split between registers and
2135 // stack, do not perform tail call, since part of the argument is in caller's
2137 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2138 getInfo<ARMFunctionInfo>();
2139 if (AFI_Caller->getArgRegsSaveSize())
2142 // If the callee takes no arguments then go on to check the results of the
2144 if (!Outs.empty()) {
2145 // Check if stack adjustment is needed. For now, do not do this if any
2146 // argument is passed on the stack.
2147 SmallVector<CCValAssign, 16> ArgLocs;
2148 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2149 *DAG.getContext(), Call);
2150 CCInfo.AnalyzeCallOperands(Outs,
2151 CCAssignFnForNode(CalleeCC, false, isVarArg));
2152 if (CCInfo.getNextStackOffset()) {
2153 MachineFunction &MF = DAG.getMachineFunction();
2155 // Check if the arguments are already laid out in the right way as
2156 // the caller's fixed stack objects.
2157 MachineFrameInfo *MFI = MF.getFrameInfo();
2158 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2159 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2160 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2162 ++i, ++realArgIdx) {
2163 CCValAssign &VA = ArgLocs[i];
2164 EVT RegVT = VA.getLocVT();
2165 SDValue Arg = OutVals[realArgIdx];
2166 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2167 if (VA.getLocInfo() == CCValAssign::Indirect)
2169 if (VA.needsCustom()) {
2170 // f64 and vector types are split into multiple registers or
2171 // register/stack-slot combinations. The types will not match
2172 // the registers; give up on memory f64 refs until we figure
2173 // out what to do about this.
2176 if (!ArgLocs[++i].isRegLoc())
2178 if (RegVT == MVT::v2f64) {
2179 if (!ArgLocs[++i].isRegLoc())
2181 if (!ArgLocs[++i].isRegLoc())
2184 } else if (!VA.isRegLoc()) {
2185 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2197 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2198 MachineFunction &MF, bool isVarArg,
2199 const SmallVectorImpl<ISD::OutputArg> &Outs,
2200 LLVMContext &Context) const {
2201 SmallVector<CCValAssign, 16> RVLocs;
2202 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2203 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2207 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2208 SDLoc DL, SelectionDAG &DAG) {
2209 const MachineFunction &MF = DAG.getMachineFunction();
2210 const Function *F = MF.getFunction();
2212 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2214 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2215 // version of the "preferred return address". These offsets affect the return
2216 // instruction if this is a return from PL1 without hypervisor extensions.
2217 // IRQ/FIQ: +4 "subs pc, lr, #4"
2218 // SWI: 0 "subs pc, lr, #0"
2219 // ABORT: +4 "subs pc, lr, #4"
2220 // UNDEF: +4/+2 "subs pc, lr, #0"
2221 // UNDEF varies depending on where the exception came from ARM or Thumb
2222 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2225 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2228 else if (IntKind == "SWI" || IntKind == "UNDEF")
2231 report_fatal_error("Unsupported interrupt attribute. If present, value "
2232 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2234 RetOps.insert(RetOps.begin() + 1,
2235 DAG.getConstant(LROffset, DL, MVT::i32, false));
2237 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2241 ARMTargetLowering::LowerReturn(SDValue Chain,
2242 CallingConv::ID CallConv, bool isVarArg,
2243 const SmallVectorImpl<ISD::OutputArg> &Outs,
2244 const SmallVectorImpl<SDValue> &OutVals,
2245 SDLoc dl, SelectionDAG &DAG) const {
2247 // CCValAssign - represent the assignment of the return value to a location.
2248 SmallVector<CCValAssign, 16> RVLocs;
2250 // CCState - Info about the registers and stack slots.
2251 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2252 *DAG.getContext(), Call);
2254 // Analyze outgoing return values.
2255 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2259 SmallVector<SDValue, 4> RetOps;
2260 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2261 bool isLittleEndian = Subtarget->isLittle();
2263 MachineFunction &MF = DAG.getMachineFunction();
2264 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2265 AFI->setReturnRegsCount(RVLocs.size());
2267 // Copy the result values into the output registers.
2268 for (unsigned i = 0, realRVLocIdx = 0;
2270 ++i, ++realRVLocIdx) {
2271 CCValAssign &VA = RVLocs[i];
2272 assert(VA.isRegLoc() && "Can only return in registers!");
2274 SDValue Arg = OutVals[realRVLocIdx];
2276 switch (VA.getLocInfo()) {
2277 default: llvm_unreachable("Unknown loc info!");
2278 case CCValAssign::Full: break;
2279 case CCValAssign::BCvt:
2280 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2284 if (VA.needsCustom()) {
2285 if (VA.getLocVT() == MVT::v2f64) {
2286 // Extract the first half and return it in two registers.
2287 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2288 DAG.getConstant(0, dl, MVT::i32));
2289 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2290 DAG.getVTList(MVT::i32, MVT::i32), Half);
2292 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2293 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2295 Flag = Chain.getValue(1);
2296 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2297 VA = RVLocs[++i]; // skip ahead to next loc
2298 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2299 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2301 Flag = Chain.getValue(1);
2302 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2303 VA = RVLocs[++i]; // skip ahead to next loc
2305 // Extract the 2nd half and fall through to handle it as an f64 value.
2306 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2307 DAG.getConstant(1, dl, MVT::i32));
2309 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2311 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2312 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2313 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2314 fmrrd.getValue(isLittleEndian ? 0 : 1),
2316 Flag = Chain.getValue(1);
2317 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2318 VA = RVLocs[++i]; // skip ahead to next loc
2319 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2320 fmrrd.getValue(isLittleEndian ? 1 : 0),
2323 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2325 // Guarantee that all emitted copies are
2326 // stuck together, avoiding something bad.
2327 Flag = Chain.getValue(1);
2328 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2331 // Update chain and glue.
2334 RetOps.push_back(Flag);
2336 // CPUs which aren't M-class use a special sequence to return from
2337 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2338 // though we use "subs pc, lr, #N").
2340 // M-class CPUs actually use a normal return sequence with a special
2341 // (hardware-provided) value in LR, so the normal code path works.
2342 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2343 !Subtarget->isMClass()) {
2344 if (Subtarget->isThumb1Only())
2345 report_fatal_error("interrupt attribute is not supported in Thumb1");
2346 return LowerInterruptReturn(RetOps, dl, DAG);
2349 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2352 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2353 if (N->getNumValues() != 1)
2355 if (!N->hasNUsesOfValue(1, 0))
2358 SDValue TCChain = Chain;
2359 SDNode *Copy = *N->use_begin();
2360 if (Copy->getOpcode() == ISD::CopyToReg) {
2361 // If the copy has a glue operand, we conservatively assume it isn't safe to
2362 // perform a tail call.
2363 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2365 TCChain = Copy->getOperand(0);
2366 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2367 SDNode *VMov = Copy;
2368 // f64 returned in a pair of GPRs.
2369 SmallPtrSet<SDNode*, 2> Copies;
2370 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2372 if (UI->getOpcode() != ISD::CopyToReg)
2376 if (Copies.size() > 2)
2379 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2381 SDValue UseChain = UI->getOperand(0);
2382 if (Copies.count(UseChain.getNode()))
2386 // We are at the top of this chain.
2387 // If the copy has a glue operand, we conservatively assume it
2388 // isn't safe to perform a tail call.
2389 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2395 } else if (Copy->getOpcode() == ISD::BITCAST) {
2396 // f32 returned in a single GPR.
2397 if (!Copy->hasOneUse())
2399 Copy = *Copy->use_begin();
2400 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2402 // If the copy has a glue operand, we conservatively assume it isn't safe to
2403 // perform a tail call.
2404 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2406 TCChain = Copy->getOperand(0);
2411 bool HasRet = false;
2412 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2414 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2415 UI->getOpcode() != ARMISD::INTRET_FLAG)
2427 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2428 if (!Subtarget->supportsTailCall())
2432 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2433 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2436 return !Subtarget->isThumb1Only();
2439 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2440 // and pass the lower and high parts through.
2441 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2443 SDValue WriteValue = Op->getOperand(2);
2445 // This function is only supposed to be called for i64 type argument.
2446 assert(WriteValue.getValueType() == MVT::i64
2447 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2449 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2450 DAG.getConstant(0, DL, MVT::i32));
2451 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2452 DAG.getConstant(1, DL, MVT::i32));
2453 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2454 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2457 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2458 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2459 // one of the above mentioned nodes. It has to be wrapped because otherwise
2460 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2461 // be used to form addressing mode. These wrapped nodes will be selected
2463 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2464 EVT PtrVT = Op.getValueType();
2465 // FIXME there is no actual debug info here
2467 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2469 if (CP->isMachineConstantPoolEntry())
2470 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2471 CP->getAlignment());
2473 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2474 CP->getAlignment());
2475 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2478 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2479 return MachineJumpTableInfo::EK_Inline;
2482 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2483 SelectionDAG &DAG) const {
2484 MachineFunction &MF = DAG.getMachineFunction();
2485 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2486 unsigned ARMPCLabelIndex = 0;
2488 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2489 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2490 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2492 if (RelocM == Reloc::Static) {
2493 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2495 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2496 ARMPCLabelIndex = AFI->createPICLabelUId();
2497 ARMConstantPoolValue *CPV =
2498 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2499 ARMCP::CPBlockAddress, PCAdj);
2500 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2502 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2504 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2505 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2506 false, false, false, 0);
2507 if (RelocM == Reloc::Static)
2509 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2510 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2513 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2515 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2516 SelectionDAG &DAG) const {
2518 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2519 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2520 MachineFunction &MF = DAG.getMachineFunction();
2521 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2522 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2523 ARMConstantPoolValue *CPV =
2524 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2525 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2526 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2527 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2529 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2530 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2531 false, false, false, 0);
2532 SDValue Chain = Argument.getValue(1);
2534 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2535 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2537 // call __tls_get_addr.
2540 Entry.Node = Argument;
2541 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2542 Args.push_back(Entry);
2544 // FIXME: is there useful debug info available here?
2545 TargetLowering::CallLoweringInfo CLI(DAG);
2546 CLI.setDebugLoc(dl).setChain(Chain)
2547 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2548 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2551 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2552 return CallResult.first;
2555 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2556 // "local exec" model.
2558 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2560 TLSModel::Model model) const {
2561 const GlobalValue *GV = GA->getGlobal();
2564 SDValue Chain = DAG.getEntryNode();
2565 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2566 // Get the Thread Pointer
2567 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2569 if (model == TLSModel::InitialExec) {
2570 MachineFunction &MF = DAG.getMachineFunction();
2571 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2572 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2573 // Initial exec model.
2574 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2575 ARMConstantPoolValue *CPV =
2576 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2577 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2579 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2580 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2581 Offset = DAG.getLoad(
2582 PtrVT, dl, Chain, Offset,
2583 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2585 Chain = Offset.getValue(1);
2587 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2588 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2590 Offset = DAG.getLoad(
2591 PtrVT, dl, Chain, Offset,
2592 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2596 assert(model == TLSModel::LocalExec);
2597 ARMConstantPoolValue *CPV =
2598 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2599 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2600 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2601 Offset = DAG.getLoad(
2602 PtrVT, dl, Chain, Offset,
2603 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2607 // The address of the thread local variable is the add of the thread
2608 // pointer with the offset of the variable.
2609 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2613 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2614 // TODO: implement the "local dynamic" model
2615 assert(Subtarget->isTargetELF() &&
2616 "TLS not implemented for non-ELF targets");
2617 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2618 if (DAG.getTarget().Options.EmulatedTLS)
2619 return LowerToTLSEmulatedModel(GA, DAG);
2621 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2624 case TLSModel::GeneralDynamic:
2625 case TLSModel::LocalDynamic:
2626 return LowerToTLSGeneralDynamicModel(GA, DAG);
2627 case TLSModel::InitialExec:
2628 case TLSModel::LocalExec:
2629 return LowerToTLSExecModels(GA, DAG, model);
2631 llvm_unreachable("bogus TLS model");
2634 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2635 SelectionDAG &DAG) const {
2636 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2638 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2639 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2640 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2641 ARMConstantPoolValue *CPV =
2642 ARMConstantPoolConstant::Create(GV,
2643 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2644 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2645 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2646 SDValue Result = DAG.getLoad(
2647 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2648 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2650 SDValue Chain = Result.getValue(1);
2651 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2652 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2654 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2655 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2656 false, false, false, 0);
2660 // If we have T2 ops, we can materialize the address directly via movt/movw
2661 // pair. This is always cheaper.
2662 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2664 // FIXME: Once remat is capable of dealing with instructions with register
2665 // operands, expand this into two nodes.
2666 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2667 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2669 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2670 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2672 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2673 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2678 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2679 SelectionDAG &DAG) const {
2680 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2682 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2683 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2685 if (Subtarget->useMovt(DAG.getMachineFunction()))
2688 // FIXME: Once remat is capable of dealing with instructions with register
2689 // operands, expand this into multiple nodes
2691 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2693 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2694 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2696 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2697 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2698 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2699 false, false, false, 0);
2703 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2704 SelectionDAG &DAG) const {
2705 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2706 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2707 "Windows on ARM expects to use movw/movt");
2709 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2710 const ARMII::TOF TargetFlags =
2711 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2712 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2718 // FIXME: Once remat is capable of dealing with instructions with register
2719 // operands, expand this into two nodes.
2720 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2721 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2723 if (GV->hasDLLImportStorageClass())
2724 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2725 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2726 false, false, false, 0);
2730 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2731 SelectionDAG &DAG) const {
2732 assert(Subtarget->isTargetELF() &&
2733 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2734 MachineFunction &MF = DAG.getMachineFunction();
2735 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2736 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2737 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2739 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2740 ARMConstantPoolValue *CPV =
2741 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2742 ARMPCLabelIndex, PCAdj);
2743 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2744 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2746 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2747 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2748 false, false, false, 0);
2749 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2750 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2754 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2756 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2757 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2758 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2759 Op.getOperand(1), Val);
2763 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2765 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2766 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2769 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2770 SelectionDAG &DAG) const {
2772 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2777 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2778 const ARMSubtarget *Subtarget) const {
2779 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2782 default: return SDValue(); // Don't custom lower most intrinsics.
2783 case Intrinsic::arm_rbit: {
2784 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2785 "RBIT intrinsic must have i32 type!");
2786 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2788 case Intrinsic::arm_thread_pointer: {
2789 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2790 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2792 case Intrinsic::eh_sjlj_lsda: {
2793 MachineFunction &MF = DAG.getMachineFunction();
2794 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2795 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2796 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2797 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2799 unsigned PCAdj = (RelocM != Reloc::PIC_)
2800 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2801 ARMConstantPoolValue *CPV =
2802 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2803 ARMCP::CPLSDA, PCAdj);
2804 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2805 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2806 SDValue Result = DAG.getLoad(
2807 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2808 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2811 if (RelocM == Reloc::PIC_) {
2812 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2813 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2817 case Intrinsic::arm_neon_vmulls:
2818 case Intrinsic::arm_neon_vmullu: {
2819 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2820 ? ARMISD::VMULLs : ARMISD::VMULLu;
2821 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2822 Op.getOperand(1), Op.getOperand(2));
2824 case Intrinsic::arm_neon_vminnm:
2825 case Intrinsic::arm_neon_vmaxnm: {
2826 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2827 ? ISD::FMINNUM : ISD::FMAXNUM;
2828 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2829 Op.getOperand(1), Op.getOperand(2));
2831 case Intrinsic::arm_neon_vminu:
2832 case Intrinsic::arm_neon_vmaxu: {
2833 if (Op.getValueType().isFloatingPoint())
2835 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2836 ? ISD::UMIN : ISD::UMAX;
2837 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2838 Op.getOperand(1), Op.getOperand(2));
2840 case Intrinsic::arm_neon_vmins:
2841 case Intrinsic::arm_neon_vmaxs: {
2842 // v{min,max}s is overloaded between signed integers and floats.
2843 if (!Op.getValueType().isFloatingPoint()) {
2844 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2845 ? ISD::SMIN : ISD::SMAX;
2846 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2847 Op.getOperand(1), Op.getOperand(2));
2849 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2850 ? ISD::FMINNAN : ISD::FMAXNAN;
2851 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2852 Op.getOperand(1), Op.getOperand(2));
2857 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2858 const ARMSubtarget *Subtarget) {
2859 // FIXME: handle "fence singlethread" more efficiently.
2861 if (!Subtarget->hasDataBarrier()) {
2862 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2863 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2865 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2866 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2867 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2868 DAG.getConstant(0, dl, MVT::i32));
2871 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2872 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2873 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2874 if (Subtarget->isMClass()) {
2875 // Only a full system barrier exists in the M-class architectures.
2876 Domain = ARM_MB::SY;
2877 } else if (Subtarget->isSwift() && Ord == Release) {
2878 // Swift happens to implement ISHST barriers in a way that's compatible with
2879 // Release semantics but weaker than ISH so we'd be fools not to use
2880 // it. Beware: other processors probably don't!
2881 Domain = ARM_MB::ISHST;
2884 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2885 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2886 DAG.getConstant(Domain, dl, MVT::i32));
2889 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2890 const ARMSubtarget *Subtarget) {
2891 // ARM pre v5TE and Thumb1 does not have preload instructions.
2892 if (!(Subtarget->isThumb2() ||
2893 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2894 // Just preserve the chain.
2895 return Op.getOperand(0);
2898 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2900 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2901 // ARMv7 with MP extension has PLDW.
2902 return Op.getOperand(0);
2904 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2905 if (Subtarget->isThumb()) {
2907 isRead = ~isRead & 1;
2908 isData = ~isData & 1;
2911 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2912 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2913 DAG.getConstant(isData, dl, MVT::i32));
2916 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2917 MachineFunction &MF = DAG.getMachineFunction();
2918 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2920 // vastart just stores the address of the VarArgsFrameIndex slot into the
2921 // memory location argument.
2923 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2924 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2925 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2926 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2927 MachinePointerInfo(SV), false, false, 0);
2931 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2932 SDValue &Root, SelectionDAG &DAG,
2934 MachineFunction &MF = DAG.getMachineFunction();
2935 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2937 const TargetRegisterClass *RC;
2938 if (AFI->isThumb1OnlyFunction())
2939 RC = &ARM::tGPRRegClass;
2941 RC = &ARM::GPRRegClass;
2943 // Transform the arguments stored in physical registers into virtual ones.
2944 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2945 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2948 if (NextVA.isMemLoc()) {
2949 MachineFrameInfo *MFI = MF.getFrameInfo();
2950 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2952 // Create load node to retrieve arguments from the stack.
2953 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2954 ArgValue2 = DAG.getLoad(
2955 MVT::i32, dl, Root, FIN,
2956 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2959 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2960 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2962 if (!Subtarget->isLittle())
2963 std::swap (ArgValue, ArgValue2);
2964 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2967 // The remaining GPRs hold either the beginning of variable-argument
2968 // data, or the beginning of an aggregate passed by value (usually
2969 // byval). Either way, we allocate stack slots adjacent to the data
2970 // provided by our caller, and store the unallocated registers there.
2971 // If this is a variadic function, the va_list pointer will begin with
2972 // these values; otherwise, this reassembles a (byval) structure that
2973 // was split between registers and memory.
2974 // Return: The frame index registers were stored into.
2976 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2977 SDLoc dl, SDValue &Chain,
2978 const Value *OrigArg,
2979 unsigned InRegsParamRecordIdx,
2981 unsigned ArgSize) const {
2982 // Currently, two use-cases possible:
2983 // Case #1. Non-var-args function, and we meet first byval parameter.
2984 // Setup first unallocated register as first byval register;
2985 // eat all remained registers
2986 // (these two actions are performed by HandleByVal method).
2987 // Then, here, we initialize stack frame with
2988 // "store-reg" instructions.
2989 // Case #2. Var-args function, that doesn't contain byval parameters.
2990 // The same: eat all remained unallocated registers,
2991 // initialize stack frame.
2993 MachineFunction &MF = DAG.getMachineFunction();
2994 MachineFrameInfo *MFI = MF.getFrameInfo();
2995 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2996 unsigned RBegin, REnd;
2997 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2998 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3000 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3001 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3006 ArgOffset = -4 * (ARM::R4 - RBegin);
3008 auto PtrVT = getPointerTy(DAG.getDataLayout());
3009 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3010 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3012 SmallVector<SDValue, 4> MemOps;
3013 const TargetRegisterClass *RC =
3014 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3016 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3017 unsigned VReg = MF.addLiveIn(Reg, RC);
3018 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3020 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3021 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3022 MemOps.push_back(Store);
3023 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3026 if (!MemOps.empty())
3027 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3031 // Setup stack frame, the va_list pointer will start from.
3033 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3034 SDLoc dl, SDValue &Chain,
3036 unsigned TotalArgRegsSaveSize,
3037 bool ForceMutable) const {
3038 MachineFunction &MF = DAG.getMachineFunction();
3039 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3041 // Try to store any remaining integer argument regs
3042 // to their spots on the stack so that they may be loaded by deferencing
3043 // the result of va_next.
3044 // If there is no regs to be stored, just point address after last
3045 // argument passed via stack.
3046 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3047 CCInfo.getInRegsParamsCount(),
3048 CCInfo.getNextStackOffset(), 4);
3049 AFI->setVarArgsFrameIndex(FrameIndex);
3053 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3054 CallingConv::ID CallConv, bool isVarArg,
3055 const SmallVectorImpl<ISD::InputArg>
3057 SDLoc dl, SelectionDAG &DAG,
3058 SmallVectorImpl<SDValue> &InVals)
3060 MachineFunction &MF = DAG.getMachineFunction();
3061 MachineFrameInfo *MFI = MF.getFrameInfo();
3063 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3065 // Assign locations to all of the incoming arguments.
3066 SmallVector<CCValAssign, 16> ArgLocs;
3067 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3068 *DAG.getContext(), Prologue);
3069 CCInfo.AnalyzeFormalArguments(Ins,
3070 CCAssignFnForNode(CallConv, /* Return*/ false,
3073 SmallVector<SDValue, 16> ArgValues;
3075 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3076 unsigned CurArgIdx = 0;
3078 // Initially ArgRegsSaveSize is zero.
3079 // Then we increase this value each time we meet byval parameter.
3080 // We also increase this value in case of varargs function.
3081 AFI->setArgRegsSaveSize(0);
3083 // Calculate the amount of stack space that we need to allocate to store
3084 // byval and variadic arguments that are passed in registers.
3085 // We need to know this before we allocate the first byval or variadic
3086 // argument, as they will be allocated a stack slot below the CFA (Canonical
3087 // Frame Address, the stack pointer at entry to the function).
3088 unsigned ArgRegBegin = ARM::R4;
3089 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3090 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3093 CCValAssign &VA = ArgLocs[i];
3094 unsigned Index = VA.getValNo();
3095 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3096 if (!Flags.isByVal())
3099 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3100 unsigned RBegin, REnd;
3101 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3102 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3104 CCInfo.nextInRegsParam();
3106 CCInfo.rewindByValRegsInfo();
3108 int lastInsIndex = -1;
3109 if (isVarArg && MFI->hasVAStart()) {
3110 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3111 if (RegIdx != array_lengthof(GPRArgRegs))
3112 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3115 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3116 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3117 auto PtrVT = getPointerTy(DAG.getDataLayout());
3119 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3120 CCValAssign &VA = ArgLocs[i];
3121 if (Ins[VA.getValNo()].isOrigArg()) {
3122 std::advance(CurOrigArg,
3123 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3124 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3126 // Arguments stored in registers.
3127 if (VA.isRegLoc()) {
3128 EVT RegVT = VA.getLocVT();
3130 if (VA.needsCustom()) {
3131 // f64 and vector types are split up into multiple registers or
3132 // combinations of registers and stack slots.
3133 if (VA.getLocVT() == MVT::v2f64) {
3134 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3136 VA = ArgLocs[++i]; // skip ahead to next loc
3138 if (VA.isMemLoc()) {
3139 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3140 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3141 ArgValue2 = DAG.getLoad(
3142 MVT::f64, dl, Chain, FIN,
3143 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3144 false, false, false, 0);
3146 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3149 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3150 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3151 ArgValue, ArgValue1,
3152 DAG.getIntPtrConstant(0, dl));
3153 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3154 ArgValue, ArgValue2,
3155 DAG.getIntPtrConstant(1, dl));
3157 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3160 const TargetRegisterClass *RC;
3162 if (RegVT == MVT::f32)
3163 RC = &ARM::SPRRegClass;
3164 else if (RegVT == MVT::f64)
3165 RC = &ARM::DPRRegClass;
3166 else if (RegVT == MVT::v2f64)
3167 RC = &ARM::QPRRegClass;
3168 else if (RegVT == MVT::i32)
3169 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3170 : &ARM::GPRRegClass;
3172 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3174 // Transform the arguments in physical registers into virtual ones.
3175 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3176 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3179 // If this is an 8 or 16-bit value, it is really passed promoted
3180 // to 32 bits. Insert an assert[sz]ext to capture this, then
3181 // truncate to the right size.
3182 switch (VA.getLocInfo()) {
3183 default: llvm_unreachable("Unknown loc info!");
3184 case CCValAssign::Full: break;
3185 case CCValAssign::BCvt:
3186 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3188 case CCValAssign::SExt:
3189 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3190 DAG.getValueType(VA.getValVT()));
3191 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3193 case CCValAssign::ZExt:
3194 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3195 DAG.getValueType(VA.getValVT()));
3196 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3200 InVals.push_back(ArgValue);
3202 } else { // VA.isRegLoc()
3205 assert(VA.isMemLoc());
3206 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3208 int index = VA.getValNo();
3210 // Some Ins[] entries become multiple ArgLoc[] entries.
3211 // Process them only once.
3212 if (index != lastInsIndex)
3214 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3215 // FIXME: For now, all byval parameter objects are marked mutable.
3216 // This can be changed with more analysis.
3217 // In case of tail call optimization mark all arguments mutable.
3218 // Since they could be overwritten by lowering of arguments in case of
3220 if (Flags.isByVal()) {
3221 assert(Ins[index].isOrigArg() &&
3222 "Byval arguments cannot be implicit");
3223 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3225 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3226 CurByValIndex, VA.getLocMemOffset(),
3227 Flags.getByValSize());
3228 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3229 CCInfo.nextInRegsParam();
3231 unsigned FIOffset = VA.getLocMemOffset();
3232 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3235 // Create load nodes to retrieve arguments from the stack.
3236 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3237 InVals.push_back(DAG.getLoad(
3238 VA.getValVT(), dl, Chain, FIN,
3239 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3240 false, false, false, 0));
3242 lastInsIndex = index;
3248 if (isVarArg && MFI->hasVAStart())
3249 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3250 CCInfo.getNextStackOffset(),
3251 TotalArgRegsSaveSize);
3253 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3258 /// isFloatingPointZero - Return true if this is +0.0.
3259 static bool isFloatingPointZero(SDValue Op) {
3260 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3261 return CFP->getValueAPF().isPosZero();
3262 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3263 // Maybe this has already been legalized into the constant pool?
3264 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3265 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3266 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3267 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3268 return CFP->getValueAPF().isPosZero();
3270 } else if (Op->getOpcode() == ISD::BITCAST &&
3271 Op->getValueType(0) == MVT::f64) {
3272 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3273 // created by LowerConstantFP().
3274 SDValue BitcastOp = Op->getOperand(0);
3275 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3276 SDValue MoveOp = BitcastOp->getOperand(0);
3277 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3278 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3286 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3287 /// the given operands.
3289 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3290 SDValue &ARMcc, SelectionDAG &DAG,
3292 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3293 unsigned C = RHSC->getZExtValue();
3294 if (!isLegalICmpImmediate(C)) {
3295 // Constant does not fit, try adjusting it by one?
3300 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3301 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3302 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3307 if (C != 0 && isLegalICmpImmediate(C-1)) {
3308 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3309 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3314 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3315 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3316 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3321 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3322 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3323 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3330 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3331 ARMISD::NodeType CompareType;
3334 CompareType = ARMISD::CMP;
3339 CompareType = ARMISD::CMPZ;
3342 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3343 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3346 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3348 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3350 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3352 if (!isFloatingPointZero(RHS))
3353 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3355 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3356 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3359 /// duplicateCmp - Glue values can have only one use, so this function
3360 /// duplicates a comparison node.
3362 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3363 unsigned Opc = Cmp.getOpcode();
3365 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3366 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3368 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3369 Cmp = Cmp.getOperand(0);
3370 Opc = Cmp.getOpcode();
3371 if (Opc == ARMISD::CMPFP)
3372 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3374 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3375 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3377 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3380 std::pair<SDValue, SDValue>
3381 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3382 SDValue &ARMcc) const {
3383 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3385 SDValue Value, OverflowCmp;
3386 SDValue LHS = Op.getOperand(0);
3387 SDValue RHS = Op.getOperand(1);
3390 // FIXME: We are currently always generating CMPs because we don't support
3391 // generating CMN through the backend. This is not as good as the natural
3392 // CMP case because it causes a register dependency and cannot be folded
3395 switch (Op.getOpcode()) {
3397 llvm_unreachable("Unknown overflow instruction!");
3399 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3400 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3401 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3404 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3405 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3406 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3409 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3410 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3411 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3414 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3415 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3416 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3420 return std::make_pair(Value, OverflowCmp);
3425 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3426 // Let legalize expand this if it isn't a legal type yet.
3427 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3430 SDValue Value, OverflowCmp;
3432 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3433 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3435 // We use 0 and 1 as false and true values.
3436 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3437 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3438 EVT VT = Op.getValueType();
3440 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3441 ARMcc, CCR, OverflowCmp);
3443 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3444 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3448 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3449 SDValue Cond = Op.getOperand(0);
3450 SDValue SelectTrue = Op.getOperand(1);
3451 SDValue SelectFalse = Op.getOperand(2);
3453 unsigned Opc = Cond.getOpcode();
3455 if (Cond.getResNo() == 1 &&
3456 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3457 Opc == ISD::USUBO)) {
3458 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3461 SDValue Value, OverflowCmp;
3463 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3464 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3465 EVT VT = Op.getValueType();
3467 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3473 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3474 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3476 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3477 const ConstantSDNode *CMOVTrue =
3478 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3479 const ConstantSDNode *CMOVFalse =
3480 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3482 if (CMOVTrue && CMOVFalse) {
3483 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3484 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3488 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3490 False = SelectFalse;
3491 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3496 if (True.getNode() && False.getNode()) {
3497 EVT VT = Op.getValueType();
3498 SDValue ARMcc = Cond.getOperand(2);
3499 SDValue CCR = Cond.getOperand(3);
3500 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3501 assert(True.getValueType() == VT);
3502 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3507 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3508 // undefined bits before doing a full-word comparison with zero.
3509 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3510 DAG.getConstant(1, dl, Cond.getValueType()));
3512 return DAG.getSelectCC(dl, Cond,
3513 DAG.getConstant(0, dl, Cond.getValueType()),
3514 SelectTrue, SelectFalse, ISD::SETNE);
3517 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3518 bool &swpCmpOps, bool &swpVselOps) {
3519 // Start by selecting the GE condition code for opcodes that return true for
3521 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3523 CondCode = ARMCC::GE;
3525 // and GT for opcodes that return false for 'equality'.
3526 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3528 CondCode = ARMCC::GT;
3530 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3531 // to swap the compare operands.
3532 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3536 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3537 // If we have an unordered opcode, we need to swap the operands to the VSEL
3538 // instruction (effectively negating the condition).
3540 // This also has the effect of swapping which one of 'less' or 'greater'
3541 // returns true, so we also swap the compare operands. It also switches
3542 // whether we return true for 'equality', so we compensate by picking the
3543 // opposite condition code to our original choice.
3544 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3545 CC == ISD::SETUGT) {
3546 swpCmpOps = !swpCmpOps;
3547 swpVselOps = !swpVselOps;
3548 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3551 // 'ordered' is 'anything but unordered', so use the VS condition code and
3552 // swap the VSEL operands.
3553 if (CC == ISD::SETO) {
3554 CondCode = ARMCC::VS;
3558 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3559 // code and swap the VSEL operands.
3560 if (CC == ISD::SETUNE) {
3561 CondCode = ARMCC::EQ;
3566 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3567 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3568 SDValue Cmp, SelectionDAG &DAG) const {
3569 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3570 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3571 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3572 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3573 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3575 SDValue TrueLow = TrueVal.getValue(0);
3576 SDValue TrueHigh = TrueVal.getValue(1);
3577 SDValue FalseLow = FalseVal.getValue(0);
3578 SDValue FalseHigh = FalseVal.getValue(1);
3580 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3582 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3583 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3585 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3587 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3592 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3593 EVT VT = Op.getValueType();
3594 SDValue LHS = Op.getOperand(0);
3595 SDValue RHS = Op.getOperand(1);
3596 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3597 SDValue TrueVal = Op.getOperand(2);
3598 SDValue FalseVal = Op.getOperand(3);
3601 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3602 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3605 // If softenSetCCOperands only returned one value, we should compare it to
3607 if (!RHS.getNode()) {
3608 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3613 if (LHS.getValueType() == MVT::i32) {
3614 // Try to generate VSEL on ARMv8.
3615 // The VSEL instruction can't use all the usual ARM condition
3616 // codes: it only has two bits to select the condition code, so it's
3617 // constrained to use only GE, GT, VS and EQ.
3619 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3620 // swap the operands of the previous compare instruction (effectively
3621 // inverting the compare condition, swapping 'less' and 'greater') and
3622 // sometimes need to swap the operands to the VSEL (which inverts the
3623 // condition in the sense of firing whenever the previous condition didn't)
3624 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3625 TrueVal.getValueType() == MVT::f64)) {
3626 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3627 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3628 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3629 CC = ISD::getSetCCInverse(CC, true);
3630 std::swap(TrueVal, FalseVal);
3635 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3636 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3637 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3640 ARMCC::CondCodes CondCode, CondCode2;
3641 FPCCToARMCC(CC, CondCode, CondCode2);
3643 // Try to generate VMAXNM/VMINNM on ARMv8.
3644 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3645 TrueVal.getValueType() == MVT::f64)) {
3646 bool swpCmpOps = false;
3647 bool swpVselOps = false;
3648 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3650 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3651 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3653 std::swap(LHS, RHS);
3655 std::swap(TrueVal, FalseVal);
3659 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3660 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3661 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3662 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3663 if (CondCode2 != ARMCC::AL) {
3664 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3665 // FIXME: Needs another CMP because flag can have but one use.
3666 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3667 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3672 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3673 /// to morph to an integer compare sequence.
3674 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3675 const ARMSubtarget *Subtarget) {
3676 SDNode *N = Op.getNode();
3677 if (!N->hasOneUse())
3678 // Otherwise it requires moving the value from fp to integer registers.
3680 if (!N->getNumValues())
3682 EVT VT = Op.getValueType();
3683 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3684 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3685 // vmrs are very slow, e.g. cortex-a8.
3688 if (isFloatingPointZero(Op)) {
3692 return ISD::isNormalLoad(N);
3695 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3696 if (isFloatingPointZero(Op))
3697 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3699 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3700 return DAG.getLoad(MVT::i32, SDLoc(Op),
3701 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3702 Ld->isVolatile(), Ld->isNonTemporal(),
3703 Ld->isInvariant(), Ld->getAlignment());
3705 llvm_unreachable("Unknown VFP cmp argument!");
3708 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3709 SDValue &RetVal1, SDValue &RetVal2) {
3712 if (isFloatingPointZero(Op)) {
3713 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3714 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3718 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3719 SDValue Ptr = Ld->getBasePtr();
3720 RetVal1 = DAG.getLoad(MVT::i32, dl,
3721 Ld->getChain(), Ptr,
3722 Ld->getPointerInfo(),
3723 Ld->isVolatile(), Ld->isNonTemporal(),
3724 Ld->isInvariant(), Ld->getAlignment());
3726 EVT PtrType = Ptr.getValueType();
3727 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3728 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3729 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3730 RetVal2 = DAG.getLoad(MVT::i32, dl,
3731 Ld->getChain(), NewPtr,
3732 Ld->getPointerInfo().getWithOffset(4),
3733 Ld->isVolatile(), Ld->isNonTemporal(),
3734 Ld->isInvariant(), NewAlign);
3738 llvm_unreachable("Unknown VFP cmp argument!");
3741 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3742 /// f32 and even f64 comparisons to integer ones.
3744 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3745 SDValue Chain = Op.getOperand(0);
3746 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3747 SDValue LHS = Op.getOperand(2);
3748 SDValue RHS = Op.getOperand(3);
3749 SDValue Dest = Op.getOperand(4);
3752 bool LHSSeenZero = false;
3753 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3754 bool RHSSeenZero = false;
3755 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3756 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3757 // If unsafe fp math optimization is enabled and there are no other uses of
3758 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3759 // to an integer comparison.
3760 if (CC == ISD::SETOEQ)
3762 else if (CC == ISD::SETUNE)
3765 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3767 if (LHS.getValueType() == MVT::f32) {
3768 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3769 bitcastf32Toi32(LHS, DAG), Mask);
3770 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3771 bitcastf32Toi32(RHS, DAG), Mask);
3772 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3773 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3774 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3775 Chain, Dest, ARMcc, CCR, Cmp);
3780 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3781 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3782 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3783 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3784 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3785 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3786 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3787 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3788 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3794 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3795 SDValue Chain = Op.getOperand(0);
3796 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3797 SDValue LHS = Op.getOperand(2);
3798 SDValue RHS = Op.getOperand(3);
3799 SDValue Dest = Op.getOperand(4);
3802 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3803 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3806 // If softenSetCCOperands only returned one value, we should compare it to
3808 if (!RHS.getNode()) {
3809 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3814 if (LHS.getValueType() == MVT::i32) {
3816 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3817 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3819 Chain, Dest, ARMcc, CCR, Cmp);
3822 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3824 if (getTargetMachine().Options.UnsafeFPMath &&
3825 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3826 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3827 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3828 if (Result.getNode())
3832 ARMCC::CondCodes CondCode, CondCode2;
3833 FPCCToARMCC(CC, CondCode, CondCode2);
3835 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3836 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3837 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3838 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3839 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3840 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3841 if (CondCode2 != ARMCC::AL) {
3842 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3843 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3844 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3849 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3850 SDValue Chain = Op.getOperand(0);
3851 SDValue Table = Op.getOperand(1);
3852 SDValue Index = Op.getOperand(2);
3855 EVT PTy = getPointerTy(DAG.getDataLayout());
3856 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3857 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3858 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3859 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3860 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3861 if (Subtarget->isThumb2()) {
3862 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3863 // which does another jump to the destination. This also makes it easier
3864 // to translate it to TBB / TBH later.
3865 // FIXME: This might not work if the function is extremely large.
3866 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3867 Addr, Op.getOperand(2), JTI);
3869 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3871 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3872 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3873 false, false, false, 0);
3874 Chain = Addr.getValue(1);
3875 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3876 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3879 DAG.getLoad(PTy, dl, Chain, Addr,
3880 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3881 false, false, false, 0);
3882 Chain = Addr.getValue(1);
3883 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3887 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3888 EVT VT = Op.getValueType();
3891 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3892 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3894 return DAG.UnrollVectorOp(Op.getNode());
3897 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3898 "Invalid type for custom lowering!");
3899 if (VT != MVT::v4i16)
3900 return DAG.UnrollVectorOp(Op.getNode());
3902 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3903 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3906 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3907 EVT VT = Op.getValueType();
3909 return LowerVectorFP_TO_INT(Op, DAG);
3910 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3912 if (Op.getOpcode() == ISD::FP_TO_SINT)
3913 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3916 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3918 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3919 /*isSigned*/ false, SDLoc(Op)).first;
3925 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3926 EVT VT = Op.getValueType();
3929 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3930 if (VT.getVectorElementType() == MVT::f32)
3932 return DAG.UnrollVectorOp(Op.getNode());
3935 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3936 "Invalid type for custom lowering!");
3937 if (VT != MVT::v4f32)
3938 return DAG.UnrollVectorOp(Op.getNode());
3942 switch (Op.getOpcode()) {
3943 default: llvm_unreachable("Invalid opcode!");
3944 case ISD::SINT_TO_FP:
3945 CastOpc = ISD::SIGN_EXTEND;
3946 Opc = ISD::SINT_TO_FP;
3948 case ISD::UINT_TO_FP:
3949 CastOpc = ISD::ZERO_EXTEND;
3950 Opc = ISD::UINT_TO_FP;
3954 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3955 return DAG.getNode(Opc, dl, VT, Op);
3958 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3959 EVT VT = Op.getValueType();
3961 return LowerVectorINT_TO_FP(Op, DAG);
3962 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3964 if (Op.getOpcode() == ISD::SINT_TO_FP)
3965 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3968 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3970 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3971 /*isSigned*/ false, SDLoc(Op)).first;
3977 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3978 // Implement fcopysign with a fabs and a conditional fneg.
3979 SDValue Tmp0 = Op.getOperand(0);
3980 SDValue Tmp1 = Op.getOperand(1);
3982 EVT VT = Op.getValueType();
3983 EVT SrcVT = Tmp1.getValueType();
3984 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3985 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3986 bool UseNEON = !InGPR && Subtarget->hasNEON();
3989 // Use VBSL to copy the sign bit.
3990 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3991 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3992 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3993 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3995 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3996 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3997 DAG.getConstant(32, dl, MVT::i32));
3998 else /*if (VT == MVT::f32)*/
3999 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4000 if (SrcVT == MVT::f32) {
4001 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4003 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4004 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4005 DAG.getConstant(32, dl, MVT::i32));
4006 } else if (VT == MVT::f32)
4007 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4008 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4009 DAG.getConstant(32, dl, MVT::i32));
4010 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4011 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4013 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4015 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4016 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4017 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4019 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4020 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4021 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4022 if (VT == MVT::f32) {
4023 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4024 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4025 DAG.getConstant(0, dl, MVT::i32));
4027 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4033 // Bitcast operand 1 to i32.
4034 if (SrcVT == MVT::f64)
4035 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4037 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4039 // Or in the signbit with integer operations.
4040 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4041 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4042 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4043 if (VT == MVT::f32) {
4044 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4045 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4046 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4047 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4050 // f64: Or the high part with signbit and then combine two parts.
4051 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4053 SDValue Lo = Tmp0.getValue(0);
4054 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4055 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4056 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4059 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4060 MachineFunction &MF = DAG.getMachineFunction();
4061 MachineFrameInfo *MFI = MF.getFrameInfo();
4062 MFI->setReturnAddressIsTaken(true);
4064 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4067 EVT VT = Op.getValueType();
4069 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4071 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4072 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4073 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4074 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4075 MachinePointerInfo(), false, false, false, 0);
4078 // Return LR, which contains the return address. Mark it an implicit live-in.
4079 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4080 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4083 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4084 const ARMBaseRegisterInfo &ARI =
4085 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4086 MachineFunction &MF = DAG.getMachineFunction();
4087 MachineFrameInfo *MFI = MF.getFrameInfo();
4088 MFI->setFrameAddressIsTaken(true);
4090 EVT VT = Op.getValueType();
4091 SDLoc dl(Op); // FIXME probably not meaningful
4092 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4093 unsigned FrameReg = ARI.getFrameRegister(MF);
4094 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4096 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4097 MachinePointerInfo(),
4098 false, false, false, 0);
4102 // FIXME? Maybe this could be a TableGen attribute on some registers and
4103 // this table could be generated automatically from RegInfo.
4104 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4105 SelectionDAG &DAG) const {
4106 unsigned Reg = StringSwitch<unsigned>(RegName)
4107 .Case("sp", ARM::SP)
4111 report_fatal_error(Twine("Invalid register name \""
4112 + StringRef(RegName) + "\"."));
4115 // Result is 64 bit value so split into two 32 bit values and return as a
4117 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4118 SelectionDAG &DAG) {
4121 // This function is only supposed to be called for i64 type destination.
4122 assert(N->getValueType(0) == MVT::i64
4123 && "ExpandREAD_REGISTER called for non-i64 type result.");
4125 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4126 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4130 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4132 Results.push_back(Read.getOperand(0));
4135 /// ExpandBITCAST - If the target supports VFP, this function is called to
4136 /// expand a bit convert where either the source or destination type is i64 to
4137 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4138 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4139 /// vectors), since the legalizer won't know what to do with that.
4140 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4141 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4143 SDValue Op = N->getOperand(0);
4145 // This function is only supposed to be called for i64 types, either as the
4146 // source or destination of the bit convert.
4147 EVT SrcVT = Op.getValueType();
4148 EVT DstVT = N->getValueType(0);
4149 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4150 "ExpandBITCAST called for non-i64 type");
4152 // Turn i64->f64 into VMOVDRR.
4153 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4154 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155 DAG.getConstant(0, dl, MVT::i32));
4156 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4157 DAG.getConstant(1, dl, MVT::i32));
4158 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4159 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4162 // Turn f64->i64 into VMOVRRD.
4163 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4165 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4166 SrcVT.getVectorNumElements() > 1)
4167 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168 DAG.getVTList(MVT::i32, MVT::i32),
4169 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4171 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4172 DAG.getVTList(MVT::i32, MVT::i32), Op);
4173 // Merge the pieces into a single i64 value.
4174 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4180 /// getZeroVector - Returns a vector of specified type with all zero elements.
4181 /// Zero vectors are used to represent vector negation and in those cases
4182 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4183 /// not support i64 elements, so sometimes the zero vectors will need to be
4184 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4186 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4187 assert(VT.isVector() && "Expected a vector type");
4188 // The canonical modified immediate encoding of a zero vector is....0!
4189 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4190 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4191 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4192 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4195 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4196 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4197 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4198 SelectionDAG &DAG) const {
4199 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4200 EVT VT = Op.getValueType();
4201 unsigned VTBits = VT.getSizeInBits();
4203 SDValue ShOpLo = Op.getOperand(0);
4204 SDValue ShOpHi = Op.getOperand(1);
4205 SDValue ShAmt = Op.getOperand(2);
4207 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4209 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4211 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4212 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4213 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4214 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4215 DAG.getConstant(VTBits, dl, MVT::i32));
4216 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4217 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4218 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4220 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4221 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4222 ISD::SETGE, ARMcc, DAG, dl);
4223 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4224 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4227 SDValue Ops[2] = { Lo, Hi };
4228 return DAG.getMergeValues(Ops, dl);
4231 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4232 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4233 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4234 SelectionDAG &DAG) const {
4235 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4236 EVT VT = Op.getValueType();
4237 unsigned VTBits = VT.getSizeInBits();
4239 SDValue ShOpLo = Op.getOperand(0);
4240 SDValue ShOpHi = Op.getOperand(1);
4241 SDValue ShAmt = Op.getOperand(2);
4244 assert(Op.getOpcode() == ISD::SHL_PARTS);
4245 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4247 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4248 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249 DAG.getConstant(VTBits, dl, MVT::i32));
4250 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4251 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4253 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4254 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4256 ISD::SETGE, ARMcc, DAG, dl);
4257 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4258 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4261 SDValue Ops[2] = { Lo, Hi };
4262 return DAG.getMergeValues(Ops, dl);
4265 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4266 SelectionDAG &DAG) const {
4267 // The rounding mode is in bits 23:22 of the FPSCR.
4268 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4269 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4270 // so that the shift + and get folded into a bitfield extract.
4272 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4273 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4275 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4276 DAG.getConstant(1U << 22, dl, MVT::i32));
4277 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4278 DAG.getConstant(22, dl, MVT::i32));
4279 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4280 DAG.getConstant(3, dl, MVT::i32));
4283 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4284 const ARMSubtarget *ST) {
4286 EVT VT = N->getValueType(0);
4287 if (VT.isVector()) {
4288 assert(ST->hasNEON());
4290 // Compute the least significant set bit: LSB = X & -X
4291 SDValue X = N->getOperand(0);
4292 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4293 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4295 EVT ElemTy = VT.getVectorElementType();
4297 if (ElemTy == MVT::i8) {
4298 // Compute with: cttz(x) = ctpop(lsb - 1)
4299 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4300 DAG.getTargetConstant(1, dl, ElemTy));
4301 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4302 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4305 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4306 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4307 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4308 unsigned NumBits = ElemTy.getSizeInBits();
4309 SDValue WidthMinus1 =
4310 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4311 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4312 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4313 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4316 // Compute with: cttz(x) = ctpop(lsb - 1)
4318 // Since we can only compute the number of bits in a byte with vcnt.8, we
4319 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4324 if (ElemTy == MVT::i64) {
4325 // Load constant 0xffff'ffff'ffff'ffff to register.
4326 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4327 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4328 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4330 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4331 DAG.getTargetConstant(1, dl, ElemTy));
4332 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4335 // Count #bits with vcnt.8.
4336 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4337 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4338 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4340 // Gather the #bits with vpaddl (pairwise add.)
4341 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4342 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4343 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4345 if (ElemTy == MVT::i16)
4348 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4349 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4350 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4352 if (ElemTy == MVT::i32)
4355 assert(ElemTy == MVT::i64);
4356 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4357 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4362 if (!ST->hasV6T2Ops())
4365 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4366 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4369 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4370 /// for each 16-bit element from operand, repeated. The basic idea is to
4371 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4373 /// Trace for v4i16:
4374 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4375 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4376 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4377 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4378 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4379 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4380 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4381 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4382 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4383 EVT VT = N->getValueType(0);
4386 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4387 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4388 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4389 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4390 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4391 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4394 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4395 /// bit-count for each 16-bit element from the operand. We need slightly
4396 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4397 /// 64/128-bit registers.
4399 /// Trace for v4i16:
4400 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4401 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4402 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4403 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4404 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4405 EVT VT = N->getValueType(0);
4408 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4409 if (VT.is64BitVector()) {
4410 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4411 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4412 DAG.getIntPtrConstant(0, DL));
4414 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4415 BitCounts, DAG.getIntPtrConstant(0, DL));
4416 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4420 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4421 /// bit-count for each 32-bit element from the operand. The idea here is
4422 /// to split the vector into 16-bit elements, leverage the 16-bit count
4423 /// routine, and then combine the results.
4425 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4426 /// input = [v0 v1 ] (vi: 32-bit elements)
4427 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4428 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4429 /// vrev: N0 = [k1 k0 k3 k2 ]
4431 /// N1 =+[k1 k0 k3 k2 ]
4433 /// N2 =+[k1 k3 k0 k2 ]
4435 /// Extended =+[k1 k3 k0 k2 ]
4437 /// Extracted=+[k1 k3 ]
4439 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4440 EVT VT = N->getValueType(0);
4443 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4445 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4446 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4447 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4448 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4449 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4451 if (VT.is64BitVector()) {
4452 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4453 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4454 DAG.getIntPtrConstant(0, DL));
4456 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4457 DAG.getIntPtrConstant(0, DL));
4458 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4462 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4463 const ARMSubtarget *ST) {
4464 EVT VT = N->getValueType(0);
4466 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4467 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4468 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4469 "Unexpected type for custom ctpop lowering");
4471 if (VT.getVectorElementType() == MVT::i32)
4472 return lowerCTPOP32BitElements(N, DAG);
4474 return lowerCTPOP16BitElements(N, DAG);
4477 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4478 const ARMSubtarget *ST) {
4479 EVT VT = N->getValueType(0);
4485 // Lower vector shifts on NEON to use VSHL.
4486 assert(ST->hasNEON() && "unexpected vector shift");
4488 // Left shifts translate directly to the vshiftu intrinsic.
4489 if (N->getOpcode() == ISD::SHL)
4490 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4491 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4493 N->getOperand(0), N->getOperand(1));
4495 assert((N->getOpcode() == ISD::SRA ||
4496 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4498 // NEON uses the same intrinsics for both left and right shifts. For
4499 // right shifts, the shift amounts are negative, so negate the vector of
4501 EVT ShiftVT = N->getOperand(1).getValueType();
4502 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4503 getZeroVector(ShiftVT, DAG, dl),
4505 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4506 Intrinsic::arm_neon_vshifts :
4507 Intrinsic::arm_neon_vshiftu);
4508 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4509 DAG.getConstant(vshiftInt, dl, MVT::i32),
4510 N->getOperand(0), NegatedCount);
4513 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4514 const ARMSubtarget *ST) {
4515 EVT VT = N->getValueType(0);
4518 // We can get here for a node like i32 = ISD::SHL i32, i64
4522 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4523 "Unknown shift to lower!");
4525 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4526 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4527 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4530 // If we are in thumb mode, we don't have RRX.
4531 if (ST->isThumb1Only()) return SDValue();
4533 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4534 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4535 DAG.getConstant(0, dl, MVT::i32));
4536 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4537 DAG.getConstant(1, dl, MVT::i32));
4539 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4540 // captures the result into a carry flag.
4541 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4542 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4544 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4545 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4547 // Merge the pieces into a single i64 value.
4548 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4551 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4552 SDValue TmpOp0, TmpOp1;
4553 bool Invert = false;
4557 SDValue Op0 = Op.getOperand(0);
4558 SDValue Op1 = Op.getOperand(1);
4559 SDValue CC = Op.getOperand(2);
4560 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4561 EVT VT = Op.getValueType();
4562 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4565 if (CmpVT.getVectorElementType() == MVT::i64)
4566 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4567 // but it's possible that our operands are 64-bit but our result is 32-bit.
4568 // Bail in this case.
4571 if (Op1.getValueType().isFloatingPoint()) {
4572 switch (SetCCOpcode) {
4573 default: llvm_unreachable("Illegal FP comparison");
4575 case ISD::SETNE: Invert = true; // Fallthrough
4577 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4579 case ISD::SETLT: Swap = true; // Fallthrough
4581 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4583 case ISD::SETLE: Swap = true; // Fallthrough
4585 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4586 case ISD::SETUGE: Swap = true; // Fallthrough
4587 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4588 case ISD::SETUGT: Swap = true; // Fallthrough
4589 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4590 case ISD::SETUEQ: Invert = true; // Fallthrough
4592 // Expand this to (OLT | OGT).
4596 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4597 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4599 case ISD::SETUO: Invert = true; // Fallthrough
4601 // Expand this to (OLT | OGE).
4605 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4606 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4610 // Integer comparisons.
4611 switch (SetCCOpcode) {
4612 default: llvm_unreachable("Illegal integer comparison");
4613 case ISD::SETNE: Invert = true;
4614 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4615 case ISD::SETLT: Swap = true;
4616 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4617 case ISD::SETLE: Swap = true;
4618 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4619 case ISD::SETULT: Swap = true;
4620 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4621 case ISD::SETULE: Swap = true;
4622 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4625 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4626 if (Opc == ARMISD::VCEQ) {
4629 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4631 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4634 // Ignore bitconvert.
4635 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4636 AndOp = AndOp.getOperand(0);
4638 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4640 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4641 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4648 std::swap(Op0, Op1);
4650 // If one of the operands is a constant vector zero, attempt to fold the
4651 // comparison to a specialized compare-against-zero form.
4653 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4655 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4656 if (Opc == ARMISD::VCGE)
4657 Opc = ARMISD::VCLEZ;
4658 else if (Opc == ARMISD::VCGT)
4659 Opc = ARMISD::VCLTZ;
4664 if (SingleOp.getNode()) {
4667 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4669 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4671 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4673 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4675 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4677 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4680 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4683 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4686 Result = DAG.getNOT(dl, Result, VT);
4691 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4692 /// valid vector constant for a NEON instruction with a "modified immediate"
4693 /// operand (e.g., VMOV). If so, return the encoded value.
4694 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4695 unsigned SplatBitSize, SelectionDAG &DAG,
4696 SDLoc dl, EVT &VT, bool is128Bits,
4697 NEONModImmType type) {
4698 unsigned OpCmode, Imm;
4700 // SplatBitSize is set to the smallest size that splats the vector, so a
4701 // zero vector will always have SplatBitSize == 8. However, NEON modified
4702 // immediate instructions others than VMOV do not support the 8-bit encoding
4703 // of a zero vector, and the default encoding of zero is supposed to be the
4708 switch (SplatBitSize) {
4710 if (type != VMOVModImm)
4712 // Any 1-byte value is OK. Op=0, Cmode=1110.
4713 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4716 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4720 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4721 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4722 if ((SplatBits & ~0xff) == 0) {
4723 // Value = 0x00nn: Op=x, Cmode=100x.
4728 if ((SplatBits & ~0xff00) == 0) {
4729 // Value = 0xnn00: Op=x, Cmode=101x.
4731 Imm = SplatBits >> 8;
4737 // NEON's 32-bit VMOV supports splat values where:
4738 // * only one byte is nonzero, or
4739 // * the least significant byte is 0xff and the second byte is nonzero, or
4740 // * the least significant 2 bytes are 0xff and the third is nonzero.
4741 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4742 if ((SplatBits & ~0xff) == 0) {
4743 // Value = 0x000000nn: Op=x, Cmode=000x.
4748 if ((SplatBits & ~0xff00) == 0) {
4749 // Value = 0x0000nn00: Op=x, Cmode=001x.
4751 Imm = SplatBits >> 8;
4754 if ((SplatBits & ~0xff0000) == 0) {
4755 // Value = 0x00nn0000: Op=x, Cmode=010x.
4757 Imm = SplatBits >> 16;
4760 if ((SplatBits & ~0xff000000) == 0) {
4761 // Value = 0xnn000000: Op=x, Cmode=011x.
4763 Imm = SplatBits >> 24;
4767 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4768 if (type == OtherModImm) return SDValue();
4770 if ((SplatBits & ~0xffff) == 0 &&
4771 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4772 // Value = 0x0000nnff: Op=x, Cmode=1100.
4774 Imm = SplatBits >> 8;
4778 if ((SplatBits & ~0xffffff) == 0 &&
4779 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4780 // Value = 0x00nnffff: Op=x, Cmode=1101.
4782 Imm = SplatBits >> 16;
4786 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4787 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4788 // VMOV.I32. A (very) minor optimization would be to replicate the value
4789 // and fall through here to test for a valid 64-bit splat. But, then the
4790 // caller would also need to check and handle the change in size.
4794 if (type != VMOVModImm)
4796 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4797 uint64_t BitMask = 0xff;
4799 unsigned ImmMask = 1;
4801 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4802 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4805 } else if ((SplatBits & BitMask) != 0) {
4812 if (DAG.getDataLayout().isBigEndian())
4813 // swap higher and lower 32 bit word
4814 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4816 // Op=1, Cmode=1110.
4818 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4823 llvm_unreachable("unexpected size for isNEONModifiedImm");
4826 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4827 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4830 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4831 const ARMSubtarget *ST) const {
4835 bool IsDouble = Op.getValueType() == MVT::f64;
4836 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4838 // Use the default (constant pool) lowering for double constants when we have
4840 if (IsDouble && Subtarget->isFPOnlySP())
4843 // Try splatting with a VMOV.f32...
4844 APFloat FPVal = CFP->getValueAPF();
4845 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4848 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4849 // We have code in place to select a valid ConstantFP already, no need to
4854 // It's a float and we are trying to use NEON operations where
4855 // possible. Lower it to a splat followed by an extract.
4857 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4858 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4860 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4861 DAG.getConstant(0, DL, MVT::i32));
4864 // The rest of our options are NEON only, make sure that's allowed before
4866 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4870 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4872 // It wouldn't really be worth bothering for doubles except for one very
4873 // important value, which does happen to match: 0.0. So make sure we don't do
4875 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4878 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4879 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4880 VMovVT, false, VMOVModImm);
4881 if (NewVal != SDValue()) {
4883 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4886 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4888 // It's a float: cast and extract a vector element.
4889 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4892 DAG.getConstant(0, DL, MVT::i32));
4895 // Finally, try a VMVN.i32
4896 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4898 if (NewVal != SDValue()) {
4900 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4903 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4905 // It's a float: cast and extract a vector element.
4906 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4908 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4909 DAG.getConstant(0, DL, MVT::i32));
4915 // check if an VEXT instruction can handle the shuffle mask when the
4916 // vector sources of the shuffle are the same.
4917 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4918 unsigned NumElts = VT.getVectorNumElements();
4920 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4926 // If this is a VEXT shuffle, the immediate value is the index of the first
4927 // element. The other shuffle indices must be the successive elements after
4929 unsigned ExpectedElt = Imm;
4930 for (unsigned i = 1; i < NumElts; ++i) {
4931 // Increment the expected index. If it wraps around, just follow it
4932 // back to index zero and keep going.
4934 if (ExpectedElt == NumElts)
4937 if (M[i] < 0) continue; // ignore UNDEF indices
4938 if (ExpectedElt != static_cast<unsigned>(M[i]))
4946 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4947 bool &ReverseVEXT, unsigned &Imm) {
4948 unsigned NumElts = VT.getVectorNumElements();
4949 ReverseVEXT = false;
4951 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4957 // If this is a VEXT shuffle, the immediate value is the index of the first
4958 // element. The other shuffle indices must be the successive elements after
4960 unsigned ExpectedElt = Imm;
4961 for (unsigned i = 1; i < NumElts; ++i) {
4962 // Increment the expected index. If it wraps around, it may still be
4963 // a VEXT but the source vectors must be swapped.
4965 if (ExpectedElt == NumElts * 2) {
4970 if (M[i] < 0) continue; // ignore UNDEF indices
4971 if (ExpectedElt != static_cast<unsigned>(M[i]))
4975 // Adjust the index value if the source operands will be swapped.
4982 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4983 /// instruction with the specified blocksize. (The order of the elements
4984 /// within each block of the vector is reversed.)
4985 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4986 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4987 "Only possible block sizes for VREV are: 16, 32, 64");
4989 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4993 unsigned NumElts = VT.getVectorNumElements();
4994 unsigned BlockElts = M[0] + 1;
4995 // If the first shuffle index is UNDEF, be optimistic.
4997 BlockElts = BlockSize / EltSz;
4999 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5002 for (unsigned i = 0; i < NumElts; ++i) {
5003 if (M[i] < 0) continue; // ignore UNDEF indices
5004 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5011 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5012 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5013 // range, then 0 is placed into the resulting vector. So pretty much any mask
5014 // of 8 elements can work here.
5015 return VT == MVT::v8i8 && M.size() == 8;
5018 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5019 // checking that pairs of elements in the shuffle mask represent the same index
5020 // in each vector, incrementing the expected index by 2 at each step.
5021 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5022 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5024 // WhichResult gives the offset for each element in the mask based on which
5025 // of the two results it belongs to.
5027 // The transpose can be represented either as:
5028 // result1 = shufflevector v1, v2, result1_shuffle_mask
5029 // result2 = shufflevector v1, v2, result2_shuffle_mask
5030 // where v1/v2 and the shuffle masks have the same number of elements
5031 // (here WhichResult (see below) indicates which result is being checked)
5034 // results = shufflevector v1, v2, shuffle_mask
5035 // where both results are returned in one vector and the shuffle mask has twice
5036 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5037 // want to check the low half and high half of the shuffle mask as if it were
5039 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5040 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5044 unsigned NumElts = VT.getVectorNumElements();
5045 if (M.size() != NumElts && M.size() != NumElts*2)
5048 // If the mask is twice as long as the result then we need to check the upper
5049 // and lower parts of the mask
5050 for (unsigned i = 0; i < M.size(); i += NumElts) {
5051 WhichResult = M[i] == 0 ? 0 : 1;
5052 for (unsigned j = 0; j < NumElts; j += 2) {
5053 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5054 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5059 if (M.size() == NumElts*2)
5065 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5066 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5067 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5068 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5069 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5073 unsigned NumElts = VT.getVectorNumElements();
5074 if (M.size() != NumElts && M.size() != NumElts*2)
5077 for (unsigned i = 0; i < M.size(); i += NumElts) {
5078 WhichResult = M[i] == 0 ? 0 : 1;
5079 for (unsigned j = 0; j < NumElts; j += 2) {
5080 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5081 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5086 if (M.size() == NumElts*2)
5092 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5093 // that the mask elements are either all even and in steps of size 2 or all odd
5094 // and in steps of size 2.
5095 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5096 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5098 // Requires similar checks to that of isVTRNMask with
5099 // respect the how results are returned.
5100 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5101 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5105 unsigned NumElts = VT.getVectorNumElements();
5106 if (M.size() != NumElts && M.size() != NumElts*2)
5109 for (unsigned i = 0; i < M.size(); i += NumElts) {
5110 WhichResult = M[i] == 0 ? 0 : 1;
5111 for (unsigned j = 0; j < NumElts; ++j) {
5112 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5117 if (M.size() == NumElts*2)
5120 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5121 if (VT.is64BitVector() && EltSz == 32)
5127 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5128 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5129 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5130 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5131 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5135 unsigned NumElts = VT.getVectorNumElements();
5136 if (M.size() != NumElts && M.size() != NumElts*2)
5139 unsigned Half = NumElts / 2;
5140 for (unsigned i = 0; i < M.size(); i += NumElts) {
5141 WhichResult = M[i] == 0 ? 0 : 1;
5142 for (unsigned j = 0; j < NumElts; j += Half) {
5143 unsigned Idx = WhichResult;
5144 for (unsigned k = 0; k < Half; ++k) {
5145 int MIdx = M[i + j + k];
5146 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5153 if (M.size() == NumElts*2)
5156 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5157 if (VT.is64BitVector() && EltSz == 32)
5163 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5164 // that pairs of elements of the shufflemask represent the same index in each
5165 // vector incrementing sequentially through the vectors.
5166 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5167 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5169 // Requires similar checks to that of isVTRNMask with respect the how results
5171 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5172 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5176 unsigned NumElts = VT.getVectorNumElements();
5177 if (M.size() != NumElts && M.size() != NumElts*2)
5180 for (unsigned i = 0; i < M.size(); i += NumElts) {
5181 WhichResult = M[i] == 0 ? 0 : 1;
5182 unsigned Idx = WhichResult * NumElts / 2;
5183 for (unsigned j = 0; j < NumElts; j += 2) {
5184 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5185 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5191 if (M.size() == NumElts*2)
5194 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5195 if (VT.is64BitVector() && EltSz == 32)
5201 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5202 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5203 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5204 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5205 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5209 unsigned NumElts = VT.getVectorNumElements();
5210 if (M.size() != NumElts && M.size() != NumElts*2)
5213 for (unsigned i = 0; i < M.size(); i += NumElts) {
5214 WhichResult = M[i] == 0 ? 0 : 1;
5215 unsigned Idx = WhichResult * NumElts / 2;
5216 for (unsigned j = 0; j < NumElts; j += 2) {
5217 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5218 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5224 if (M.size() == NumElts*2)
5227 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5228 if (VT.is64BitVector() && EltSz == 32)
5234 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5235 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5236 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5237 unsigned &WhichResult,
5240 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5241 return ARMISD::VTRN;
5242 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5243 return ARMISD::VUZP;
5244 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5245 return ARMISD::VZIP;
5248 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5249 return ARMISD::VTRN;
5250 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5251 return ARMISD::VUZP;
5252 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5253 return ARMISD::VZIP;
5258 /// \return true if this is a reverse operation on an vector.
5259 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5260 unsigned NumElts = VT.getVectorNumElements();
5261 // Make sure the mask has the right size.
5262 if (NumElts != M.size())
5265 // Look for <15, ..., 3, -1, 1, 0>.
5266 for (unsigned i = 0; i != NumElts; ++i)
5267 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5273 // If N is an integer constant that can be moved into a register in one
5274 // instruction, return an SDValue of such a constant (will become a MOV
5275 // instruction). Otherwise return null.
5276 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5277 const ARMSubtarget *ST, SDLoc dl) {
5279 if (!isa<ConstantSDNode>(N))
5281 Val = cast<ConstantSDNode>(N)->getZExtValue();
5283 if (ST->isThumb1Only()) {
5284 if (Val <= 255 || ~Val <= 255)
5285 return DAG.getConstant(Val, dl, MVT::i32);
5287 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5288 return DAG.getConstant(Val, dl, MVT::i32);
5293 // If this is a case we can't handle, return null and let the default
5294 // expansion code take care of it.
5295 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5296 const ARMSubtarget *ST) const {
5297 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5299 EVT VT = Op.getValueType();
5301 APInt SplatBits, SplatUndef;
5302 unsigned SplatBitSize;
5304 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5305 if (SplatBitSize <= 64) {
5306 // Check if an immediate VMOV works.
5308 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5309 SplatUndef.getZExtValue(), SplatBitSize,
5310 DAG, dl, VmovVT, VT.is128BitVector(),
5312 if (Val.getNode()) {
5313 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5314 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5317 // Try an immediate VMVN.
5318 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5319 Val = isNEONModifiedImm(NegatedImm,
5320 SplatUndef.getZExtValue(), SplatBitSize,
5321 DAG, dl, VmovVT, VT.is128BitVector(),
5323 if (Val.getNode()) {
5324 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5325 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5328 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5329 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5330 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5332 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5333 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5339 // Scan through the operands to see if only one value is used.
5341 // As an optimisation, even if more than one value is used it may be more
5342 // profitable to splat with one value then change some lanes.
5344 // Heuristically we decide to do this if the vector has a "dominant" value,
5345 // defined as splatted to more than half of the lanes.
5346 unsigned NumElts = VT.getVectorNumElements();
5347 bool isOnlyLowElement = true;
5348 bool usesOnlyOneValue = true;
5349 bool hasDominantValue = false;
5350 bool isConstant = true;
5352 // Map of the number of times a particular SDValue appears in the
5354 DenseMap<SDValue, unsigned> ValueCounts;
5356 for (unsigned i = 0; i < NumElts; ++i) {
5357 SDValue V = Op.getOperand(i);
5358 if (V.getOpcode() == ISD::UNDEF)
5361 isOnlyLowElement = false;
5362 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5365 ValueCounts.insert(std::make_pair(V, 0));
5366 unsigned &Count = ValueCounts[V];
5368 // Is this value dominant? (takes up more than half of the lanes)
5369 if (++Count > (NumElts / 2)) {
5370 hasDominantValue = true;
5374 if (ValueCounts.size() != 1)
5375 usesOnlyOneValue = false;
5376 if (!Value.getNode() && ValueCounts.size() > 0)
5377 Value = ValueCounts.begin()->first;
5379 if (ValueCounts.size() == 0)
5380 return DAG.getUNDEF(VT);
5382 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5383 // Keep going if we are hitting this case.
5384 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5385 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5387 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5389 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5390 // i32 and try again.
5391 if (hasDominantValue && EltSize <= 32) {
5395 // If we are VDUPing a value that comes directly from a vector, that will
5396 // cause an unnecessary move to and from a GPR, where instead we could
5397 // just use VDUPLANE. We can only do this if the lane being extracted
5398 // is at a constant index, as the VDUP from lane instructions only have
5399 // constant-index forms.
5400 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5401 isa<ConstantSDNode>(Value->getOperand(1))) {
5402 // We need to create a new undef vector to use for the VDUPLANE if the
5403 // size of the vector from which we get the value is different than the
5404 // size of the vector that we need to create. We will insert the element
5405 // such that the register coalescer will remove unnecessary copies.
5406 if (VT != Value->getOperand(0).getValueType()) {
5407 ConstantSDNode *constIndex;
5408 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5409 assert(constIndex && "The index is not a constant!");
5410 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5411 VT.getVectorNumElements();
5412 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5413 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5414 Value, DAG.getConstant(index, dl, MVT::i32)),
5415 DAG.getConstant(index, dl, MVT::i32));
5417 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5418 Value->getOperand(0), Value->getOperand(1));
5420 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5422 if (!usesOnlyOneValue) {
5423 // The dominant value was splatted as 'N', but we now have to insert
5424 // all differing elements.
5425 for (unsigned I = 0; I < NumElts; ++I) {
5426 if (Op.getOperand(I) == Value)
5428 SmallVector<SDValue, 3> Ops;
5430 Ops.push_back(Op.getOperand(I));
5431 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5432 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5437 if (VT.getVectorElementType().isFloatingPoint()) {
5438 SmallVector<SDValue, 8> Ops;
5439 for (unsigned i = 0; i < NumElts; ++i)
5440 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5442 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5443 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5444 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5446 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5448 if (usesOnlyOneValue) {
5449 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5450 if (isConstant && Val.getNode())
5451 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5455 // If all elements are constants and the case above didn't get hit, fall back
5456 // to the default expansion, which will generate a load from the constant
5461 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5463 SDValue shuffle = ReconstructShuffle(Op, DAG);
5464 if (shuffle != SDValue())
5468 // Vectors with 32- or 64-bit elements can be built by directly assigning
5469 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5470 // will be legalized.
5471 if (EltSize >= 32) {
5472 // Do the expansion with floating-point types, since that is what the VFP
5473 // registers are defined to use, and since i64 is not legal.
5474 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5475 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5476 SmallVector<SDValue, 8> Ops;
5477 for (unsigned i = 0; i < NumElts; ++i)
5478 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5479 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5480 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5483 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5484 // know the default expansion would otherwise fall back on something even
5485 // worse. For a vector with one or two non-undef values, that's
5486 // scalar_to_vector for the elements followed by a shuffle (provided the
5487 // shuffle is valid for the target) and materialization element by element
5488 // on the stack followed by a load for everything else.
5489 if (!isConstant && !usesOnlyOneValue) {
5490 SDValue Vec = DAG.getUNDEF(VT);
5491 for (unsigned i = 0 ; i < NumElts; ++i) {
5492 SDValue V = Op.getOperand(i);
5493 if (V.getOpcode() == ISD::UNDEF)
5495 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5496 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5504 /// getExtFactor - Determine the adjustment factor for the position when
5505 /// generating an "extract from vector registers" instruction.
5506 static unsigned getExtFactor(SDValue &V) {
5507 EVT EltType = V.getValueType().getVectorElementType();
5508 return EltType.getSizeInBits() / 8;
5511 // Gather data to see if the operation can be modelled as a
5512 // shuffle in combination with VEXTs.
5513 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5514 SelectionDAG &DAG) const {
5515 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5517 EVT VT = Op.getValueType();
5518 unsigned NumElts = VT.getVectorNumElements();
5520 struct ShuffleSourceInfo {
5525 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5526 // be compatible with the shuffle we intend to construct. As a result
5527 // ShuffleVec will be some sliding window into the original Vec.
5530 // Code should guarantee that element i in Vec starts at element "WindowBase
5531 // + i * WindowScale in ShuffleVec".
5535 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5536 ShuffleSourceInfo(SDValue Vec)
5537 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5541 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5543 SmallVector<ShuffleSourceInfo, 2> Sources;
5544 for (unsigned i = 0; i < NumElts; ++i) {
5545 SDValue V = Op.getOperand(i);
5546 if (V.getOpcode() == ISD::UNDEF)
5548 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5549 // A shuffle can only come from building a vector from various
5550 // elements of other vectors.
5554 // Add this element source to the list if it's not already there.
5555 SDValue SourceVec = V.getOperand(0);
5556 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5557 if (Source == Sources.end())
5558 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5560 // Update the minimum and maximum lane number seen.
5561 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5562 Source->MinElt = std::min(Source->MinElt, EltNo);
5563 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5566 // Currently only do something sane when at most two source vectors
5568 if (Sources.size() > 2)
5571 // Find out the smallest element size among result and two sources, and use
5572 // it as element size to build the shuffle_vector.
5573 EVT SmallestEltTy = VT.getVectorElementType();
5574 for (auto &Source : Sources) {
5575 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5576 if (SrcEltTy.bitsLT(SmallestEltTy))
5577 SmallestEltTy = SrcEltTy;
5579 unsigned ResMultiplier =
5580 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5581 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5582 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5584 // If the source vector is too wide or too narrow, we may nevertheless be able
5585 // to construct a compatible shuffle either by concatenating it with UNDEF or
5586 // extracting a suitable range of elements.
5587 for (auto &Src : Sources) {
5588 EVT SrcVT = Src.ShuffleVec.getValueType();
5590 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5593 // This stage of the search produces a source with the same element type as
5594 // the original, but with a total width matching the BUILD_VECTOR output.
5595 EVT EltVT = SrcVT.getVectorElementType();
5596 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5597 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5599 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5600 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5602 // We can pad out the smaller vector for free, so if it's part of a
5605 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5606 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5610 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5613 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5614 // Span too large for a VEXT to cope
5618 if (Src.MinElt >= NumSrcElts) {
5619 // The extraction can just take the second half
5621 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5622 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5623 Src.WindowBase = -NumSrcElts;
5624 } else if (Src.MaxElt < NumSrcElts) {
5625 // The extraction can just take the first half
5627 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5628 DAG.getConstant(0, dl, MVT::i32));
5630 // An actual VEXT is needed
5632 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5633 DAG.getConstant(0, dl, MVT::i32));
5635 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5636 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5637 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5639 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5641 DAG.getConstant(Imm, dl, MVT::i32));
5642 Src.WindowBase = -Src.MinElt;
5646 // Another possible incompatibility occurs from the vector element types. We
5647 // can fix this by bitcasting the source vectors to the same type we intend
5649 for (auto &Src : Sources) {
5650 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5651 if (SrcEltTy == SmallestEltTy)
5653 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5654 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5655 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5656 Src.WindowBase *= Src.WindowScale;
5659 // Final sanity check before we try to actually produce a shuffle.
5661 for (auto Src : Sources)
5662 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5665 // The stars all align, our next step is to produce the mask for the shuffle.
5666 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5667 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5668 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5669 SDValue Entry = Op.getOperand(i);
5670 if (Entry.getOpcode() == ISD::UNDEF)
5673 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5674 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5676 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5677 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5679 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5680 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5681 VT.getVectorElementType().getSizeInBits());
5682 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5684 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5685 // starting at the appropriate offset.
5686 int *LaneMask = &Mask[i * ResMultiplier];
5688 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5689 ExtractBase += NumElts * (Src - Sources.begin());
5690 for (int j = 0; j < LanesDefined; ++j)
5691 LaneMask[j] = ExtractBase + j;
5694 // Final check before we try to produce nonsense...
5695 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5698 // We can't handle more than two sources. This should have already
5699 // been checked before this point.
5700 assert(Sources.size() <= 2 && "Too many sources!");
5702 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5703 for (unsigned i = 0; i < Sources.size(); ++i)
5704 ShuffleOps[i] = Sources[i].ShuffleVec;
5706 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5707 ShuffleOps[1], &Mask[0]);
5708 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5711 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5712 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5713 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5714 /// are assumed to be legal.
5716 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5718 if (VT.getVectorNumElements() == 4 &&
5719 (VT.is128BitVector() || VT.is64BitVector())) {
5720 unsigned PFIndexes[4];
5721 for (unsigned i = 0; i != 4; ++i) {
5725 PFIndexes[i] = M[i];
5728 // Compute the index in the perfect shuffle table.
5729 unsigned PFTableIndex =
5730 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5731 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5732 unsigned Cost = (PFEntry >> 30);
5738 bool ReverseVEXT, isV_UNDEF;
5739 unsigned Imm, WhichResult;
5741 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5742 return (EltSize >= 32 ||
5743 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5744 isVREVMask(M, VT, 64) ||
5745 isVREVMask(M, VT, 32) ||
5746 isVREVMask(M, VT, 16) ||
5747 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5748 isVTBLMask(M, VT) ||
5749 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5750 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5753 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5754 /// the specified operations to build the shuffle.
5755 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5756 SDValue RHS, SelectionDAG &DAG,
5758 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5759 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5760 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5763 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5772 OP_VUZPL, // VUZP, left result
5773 OP_VUZPR, // VUZP, right result
5774 OP_VZIPL, // VZIP, left result
5775 OP_VZIPR, // VZIP, right result
5776 OP_VTRNL, // VTRN, left result
5777 OP_VTRNR // VTRN, right result
5780 if (OpNum == OP_COPY) {
5781 if (LHSID == (1*9+2)*9+3) return LHS;
5782 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5786 SDValue OpLHS, OpRHS;
5787 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5788 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5789 EVT VT = OpLHS.getValueType();
5792 default: llvm_unreachable("Unknown shuffle opcode!");
5794 // VREV divides the vector in half and swaps within the half.
5795 if (VT.getVectorElementType() == MVT::i32 ||
5796 VT.getVectorElementType() == MVT::f32)
5797 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5798 // vrev <4 x i16> -> VREV32
5799 if (VT.getVectorElementType() == MVT::i16)
5800 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5801 // vrev <4 x i8> -> VREV16
5802 assert(VT.getVectorElementType() == MVT::i8);
5803 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5808 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5809 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5813 return DAG.getNode(ARMISD::VEXT, dl, VT,
5815 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5818 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5819 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5822 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5823 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5826 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5827 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5831 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5832 ArrayRef<int> ShuffleMask,
5833 SelectionDAG &DAG) {
5834 // Check to see if we can use the VTBL instruction.
5835 SDValue V1 = Op.getOperand(0);
5836 SDValue V2 = Op.getOperand(1);
5839 SmallVector<SDValue, 8> VTBLMask;
5840 for (ArrayRef<int>::iterator
5841 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5842 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5844 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5845 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5846 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5848 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5849 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5852 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5853 SelectionDAG &DAG) {
5855 SDValue OpLHS = Op.getOperand(0);
5856 EVT VT = OpLHS.getValueType();
5858 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5859 "Expect an v8i16/v16i8 type");
5860 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5861 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5862 // extract the first 8 bytes into the top double word and the last 8 bytes
5863 // into the bottom double word. The v8i16 case is similar.
5864 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5865 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5866 DAG.getConstant(ExtractNum, DL, MVT::i32));
5869 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5870 SDValue V1 = Op.getOperand(0);
5871 SDValue V2 = Op.getOperand(1);
5873 EVT VT = Op.getValueType();
5874 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5876 // Convert shuffles that are directly supported on NEON to target-specific
5877 // DAG nodes, instead of keeping them as shuffles and matching them again
5878 // during code selection. This is more efficient and avoids the possibility
5879 // of inconsistencies between legalization and selection.
5880 // FIXME: floating-point vectors should be canonicalized to integer vectors
5881 // of the same time so that they get CSEd properly.
5882 ArrayRef<int> ShuffleMask = SVN->getMask();
5884 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5885 if (EltSize <= 32) {
5886 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5887 int Lane = SVN->getSplatIndex();
5888 // If this is undef splat, generate it via "just" vdup, if possible.
5889 if (Lane == -1) Lane = 0;
5891 // Test if V1 is a SCALAR_TO_VECTOR.
5892 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5893 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5895 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5896 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5898 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5899 !isa<ConstantSDNode>(V1.getOperand(0))) {
5900 bool IsScalarToVector = true;
5901 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5902 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5903 IsScalarToVector = false;
5906 if (IsScalarToVector)
5907 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5909 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5910 DAG.getConstant(Lane, dl, MVT::i32));
5915 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5918 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5919 DAG.getConstant(Imm, dl, MVT::i32));
5922 if (isVREVMask(ShuffleMask, VT, 64))
5923 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5924 if (isVREVMask(ShuffleMask, VT, 32))
5925 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5926 if (isVREVMask(ShuffleMask, VT, 16))
5927 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5929 if (V2->getOpcode() == ISD::UNDEF &&
5930 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5931 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5932 DAG.getConstant(Imm, dl, MVT::i32));
5935 // Check for Neon shuffles that modify both input vectors in place.
5936 // If both results are used, i.e., if there are two shuffles with the same
5937 // source operands and with masks corresponding to both results of one of
5938 // these operations, DAG memoization will ensure that a single node is
5939 // used for both shuffles.
5940 unsigned WhichResult;
5942 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5943 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5946 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5947 .getValue(WhichResult);
5950 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5951 // shuffles that produce a result larger than their operands with:
5952 // shuffle(concat(v1, undef), concat(v2, undef))
5954 // shuffle(concat(v1, v2), undef)
5955 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5957 // This is useful in the general case, but there are special cases where
5958 // native shuffles produce larger results: the two-result ops.
5960 // Look through the concat when lowering them:
5961 // shuffle(concat(v1, v2), undef)
5963 // concat(VZIP(v1, v2):0, :1)
5965 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5966 V2->getOpcode() == ISD::UNDEF) {
5967 SDValue SubV1 = V1->getOperand(0);
5968 SDValue SubV2 = V1->getOperand(1);
5969 EVT SubVT = SubV1.getValueType();
5971 // We expect these to have been canonicalized to -1.
5972 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5973 return i < (int)VT.getVectorNumElements();
5974 }) && "Unexpected shuffle index into UNDEF operand!");
5976 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5977 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5980 assert((WhichResult == 0) &&
5981 "In-place shuffle of concat can only have one result!");
5982 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5984 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5990 // If the shuffle is not directly supported and it has 4 elements, use
5991 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5992 unsigned NumElts = VT.getVectorNumElements();
5994 unsigned PFIndexes[4];
5995 for (unsigned i = 0; i != 4; ++i) {
5996 if (ShuffleMask[i] < 0)
5999 PFIndexes[i] = ShuffleMask[i];
6002 // Compute the index in the perfect shuffle table.
6003 unsigned PFTableIndex =
6004 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6005 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6006 unsigned Cost = (PFEntry >> 30);
6009 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6012 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6013 if (EltSize >= 32) {
6014 // Do the expansion with floating-point types, since that is what the VFP
6015 // registers are defined to use, and since i64 is not legal.
6016 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6017 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6018 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6019 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6020 SmallVector<SDValue, 8> Ops;
6021 for (unsigned i = 0; i < NumElts; ++i) {
6022 if (ShuffleMask[i] < 0)
6023 Ops.push_back(DAG.getUNDEF(EltVT));
6025 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6026 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6027 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6030 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6031 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6034 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6035 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6037 if (VT == MVT::v8i8) {
6038 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6039 if (NewOp.getNode())
6046 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6047 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6048 SDValue Lane = Op.getOperand(2);
6049 if (!isa<ConstantSDNode>(Lane))
6055 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6056 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6057 SDValue Lane = Op.getOperand(1);
6058 if (!isa<ConstantSDNode>(Lane))
6061 SDValue Vec = Op.getOperand(0);
6062 if (Op.getValueType() == MVT::i32 &&
6063 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6065 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6071 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6072 // The only time a CONCAT_VECTORS operation can have legal types is when
6073 // two 64-bit vectors are concatenated to a 128-bit vector.
6074 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6075 "unexpected CONCAT_VECTORS");
6077 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6078 SDValue Op0 = Op.getOperand(0);
6079 SDValue Op1 = Op.getOperand(1);
6080 if (Op0.getOpcode() != ISD::UNDEF)
6081 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6082 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6083 DAG.getIntPtrConstant(0, dl));
6084 if (Op1.getOpcode() != ISD::UNDEF)
6085 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6086 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6087 DAG.getIntPtrConstant(1, dl));
6088 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6091 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6092 /// element has been zero/sign-extended, depending on the isSigned parameter,
6093 /// from an integer type half its size.
6094 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6096 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6097 EVT VT = N->getValueType(0);
6098 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6099 SDNode *BVN = N->getOperand(0).getNode();
6100 if (BVN->getValueType(0) != MVT::v4i32 ||
6101 BVN->getOpcode() != ISD::BUILD_VECTOR)
6103 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6104 unsigned HiElt = 1 - LoElt;
6105 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6106 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6107 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6108 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6109 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6112 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6113 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6116 if (Hi0->isNullValue() && Hi1->isNullValue())
6122 if (N->getOpcode() != ISD::BUILD_VECTOR)
6125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6126 SDNode *Elt = N->getOperand(i).getNode();
6127 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6128 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6129 unsigned HalfSize = EltSize / 2;
6131 if (!isIntN(HalfSize, C->getSExtValue()))
6134 if (!isUIntN(HalfSize, C->getZExtValue()))
6145 /// isSignExtended - Check if a node is a vector value that is sign-extended
6146 /// or a constant BUILD_VECTOR with sign-extended elements.
6147 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6148 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6150 if (isExtendedBUILD_VECTOR(N, DAG, true))
6155 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6156 /// or a constant BUILD_VECTOR with zero-extended elements.
6157 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6158 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6160 if (isExtendedBUILD_VECTOR(N, DAG, false))
6165 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6166 if (OrigVT.getSizeInBits() >= 64)
6169 assert(OrigVT.isSimple() && "Expecting a simple value type");
6171 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6172 switch (OrigSimpleTy) {
6173 default: llvm_unreachable("Unexpected Vector Type");
6182 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6183 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6184 /// We insert the required extension here to get the vector to fill a D register.
6185 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6188 unsigned ExtOpcode) {
6189 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6190 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6191 // 64-bits we need to insert a new extension so that it will be 64-bits.
6192 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6193 if (OrigTy.getSizeInBits() >= 64)
6196 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6197 EVT NewVT = getExtensionTo64Bits(OrigTy);
6199 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6202 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6203 /// does not do any sign/zero extension. If the original vector is less
6204 /// than 64 bits, an appropriate extension will be added after the load to
6205 /// reach a total size of 64 bits. We have to add the extension separately
6206 /// because ARM does not have a sign/zero extending load for vectors.
6207 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6208 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6210 // The load already has the right type.
6211 if (ExtendedTy == LD->getMemoryVT())
6212 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6213 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6214 LD->isNonTemporal(), LD->isInvariant(),
6215 LD->getAlignment());
6217 // We need to create a zextload/sextload. We cannot just create a load
6218 // followed by a zext/zext node because LowerMUL is also run during normal
6219 // operation legalization where we can't create illegal types.
6220 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6221 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6222 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6223 LD->isNonTemporal(), LD->getAlignment());
6226 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6227 /// extending load, or BUILD_VECTOR with extended elements, return the
6228 /// unextended value. The unextended vector should be 64 bits so that it can
6229 /// be used as an operand to a VMULL instruction. If the original vector size
6230 /// before extension is less than 64 bits we add a an extension to resize
6231 /// the vector to 64 bits.
6232 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6233 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6234 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6235 N->getOperand(0)->getValueType(0),
6239 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6240 return SkipLoadExtensionForVMULL(LD, DAG);
6242 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6243 // have been legalized as a BITCAST from v4i32.
6244 if (N->getOpcode() == ISD::BITCAST) {
6245 SDNode *BVN = N->getOperand(0).getNode();
6246 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6247 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6248 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6249 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6250 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6252 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6253 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6254 EVT VT = N->getValueType(0);
6255 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6256 unsigned NumElts = VT.getVectorNumElements();
6257 MVT TruncVT = MVT::getIntegerVT(EltSize);
6258 SmallVector<SDValue, 8> Ops;
6260 for (unsigned i = 0; i != NumElts; ++i) {
6261 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6262 const APInt &CInt = C->getAPIntValue();
6263 // Element types smaller than 32 bits are not legal, so use i32 elements.
6264 // The values are implicitly truncated so sext vs. zext doesn't matter.
6265 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6267 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6268 MVT::getVectorVT(TruncVT, NumElts), Ops);
6271 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6272 unsigned Opcode = N->getOpcode();
6273 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6274 SDNode *N0 = N->getOperand(0).getNode();
6275 SDNode *N1 = N->getOperand(1).getNode();
6276 return N0->hasOneUse() && N1->hasOneUse() &&
6277 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6282 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6283 unsigned Opcode = N->getOpcode();
6284 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6285 SDNode *N0 = N->getOperand(0).getNode();
6286 SDNode *N1 = N->getOperand(1).getNode();
6287 return N0->hasOneUse() && N1->hasOneUse() &&
6288 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6293 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6294 // Multiplications are only custom-lowered for 128-bit vectors so that
6295 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6296 EVT VT = Op.getValueType();
6297 assert(VT.is128BitVector() && VT.isInteger() &&
6298 "unexpected type for custom-lowering ISD::MUL");
6299 SDNode *N0 = Op.getOperand(0).getNode();
6300 SDNode *N1 = Op.getOperand(1).getNode();
6301 unsigned NewOpc = 0;
6303 bool isN0SExt = isSignExtended(N0, DAG);
6304 bool isN1SExt = isSignExtended(N1, DAG);
6305 if (isN0SExt && isN1SExt)
6306 NewOpc = ARMISD::VMULLs;
6308 bool isN0ZExt = isZeroExtended(N0, DAG);
6309 bool isN1ZExt = isZeroExtended(N1, DAG);
6310 if (isN0ZExt && isN1ZExt)
6311 NewOpc = ARMISD::VMULLu;
6312 else if (isN1SExt || isN1ZExt) {
6313 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6314 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6315 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6316 NewOpc = ARMISD::VMULLs;
6318 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6319 NewOpc = ARMISD::VMULLu;
6321 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6323 NewOpc = ARMISD::VMULLu;
6329 if (VT == MVT::v2i64)
6330 // Fall through to expand this. It is not legal.
6333 // Other vector multiplications are legal.
6338 // Legalize to a VMULL instruction.
6341 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6343 Op0 = SkipExtensionForVMULL(N0, DAG);
6344 assert(Op0.getValueType().is64BitVector() &&
6345 Op1.getValueType().is64BitVector() &&
6346 "unexpected types for extended operands to VMULL");
6347 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6350 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6351 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6358 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6359 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6360 EVT Op1VT = Op1.getValueType();
6361 return DAG.getNode(N0->getOpcode(), DL, VT,
6362 DAG.getNode(NewOpc, DL, VT,
6363 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6364 DAG.getNode(NewOpc, DL, VT,
6365 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6369 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6371 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6372 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6373 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6374 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6375 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6376 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6377 // Get reciprocal estimate.
6378 // float4 recip = vrecpeq_f32(yf);
6379 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6380 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6382 // Because char has a smaller range than uchar, we can actually get away
6383 // without any newton steps. This requires that we use a weird bias
6384 // of 0xb000, however (again, this has been exhaustively tested).
6385 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6386 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6387 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6388 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6389 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6390 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6391 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6392 // Convert back to short.
6393 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6394 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6399 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6401 // Convert to float.
6402 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6403 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6404 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6405 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6406 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6407 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6409 // Use reciprocal estimate and one refinement step.
6410 // float4 recip = vrecpeq_f32(yf);
6411 // recip *= vrecpsq_f32(yf, recip);
6412 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6413 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6415 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6416 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6418 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6419 // Because short has a smaller range than ushort, we can actually get away
6420 // with only a single newton step. This requires that we use a weird bias
6421 // of 89, however (again, this has been exhaustively tested).
6422 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6423 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6424 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6425 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6426 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6427 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6428 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6429 // Convert back to integer and return.
6430 // return vmovn_s32(vcvt_s32_f32(result));
6431 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6432 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6436 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6437 EVT VT = Op.getValueType();
6438 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6439 "unexpected type for custom-lowering ISD::SDIV");
6442 SDValue N0 = Op.getOperand(0);
6443 SDValue N1 = Op.getOperand(1);
6446 if (VT == MVT::v8i8) {
6447 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6448 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6450 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6451 DAG.getIntPtrConstant(4, dl));
6452 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6453 DAG.getIntPtrConstant(4, dl));
6454 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6455 DAG.getIntPtrConstant(0, dl));
6456 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6457 DAG.getIntPtrConstant(0, dl));
6459 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6460 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6462 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6463 N0 = LowerCONCAT_VECTORS(N0, DAG);
6465 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6468 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6471 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6472 EVT VT = Op.getValueType();
6473 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6474 "unexpected type for custom-lowering ISD::UDIV");
6477 SDValue N0 = Op.getOperand(0);
6478 SDValue N1 = Op.getOperand(1);
6481 if (VT == MVT::v8i8) {
6482 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6483 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6485 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6486 DAG.getIntPtrConstant(4, dl));
6487 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6488 DAG.getIntPtrConstant(4, dl));
6489 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6490 DAG.getIntPtrConstant(0, dl));
6491 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6492 DAG.getIntPtrConstant(0, dl));
6494 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6495 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6497 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6498 N0 = LowerCONCAT_VECTORS(N0, DAG);
6500 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6501 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6507 // v4i16 sdiv ... Convert to float.
6508 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6509 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6510 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6511 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6512 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6513 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6515 // Use reciprocal estimate and two refinement steps.
6516 // float4 recip = vrecpeq_f32(yf);
6517 // recip *= vrecpsq_f32(yf, recip);
6518 // recip *= vrecpsq_f32(yf, recip);
6519 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6520 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6522 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6523 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6525 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6526 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6527 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6529 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6530 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6531 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6532 // and that it will never cause us to return an answer too large).
6533 // float4 result = as_float4(as_int4(xf*recip) + 2);
6534 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6535 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6536 N1 = DAG.getConstant(2, dl, MVT::i32);
6537 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6538 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6539 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6540 // Convert back to integer and return.
6541 // return vmovn_u32(vcvt_s32_f32(result));
6542 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6543 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6547 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6548 EVT VT = Op.getNode()->getValueType(0);
6549 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6552 bool ExtraOp = false;
6553 switch (Op.getOpcode()) {
6554 default: llvm_unreachable("Invalid code");
6555 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6556 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6557 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6558 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6562 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6564 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6565 Op.getOperand(1), Op.getOperand(2));
6568 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6569 assert(Subtarget->isTargetDarwin());
6571 // For iOS, we want to call an alternative entry point: __sincos_stret,
6572 // return values are passed via sret.
6574 SDValue Arg = Op.getOperand(0);
6575 EVT ArgVT = Arg.getValueType();
6576 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6577 auto PtrVT = getPointerTy(DAG.getDataLayout());
6579 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6581 // Pair of floats / doubles used to pass the result.
6582 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6584 // Create stack object for sret.
6585 auto &DL = DAG.getDataLayout();
6586 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6587 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6588 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6589 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6595 Entry.Ty = RetTy->getPointerTo();
6596 Entry.isSExt = false;
6597 Entry.isZExt = false;
6598 Entry.isSRet = true;
6599 Args.push_back(Entry);
6603 Entry.isSExt = false;
6604 Entry.isZExt = false;
6605 Args.push_back(Entry);
6607 const char *LibcallName = (ArgVT == MVT::f64)
6608 ? "__sincos_stret" : "__sincosf_stret";
6609 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6611 TargetLowering::CallLoweringInfo CLI(DAG);
6612 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6613 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6615 .setDiscardResult();
6617 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6619 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6620 MachinePointerInfo(), false, false, false, 0);
6622 // Address of cos field.
6623 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6624 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6625 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6626 MachinePointerInfo(), false, false, false, 0);
6628 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6629 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6630 LoadSin.getValue(0), LoadCos.getValue(0));
6633 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6634 // Monotonic load/store is legal for all targets
6635 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6638 // Acquire/Release load/store is not legal for targets without a
6639 // dmb or equivalent available.
6643 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6644 SmallVectorImpl<SDValue> &Results,
6646 const ARMSubtarget *Subtarget) {
6648 SDValue Cycles32, OutChain;
6650 if (Subtarget->hasPerfMon()) {
6651 // Under Power Management extensions, the cycle-count is:
6652 // mrc p15, #0, <Rt>, c9, c13, #0
6653 SDValue Ops[] = { N->getOperand(0), // Chain
6654 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6655 DAG.getConstant(15, DL, MVT::i32),
6656 DAG.getConstant(0, DL, MVT::i32),
6657 DAG.getConstant(9, DL, MVT::i32),
6658 DAG.getConstant(13, DL, MVT::i32),
6659 DAG.getConstant(0, DL, MVT::i32)
6662 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6663 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6664 OutChain = Cycles32.getValue(1);
6666 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6667 // there are older ARM CPUs that have implementation-specific ways of
6668 // obtaining this information (FIXME!).
6669 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6670 OutChain = DAG.getEntryNode();
6674 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6675 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6676 Results.push_back(Cycles64);
6677 Results.push_back(OutChain);
6680 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6681 switch (Op.getOpcode()) {
6682 default: llvm_unreachable("Don't know how to custom lower this!");
6683 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6684 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6685 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6686 case ISD::GlobalAddress:
6687 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6688 default: llvm_unreachable("unknown object format");
6690 return LowerGlobalAddressWindows(Op, DAG);
6692 return LowerGlobalAddressELF(Op, DAG);
6694 return LowerGlobalAddressDarwin(Op, DAG);
6696 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6697 case ISD::SELECT: return LowerSELECT(Op, DAG);
6698 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6699 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6700 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6701 case ISD::VASTART: return LowerVASTART(Op, DAG);
6702 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6703 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6704 case ISD::SINT_TO_FP:
6705 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6706 case ISD::FP_TO_SINT:
6707 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6708 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6709 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6710 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6711 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6712 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6713 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6714 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6715 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6717 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6720 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6721 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6722 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6723 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6724 case ISD::SRL_PARTS:
6725 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6727 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6728 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6729 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6730 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6731 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6732 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6733 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6734 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6735 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6736 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6737 case ISD::MUL: return LowerMUL(Op, DAG);
6738 case ISD::SDIV: return LowerSDIV(Op, DAG);
6739 case ISD::UDIV: return LowerUDIV(Op, DAG);
6743 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6748 return LowerXALUO(Op, DAG);
6749 case ISD::ATOMIC_LOAD:
6750 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6751 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6753 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6754 case ISD::DYNAMIC_STACKALLOC:
6755 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6756 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6757 llvm_unreachable("Don't know how to custom lower this!");
6758 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6759 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6763 /// ReplaceNodeResults - Replace the results of node with an illegal result
6764 /// type with new values built out of custom code.
6765 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6766 SmallVectorImpl<SDValue>&Results,
6767 SelectionDAG &DAG) const {
6769 switch (N->getOpcode()) {
6771 llvm_unreachable("Don't know how to custom expand this!");
6772 case ISD::READ_REGISTER:
6773 ExpandREAD_REGISTER(N, Results, DAG);
6776 Res = ExpandBITCAST(N, DAG);
6780 Res = Expand64BitShift(N, DAG, Subtarget);
6784 Res = LowerREM(N, DAG);
6786 case ISD::READCYCLECOUNTER:
6787 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6791 Results.push_back(Res);
6794 //===----------------------------------------------------------------------===//
6795 // ARM Scheduler Hooks
6796 //===----------------------------------------------------------------------===//
6798 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6799 /// registers the function context.
6800 void ARMTargetLowering::
6801 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6802 MachineBasicBlock *DispatchBB, int FI) const {
6803 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6804 DebugLoc dl = MI->getDebugLoc();
6805 MachineFunction *MF = MBB->getParent();
6806 MachineRegisterInfo *MRI = &MF->getRegInfo();
6807 MachineConstantPool *MCP = MF->getConstantPool();
6808 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6809 const Function *F = MF->getFunction();
6811 bool isThumb = Subtarget->isThumb();
6812 bool isThumb2 = Subtarget->isThumb2();
6814 unsigned PCLabelId = AFI->createPICLabelUId();
6815 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6816 ARMConstantPoolValue *CPV =
6817 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6818 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6820 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6821 : &ARM::GPRRegClass;
6823 // Grab constant pool and fixed stack memory operands.
6824 MachineMemOperand *CPMMO =
6825 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6826 MachineMemOperand::MOLoad, 4, 4);
6828 MachineMemOperand *FIMMOSt =
6829 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6830 MachineMemOperand::MOStore, 4, 4);
6832 // Load the address of the dispatch MBB into the jump buffer.
6834 // Incoming value: jbuf
6835 // ldr.n r5, LCPI1_1
6838 // str r5, [$jbuf, #+4] ; &jbuf[1]
6839 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6840 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6841 .addConstantPoolIndex(CPI)
6842 .addMemOperand(CPMMO));
6843 // Set the low bit because of thumb mode.
6844 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6846 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6847 .addReg(NewVReg1, RegState::Kill)
6849 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6850 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6851 .addReg(NewVReg2, RegState::Kill)
6853 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6854 .addReg(NewVReg3, RegState::Kill)
6856 .addImm(36) // &jbuf[1] :: pc
6857 .addMemOperand(FIMMOSt));
6858 } else if (isThumb) {
6859 // Incoming value: jbuf
6860 // ldr.n r1, LCPI1_4
6864 // add r2, $jbuf, #+4 ; &jbuf[1]
6866 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6867 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6868 .addConstantPoolIndex(CPI)
6869 .addMemOperand(CPMMO));
6870 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6871 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6872 .addReg(NewVReg1, RegState::Kill)
6874 // Set the low bit because of thumb mode.
6875 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6876 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6877 .addReg(ARM::CPSR, RegState::Define)
6879 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6880 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6881 .addReg(ARM::CPSR, RegState::Define)
6882 .addReg(NewVReg2, RegState::Kill)
6883 .addReg(NewVReg3, RegState::Kill));
6884 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6885 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6887 .addImm(36); // &jbuf[1] :: pc
6888 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6889 .addReg(NewVReg4, RegState::Kill)
6890 .addReg(NewVReg5, RegState::Kill)
6892 .addMemOperand(FIMMOSt));
6894 // Incoming value: jbuf
6897 // str r1, [$jbuf, #+4] ; &jbuf[1]
6898 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6899 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6900 .addConstantPoolIndex(CPI)
6902 .addMemOperand(CPMMO));
6903 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6904 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6905 .addReg(NewVReg1, RegState::Kill)
6906 .addImm(PCLabelId));
6907 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6908 .addReg(NewVReg2, RegState::Kill)
6910 .addImm(36) // &jbuf[1] :: pc
6911 .addMemOperand(FIMMOSt));
6915 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6916 MachineBasicBlock *MBB) const {
6917 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6918 DebugLoc dl = MI->getDebugLoc();
6919 MachineFunction *MF = MBB->getParent();
6920 MachineRegisterInfo *MRI = &MF->getRegInfo();
6921 MachineFrameInfo *MFI = MF->getFrameInfo();
6922 int FI = MFI->getFunctionContextIndex();
6924 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6925 : &ARM::GPRnopcRegClass;
6927 // Get a mapping of the call site numbers to all of the landing pads they're
6929 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6930 unsigned MaxCSNum = 0;
6931 MachineModuleInfo &MMI = MF->getMMI();
6932 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6934 if (!BB->isLandingPad()) continue;
6936 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6938 for (MachineBasicBlock::iterator
6939 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6940 if (!II->isEHLabel()) continue;
6942 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6943 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6945 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6946 for (SmallVectorImpl<unsigned>::iterator
6947 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6948 CSI != CSE; ++CSI) {
6949 CallSiteNumToLPad[*CSI].push_back(BB);
6950 MaxCSNum = std::max(MaxCSNum, *CSI);
6956 // Get an ordered list of the machine basic blocks for the jump table.
6957 std::vector<MachineBasicBlock*> LPadList;
6958 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6959 LPadList.reserve(CallSiteNumToLPad.size());
6960 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6961 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6962 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6963 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6964 LPadList.push_back(*II);
6965 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6969 assert(!LPadList.empty() &&
6970 "No landing pad destinations for the dispatch jump table!");
6972 // Create the jump table and associated information.
6973 MachineJumpTableInfo *JTI =
6974 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6975 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6976 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6978 // Create the MBBs for the dispatch code.
6980 // Shove the dispatch's address into the return slot in the function context.
6981 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6982 DispatchBB->setIsLandingPad();
6984 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6985 unsigned trap_opcode;
6986 if (Subtarget->isThumb())
6987 trap_opcode = ARM::tTRAP;
6989 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6991 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6992 DispatchBB->addSuccessor(TrapBB);
6994 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6995 DispatchBB->addSuccessor(DispContBB);
6998 MF->insert(MF->end(), DispatchBB);
6999 MF->insert(MF->end(), DispContBB);
7000 MF->insert(MF->end(), TrapBB);
7002 // Insert code into the entry block that creates and registers the function
7004 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7006 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7007 MachinePointerInfo::getFixedStack(*MF, FI),
7008 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7010 MachineInstrBuilder MIB;
7011 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7013 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7014 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7016 // Add a register mask with no preserved registers. This results in all
7017 // registers being marked as clobbered.
7018 MIB.addRegMask(RI.getNoPreservedMask());
7020 unsigned NumLPads = LPadList.size();
7021 if (Subtarget->isThumb2()) {
7022 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7023 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7026 .addMemOperand(FIMMOLd));
7028 if (NumLPads < 256) {
7029 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7031 .addImm(LPadList.size()));
7033 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7034 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7035 .addImm(NumLPads & 0xFFFF));
7037 unsigned VReg2 = VReg1;
7038 if ((NumLPads & 0xFFFF0000) != 0) {
7039 VReg2 = MRI->createVirtualRegister(TRC);
7040 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7042 .addImm(NumLPads >> 16));
7045 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7050 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7055 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7056 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7057 .addJumpTableIndex(MJTI));
7059 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7062 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7063 .addReg(NewVReg3, RegState::Kill)
7065 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7067 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7068 .addReg(NewVReg4, RegState::Kill)
7070 .addJumpTableIndex(MJTI);
7071 } else if (Subtarget->isThumb()) {
7072 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7073 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7076 .addMemOperand(FIMMOLd));
7078 if (NumLPads < 256) {
7079 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7083 MachineConstantPool *ConstantPool = MF->getConstantPool();
7084 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7085 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7087 // MachineConstantPool wants an explicit alignment.
7088 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7090 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7091 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7093 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7094 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7095 .addReg(VReg1, RegState::Define)
7096 .addConstantPoolIndex(Idx));
7097 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7102 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7107 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7108 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7109 .addReg(ARM::CPSR, RegState::Define)
7113 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7114 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7115 .addJumpTableIndex(MJTI));
7117 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7118 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7119 .addReg(ARM::CPSR, RegState::Define)
7120 .addReg(NewVReg2, RegState::Kill)
7123 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7124 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7126 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7127 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7128 .addReg(NewVReg4, RegState::Kill)
7130 .addMemOperand(JTMMOLd));
7132 unsigned NewVReg6 = NewVReg5;
7133 if (RelocM == Reloc::PIC_) {
7134 NewVReg6 = MRI->createVirtualRegister(TRC);
7135 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7136 .addReg(ARM::CPSR, RegState::Define)
7137 .addReg(NewVReg5, RegState::Kill)
7141 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7142 .addReg(NewVReg6, RegState::Kill)
7143 .addJumpTableIndex(MJTI);
7145 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7146 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7149 .addMemOperand(FIMMOLd));
7151 if (NumLPads < 256) {
7152 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7155 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7156 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7157 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7158 .addImm(NumLPads & 0xFFFF));
7160 unsigned VReg2 = VReg1;
7161 if ((NumLPads & 0xFFFF0000) != 0) {
7162 VReg2 = MRI->createVirtualRegister(TRC);
7163 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7165 .addImm(NumLPads >> 16));
7168 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7172 MachineConstantPool *ConstantPool = MF->getConstantPool();
7173 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7174 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7176 // MachineConstantPool wants an explicit alignment.
7177 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7179 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7180 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7182 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7183 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7184 .addReg(VReg1, RegState::Define)
7185 .addConstantPoolIndex(Idx)
7187 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7189 .addReg(VReg1, RegState::Kill));
7192 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7197 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7199 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7201 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7202 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7203 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7204 .addJumpTableIndex(MJTI));
7206 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7207 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7208 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7210 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7211 .addReg(NewVReg3, RegState::Kill)
7214 .addMemOperand(JTMMOLd));
7216 if (RelocM == Reloc::PIC_) {
7217 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7218 .addReg(NewVReg5, RegState::Kill)
7220 .addJumpTableIndex(MJTI);
7222 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7223 .addReg(NewVReg5, RegState::Kill)
7224 .addJumpTableIndex(MJTI);
7228 // Add the jump table entries as successors to the MBB.
7229 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7230 for (std::vector<MachineBasicBlock*>::iterator
7231 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7232 MachineBasicBlock *CurMBB = *I;
7233 if (SeenMBBs.insert(CurMBB).second)
7234 DispContBB->addSuccessor(CurMBB);
7237 // N.B. the order the invoke BBs are processed in doesn't matter here.
7238 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7239 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7240 for (MachineBasicBlock *BB : InvokeBBs) {
7242 // Remove the landing pad successor from the invoke block and replace it
7243 // with the new dispatch block.
7244 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7246 while (!Successors.empty()) {
7247 MachineBasicBlock *SMBB = Successors.pop_back_val();
7248 if (SMBB->isLandingPad()) {
7249 BB->removeSuccessor(SMBB);
7250 MBBLPads.push_back(SMBB);
7254 BB->addSuccessor(DispatchBB);
7256 // Find the invoke call and mark all of the callee-saved registers as
7257 // 'implicit defined' so that they're spilled. This prevents code from
7258 // moving instructions to before the EH block, where they will never be
7260 for (MachineBasicBlock::reverse_iterator
7261 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7262 if (!II->isCall()) continue;
7264 DenseMap<unsigned, bool> DefRegs;
7265 for (MachineInstr::mop_iterator
7266 OI = II->operands_begin(), OE = II->operands_end();
7268 if (!OI->isReg()) continue;
7269 DefRegs[OI->getReg()] = true;
7272 MachineInstrBuilder MIB(*MF, &*II);
7274 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7275 unsigned Reg = SavedRegs[i];
7276 if (Subtarget->isThumb2() &&
7277 !ARM::tGPRRegClass.contains(Reg) &&
7278 !ARM::hGPRRegClass.contains(Reg))
7280 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7282 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7285 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7292 // Mark all former landing pads as non-landing pads. The dispatch is the only
7294 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7295 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7296 (*I)->setIsLandingPad(false);
7298 // The instruction is gone now.
7299 MI->eraseFromParent();
7303 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7304 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7305 E = MBB->succ_end(); I != E; ++I)
7308 llvm_unreachable("Expecting a BB with two successors!");
7311 /// Return the load opcode for a given load size. If load size >= 8,
7312 /// neon opcode will be returned.
7313 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7315 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7316 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7318 return LdSize == 4 ? ARM::tLDRi
7319 : LdSize == 2 ? ARM::tLDRHi
7320 : LdSize == 1 ? ARM::tLDRBi : 0;
7322 return LdSize == 4 ? ARM::t2LDR_POST
7323 : LdSize == 2 ? ARM::t2LDRH_POST
7324 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7325 return LdSize == 4 ? ARM::LDR_POST_IMM
7326 : LdSize == 2 ? ARM::LDRH_POST
7327 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7330 /// Return the store opcode for a given store size. If store size >= 8,
7331 /// neon opcode will be returned.
7332 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7334 return StSize == 16 ? ARM::VST1q32wb_fixed
7335 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7337 return StSize == 4 ? ARM::tSTRi
7338 : StSize == 2 ? ARM::tSTRHi
7339 : StSize == 1 ? ARM::tSTRBi : 0;
7341 return StSize == 4 ? ARM::t2STR_POST
7342 : StSize == 2 ? ARM::t2STRH_POST
7343 : StSize == 1 ? ARM::t2STRB_POST : 0;
7344 return StSize == 4 ? ARM::STR_POST_IMM
7345 : StSize == 2 ? ARM::STRH_POST
7346 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7349 /// Emit a post-increment load operation with given size. The instructions
7350 /// will be added to BB at Pos.
7351 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7352 const TargetInstrInfo *TII, DebugLoc dl,
7353 unsigned LdSize, unsigned Data, unsigned AddrIn,
7354 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7355 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7356 assert(LdOpc != 0 && "Should have a load opcode");
7358 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7359 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7361 } else if (IsThumb1) {
7362 // load + update AddrIn
7363 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7364 .addReg(AddrIn).addImm(0));
7365 MachineInstrBuilder MIB =
7366 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7367 MIB = AddDefaultT1CC(MIB);
7368 MIB.addReg(AddrIn).addImm(LdSize);
7369 AddDefaultPred(MIB);
7370 } else if (IsThumb2) {
7371 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7372 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7375 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7376 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7377 .addReg(0).addImm(LdSize));
7381 /// Emit a post-increment store operation with given size. The instructions
7382 /// will be added to BB at Pos.
7383 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7384 const TargetInstrInfo *TII, DebugLoc dl,
7385 unsigned StSize, unsigned Data, unsigned AddrIn,
7386 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7387 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7388 assert(StOpc != 0 && "Should have a store opcode");
7390 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7391 .addReg(AddrIn).addImm(0).addReg(Data));
7392 } else if (IsThumb1) {
7393 // store + update AddrIn
7394 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7395 .addReg(AddrIn).addImm(0));
7396 MachineInstrBuilder MIB =
7397 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7398 MIB = AddDefaultT1CC(MIB);
7399 MIB.addReg(AddrIn).addImm(StSize);
7400 AddDefaultPred(MIB);
7401 } else if (IsThumb2) {
7402 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7403 .addReg(Data).addReg(AddrIn).addImm(StSize));
7405 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7406 .addReg(Data).addReg(AddrIn).addReg(0)
7412 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7413 MachineBasicBlock *BB) const {
7414 // This pseudo instruction has 3 operands: dst, src, size
7415 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7416 // Otherwise, we will generate unrolled scalar copies.
7417 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7418 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7419 MachineFunction::iterator It = BB;
7422 unsigned dest = MI->getOperand(0).getReg();
7423 unsigned src = MI->getOperand(1).getReg();
7424 unsigned SizeVal = MI->getOperand(2).getImm();
7425 unsigned Align = MI->getOperand(3).getImm();
7426 DebugLoc dl = MI->getDebugLoc();
7428 MachineFunction *MF = BB->getParent();
7429 MachineRegisterInfo &MRI = MF->getRegInfo();
7430 unsigned UnitSize = 0;
7431 const TargetRegisterClass *TRC = nullptr;
7432 const TargetRegisterClass *VecTRC = nullptr;
7434 bool IsThumb1 = Subtarget->isThumb1Only();
7435 bool IsThumb2 = Subtarget->isThumb2();
7439 } else if (Align & 2) {
7442 // Check whether we can use NEON instructions.
7443 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7444 Subtarget->hasNEON()) {
7445 if ((Align % 16 == 0) && SizeVal >= 16)
7447 else if ((Align % 8 == 0) && SizeVal >= 8)
7450 // Can't use NEON instructions.
7455 // Select the correct opcode and register class for unit size load/store
7456 bool IsNeon = UnitSize >= 8;
7457 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7459 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7460 : UnitSize == 8 ? &ARM::DPRRegClass
7463 unsigned BytesLeft = SizeVal % UnitSize;
7464 unsigned LoopSize = SizeVal - BytesLeft;
7466 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7467 // Use LDR and STR to copy.
7468 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7469 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7470 unsigned srcIn = src;
7471 unsigned destIn = dest;
7472 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7473 unsigned srcOut = MRI.createVirtualRegister(TRC);
7474 unsigned destOut = MRI.createVirtualRegister(TRC);
7475 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7476 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7477 IsThumb1, IsThumb2);
7478 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7479 IsThumb1, IsThumb2);
7484 // Handle the leftover bytes with LDRB and STRB.
7485 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7486 // [destOut] = STRB_POST(scratch, destIn, 1)
7487 for (unsigned i = 0; i < BytesLeft; i++) {
7488 unsigned srcOut = MRI.createVirtualRegister(TRC);
7489 unsigned destOut = MRI.createVirtualRegister(TRC);
7490 unsigned scratch = MRI.createVirtualRegister(TRC);
7491 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7492 IsThumb1, IsThumb2);
7493 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7494 IsThumb1, IsThumb2);
7498 MI->eraseFromParent(); // The instruction is gone now.
7502 // Expand the pseudo op to a loop.
7505 // movw varEnd, # --> with thumb2
7507 // ldrcp varEnd, idx --> without thumb2
7508 // fallthrough --> loopMBB
7510 // PHI varPhi, varEnd, varLoop
7511 // PHI srcPhi, src, srcLoop
7512 // PHI destPhi, dst, destLoop
7513 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7514 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7515 // subs varLoop, varPhi, #UnitSize
7517 // fallthrough --> exitMBB
7519 // epilogue to handle left-over bytes
7520 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7521 // [destOut] = STRB_POST(scratch, destLoop, 1)
7522 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7523 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7524 MF->insert(It, loopMBB);
7525 MF->insert(It, exitMBB);
7527 // Transfer the remainder of BB and its successor edges to exitMBB.
7528 exitMBB->splice(exitMBB->begin(), BB,
7529 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7530 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7532 // Load an immediate to varEnd.
7533 unsigned varEnd = MRI.createVirtualRegister(TRC);
7534 if (Subtarget->useMovt(*MF)) {
7535 unsigned Vtmp = varEnd;
7536 if ((LoopSize & 0xFFFF0000) != 0)
7537 Vtmp = MRI.createVirtualRegister(TRC);
7538 AddDefaultPred(BuildMI(BB, dl,
7539 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7540 Vtmp).addImm(LoopSize & 0xFFFF));
7542 if ((LoopSize & 0xFFFF0000) != 0)
7543 AddDefaultPred(BuildMI(BB, dl,
7544 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7547 .addImm(LoopSize >> 16));
7549 MachineConstantPool *ConstantPool = MF->getConstantPool();
7550 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7551 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7553 // MachineConstantPool wants an explicit alignment.
7554 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7556 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7557 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7560 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7561 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7563 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7564 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7566 BB->addSuccessor(loopMBB);
7568 // Generate the loop body:
7569 // varPhi = PHI(varLoop, varEnd)
7570 // srcPhi = PHI(srcLoop, src)
7571 // destPhi = PHI(destLoop, dst)
7572 MachineBasicBlock *entryBB = BB;
7574 unsigned varLoop = MRI.createVirtualRegister(TRC);
7575 unsigned varPhi = MRI.createVirtualRegister(TRC);
7576 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7577 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7578 unsigned destLoop = MRI.createVirtualRegister(TRC);
7579 unsigned destPhi = MRI.createVirtualRegister(TRC);
7581 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7582 .addReg(varLoop).addMBB(loopMBB)
7583 .addReg(varEnd).addMBB(entryBB);
7584 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7585 .addReg(srcLoop).addMBB(loopMBB)
7586 .addReg(src).addMBB(entryBB);
7587 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7588 .addReg(destLoop).addMBB(loopMBB)
7589 .addReg(dest).addMBB(entryBB);
7591 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7592 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7593 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7594 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7595 IsThumb1, IsThumb2);
7596 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7597 IsThumb1, IsThumb2);
7599 // Decrement loop variable by UnitSize.
7601 MachineInstrBuilder MIB =
7602 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7603 MIB = AddDefaultT1CC(MIB);
7604 MIB.addReg(varPhi).addImm(UnitSize);
7605 AddDefaultPred(MIB);
7607 MachineInstrBuilder MIB =
7608 BuildMI(*BB, BB->end(), dl,
7609 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7610 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7611 MIB->getOperand(5).setReg(ARM::CPSR);
7612 MIB->getOperand(5).setIsDef(true);
7614 BuildMI(*BB, BB->end(), dl,
7615 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7616 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7618 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7619 BB->addSuccessor(loopMBB);
7620 BB->addSuccessor(exitMBB);
7622 // Add epilogue to handle BytesLeft.
7624 MachineInstr *StartOfExit = exitMBB->begin();
7626 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7627 // [destOut] = STRB_POST(scratch, destLoop, 1)
7628 unsigned srcIn = srcLoop;
7629 unsigned destIn = destLoop;
7630 for (unsigned i = 0; i < BytesLeft; i++) {
7631 unsigned srcOut = MRI.createVirtualRegister(TRC);
7632 unsigned destOut = MRI.createVirtualRegister(TRC);
7633 unsigned scratch = MRI.createVirtualRegister(TRC);
7634 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7635 IsThumb1, IsThumb2);
7636 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7637 IsThumb1, IsThumb2);
7642 MI->eraseFromParent(); // The instruction is gone now.
7647 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7648 MachineBasicBlock *MBB) const {
7649 const TargetMachine &TM = getTargetMachine();
7650 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7651 DebugLoc DL = MI->getDebugLoc();
7653 assert(Subtarget->isTargetWindows() &&
7654 "__chkstk is only supported on Windows");
7655 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7657 // __chkstk takes the number of words to allocate on the stack in R4, and
7658 // returns the stack adjustment in number of bytes in R4. This will not
7659 // clober any other registers (other than the obvious lr).
7661 // Although, technically, IP should be considered a register which may be
7662 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7663 // thumb-2 environment, so there is no interworking required. As a result, we
7664 // do not expect a veneer to be emitted by the linker, clobbering IP.
7666 // Each module receives its own copy of __chkstk, so no import thunk is
7667 // required, again, ensuring that IP is not clobbered.
7669 // Finally, although some linkers may theoretically provide a trampoline for
7670 // out of range calls (which is quite common due to a 32M range limitation of
7671 // branches for Thumb), we can generate the long-call version via
7672 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7675 switch (TM.getCodeModel()) {
7676 case CodeModel::Small:
7677 case CodeModel::Medium:
7678 case CodeModel::Default:
7679 case CodeModel::Kernel:
7680 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7681 .addImm((unsigned)ARMCC::AL).addReg(0)
7682 .addExternalSymbol("__chkstk")
7683 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7684 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7685 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7687 case CodeModel::Large:
7688 case CodeModel::JITDefault: {
7689 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7690 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7692 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7693 .addExternalSymbol("__chkstk");
7694 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7695 .addImm((unsigned)ARMCC::AL).addReg(0)
7696 .addReg(Reg, RegState::Kill)
7697 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7698 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7699 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7704 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7706 .addReg(ARM::SP).addReg(ARM::R4)));
7708 MI->eraseFromParent();
7713 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7714 MachineBasicBlock *BB) const {
7715 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7716 DebugLoc dl = MI->getDebugLoc();
7717 bool isThumb2 = Subtarget->isThumb2();
7718 switch (MI->getOpcode()) {
7721 llvm_unreachable("Unexpected instr type to insert");
7723 // The Thumb2 pre-indexed stores have the same MI operands, they just
7724 // define them differently in the .td files from the isel patterns, so
7725 // they need pseudos.
7726 case ARM::t2STR_preidx:
7727 MI->setDesc(TII->get(ARM::t2STR_PRE));
7729 case ARM::t2STRB_preidx:
7730 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7732 case ARM::t2STRH_preidx:
7733 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7736 case ARM::STRi_preidx:
7737 case ARM::STRBi_preidx: {
7738 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7739 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7740 // Decode the offset.
7741 unsigned Offset = MI->getOperand(4).getImm();
7742 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7743 Offset = ARM_AM::getAM2Offset(Offset);
7747 MachineMemOperand *MMO = *MI->memoperands_begin();
7748 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7749 .addOperand(MI->getOperand(0)) // Rn_wb
7750 .addOperand(MI->getOperand(1)) // Rt
7751 .addOperand(MI->getOperand(2)) // Rn
7752 .addImm(Offset) // offset (skip GPR==zero_reg)
7753 .addOperand(MI->getOperand(5)) // pred
7754 .addOperand(MI->getOperand(6))
7755 .addMemOperand(MMO);
7756 MI->eraseFromParent();
7759 case ARM::STRr_preidx:
7760 case ARM::STRBr_preidx:
7761 case ARM::STRH_preidx: {
7763 switch (MI->getOpcode()) {
7764 default: llvm_unreachable("unexpected opcode!");
7765 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7766 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7767 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7769 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7770 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7771 MIB.addOperand(MI->getOperand(i));
7772 MI->eraseFromParent();
7776 case ARM::tMOVCCr_pseudo: {
7777 // To "insert" a SELECT_CC instruction, we actually have to insert the
7778 // diamond control-flow pattern. The incoming instruction knows the
7779 // destination vreg to set, the condition code register to branch on, the
7780 // true/false values to select between, and a branch opcode to use.
7781 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7782 MachineFunction::iterator It = BB;
7788 // cmpTY ccX, r1, r2
7790 // fallthrough --> copy0MBB
7791 MachineBasicBlock *thisMBB = BB;
7792 MachineFunction *F = BB->getParent();
7793 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7794 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7795 F->insert(It, copy0MBB);
7796 F->insert(It, sinkMBB);
7798 // Transfer the remainder of BB and its successor edges to sinkMBB.
7799 sinkMBB->splice(sinkMBB->begin(), BB,
7800 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7801 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7803 BB->addSuccessor(copy0MBB);
7804 BB->addSuccessor(sinkMBB);
7806 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7807 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7810 // %FalseValue = ...
7811 // # fallthrough to sinkMBB
7814 // Update machine-CFG edges
7815 BB->addSuccessor(sinkMBB);
7818 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7821 BuildMI(*BB, BB->begin(), dl,
7822 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7823 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7824 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7826 MI->eraseFromParent(); // The pseudo instruction is gone now.
7831 case ARM::BCCZi64: {
7832 // If there is an unconditional branch to the other successor, remove it.
7833 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7835 // Compare both parts that make up the double comparison separately for
7837 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7839 unsigned LHS1 = MI->getOperand(1).getReg();
7840 unsigned LHS2 = MI->getOperand(2).getReg();
7842 AddDefaultPred(BuildMI(BB, dl,
7843 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7844 .addReg(LHS1).addImm(0));
7845 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7846 .addReg(LHS2).addImm(0)
7847 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7849 unsigned RHS1 = MI->getOperand(3).getReg();
7850 unsigned RHS2 = MI->getOperand(4).getReg();
7851 AddDefaultPred(BuildMI(BB, dl,
7852 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7853 .addReg(LHS1).addReg(RHS1));
7854 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7855 .addReg(LHS2).addReg(RHS2)
7856 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7859 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7860 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7861 if (MI->getOperand(0).getImm() == ARMCC::NE)
7862 std::swap(destMBB, exitMBB);
7864 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7865 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7867 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7869 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7871 MI->eraseFromParent(); // The pseudo instruction is gone now.
7875 case ARM::Int_eh_sjlj_setjmp:
7876 case ARM::Int_eh_sjlj_setjmp_nofp:
7877 case ARM::tInt_eh_sjlj_setjmp:
7878 case ARM::t2Int_eh_sjlj_setjmp:
7879 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7882 case ARM::Int_eh_sjlj_setup_dispatch:
7883 EmitSjLjDispatchBlock(MI, BB);
7888 // To insert an ABS instruction, we have to insert the
7889 // diamond control-flow pattern. The incoming instruction knows the
7890 // source vreg to test against 0, the destination vreg to set,
7891 // the condition code register to branch on, the
7892 // true/false values to select between, and a branch opcode to use.
7897 // BCC (branch to SinkBB if V0 >= 0)
7898 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7899 // SinkBB: V1 = PHI(V2, V3)
7900 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7901 MachineFunction::iterator BBI = BB;
7903 MachineFunction *Fn = BB->getParent();
7904 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7905 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7906 Fn->insert(BBI, RSBBB);
7907 Fn->insert(BBI, SinkBB);
7909 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7910 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7911 bool ABSSrcKIll = MI->getOperand(1).isKill();
7912 bool isThumb2 = Subtarget->isThumb2();
7913 MachineRegisterInfo &MRI = Fn->getRegInfo();
7914 // In Thumb mode S must not be specified if source register is the SP or
7915 // PC and if destination register is the SP, so restrict register class
7916 unsigned NewRsbDstReg =
7917 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7919 // Transfer the remainder of BB and its successor edges to sinkMBB.
7920 SinkBB->splice(SinkBB->begin(), BB,
7921 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7922 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7924 BB->addSuccessor(RSBBB);
7925 BB->addSuccessor(SinkBB);
7927 // fall through to SinkMBB
7928 RSBBB->addSuccessor(SinkBB);
7930 // insert a cmp at the end of BB
7931 AddDefaultPred(BuildMI(BB, dl,
7932 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7933 .addReg(ABSSrcReg).addImm(0));
7935 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7937 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7938 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7940 // insert rsbri in RSBBB
7941 // Note: BCC and rsbri will be converted into predicated rsbmi
7942 // by if-conversion pass
7943 BuildMI(*RSBBB, RSBBB->begin(), dl,
7944 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7945 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7946 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7948 // insert PHI in SinkBB,
7949 // reuse ABSDstReg to not change uses of ABS instruction
7950 BuildMI(*SinkBB, SinkBB->begin(), dl,
7951 TII->get(ARM::PHI), ABSDstReg)
7952 .addReg(NewRsbDstReg).addMBB(RSBBB)
7953 .addReg(ABSSrcReg).addMBB(BB);
7955 // remove ABS instruction
7956 MI->eraseFromParent();
7958 // return last added BB
7961 case ARM::COPY_STRUCT_BYVAL_I32:
7963 return EmitStructByval(MI, BB);
7964 case ARM::WIN__CHKSTK:
7965 return EmitLowered__chkstk(MI, BB);
7969 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7970 SDNode *Node) const {
7971 const MCInstrDesc *MCID = &MI->getDesc();
7972 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7973 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7974 // operand is still set to noreg. If needed, set the optional operand's
7975 // register to CPSR, and remove the redundant implicit def.
7977 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7979 // Rename pseudo opcodes.
7980 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7982 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7983 MCID = &TII->get(NewOpc);
7985 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7986 "converted opcode should be the same except for cc_out");
7990 // Add the optional cc_out operand
7991 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7993 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7995 // Any ARM instruction that sets the 's' bit should specify an optional
7996 // "cc_out" operand in the last operand position.
7997 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7998 assert(!NewOpc && "Optional cc_out operand required");
8001 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8002 // since we already have an optional CPSR def.
8003 bool definesCPSR = false;
8004 bool deadCPSR = false;
8005 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8007 const MachineOperand &MO = MI->getOperand(i);
8008 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8012 MI->RemoveOperand(i);
8017 assert(!NewOpc && "Optional cc_out operand required");
8020 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8022 assert(!MI->getOperand(ccOutIdx).getReg() &&
8023 "expect uninitialized optional cc_out operand");
8027 // If this instruction was defined with an optional CPSR def and its dag node
8028 // had a live implicit CPSR def, then activate the optional CPSR def.
8029 MachineOperand &MO = MI->getOperand(ccOutIdx);
8030 MO.setReg(ARM::CPSR);
8034 //===----------------------------------------------------------------------===//
8035 // ARM Optimization Hooks
8036 //===----------------------------------------------------------------------===//
8038 // Helper function that checks if N is a null or all ones constant.
8039 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8040 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8043 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8046 // Return true if N is conditionally 0 or all ones.
8047 // Detects these expressions where cc is an i1 value:
8049 // (select cc 0, y) [AllOnes=0]
8050 // (select cc y, 0) [AllOnes=0]
8051 // (zext cc) [AllOnes=0]
8052 // (sext cc) [AllOnes=0/1]
8053 // (select cc -1, y) [AllOnes=1]
8054 // (select cc y, -1) [AllOnes=1]
8056 // Invert is set when N is the null/all ones constant when CC is false.
8057 // OtherOp is set to the alternative value of N.
8058 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8059 SDValue &CC, bool &Invert,
8061 SelectionDAG &DAG) {
8062 switch (N->getOpcode()) {
8063 default: return false;
8065 CC = N->getOperand(0);
8066 SDValue N1 = N->getOperand(1);
8067 SDValue N2 = N->getOperand(2);
8068 if (isZeroOrAllOnes(N1, AllOnes)) {
8073 if (isZeroOrAllOnes(N2, AllOnes)) {
8080 case ISD::ZERO_EXTEND:
8081 // (zext cc) can never be the all ones value.
8085 case ISD::SIGN_EXTEND: {
8087 EVT VT = N->getValueType(0);
8088 CC = N->getOperand(0);
8089 if (CC.getValueType() != MVT::i1)
8093 // When looking for an AllOnes constant, N is an sext, and the 'other'
8095 OtherOp = DAG.getConstant(0, dl, VT);
8096 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8097 // When looking for a 0 constant, N can be zext or sext.
8098 OtherOp = DAG.getConstant(1, dl, VT);
8100 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8107 // Combine a constant select operand into its use:
8109 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8110 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8111 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8112 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8113 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8115 // The transform is rejected if the select doesn't have a constant operand that
8116 // is null, or all ones when AllOnes is set.
8118 // Also recognize sext/zext from i1:
8120 // (add (zext cc), x) -> (select cc (add x, 1), x)
8121 // (add (sext cc), x) -> (select cc (add x, -1), x)
8123 // These transformations eventually create predicated instructions.
8125 // @param N The node to transform.
8126 // @param Slct The N operand that is a select.
8127 // @param OtherOp The other N operand (x above).
8128 // @param DCI Context.
8129 // @param AllOnes Require the select constant to be all ones instead of null.
8130 // @returns The new node, or SDValue() on failure.
8132 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8133 TargetLowering::DAGCombinerInfo &DCI,
8134 bool AllOnes = false) {
8135 SelectionDAG &DAG = DCI.DAG;
8136 EVT VT = N->getValueType(0);
8137 SDValue NonConstantVal;
8140 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8141 NonConstantVal, DAG))
8144 // Slct is now know to be the desired identity constant when CC is true.
8145 SDValue TrueVal = OtherOp;
8146 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8147 OtherOp, NonConstantVal);
8148 // Unless SwapSelectOps says CC should be false.
8150 std::swap(TrueVal, FalseVal);
8152 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8153 CCOp, TrueVal, FalseVal);
8156 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8158 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8159 TargetLowering::DAGCombinerInfo &DCI) {
8160 SDValue N0 = N->getOperand(0);
8161 SDValue N1 = N->getOperand(1);
8162 if (N0.getNode()->hasOneUse()) {
8163 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8164 if (Result.getNode())
8167 if (N1.getNode()->hasOneUse()) {
8168 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8169 if (Result.getNode())
8175 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8176 // (only after legalization).
8177 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8178 TargetLowering::DAGCombinerInfo &DCI,
8179 const ARMSubtarget *Subtarget) {
8181 // Only perform optimization if after legalize, and if NEON is available. We
8182 // also expected both operands to be BUILD_VECTORs.
8183 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8184 || N0.getOpcode() != ISD::BUILD_VECTOR
8185 || N1.getOpcode() != ISD::BUILD_VECTOR)
8188 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8189 EVT VT = N->getValueType(0);
8190 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8193 // Check that the vector operands are of the right form.
8194 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8195 // operands, where N is the size of the formed vector.
8196 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8197 // index such that we have a pair wise add pattern.
8199 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8200 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8202 SDValue Vec = N0->getOperand(0)->getOperand(0);
8203 SDNode *V = Vec.getNode();
8204 unsigned nextIndex = 0;
8206 // For each operands to the ADD which are BUILD_VECTORs,
8207 // check to see if each of their operands are an EXTRACT_VECTOR with
8208 // the same vector and appropriate index.
8209 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8210 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8211 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8213 SDValue ExtVec0 = N0->getOperand(i);
8214 SDValue ExtVec1 = N1->getOperand(i);
8216 // First operand is the vector, verify its the same.
8217 if (V != ExtVec0->getOperand(0).getNode() ||
8218 V != ExtVec1->getOperand(0).getNode())
8221 // Second is the constant, verify its correct.
8222 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8223 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8225 // For the constant, we want to see all the even or all the odd.
8226 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8227 || C1->getZExtValue() != nextIndex+1)
8236 // Create VPADDL node.
8237 SelectionDAG &DAG = DCI.DAG;
8238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8242 // Build operand list.
8243 SmallVector<SDValue, 8> Ops;
8244 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8245 TLI.getPointerTy(DAG.getDataLayout())));
8247 // Input is the vector.
8250 // Get widened type and narrowed type.
8252 unsigned numElem = VT.getVectorNumElements();
8254 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8255 switch (inputLaneType.getSimpleVT().SimpleTy) {
8256 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8257 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8258 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8260 llvm_unreachable("Invalid vector element type for padd optimization.");
8263 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8264 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8265 return DAG.getNode(ExtOp, dl, VT, tmp);
8268 static SDValue findMUL_LOHI(SDValue V) {
8269 if (V->getOpcode() == ISD::UMUL_LOHI ||
8270 V->getOpcode() == ISD::SMUL_LOHI)
8275 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8276 TargetLowering::DAGCombinerInfo &DCI,
8277 const ARMSubtarget *Subtarget) {
8279 if (Subtarget->isThumb1Only()) return SDValue();
8281 // Only perform the checks after legalize when the pattern is available.
8282 if (DCI.isBeforeLegalize()) return SDValue();
8284 // Look for multiply add opportunities.
8285 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8286 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8287 // a glue link from the first add to the second add.
8288 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8289 // a S/UMLAL instruction.
8292 // / \ [no multiline comment]
8298 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8299 SDValue AddcOp0 = AddcNode->getOperand(0);
8300 SDValue AddcOp1 = AddcNode->getOperand(1);
8302 // Check if the two operands are from the same mul_lohi node.
8303 if (AddcOp0.getNode() == AddcOp1.getNode())
8306 assert(AddcNode->getNumValues() == 2 &&
8307 AddcNode->getValueType(0) == MVT::i32 &&
8308 "Expect ADDC with two result values. First: i32");
8310 // Check that we have a glued ADDC node.
8311 if (AddcNode->getValueType(1) != MVT::Glue)
8314 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8315 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8316 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8317 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8318 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8321 // Look for the glued ADDE.
8322 SDNode* AddeNode = AddcNode->getGluedUser();
8326 // Make sure it is really an ADDE.
8327 if (AddeNode->getOpcode() != ISD::ADDE)
8330 assert(AddeNode->getNumOperands() == 3 &&
8331 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8332 "ADDE node has the wrong inputs");
8334 // Check for the triangle shape.
8335 SDValue AddeOp0 = AddeNode->getOperand(0);
8336 SDValue AddeOp1 = AddeNode->getOperand(1);
8338 // Make sure that the ADDE operands are not coming from the same node.
8339 if (AddeOp0.getNode() == AddeOp1.getNode())
8342 // Find the MUL_LOHI node walking up ADDE's operands.
8343 bool IsLeftOperandMUL = false;
8344 SDValue MULOp = findMUL_LOHI(AddeOp0);
8345 if (MULOp == SDValue())
8346 MULOp = findMUL_LOHI(AddeOp1);
8348 IsLeftOperandMUL = true;
8349 if (MULOp == SDValue())
8352 // Figure out the right opcode.
8353 unsigned Opc = MULOp->getOpcode();
8354 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8356 // Figure out the high and low input values to the MLAL node.
8357 SDValue* HiAdd = nullptr;
8358 SDValue* LoMul = nullptr;
8359 SDValue* LowAdd = nullptr;
8361 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8362 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8365 if (IsLeftOperandMUL)
8371 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8372 // whose low result is fed to the ADDC we are checking.
8374 if (AddcOp0 == MULOp.getValue(0)) {
8378 if (AddcOp1 == MULOp.getValue(0)) {
8386 // Create the merged node.
8387 SelectionDAG &DAG = DCI.DAG;
8389 // Build operand list.
8390 SmallVector<SDValue, 8> Ops;
8391 Ops.push_back(LoMul->getOperand(0));
8392 Ops.push_back(LoMul->getOperand(1));
8393 Ops.push_back(*LowAdd);
8394 Ops.push_back(*HiAdd);
8396 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8397 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8399 // Replace the ADDs' nodes uses by the MLA node's values.
8400 SDValue HiMLALResult(MLALNode.getNode(), 1);
8401 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8403 SDValue LoMLALResult(MLALNode.getNode(), 0);
8404 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8406 // Return original node to notify the driver to stop replacing.
8407 SDValue resNode(AddcNode, 0);
8411 /// PerformADDCCombine - Target-specific dag combine transform from
8412 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8413 static SDValue PerformADDCCombine(SDNode *N,
8414 TargetLowering::DAGCombinerInfo &DCI,
8415 const ARMSubtarget *Subtarget) {
8417 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8421 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8422 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8423 /// called with the default operands, and if that fails, with commuted
8425 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8426 TargetLowering::DAGCombinerInfo &DCI,
8427 const ARMSubtarget *Subtarget){
8429 // Attempt to create vpaddl for this add.
8430 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8431 if (Result.getNode())
8434 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8435 if (N0.getNode()->hasOneUse()) {
8436 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8437 if (Result.getNode()) return Result;
8442 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8444 static SDValue PerformADDCombine(SDNode *N,
8445 TargetLowering::DAGCombinerInfo &DCI,
8446 const ARMSubtarget *Subtarget) {
8447 SDValue N0 = N->getOperand(0);
8448 SDValue N1 = N->getOperand(1);
8450 // First try with the default operand order.
8451 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8452 if (Result.getNode())
8455 // If that didn't work, try again with the operands commuted.
8456 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8459 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8461 static SDValue PerformSUBCombine(SDNode *N,
8462 TargetLowering::DAGCombinerInfo &DCI) {
8463 SDValue N0 = N->getOperand(0);
8464 SDValue N1 = N->getOperand(1);
8466 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8467 if (N1.getNode()->hasOneUse()) {
8468 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8469 if (Result.getNode()) return Result;
8475 /// PerformVMULCombine
8476 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8477 /// special multiplier accumulator forwarding.
8483 // However, for (A + B) * (A + B),
8490 static SDValue PerformVMULCombine(SDNode *N,
8491 TargetLowering::DAGCombinerInfo &DCI,
8492 const ARMSubtarget *Subtarget) {
8493 if (!Subtarget->hasVMLxForwarding())
8496 SelectionDAG &DAG = DCI.DAG;
8497 SDValue N0 = N->getOperand(0);
8498 SDValue N1 = N->getOperand(1);
8499 unsigned Opcode = N0.getOpcode();
8500 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8501 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8502 Opcode = N1.getOpcode();
8503 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8504 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8512 EVT VT = N->getValueType(0);
8514 SDValue N00 = N0->getOperand(0);
8515 SDValue N01 = N0->getOperand(1);
8516 return DAG.getNode(Opcode, DL, VT,
8517 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8518 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8521 static SDValue PerformMULCombine(SDNode *N,
8522 TargetLowering::DAGCombinerInfo &DCI,
8523 const ARMSubtarget *Subtarget) {
8524 SelectionDAG &DAG = DCI.DAG;
8526 if (Subtarget->isThumb1Only())
8529 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8532 EVT VT = N->getValueType(0);
8533 if (VT.is64BitVector() || VT.is128BitVector())
8534 return PerformVMULCombine(N, DCI, Subtarget);
8538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8542 int64_t MulAmt = C->getSExtValue();
8543 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8545 ShiftAmt = ShiftAmt & (32 - 1);
8546 SDValue V = N->getOperand(0);
8550 MulAmt >>= ShiftAmt;
8553 if (isPowerOf2_32(MulAmt - 1)) {
8554 // (mul x, 2^N + 1) => (add (shl x, N), x)
8555 Res = DAG.getNode(ISD::ADD, DL, VT,
8557 DAG.getNode(ISD::SHL, DL, VT,
8559 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8561 } else if (isPowerOf2_32(MulAmt + 1)) {
8562 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8563 Res = DAG.getNode(ISD::SUB, DL, VT,
8564 DAG.getNode(ISD::SHL, DL, VT,
8566 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8572 uint64_t MulAmtAbs = -MulAmt;
8573 if (isPowerOf2_32(MulAmtAbs + 1)) {
8574 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8575 Res = DAG.getNode(ISD::SUB, DL, VT,
8577 DAG.getNode(ISD::SHL, DL, VT,
8579 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8581 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8582 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8583 Res = DAG.getNode(ISD::ADD, DL, VT,
8585 DAG.getNode(ISD::SHL, DL, VT,
8587 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8589 Res = DAG.getNode(ISD::SUB, DL, VT,
8590 DAG.getConstant(0, DL, MVT::i32), Res);
8597 Res = DAG.getNode(ISD::SHL, DL, VT,
8598 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8600 // Do not add new nodes to DAG combiner worklist.
8601 DCI.CombineTo(N, Res, false);
8605 static SDValue PerformANDCombine(SDNode *N,
8606 TargetLowering::DAGCombinerInfo &DCI,
8607 const ARMSubtarget *Subtarget) {
8609 // Attempt to use immediate-form VBIC
8610 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8612 EVT VT = N->getValueType(0);
8613 SelectionDAG &DAG = DCI.DAG;
8615 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8618 APInt SplatBits, SplatUndef;
8619 unsigned SplatBitSize;
8622 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8623 if (SplatBitSize <= 64) {
8625 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8626 SplatUndef.getZExtValue(), SplatBitSize,
8627 DAG, dl, VbicVT, VT.is128BitVector(),
8629 if (Val.getNode()) {
8631 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8632 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8633 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8638 if (!Subtarget->isThumb1Only()) {
8639 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8640 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8641 if (Result.getNode())
8648 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8649 static SDValue PerformORCombine(SDNode *N,
8650 TargetLowering::DAGCombinerInfo &DCI,
8651 const ARMSubtarget *Subtarget) {
8652 // Attempt to use immediate-form VORR
8653 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8655 EVT VT = N->getValueType(0);
8656 SelectionDAG &DAG = DCI.DAG;
8658 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8661 APInt SplatBits, SplatUndef;
8662 unsigned SplatBitSize;
8664 if (BVN && Subtarget->hasNEON() &&
8665 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8666 if (SplatBitSize <= 64) {
8668 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8669 SplatUndef.getZExtValue(), SplatBitSize,
8670 DAG, dl, VorrVT, VT.is128BitVector(),
8672 if (Val.getNode()) {
8674 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8675 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8676 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8681 if (!Subtarget->isThumb1Only()) {
8682 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8683 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8684 if (Result.getNode())
8688 // The code below optimizes (or (and X, Y), Z).
8689 // The AND operand needs to have a single user to make these optimizations
8691 SDValue N0 = N->getOperand(0);
8692 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8694 SDValue N1 = N->getOperand(1);
8696 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8697 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8698 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8700 unsigned SplatBitSize;
8703 APInt SplatBits0, SplatBits1;
8704 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8705 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8706 // Ensure that the second operand of both ands are constants
8707 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8708 HasAnyUndefs) && !HasAnyUndefs) {
8709 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8710 HasAnyUndefs) && !HasAnyUndefs) {
8711 // Ensure that the bit width of the constants are the same and that
8712 // the splat arguments are logical inverses as per the pattern we
8713 // are trying to simplify.
8714 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8715 SplatBits0 == ~SplatBits1) {
8716 // Canonicalize the vector type to make instruction selection
8718 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8719 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8723 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8729 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8732 // BFI is only available on V6T2+
8733 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8737 // 1) or (and A, mask), val => ARMbfi A, val, mask
8738 // iff (val & mask) == val
8740 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8741 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8742 // && mask == ~mask2
8743 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8744 // && ~mask == mask2
8745 // (i.e., copy a bitfield value into another bitfield of the same width)
8750 SDValue N00 = N0.getOperand(0);
8752 // The value and the mask need to be constants so we can verify this is
8753 // actually a bitfield set. If the mask is 0xffff, we can do better
8754 // via a movt instruction, so don't use BFI in that case.
8755 SDValue MaskOp = N0.getOperand(1);
8756 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8759 unsigned Mask = MaskC->getZExtValue();
8763 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8766 unsigned Val = N1C->getZExtValue();
8767 if ((Val & ~Mask) != Val)
8770 if (ARM::isBitFieldInvertedMask(Mask)) {
8771 Val >>= countTrailingZeros(~Mask);
8773 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8774 DAG.getConstant(Val, DL, MVT::i32),
8775 DAG.getConstant(Mask, DL, MVT::i32));
8777 // Do not add new nodes to DAG combiner worklist.
8778 DCI.CombineTo(N, Res, false);
8781 } else if (N1.getOpcode() == ISD::AND) {
8782 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8783 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8786 unsigned Mask2 = N11C->getZExtValue();
8788 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8790 if (ARM::isBitFieldInvertedMask(Mask) &&
8792 // The pack halfword instruction works better for masks that fit it,
8793 // so use that when it's available.
8794 if (Subtarget->hasT2ExtractPack() &&
8795 (Mask == 0xffff || Mask == 0xffff0000))
8798 unsigned amt = countTrailingZeros(Mask2);
8799 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8800 DAG.getConstant(amt, DL, MVT::i32));
8801 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8802 DAG.getConstant(Mask, DL, MVT::i32));
8803 // Do not add new nodes to DAG combiner worklist.
8804 DCI.CombineTo(N, Res, false);
8806 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8808 // The pack halfword instruction works better for masks that fit it,
8809 // so use that when it's available.
8810 if (Subtarget->hasT2ExtractPack() &&
8811 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8814 unsigned lsb = countTrailingZeros(Mask);
8815 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8816 DAG.getConstant(lsb, DL, MVT::i32));
8817 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8818 DAG.getConstant(Mask2, DL, MVT::i32));
8819 // Do not add new nodes to DAG combiner worklist.
8820 DCI.CombineTo(N, Res, false);
8825 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8826 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8827 ARM::isBitFieldInvertedMask(~Mask)) {
8828 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8829 // where lsb(mask) == #shamt and masked bits of B are known zero.
8830 SDValue ShAmt = N00.getOperand(1);
8831 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8832 unsigned LSB = countTrailingZeros(Mask);
8836 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8837 DAG.getConstant(~Mask, DL, MVT::i32));
8839 // Do not add new nodes to DAG combiner worklist.
8840 DCI.CombineTo(N, Res, false);
8846 static SDValue PerformXORCombine(SDNode *N,
8847 TargetLowering::DAGCombinerInfo &DCI,
8848 const ARMSubtarget *Subtarget) {
8849 EVT VT = N->getValueType(0);
8850 SelectionDAG &DAG = DCI.DAG;
8852 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8855 if (!Subtarget->isThumb1Only()) {
8856 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8857 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8858 if (Result.getNode())
8865 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8866 /// the bits being cleared by the AND are not demanded by the BFI.
8867 static SDValue PerformBFICombine(SDNode *N,
8868 TargetLowering::DAGCombinerInfo &DCI) {
8869 SDValue N1 = N->getOperand(1);
8870 if (N1.getOpcode() == ISD::AND) {
8871 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8874 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8875 unsigned LSB = countTrailingZeros(~InvMask);
8876 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8878 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8879 "undefined behavior");
8880 unsigned Mask = (1u << Width) - 1;
8881 unsigned Mask2 = N11C->getZExtValue();
8882 if ((Mask & (~Mask2)) == 0)
8883 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8884 N->getOperand(0), N1.getOperand(0),
8890 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8891 /// ARMISD::VMOVRRD.
8892 static SDValue PerformVMOVRRDCombine(SDNode *N,
8893 TargetLowering::DAGCombinerInfo &DCI,
8894 const ARMSubtarget *Subtarget) {
8895 // vmovrrd(vmovdrr x, y) -> x,y
8896 SDValue InDouble = N->getOperand(0);
8897 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8898 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8900 // vmovrrd(load f64) -> (load i32), (load i32)
8901 SDNode *InNode = InDouble.getNode();
8902 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8903 InNode->getValueType(0) == MVT::f64 &&
8904 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8905 !cast<LoadSDNode>(InNode)->isVolatile()) {
8906 // TODO: Should this be done for non-FrameIndex operands?
8907 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8909 SelectionDAG &DAG = DCI.DAG;
8911 SDValue BasePtr = LD->getBasePtr();
8912 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8913 LD->getPointerInfo(), LD->isVolatile(),
8914 LD->isNonTemporal(), LD->isInvariant(),
8915 LD->getAlignment());
8917 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8918 DAG.getConstant(4, DL, MVT::i32));
8919 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8920 LD->getPointerInfo(), LD->isVolatile(),
8921 LD->isNonTemporal(), LD->isInvariant(),
8922 std::min(4U, LD->getAlignment() / 2));
8924 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8925 if (DCI.DAG.getDataLayout().isBigEndian())
8926 std::swap (NewLD1, NewLD2);
8927 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8934 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8935 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8936 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8937 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8938 SDValue Op0 = N->getOperand(0);
8939 SDValue Op1 = N->getOperand(1);
8940 if (Op0.getOpcode() == ISD::BITCAST)
8941 Op0 = Op0.getOperand(0);
8942 if (Op1.getOpcode() == ISD::BITCAST)
8943 Op1 = Op1.getOperand(0);
8944 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8945 Op0.getNode() == Op1.getNode() &&
8946 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8947 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8948 N->getValueType(0), Op0.getOperand(0));
8952 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8953 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8954 /// i64 vector to have f64 elements, since the value can then be loaded
8955 /// directly into a VFP register.
8956 static bool hasNormalLoadOperand(SDNode *N) {
8957 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8958 for (unsigned i = 0; i < NumElts; ++i) {
8959 SDNode *Elt = N->getOperand(i).getNode();
8960 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8966 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8967 /// ISD::BUILD_VECTOR.
8968 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8969 TargetLowering::DAGCombinerInfo &DCI,
8970 const ARMSubtarget *Subtarget) {
8971 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8972 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8973 // into a pair of GPRs, which is fine when the value is used as a scalar,
8974 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8975 SelectionDAG &DAG = DCI.DAG;
8976 if (N->getNumOperands() == 2) {
8977 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8982 // Load i64 elements as f64 values so that type legalization does not split
8983 // them up into i32 values.
8984 EVT VT = N->getValueType(0);
8985 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8988 SmallVector<SDValue, 8> Ops;
8989 unsigned NumElts = VT.getVectorNumElements();
8990 for (unsigned i = 0; i < NumElts; ++i) {
8991 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8993 // Make the DAGCombiner fold the bitcast.
8994 DCI.AddToWorklist(V.getNode());
8996 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8997 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8998 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9001 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9003 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9004 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9005 // At that time, we may have inserted bitcasts from integer to float.
9006 // If these bitcasts have survived DAGCombine, change the lowering of this
9007 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9008 // force to use floating point types.
9010 // Make sure we can change the type of the vector.
9011 // This is possible iff:
9012 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9013 // 1.1. Vector is used only once.
9014 // 1.2. Use is a bit convert to an integer type.
9015 // 2. The size of its operands are 32-bits (64-bits are not legal).
9016 EVT VT = N->getValueType(0);
9017 EVT EltVT = VT.getVectorElementType();
9019 // Check 1.1. and 2.
9020 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9023 // By construction, the input type must be float.
9024 assert(EltVT == MVT::f32 && "Unexpected type!");
9027 SDNode *Use = *N->use_begin();
9028 if (Use->getOpcode() != ISD::BITCAST ||
9029 Use->getValueType(0).isFloatingPoint())
9032 // Check profitability.
9033 // Model is, if more than half of the relevant operands are bitcast from
9034 // i32, turn the build_vector into a sequence of insert_vector_elt.
9035 // Relevant operands are everything that is not statically
9036 // (i.e., at compile time) bitcasted.
9037 unsigned NumOfBitCastedElts = 0;
9038 unsigned NumElts = VT.getVectorNumElements();
9039 unsigned NumOfRelevantElts = NumElts;
9040 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9041 SDValue Elt = N->getOperand(Idx);
9042 if (Elt->getOpcode() == ISD::BITCAST) {
9043 // Assume only bit cast to i32 will go away.
9044 if (Elt->getOperand(0).getValueType() == MVT::i32)
9045 ++NumOfBitCastedElts;
9046 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9047 // Constants are statically casted, thus do not count them as
9048 // relevant operands.
9049 --NumOfRelevantElts;
9052 // Check if more than half of the elements require a non-free bitcast.
9053 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9056 SelectionDAG &DAG = DCI.DAG;
9057 // Create the new vector type.
9058 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9059 // Check if the type is legal.
9060 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9061 if (!TLI.isTypeLegal(VecVT))
9065 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9066 // => BITCAST INSERT_VECTOR_ELT
9067 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9069 SDValue Vec = DAG.getUNDEF(VecVT);
9071 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9072 SDValue V = N->getOperand(Idx);
9073 if (V.getOpcode() == ISD::UNDEF)
9075 if (V.getOpcode() == ISD::BITCAST &&
9076 V->getOperand(0).getValueType() == MVT::i32)
9077 // Fold obvious case.
9078 V = V.getOperand(0);
9080 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9081 // Make the DAGCombiner fold the bitcasts.
9082 DCI.AddToWorklist(V.getNode());
9084 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9085 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9087 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9088 // Make the DAGCombiner fold the bitcasts.
9089 DCI.AddToWorklist(Vec.getNode());
9093 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9094 /// ISD::INSERT_VECTOR_ELT.
9095 static SDValue PerformInsertEltCombine(SDNode *N,
9096 TargetLowering::DAGCombinerInfo &DCI) {
9097 // Bitcast an i64 load inserted into a vector to f64.
9098 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9099 EVT VT = N->getValueType(0);
9100 SDNode *Elt = N->getOperand(1).getNode();
9101 if (VT.getVectorElementType() != MVT::i64 ||
9102 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9105 SelectionDAG &DAG = DCI.DAG;
9107 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9108 VT.getVectorNumElements());
9109 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9110 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9111 // Make the DAGCombiner fold the bitcasts.
9112 DCI.AddToWorklist(Vec.getNode());
9113 DCI.AddToWorklist(V.getNode());
9114 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9115 Vec, V, N->getOperand(2));
9116 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9119 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9120 /// ISD::VECTOR_SHUFFLE.
9121 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9122 // The LLVM shufflevector instruction does not require the shuffle mask
9123 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9124 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9125 // operands do not match the mask length, they are extended by concatenating
9126 // them with undef vectors. That is probably the right thing for other
9127 // targets, but for NEON it is better to concatenate two double-register
9128 // size vector operands into a single quad-register size vector. Do that
9129 // transformation here:
9130 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9131 // shuffle(concat(v1, v2), undef)
9132 SDValue Op0 = N->getOperand(0);
9133 SDValue Op1 = N->getOperand(1);
9134 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9135 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9136 Op0.getNumOperands() != 2 ||
9137 Op1.getNumOperands() != 2)
9139 SDValue Concat0Op1 = Op0.getOperand(1);
9140 SDValue Concat1Op1 = Op1.getOperand(1);
9141 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9142 Concat1Op1.getOpcode() != ISD::UNDEF)
9144 // Skip the transformation if any of the types are illegal.
9145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9146 EVT VT = N->getValueType(0);
9147 if (!TLI.isTypeLegal(VT) ||
9148 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9149 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9152 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9153 Op0.getOperand(0), Op1.getOperand(0));
9154 // Translate the shuffle mask.
9155 SmallVector<int, 16> NewMask;
9156 unsigned NumElts = VT.getVectorNumElements();
9157 unsigned HalfElts = NumElts/2;
9158 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9159 for (unsigned n = 0; n < NumElts; ++n) {
9160 int MaskElt = SVN->getMaskElt(n);
9162 if (MaskElt < (int)HalfElts)
9164 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9165 NewElt = HalfElts + MaskElt - NumElts;
9166 NewMask.push_back(NewElt);
9168 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9169 DAG.getUNDEF(VT), NewMask.data());
9172 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9173 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9174 /// base address updates.
9175 /// For generic load/stores, the memory type is assumed to be a vector.
9176 /// The caller is assumed to have checked legality.
9177 static SDValue CombineBaseUpdate(SDNode *N,
9178 TargetLowering::DAGCombinerInfo &DCI) {
9179 SelectionDAG &DAG = DCI.DAG;
9180 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9181 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9182 const bool isStore = N->getOpcode() == ISD::STORE;
9183 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9184 SDValue Addr = N->getOperand(AddrOpIdx);
9185 MemSDNode *MemN = cast<MemSDNode>(N);
9188 // Search for a use of the address operand that is an increment.
9189 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9190 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9192 if (User->getOpcode() != ISD::ADD ||
9193 UI.getUse().getResNo() != Addr.getResNo())
9196 // Check that the add is independent of the load/store. Otherwise, folding
9197 // it would create a cycle.
9198 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9201 // Find the new opcode for the updating load/store.
9202 bool isLoadOp = true;
9203 bool isLaneOp = false;
9204 unsigned NewOpc = 0;
9205 unsigned NumVecs = 0;
9207 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9209 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9210 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9212 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9214 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9216 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9218 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9219 NumVecs = 2; isLaneOp = true; break;
9220 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9221 NumVecs = 3; isLaneOp = true; break;
9222 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9223 NumVecs = 4; isLaneOp = true; break;
9224 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9225 NumVecs = 1; isLoadOp = false; break;
9226 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9227 NumVecs = 2; isLoadOp = false; break;
9228 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9229 NumVecs = 3; isLoadOp = false; break;
9230 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9231 NumVecs = 4; isLoadOp = false; break;
9232 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9233 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9234 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9235 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9236 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9237 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9241 switch (N->getOpcode()) {
9242 default: llvm_unreachable("unexpected opcode for Neon base update");
9243 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9244 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9245 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9246 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9247 NumVecs = 1; isLaneOp = false; break;
9248 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9249 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9253 // Find the size of memory referenced by the load/store.
9256 VecTy = N->getValueType(0);
9257 } else if (isIntrinsic) {
9258 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9260 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9261 VecTy = N->getOperand(1).getValueType();
9264 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9266 NumBytes /= VecTy.getVectorNumElements();
9268 // If the increment is a constant, it must match the memory ref size.
9269 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9270 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9271 uint64_t IncVal = CInc->getZExtValue();
9272 if (IncVal != NumBytes)
9274 } else if (NumBytes >= 3 * 16) {
9275 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9276 // separate instructions that make it harder to use a non-constant update.
9280 // OK, we found an ADD we can fold into the base update.
9281 // Now, create a _UPD node, taking care of not breaking alignment.
9283 EVT AlignedVecTy = VecTy;
9284 unsigned Alignment = MemN->getAlignment();
9286 // If this is a less-than-standard-aligned load/store, change the type to
9287 // match the standard alignment.
9288 // The alignment is overlooked when selecting _UPD variants; and it's
9289 // easier to introduce bitcasts here than fix that.
9290 // There are 3 ways to get to this base-update combine:
9291 // - intrinsics: they are assumed to be properly aligned (to the standard
9292 // alignment of the memory type), so we don't need to do anything.
9293 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9294 // intrinsics, so, likewise, there's nothing to do.
9295 // - generic load/store instructions: the alignment is specified as an
9296 // explicit operand, rather than implicitly as the standard alignment
9297 // of the memory type (like the intrisics). We need to change the
9298 // memory type to match the explicit alignment. That way, we don't
9299 // generate non-standard-aligned ARMISD::VLDx nodes.
9300 if (isa<LSBaseSDNode>(N)) {
9303 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9304 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9305 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9306 assert(!isLaneOp && "Unexpected generic load/store lane.");
9307 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9308 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9310 // Don't set an explicit alignment on regular load/stores that we want
9311 // to transform to VLD/VST 1_UPD nodes.
9312 // This matches the behavior of regular load/stores, which only get an
9313 // explicit alignment if the MMO alignment is larger than the standard
9314 // alignment of the memory type.
9315 // Intrinsics, however, always get an explicit alignment, set to the
9316 // alignment of the MMO.
9320 // Create the new updating load/store node.
9321 // First, create an SDVTList for the new updating node's results.
9323 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9325 for (n = 0; n < NumResultVecs; ++n)
9326 Tys[n] = AlignedVecTy;
9327 Tys[n++] = MVT::i32;
9328 Tys[n] = MVT::Other;
9329 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9331 // Then, gather the new node's operands.
9332 SmallVector<SDValue, 8> Ops;
9333 Ops.push_back(N->getOperand(0)); // incoming chain
9334 Ops.push_back(N->getOperand(AddrOpIdx));
9337 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9338 // Try to match the intrinsic's signature
9339 Ops.push_back(StN->getValue());
9341 // Loads (and of course intrinsics) match the intrinsics' signature,
9342 // so just add all but the alignment operand.
9343 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9344 Ops.push_back(N->getOperand(i));
9347 // For all node types, the alignment operand is always the last one.
9348 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9350 // If this is a non-standard-aligned STORE, the penultimate operand is the
9351 // stored value. Bitcast it to the aligned type.
9352 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9353 SDValue &StVal = Ops[Ops.size()-2];
9354 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9357 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9359 MemN->getMemOperand());
9362 SmallVector<SDValue, 5> NewResults;
9363 for (unsigned i = 0; i < NumResultVecs; ++i)
9364 NewResults.push_back(SDValue(UpdN.getNode(), i));
9366 // If this is an non-standard-aligned LOAD, the first result is the loaded
9367 // value. Bitcast it to the expected result type.
9368 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9369 SDValue &LdVal = NewResults[0];
9370 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9373 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9374 DCI.CombineTo(N, NewResults);
9375 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9382 static SDValue PerformVLDCombine(SDNode *N,
9383 TargetLowering::DAGCombinerInfo &DCI) {
9384 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9387 return CombineBaseUpdate(N, DCI);
9390 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9391 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9392 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9394 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9395 SelectionDAG &DAG = DCI.DAG;
9396 EVT VT = N->getValueType(0);
9397 // vldN-dup instructions only support 64-bit vectors for N > 1.
9398 if (!VT.is64BitVector())
9401 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9402 SDNode *VLD = N->getOperand(0).getNode();
9403 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9405 unsigned NumVecs = 0;
9406 unsigned NewOpc = 0;
9407 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9408 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9410 NewOpc = ARMISD::VLD2DUP;
9411 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9413 NewOpc = ARMISD::VLD3DUP;
9414 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9416 NewOpc = ARMISD::VLD4DUP;
9421 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9422 // numbers match the load.
9423 unsigned VLDLaneNo =
9424 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9425 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9427 // Ignore uses of the chain result.
9428 if (UI.getUse().getResNo() == NumVecs)
9431 if (User->getOpcode() != ARMISD::VDUPLANE ||
9432 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9436 // Create the vldN-dup node.
9439 for (n = 0; n < NumVecs; ++n)
9441 Tys[n] = MVT::Other;
9442 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9443 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9444 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9445 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9446 Ops, VLDMemInt->getMemoryVT(),
9447 VLDMemInt->getMemOperand());
9450 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9452 unsigned ResNo = UI.getUse().getResNo();
9453 // Ignore uses of the chain result.
9454 if (ResNo == NumVecs)
9457 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9460 // Now the vldN-lane intrinsic is dead except for its chain result.
9461 // Update uses of the chain.
9462 std::vector<SDValue> VLDDupResults;
9463 for (unsigned n = 0; n < NumVecs; ++n)
9464 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9465 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9466 DCI.CombineTo(VLD, VLDDupResults);
9471 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9472 /// ARMISD::VDUPLANE.
9473 static SDValue PerformVDUPLANECombine(SDNode *N,
9474 TargetLowering::DAGCombinerInfo &DCI) {
9475 SDValue Op = N->getOperand(0);
9477 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9478 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9479 if (CombineVLDDUP(N, DCI))
9480 return SDValue(N, 0);
9482 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9483 // redundant. Ignore bit_converts for now; element sizes are checked below.
9484 while (Op.getOpcode() == ISD::BITCAST)
9485 Op = Op.getOperand(0);
9486 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9489 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9490 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9491 // The canonical VMOV for a zero vector uses a 32-bit element size.
9492 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9494 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9496 EVT VT = N->getValueType(0);
9497 if (EltSize > VT.getVectorElementType().getSizeInBits())
9500 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9503 static SDValue PerformLOADCombine(SDNode *N,
9504 TargetLowering::DAGCombinerInfo &DCI) {
9505 EVT VT = N->getValueType(0);
9507 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9508 if (ISD::isNormalLoad(N) && VT.isVector() &&
9509 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9510 return CombineBaseUpdate(N, DCI);
9515 /// PerformSTORECombine - Target-specific dag combine xforms for
9517 static SDValue PerformSTORECombine(SDNode *N,
9518 TargetLowering::DAGCombinerInfo &DCI) {
9519 StoreSDNode *St = cast<StoreSDNode>(N);
9520 if (St->isVolatile())
9523 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9524 // pack all of the elements in one place. Next, store to memory in fewer
9526 SDValue StVal = St->getValue();
9527 EVT VT = StVal.getValueType();
9528 if (St->isTruncatingStore() && VT.isVector()) {
9529 SelectionDAG &DAG = DCI.DAG;
9530 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9531 EVT StVT = St->getMemoryVT();
9532 unsigned NumElems = VT.getVectorNumElements();
9533 assert(StVT != VT && "Cannot truncate to the same type");
9534 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9535 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9537 // From, To sizes and ElemCount must be pow of two
9538 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9540 // We are going to use the original vector elt for storing.
9541 // Accumulated smaller vector elements must be a multiple of the store size.
9542 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9544 unsigned SizeRatio = FromEltSz / ToEltSz;
9545 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9547 // Create a type on which we perform the shuffle.
9548 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9549 NumElems*SizeRatio);
9550 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9553 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9554 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9555 for (unsigned i = 0; i < NumElems; ++i)
9556 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9557 ? (i + 1) * SizeRatio - 1
9560 // Can't shuffle using an illegal type.
9561 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9563 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9564 DAG.getUNDEF(WideVec.getValueType()),
9566 // At this point all of the data is stored at the bottom of the
9567 // register. We now need to save it to mem.
9569 // Find the largest store unit
9570 MVT StoreType = MVT::i8;
9571 for (MVT Tp : MVT::integer_valuetypes()) {
9572 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9575 // Didn't find a legal store type.
9576 if (!TLI.isTypeLegal(StoreType))
9579 // Bitcast the original vector into a vector of store-size units
9580 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9581 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9582 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9583 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9584 SmallVector<SDValue, 8> Chains;
9585 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9586 TLI.getPointerTy(DAG.getDataLayout()));
9587 SDValue BasePtr = St->getBasePtr();
9589 // Perform one or more big stores into memory.
9590 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9591 for (unsigned I = 0; I < E; I++) {
9592 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9593 StoreType, ShuffWide,
9594 DAG.getIntPtrConstant(I, DL));
9595 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9596 St->getPointerInfo(), St->isVolatile(),
9597 St->isNonTemporal(), St->getAlignment());
9598 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9600 Chains.push_back(Ch);
9602 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9605 if (!ISD::isNormalStore(St))
9608 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9609 // ARM stores of arguments in the same cache line.
9610 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9611 StVal.getNode()->hasOneUse()) {
9612 SelectionDAG &DAG = DCI.DAG;
9613 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9615 SDValue BasePtr = St->getBasePtr();
9616 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9617 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9618 BasePtr, St->getPointerInfo(), St->isVolatile(),
9619 St->isNonTemporal(), St->getAlignment());
9621 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9622 DAG.getConstant(4, DL, MVT::i32));
9623 return DAG.getStore(NewST1.getValue(0), DL,
9624 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9625 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9626 St->isNonTemporal(),
9627 std::min(4U, St->getAlignment() / 2));
9630 if (StVal.getValueType() == MVT::i64 &&
9631 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9633 // Bitcast an i64 store extracted from a vector to f64.
9634 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9635 SelectionDAG &DAG = DCI.DAG;
9637 SDValue IntVec = StVal.getOperand(0);
9638 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9639 IntVec.getValueType().getVectorNumElements());
9640 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9641 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9642 Vec, StVal.getOperand(1));
9644 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9645 // Make the DAGCombiner fold the bitcasts.
9646 DCI.AddToWorklist(Vec.getNode());
9647 DCI.AddToWorklist(ExtElt.getNode());
9648 DCI.AddToWorklist(V.getNode());
9649 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9650 St->getPointerInfo(), St->isVolatile(),
9651 St->isNonTemporal(), St->getAlignment(),
9655 // If this is a legal vector store, try to combine it into a VST1_UPD.
9656 if (ISD::isNormalStore(N) && VT.isVector() &&
9657 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9658 return CombineBaseUpdate(N, DCI);
9663 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9664 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9665 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9669 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9671 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9676 APFloat APF = C->getValueAPF();
9677 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9678 != APFloat::opOK || !isExact)
9681 c0 = (I == 0) ? cN : c0;
9682 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9689 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9690 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9691 /// when the VMUL has a constant operand that is a power of 2.
9693 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9694 /// vmul.f32 d16, d17, d16
9695 /// vcvt.s32.f32 d16, d16
9697 /// vcvt.s32.f32 d16, d16, #3
9698 static SDValue PerformVCVTCombine(SDNode *N,
9699 TargetLowering::DAGCombinerInfo &DCI,
9700 const ARMSubtarget *Subtarget) {
9701 SelectionDAG &DAG = DCI.DAG;
9702 SDValue Op = N->getOperand(0);
9704 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9705 Op.getOpcode() != ISD::FMUL)
9709 SDValue N0 = Op->getOperand(0);
9710 SDValue ConstVec = Op->getOperand(1);
9711 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9713 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9714 !isConstVecPow2(ConstVec, isSigned, C))
9717 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9718 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9719 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9720 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9722 // These instructions only exist converting from f32 to i32. We can handle
9723 // smaller integers by generating an extra truncate, but larger ones would
9724 // be lossy. We also can't handle more then 4 lanes, since these intructions
9725 // only support v2i32/v4i32 types.
9730 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9731 Intrinsic::arm_neon_vcvtfp2fxu;
9732 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9733 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9734 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9736 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9738 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9739 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9744 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9745 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9746 /// when the VDIV has a constant operand that is a power of 2.
9748 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9749 /// vcvt.f32.s32 d16, d16
9750 /// vdiv.f32 d16, d17, d16
9752 /// vcvt.f32.s32 d16, d16, #3
9753 static SDValue PerformVDIVCombine(SDNode *N,
9754 TargetLowering::DAGCombinerInfo &DCI,
9755 const ARMSubtarget *Subtarget) {
9756 SelectionDAG &DAG = DCI.DAG;
9757 SDValue Op = N->getOperand(0);
9758 unsigned OpOpcode = Op.getNode()->getOpcode();
9760 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9761 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9765 SDValue ConstVec = N->getOperand(1);
9766 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9768 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9769 !isConstVecPow2(ConstVec, isSigned, C))
9772 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9773 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9774 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9775 // These instructions only exist converting from i32 to f32. We can handle
9776 // smaller integers by generating an extra extend, but larger ones would
9782 SDValue ConvInput = Op.getOperand(0);
9783 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9784 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9785 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9786 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9789 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9790 Intrinsic::arm_neon_vcvtfxu2fp;
9791 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9793 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9794 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9797 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9798 /// operand of a vector shift operation, where all the elements of the
9799 /// build_vector must have the same constant integer value.
9800 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9801 // Ignore bit_converts.
9802 while (Op.getOpcode() == ISD::BITCAST)
9803 Op = Op.getOperand(0);
9804 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9805 APInt SplatBits, SplatUndef;
9806 unsigned SplatBitSize;
9808 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9809 HasAnyUndefs, ElementBits) ||
9810 SplatBitSize > ElementBits)
9812 Cnt = SplatBits.getSExtValue();
9816 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9817 /// operand of a vector shift left operation. That value must be in the range:
9818 /// 0 <= Value < ElementBits for a left shift; or
9819 /// 0 <= Value <= ElementBits for a long left shift.
9820 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9821 assert(VT.isVector() && "vector shift count is not a vector type");
9822 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9823 if (! getVShiftImm(Op, ElementBits, Cnt))
9825 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9828 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9829 /// operand of a vector shift right operation. For a shift opcode, the value
9830 /// is positive, but for an intrinsic the value count must be negative. The
9831 /// absolute value must be in the range:
9832 /// 1 <= |Value| <= ElementBits for a right shift; or
9833 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9834 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9836 assert(VT.isVector() && "vector shift count is not a vector type");
9837 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9838 if (! getVShiftImm(Op, ElementBits, Cnt))
9841 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9842 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9849 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9850 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9851 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9854 // Don't do anything for most intrinsics.
9857 case Intrinsic::arm_neon_vabds:
9858 if (!N->getValueType(0).isInteger())
9860 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9861 N->getOperand(1), N->getOperand(2));
9862 case Intrinsic::arm_neon_vabdu:
9863 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9864 N->getOperand(1), N->getOperand(2));
9866 // Vector shifts: check for immediate versions and lower them.
9867 // Note: This is done during DAG combining instead of DAG legalizing because
9868 // the build_vectors for 64-bit vector element shift counts are generally
9869 // not legal, and it is hard to see their values after they get legalized to
9870 // loads from a constant pool.
9871 case Intrinsic::arm_neon_vshifts:
9872 case Intrinsic::arm_neon_vshiftu:
9873 case Intrinsic::arm_neon_vrshifts:
9874 case Intrinsic::arm_neon_vrshiftu:
9875 case Intrinsic::arm_neon_vrshiftn:
9876 case Intrinsic::arm_neon_vqshifts:
9877 case Intrinsic::arm_neon_vqshiftu:
9878 case Intrinsic::arm_neon_vqshiftsu:
9879 case Intrinsic::arm_neon_vqshiftns:
9880 case Intrinsic::arm_neon_vqshiftnu:
9881 case Intrinsic::arm_neon_vqshiftnsu:
9882 case Intrinsic::arm_neon_vqrshiftns:
9883 case Intrinsic::arm_neon_vqrshiftnu:
9884 case Intrinsic::arm_neon_vqrshiftnsu: {
9885 EVT VT = N->getOperand(1).getValueType();
9887 unsigned VShiftOpc = 0;
9890 case Intrinsic::arm_neon_vshifts:
9891 case Intrinsic::arm_neon_vshiftu:
9892 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9893 VShiftOpc = ARMISD::VSHL;
9896 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9897 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9898 ARMISD::VSHRs : ARMISD::VSHRu);
9903 case Intrinsic::arm_neon_vrshifts:
9904 case Intrinsic::arm_neon_vrshiftu:
9905 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9909 case Intrinsic::arm_neon_vqshifts:
9910 case Intrinsic::arm_neon_vqshiftu:
9911 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9915 case Intrinsic::arm_neon_vqshiftsu:
9916 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9918 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9920 case Intrinsic::arm_neon_vrshiftn:
9921 case Intrinsic::arm_neon_vqshiftns:
9922 case Intrinsic::arm_neon_vqshiftnu:
9923 case Intrinsic::arm_neon_vqshiftnsu:
9924 case Intrinsic::arm_neon_vqrshiftns:
9925 case Intrinsic::arm_neon_vqrshiftnu:
9926 case Intrinsic::arm_neon_vqrshiftnsu:
9927 // Narrowing shifts require an immediate right shift.
9928 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9930 llvm_unreachable("invalid shift count for narrowing vector shift "
9934 llvm_unreachable("unhandled vector shift");
9938 case Intrinsic::arm_neon_vshifts:
9939 case Intrinsic::arm_neon_vshiftu:
9940 // Opcode already set above.
9942 case Intrinsic::arm_neon_vrshifts:
9943 VShiftOpc = ARMISD::VRSHRs; break;
9944 case Intrinsic::arm_neon_vrshiftu:
9945 VShiftOpc = ARMISD::VRSHRu; break;
9946 case Intrinsic::arm_neon_vrshiftn:
9947 VShiftOpc = ARMISD::VRSHRN; break;
9948 case Intrinsic::arm_neon_vqshifts:
9949 VShiftOpc = ARMISD::VQSHLs; break;
9950 case Intrinsic::arm_neon_vqshiftu:
9951 VShiftOpc = ARMISD::VQSHLu; break;
9952 case Intrinsic::arm_neon_vqshiftsu:
9953 VShiftOpc = ARMISD::VQSHLsu; break;
9954 case Intrinsic::arm_neon_vqshiftns:
9955 VShiftOpc = ARMISD::VQSHRNs; break;
9956 case Intrinsic::arm_neon_vqshiftnu:
9957 VShiftOpc = ARMISD::VQSHRNu; break;
9958 case Intrinsic::arm_neon_vqshiftnsu:
9959 VShiftOpc = ARMISD::VQSHRNsu; break;
9960 case Intrinsic::arm_neon_vqrshiftns:
9961 VShiftOpc = ARMISD::VQRSHRNs; break;
9962 case Intrinsic::arm_neon_vqrshiftnu:
9963 VShiftOpc = ARMISD::VQRSHRNu; break;
9964 case Intrinsic::arm_neon_vqrshiftnsu:
9965 VShiftOpc = ARMISD::VQRSHRNsu; break;
9969 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9970 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9973 case Intrinsic::arm_neon_vshiftins: {
9974 EVT VT = N->getOperand(1).getValueType();
9976 unsigned VShiftOpc = 0;
9978 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9979 VShiftOpc = ARMISD::VSLI;
9980 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9981 VShiftOpc = ARMISD::VSRI;
9983 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9987 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9988 N->getOperand(1), N->getOperand(2),
9989 DAG.getConstant(Cnt, dl, MVT::i32));
9992 case Intrinsic::arm_neon_vqrshifts:
9993 case Intrinsic::arm_neon_vqrshiftu:
9994 // No immediate versions of these to check for.
10001 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10002 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10003 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10004 /// vector element shift counts are generally not legal, and it is hard to see
10005 /// their values after they get legalized to loads from a constant pool.
10006 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10007 const ARMSubtarget *ST) {
10008 EVT VT = N->getValueType(0);
10009 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10010 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10011 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10012 SDValue N1 = N->getOperand(1);
10013 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10014 SDValue N0 = N->getOperand(0);
10015 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10016 DAG.MaskedValueIsZero(N0.getOperand(0),
10017 APInt::getHighBitsSet(32, 16)))
10018 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10022 // Nothing to be done for scalar shifts.
10023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10024 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10027 assert(ST->hasNEON() && "unexpected vector shift");
10030 switch (N->getOpcode()) {
10031 default: llvm_unreachable("unexpected shift opcode");
10034 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10036 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10037 DAG.getConstant(Cnt, dl, MVT::i32));
10043 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10044 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10045 ARMISD::VSHRs : ARMISD::VSHRu);
10047 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10048 DAG.getConstant(Cnt, dl, MVT::i32));
10054 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10055 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10056 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10057 const ARMSubtarget *ST) {
10058 SDValue N0 = N->getOperand(0);
10060 // Check for sign- and zero-extensions of vector extract operations of 8-
10061 // and 16-bit vector elements. NEON supports these directly. They are
10062 // handled during DAG combining because type legalization will promote them
10063 // to 32-bit types and it is messy to recognize the operations after that.
10064 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10065 SDValue Vec = N0.getOperand(0);
10066 SDValue Lane = N0.getOperand(1);
10067 EVT VT = N->getValueType(0);
10068 EVT EltVT = N0.getValueType();
10069 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10071 if (VT == MVT::i32 &&
10072 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10073 TLI.isTypeLegal(Vec.getValueType()) &&
10074 isa<ConstantSDNode>(Lane)) {
10077 switch (N->getOpcode()) {
10078 default: llvm_unreachable("unexpected opcode");
10079 case ISD::SIGN_EXTEND:
10080 Opc = ARMISD::VGETLANEs;
10082 case ISD::ZERO_EXTEND:
10083 case ISD::ANY_EXTEND:
10084 Opc = ARMISD::VGETLANEu;
10087 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10094 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10096 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10097 SDValue Cmp = N->getOperand(4);
10098 if (Cmp.getOpcode() != ARMISD::CMPZ)
10099 // Only looking at EQ and NE cases.
10102 EVT VT = N->getValueType(0);
10104 SDValue LHS = Cmp.getOperand(0);
10105 SDValue RHS = Cmp.getOperand(1);
10106 SDValue FalseVal = N->getOperand(0);
10107 SDValue TrueVal = N->getOperand(1);
10108 SDValue ARMcc = N->getOperand(2);
10109 ARMCC::CondCodes CC =
10110 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10128 /// FIXME: Turn this into a target neutral optimization?
10130 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10131 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10132 N->getOperand(3), Cmp);
10133 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10135 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10136 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10137 N->getOperand(3), NewCmp);
10140 if (Res.getNode()) {
10141 APInt KnownZero, KnownOne;
10142 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10143 // Capture demanded bits information that would be otherwise lost.
10144 if (KnownZero == 0xfffffffe)
10145 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10146 DAG.getValueType(MVT::i1));
10147 else if (KnownZero == 0xffffff00)
10148 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10149 DAG.getValueType(MVT::i8));
10150 else if (KnownZero == 0xffff0000)
10151 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10152 DAG.getValueType(MVT::i16));
10158 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10159 DAGCombinerInfo &DCI) const {
10160 switch (N->getOpcode()) {
10162 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10163 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10164 case ISD::SUB: return PerformSUBCombine(N, DCI);
10165 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10166 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10167 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10168 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10169 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10170 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10171 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10172 case ISD::STORE: return PerformSTORECombine(N, DCI);
10173 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10174 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10175 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10176 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10177 case ISD::FP_TO_SINT:
10178 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10179 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10180 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10183 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10184 case ISD::SIGN_EXTEND:
10185 case ISD::ZERO_EXTEND:
10186 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10187 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10188 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10189 case ARMISD::VLD2DUP:
10190 case ARMISD::VLD3DUP:
10191 case ARMISD::VLD4DUP:
10192 return PerformVLDCombine(N, DCI);
10193 case ARMISD::BUILD_VECTOR:
10194 return PerformARMBUILD_VECTORCombine(N, DCI);
10195 case ISD::INTRINSIC_VOID:
10196 case ISD::INTRINSIC_W_CHAIN:
10197 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10198 case Intrinsic::arm_neon_vld1:
10199 case Intrinsic::arm_neon_vld2:
10200 case Intrinsic::arm_neon_vld3:
10201 case Intrinsic::arm_neon_vld4:
10202 case Intrinsic::arm_neon_vld2lane:
10203 case Intrinsic::arm_neon_vld3lane:
10204 case Intrinsic::arm_neon_vld4lane:
10205 case Intrinsic::arm_neon_vst1:
10206 case Intrinsic::arm_neon_vst2:
10207 case Intrinsic::arm_neon_vst3:
10208 case Intrinsic::arm_neon_vst4:
10209 case Intrinsic::arm_neon_vst2lane:
10210 case Intrinsic::arm_neon_vst3lane:
10211 case Intrinsic::arm_neon_vst4lane:
10212 return PerformVLDCombine(N, DCI);
10220 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10222 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10225 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10228 bool *Fast) const {
10229 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10230 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10232 switch (VT.getSimpleVT().SimpleTy) {
10238 // Unaligned access can use (for example) LRDB, LRDH, LDR
10239 if (AllowsUnaligned) {
10241 *Fast = Subtarget->hasV7Ops();
10248 // For any little-endian targets with neon, we can support unaligned ld/st
10249 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10250 // A big-endian target may also explicitly support unaligned accesses
10251 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10261 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10262 unsigned AlignCheck) {
10263 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10264 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10267 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10268 unsigned DstAlign, unsigned SrcAlign,
10269 bool IsMemset, bool ZeroMemset,
10271 MachineFunction &MF) const {
10272 const Function *F = MF.getFunction();
10274 // See if we can use NEON instructions for this...
10275 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10276 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10279 (memOpAlign(SrcAlign, DstAlign, 16) ||
10280 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10282 } else if (Size >= 8 &&
10283 (memOpAlign(SrcAlign, DstAlign, 8) ||
10284 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10290 // Lowering to i32/i16 if the size permits.
10293 else if (Size >= 2)
10296 // Let the target-independent logic figure it out.
10300 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10301 if (Val.getOpcode() != ISD::LOAD)
10304 EVT VT1 = Val.getValueType();
10305 if (!VT1.isSimple() || !VT1.isInteger() ||
10306 !VT2.isSimple() || !VT2.isInteger())
10309 switch (VT1.getSimpleVT().SimpleTy) {
10314 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10321 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10322 EVT VT = ExtVal.getValueType();
10324 if (!isTypeLegal(VT))
10327 // Don't create a loadext if we can fold the extension into a wide/long
10329 // If there's more than one user instruction, the loadext is desirable no
10330 // matter what. There can be two uses by the same instruction.
10331 if (ExtVal->use_empty() ||
10332 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10335 SDNode *U = *ExtVal->use_begin();
10336 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10337 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10343 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10344 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10347 if (!isTypeLegal(EVT::getEVT(Ty1)))
10350 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10352 // Assuming the caller doesn't have a zeroext or signext return parameter,
10353 // truncation all the way down to i1 is valid.
10358 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10362 unsigned Scale = 1;
10363 switch (VT.getSimpleVT().SimpleTy) {
10364 default: return false;
10379 if ((V & (Scale - 1)) != 0)
10382 return V == (V & ((1LL << 5) - 1));
10385 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10386 const ARMSubtarget *Subtarget) {
10387 bool isNeg = false;
10393 switch (VT.getSimpleVT().SimpleTy) {
10394 default: return false;
10399 // + imm12 or - imm8
10401 return V == (V & ((1LL << 8) - 1));
10402 return V == (V & ((1LL << 12) - 1));
10405 // Same as ARM mode. FIXME: NEON?
10406 if (!Subtarget->hasVFP2())
10411 return V == (V & ((1LL << 8) - 1));
10415 /// isLegalAddressImmediate - Return true if the integer value can be used
10416 /// as the offset of the target addressing mode for load / store of the
10418 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10419 const ARMSubtarget *Subtarget) {
10423 if (!VT.isSimple())
10426 if (Subtarget->isThumb1Only())
10427 return isLegalT1AddressImmediate(V, VT);
10428 else if (Subtarget->isThumb2())
10429 return isLegalT2AddressImmediate(V, VT, Subtarget);
10434 switch (VT.getSimpleVT().SimpleTy) {
10435 default: return false;
10440 return V == (V & ((1LL << 12) - 1));
10443 return V == (V & ((1LL << 8) - 1));
10446 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10451 return V == (V & ((1LL << 8) - 1));
10455 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10457 int Scale = AM.Scale;
10461 switch (VT.getSimpleVT().SimpleTy) {
10462 default: return false;
10470 Scale = Scale & ~1;
10471 return Scale == 2 || Scale == 4 || Scale == 8;
10474 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10478 // Note, we allow "void" uses (basically, uses that aren't loads or
10479 // stores), because arm allows folding a scale into many arithmetic
10480 // operations. This should be made more precise and revisited later.
10482 // Allow r << imm, but the imm has to be a multiple of two.
10483 if (Scale & 1) return false;
10484 return isPowerOf2_32(Scale);
10488 /// isLegalAddressingMode - Return true if the addressing mode represented
10489 /// by AM is legal for this target, for a load/store of the specified type.
10490 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10491 const AddrMode &AM, Type *Ty,
10492 unsigned AS) const {
10493 EVT VT = getValueType(DL, Ty, true);
10494 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10497 // Can never fold addr of global into load/store.
10501 switch (AM.Scale) {
10502 case 0: // no scale reg, must be "r+i" or "r", or "i".
10505 if (Subtarget->isThumb1Only())
10509 // ARM doesn't support any R+R*scale+imm addr modes.
10513 if (!VT.isSimple())
10516 if (Subtarget->isThumb2())
10517 return isLegalT2ScaledAddressingMode(AM, VT);
10519 int Scale = AM.Scale;
10520 switch (VT.getSimpleVT().SimpleTy) {
10521 default: return false;
10525 if (Scale < 0) Scale = -Scale;
10529 return isPowerOf2_32(Scale & ~1);
10533 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10538 // Note, we allow "void" uses (basically, uses that aren't loads or
10539 // stores), because arm allows folding a scale into many arithmetic
10540 // operations. This should be made more precise and revisited later.
10542 // Allow r << imm, but the imm has to be a multiple of two.
10543 if (Scale & 1) return false;
10544 return isPowerOf2_32(Scale);
10550 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10551 /// icmp immediate, that is the target has icmp instructions which can compare
10552 /// a register against the immediate without having to materialize the
10553 /// immediate into a register.
10554 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10555 // Thumb2 and ARM modes can use cmn for negative immediates.
10556 if (!Subtarget->isThumb())
10557 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10558 if (Subtarget->isThumb2())
10559 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10560 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10561 return Imm >= 0 && Imm <= 255;
10564 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10565 /// *or sub* immediate, that is the target has add or sub instructions which can
10566 /// add a register with the immediate without having to materialize the
10567 /// immediate into a register.
10568 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10569 // Same encoding for add/sub, just flip the sign.
10570 int64_t AbsImm = std::abs(Imm);
10571 if (!Subtarget->isThumb())
10572 return ARM_AM::getSOImmVal(AbsImm) != -1;
10573 if (Subtarget->isThumb2())
10574 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10575 // Thumb1 only has 8-bit unsigned immediate.
10576 return AbsImm >= 0 && AbsImm <= 255;
10579 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10580 bool isSEXTLoad, SDValue &Base,
10581 SDValue &Offset, bool &isInc,
10582 SelectionDAG &DAG) {
10583 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10586 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10587 // AddressingMode 3
10588 Base = Ptr->getOperand(0);
10589 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10590 int RHSC = (int)RHS->getZExtValue();
10591 if (RHSC < 0 && RHSC > -256) {
10592 assert(Ptr->getOpcode() == ISD::ADD);
10594 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10598 isInc = (Ptr->getOpcode() == ISD::ADD);
10599 Offset = Ptr->getOperand(1);
10601 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10602 // AddressingMode 2
10603 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10604 int RHSC = (int)RHS->getZExtValue();
10605 if (RHSC < 0 && RHSC > -0x1000) {
10606 assert(Ptr->getOpcode() == ISD::ADD);
10608 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10609 Base = Ptr->getOperand(0);
10614 if (Ptr->getOpcode() == ISD::ADD) {
10616 ARM_AM::ShiftOpc ShOpcVal=
10617 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10618 if (ShOpcVal != ARM_AM::no_shift) {
10619 Base = Ptr->getOperand(1);
10620 Offset = Ptr->getOperand(0);
10622 Base = Ptr->getOperand(0);
10623 Offset = Ptr->getOperand(1);
10628 isInc = (Ptr->getOpcode() == ISD::ADD);
10629 Base = Ptr->getOperand(0);
10630 Offset = Ptr->getOperand(1);
10634 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10638 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10639 bool isSEXTLoad, SDValue &Base,
10640 SDValue &Offset, bool &isInc,
10641 SelectionDAG &DAG) {
10642 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10645 Base = Ptr->getOperand(0);
10646 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10647 int RHSC = (int)RHS->getZExtValue();
10648 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10649 assert(Ptr->getOpcode() == ISD::ADD);
10651 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10653 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10654 isInc = Ptr->getOpcode() == ISD::ADD;
10655 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10663 /// getPreIndexedAddressParts - returns true by value, base pointer and
10664 /// offset pointer and addressing mode by reference if the node's address
10665 /// can be legally represented as pre-indexed load / store address.
10667 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10669 ISD::MemIndexedMode &AM,
10670 SelectionDAG &DAG) const {
10671 if (Subtarget->isThumb1Only())
10676 bool isSEXTLoad = false;
10677 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10678 Ptr = LD->getBasePtr();
10679 VT = LD->getMemoryVT();
10680 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10681 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10682 Ptr = ST->getBasePtr();
10683 VT = ST->getMemoryVT();
10688 bool isLegal = false;
10689 if (Subtarget->isThumb2())
10690 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10691 Offset, isInc, DAG);
10693 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10694 Offset, isInc, DAG);
10698 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10702 /// getPostIndexedAddressParts - returns true by value, base pointer and
10703 /// offset pointer and addressing mode by reference if this node can be
10704 /// combined with a load / store to form a post-indexed load / store.
10705 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10708 ISD::MemIndexedMode &AM,
10709 SelectionDAG &DAG) const {
10710 if (Subtarget->isThumb1Only())
10715 bool isSEXTLoad = false;
10716 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10717 VT = LD->getMemoryVT();
10718 Ptr = LD->getBasePtr();
10719 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10720 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10721 VT = ST->getMemoryVT();
10722 Ptr = ST->getBasePtr();
10727 bool isLegal = false;
10728 if (Subtarget->isThumb2())
10729 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10732 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10738 // Swap base ptr and offset to catch more post-index load / store when
10739 // it's legal. In Thumb2 mode, offset must be an immediate.
10740 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10741 !Subtarget->isThumb2())
10742 std::swap(Base, Offset);
10744 // Post-indexed load / store update the base pointer.
10749 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10753 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10756 const SelectionDAG &DAG,
10757 unsigned Depth) const {
10758 unsigned BitWidth = KnownOne.getBitWidth();
10759 KnownZero = KnownOne = APInt(BitWidth, 0);
10760 switch (Op.getOpcode()) {
10766 // These nodes' second result is a boolean
10767 if (Op.getResNo() == 0)
10769 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10771 case ARMISD::CMOV: {
10772 // Bits are known zero/one if known on the LHS and RHS.
10773 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10774 if (KnownZero == 0 && KnownOne == 0) return;
10776 APInt KnownZeroRHS, KnownOneRHS;
10777 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10778 KnownZero &= KnownZeroRHS;
10779 KnownOne &= KnownOneRHS;
10782 case ISD::INTRINSIC_W_CHAIN: {
10783 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10784 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10787 case Intrinsic::arm_ldaex:
10788 case Intrinsic::arm_ldrex: {
10789 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10790 unsigned MemBits = VT.getScalarType().getSizeInBits();
10791 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10799 //===----------------------------------------------------------------------===//
10800 // ARM Inline Assembly Support
10801 //===----------------------------------------------------------------------===//
10803 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10804 // Looking for "rev" which is V6+.
10805 if (!Subtarget->hasV6Ops())
10808 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10809 std::string AsmStr = IA->getAsmString();
10810 SmallVector<StringRef, 4> AsmPieces;
10811 SplitString(AsmStr, AsmPieces, ";\n");
10813 switch (AsmPieces.size()) {
10814 default: return false;
10816 AsmStr = AsmPieces[0];
10818 SplitString(AsmStr, AsmPieces, " \t,");
10821 if (AsmPieces.size() == 3 &&
10822 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10823 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10824 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10825 if (Ty && Ty->getBitWidth() == 32)
10826 return IntrinsicLowering::LowerToByteSwap(CI);
10834 /// getConstraintType - Given a constraint letter, return the type of
10835 /// constraint it is for this target.
10836 ARMTargetLowering::ConstraintType
10837 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10838 if (Constraint.size() == 1) {
10839 switch (Constraint[0]) {
10841 case 'l': return C_RegisterClass;
10842 case 'w': return C_RegisterClass;
10843 case 'h': return C_RegisterClass;
10844 case 'x': return C_RegisterClass;
10845 case 't': return C_RegisterClass;
10846 case 'j': return C_Other; // Constant for movw.
10847 // An address with a single base register. Due to the way we
10848 // currently handle addresses it is the same as an 'r' memory constraint.
10849 case 'Q': return C_Memory;
10851 } else if (Constraint.size() == 2) {
10852 switch (Constraint[0]) {
10854 // All 'U+' constraints are addresses.
10855 case 'U': return C_Memory;
10858 return TargetLowering::getConstraintType(Constraint);
10861 /// Examine constraint type and operand type and determine a weight value.
10862 /// This object must already have been set up with the operand type
10863 /// and the current alternative constraint selected.
10864 TargetLowering::ConstraintWeight
10865 ARMTargetLowering::getSingleConstraintMatchWeight(
10866 AsmOperandInfo &info, const char *constraint) const {
10867 ConstraintWeight weight = CW_Invalid;
10868 Value *CallOperandVal = info.CallOperandVal;
10869 // If we don't have a value, we can't do a match,
10870 // but allow it at the lowest weight.
10871 if (!CallOperandVal)
10873 Type *type = CallOperandVal->getType();
10874 // Look at the constraint type.
10875 switch (*constraint) {
10877 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10880 if (type->isIntegerTy()) {
10881 if (Subtarget->isThumb())
10882 weight = CW_SpecificReg;
10884 weight = CW_Register;
10888 if (type->isFloatingPointTy())
10889 weight = CW_Register;
10895 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10896 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10897 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10898 if (Constraint.size() == 1) {
10899 // GCC ARM Constraint Letters
10900 switch (Constraint[0]) {
10901 case 'l': // Low regs or general regs.
10902 if (Subtarget->isThumb())
10903 return RCPair(0U, &ARM::tGPRRegClass);
10904 return RCPair(0U, &ARM::GPRRegClass);
10905 case 'h': // High regs or no regs.
10906 if (Subtarget->isThumb())
10907 return RCPair(0U, &ARM::hGPRRegClass);
10910 if (Subtarget->isThumb1Only())
10911 return RCPair(0U, &ARM::tGPRRegClass);
10912 return RCPair(0U, &ARM::GPRRegClass);
10914 if (VT == MVT::Other)
10916 if (VT == MVT::f32)
10917 return RCPair(0U, &ARM::SPRRegClass);
10918 if (VT.getSizeInBits() == 64)
10919 return RCPair(0U, &ARM::DPRRegClass);
10920 if (VT.getSizeInBits() == 128)
10921 return RCPair(0U, &ARM::QPRRegClass);
10924 if (VT == MVT::Other)
10926 if (VT == MVT::f32)
10927 return RCPair(0U, &ARM::SPR_8RegClass);
10928 if (VT.getSizeInBits() == 64)
10929 return RCPair(0U, &ARM::DPR_8RegClass);
10930 if (VT.getSizeInBits() == 128)
10931 return RCPair(0U, &ARM::QPR_8RegClass);
10934 if (VT == MVT::f32)
10935 return RCPair(0U, &ARM::SPRRegClass);
10939 if (StringRef("{cc}").equals_lower(Constraint))
10940 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10942 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10945 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10946 /// vector. If it is invalid, don't add anything to Ops.
10947 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10948 std::string &Constraint,
10949 std::vector<SDValue>&Ops,
10950 SelectionDAG &DAG) const {
10953 // Currently only support length 1 constraints.
10954 if (Constraint.length() != 1) return;
10956 char ConstraintLetter = Constraint[0];
10957 switch (ConstraintLetter) {
10960 case 'I': case 'J': case 'K': case 'L':
10961 case 'M': case 'N': case 'O':
10962 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10966 int64_t CVal64 = C->getSExtValue();
10967 int CVal = (int) CVal64;
10968 // None of these constraints allow values larger than 32 bits. Check
10969 // that the value fits in an int.
10970 if (CVal != CVal64)
10973 switch (ConstraintLetter) {
10975 // Constant suitable for movw, must be between 0 and
10977 if (Subtarget->hasV6T2Ops())
10978 if (CVal >= 0 && CVal <= 65535)
10982 if (Subtarget->isThumb1Only()) {
10983 // This must be a constant between 0 and 255, for ADD
10985 if (CVal >= 0 && CVal <= 255)
10987 } else if (Subtarget->isThumb2()) {
10988 // A constant that can be used as an immediate value in a
10989 // data-processing instruction.
10990 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10993 // A constant that can be used as an immediate value in a
10994 // data-processing instruction.
10995 if (ARM_AM::getSOImmVal(CVal) != -1)
11001 if (Subtarget->isThumb()) { // FIXME thumb2
11002 // This must be a constant between -255 and -1, for negated ADD
11003 // immediates. This can be used in GCC with an "n" modifier that
11004 // prints the negated value, for use with SUB instructions. It is
11005 // not useful otherwise but is implemented for compatibility.
11006 if (CVal >= -255 && CVal <= -1)
11009 // This must be a constant between -4095 and 4095. It is not clear
11010 // what this constraint is intended for. Implemented for
11011 // compatibility with GCC.
11012 if (CVal >= -4095 && CVal <= 4095)
11018 if (Subtarget->isThumb1Only()) {
11019 // A 32-bit value where only one byte has a nonzero value. Exclude
11020 // zero to match GCC. This constraint is used by GCC internally for
11021 // constants that can be loaded with a move/shift combination.
11022 // It is not useful otherwise but is implemented for compatibility.
11023 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11025 } else if (Subtarget->isThumb2()) {
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::getT2SOImmVal(~CVal) != -1)
11034 // A constant whose bitwise inverse can be used as an immediate
11035 // value in a data-processing instruction. This can be used in GCC
11036 // with a "B" modifier that prints the inverted value, for use with
11037 // BIC and MVN instructions. It is not useful otherwise but is
11038 // implemented for compatibility.
11039 if (ARM_AM::getSOImmVal(~CVal) != -1)
11045 if (Subtarget->isThumb1Only()) {
11046 // This must be a constant between -7 and 7,
11047 // for 3-operand ADD/SUB immediate instructions.
11048 if (CVal >= -7 && CVal < 7)
11050 } else if (Subtarget->isThumb2()) {
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::getT2SOImmVal(-CVal) != -1)
11059 // A constant whose negation can be used as an immediate value in a
11060 // data-processing instruction. This can be used in GCC with an "n"
11061 // modifier that prints the negated value, for use with SUB
11062 // instructions. It is not useful otherwise but is implemented for
11064 if (ARM_AM::getSOImmVal(-CVal) != -1)
11070 if (Subtarget->isThumb()) { // FIXME thumb2
11071 // This must be a multiple of 4 between 0 and 1020, for
11072 // ADD sp + immediate.
11073 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11076 // A power of two or a constant between 0 and 32. This is used in
11077 // GCC for the shift amount on shifted register operands, but it is
11078 // useful in general for any shift amounts.
11079 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11085 if (Subtarget->isThumb()) { // FIXME thumb2
11086 // This must be a constant between 0 and 31, for shift amounts.
11087 if (CVal >= 0 && CVal <= 31)
11093 if (Subtarget->isThumb()) { // FIXME thumb2
11094 // This must be a multiple of 4 between -508 and 508, for
11095 // ADD/SUB sp = sp + immediate.
11096 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11101 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11105 if (Result.getNode()) {
11106 Ops.push_back(Result);
11109 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11112 static RTLIB::Libcall getDivRemLibcall(
11113 const SDNode *N, MVT::SimpleValueType SVT) {
11114 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11115 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11116 "Unhandled Opcode in getDivRemLibcall");
11117 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11118 N->getOpcode() == ISD::SREM;
11121 default: llvm_unreachable("Unexpected request for libcall!");
11122 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11123 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11124 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11125 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11130 static TargetLowering::ArgListTy getDivRemArgList(
11131 const SDNode *N, LLVMContext *Context) {
11132 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11133 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11134 "Unhandled Opcode in getDivRemArgList");
11135 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11136 N->getOpcode() == ISD::SREM;
11137 TargetLowering::ArgListTy Args;
11138 TargetLowering::ArgListEntry Entry;
11139 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11140 EVT ArgVT = N->getOperand(i).getValueType();
11141 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11142 Entry.Node = N->getOperand(i);
11144 Entry.isSExt = isSigned;
11145 Entry.isZExt = !isSigned;
11146 Args.push_back(Entry);
11151 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11152 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11153 "Register-based DivRem lowering only");
11154 unsigned Opcode = Op->getOpcode();
11155 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11156 "Invalid opcode for Div/Rem lowering");
11157 bool isSigned = (Opcode == ISD::SDIVREM);
11158 EVT VT = Op->getValueType(0);
11159 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11161 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11162 VT.getSimpleVT().SimpleTy);
11163 SDValue InChain = DAG.getEntryNode();
11165 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11168 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11169 getPointerTy(DAG.getDataLayout()));
11171 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11174 TargetLowering::CallLoweringInfo CLI(DAG);
11175 CLI.setDebugLoc(dl).setChain(InChain)
11176 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11177 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11179 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11180 return CallInfo.first;
11183 // Lowers REM using divmod helpers
11184 // see RTABI section 4.2/4.3
11185 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11186 // Build return types (div and rem)
11187 std::vector<Type*> RetTyParams;
11188 Type *RetTyElement;
11190 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11191 default: llvm_unreachable("Unexpected request for libcall!");
11192 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11193 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11194 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11195 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11198 RetTyParams.push_back(RetTyElement);
11199 RetTyParams.push_back(RetTyElement);
11200 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11201 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11203 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11205 SDValue InChain = DAG.getEntryNode();
11206 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11207 bool isSigned = N->getOpcode() == ISD::SREM;
11208 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11209 getPointerTy(DAG.getDataLayout()));
11212 CallLoweringInfo CLI(DAG);
11213 CLI.setChain(InChain)
11214 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11215 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11216 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11218 // Return second (rem) result operand (first contains div)
11219 SDNode *ResNode = CallResult.first.getNode();
11220 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11221 return ResNode->getOperand(1);
11225 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11226 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11230 SDValue Chain = Op.getOperand(0);
11231 SDValue Size = Op.getOperand(1);
11233 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11234 DAG.getConstant(2, DL, MVT::i32));
11237 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11238 Flag = Chain.getValue(1);
11240 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11241 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11243 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11244 Chain = NewSP.getValue(1);
11246 SDValue Ops[2] = { NewSP, Chain };
11247 return DAG.getMergeValues(Ops, DL);
11250 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11251 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11252 "Unexpected type for custom-lowering FP_EXTEND");
11255 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11257 SDValue SrcVal = Op.getOperand(0);
11258 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11259 /*isSigned*/ false, SDLoc(Op)).first;
11262 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11263 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11264 Subtarget->isFPOnlySP() &&
11265 "Unexpected type for custom-lowering FP_ROUND");
11268 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11270 SDValue SrcVal = Op.getOperand(0);
11271 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11272 /*isSigned*/ false, SDLoc(Op)).first;
11276 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11277 // The ARM target isn't yet aware of offsets.
11281 bool ARM::isBitFieldInvertedMask(unsigned v) {
11282 if (v == 0xffffffff)
11285 // there can be 1's on either or both "outsides", all the "inside"
11286 // bits must be 0's
11287 return isShiftedMask_32(~v);
11290 /// isFPImmLegal - Returns true if the target can instruction select the
11291 /// specified FP immediate natively. If false, the legalizer will
11292 /// materialize the FP immediate as a load from a constant pool.
11293 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11294 if (!Subtarget->hasVFP3())
11296 if (VT == MVT::f32)
11297 return ARM_AM::getFP32Imm(Imm) != -1;
11298 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11299 return ARM_AM::getFP64Imm(Imm) != -1;
11303 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11304 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11305 /// specified in the intrinsic calls.
11306 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11308 unsigned Intrinsic) const {
11309 switch (Intrinsic) {
11310 case Intrinsic::arm_neon_vld1:
11311 case Intrinsic::arm_neon_vld2:
11312 case Intrinsic::arm_neon_vld3:
11313 case Intrinsic::arm_neon_vld4:
11314 case Intrinsic::arm_neon_vld2lane:
11315 case Intrinsic::arm_neon_vld3lane:
11316 case Intrinsic::arm_neon_vld4lane: {
11317 Info.opc = ISD::INTRINSIC_W_CHAIN;
11318 // Conservatively set memVT to the entire set of vectors loaded.
11319 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11320 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11321 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11322 Info.ptrVal = I.getArgOperand(0);
11324 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11325 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11326 Info.vol = false; // volatile loads with NEON intrinsics not supported
11327 Info.readMem = true;
11328 Info.writeMem = false;
11331 case Intrinsic::arm_neon_vst1:
11332 case Intrinsic::arm_neon_vst2:
11333 case Intrinsic::arm_neon_vst3:
11334 case Intrinsic::arm_neon_vst4:
11335 case Intrinsic::arm_neon_vst2lane:
11336 case Intrinsic::arm_neon_vst3lane:
11337 case Intrinsic::arm_neon_vst4lane: {
11338 Info.opc = ISD::INTRINSIC_VOID;
11339 // Conservatively set memVT to the entire set of vectors stored.
11340 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11341 unsigned NumElts = 0;
11342 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11343 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11344 if (!ArgTy->isVectorTy())
11346 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11348 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11349 Info.ptrVal = I.getArgOperand(0);
11351 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11352 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11353 Info.vol = false; // volatile stores with NEON intrinsics not supported
11354 Info.readMem = false;
11355 Info.writeMem = true;
11358 case Intrinsic::arm_ldaex:
11359 case Intrinsic::arm_ldrex: {
11360 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11361 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11362 Info.opc = ISD::INTRINSIC_W_CHAIN;
11363 Info.memVT = MVT::getVT(PtrTy->getElementType());
11364 Info.ptrVal = I.getArgOperand(0);
11366 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11368 Info.readMem = true;
11369 Info.writeMem = false;
11372 case Intrinsic::arm_stlex:
11373 case Intrinsic::arm_strex: {
11374 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11375 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11376 Info.opc = ISD::INTRINSIC_W_CHAIN;
11377 Info.memVT = MVT::getVT(PtrTy->getElementType());
11378 Info.ptrVal = I.getArgOperand(1);
11380 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11382 Info.readMem = false;
11383 Info.writeMem = true;
11386 case Intrinsic::arm_stlexd:
11387 case Intrinsic::arm_strexd: {
11388 Info.opc = ISD::INTRINSIC_W_CHAIN;
11389 Info.memVT = MVT::i64;
11390 Info.ptrVal = I.getArgOperand(2);
11394 Info.readMem = false;
11395 Info.writeMem = true;
11398 case Intrinsic::arm_ldaexd:
11399 case Intrinsic::arm_ldrexd: {
11400 Info.opc = ISD::INTRINSIC_W_CHAIN;
11401 Info.memVT = MVT::i64;
11402 Info.ptrVal = I.getArgOperand(0);
11406 Info.readMem = true;
11407 Info.writeMem = false;
11417 /// \brief Returns true if it is beneficial to convert a load of a constant
11418 /// to just the constant itself.
11419 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11421 assert(Ty->isIntegerTy());
11423 unsigned Bits = Ty->getPrimitiveSizeInBits();
11424 if (Bits == 0 || Bits > 32)
11429 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11431 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11432 ARM_MB::MemBOpt Domain) const {
11433 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11435 // First, if the target has no DMB, see what fallback we can use.
11436 if (!Subtarget->hasDataBarrier()) {
11437 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11438 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11440 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11441 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11442 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11443 Builder.getInt32(0), Builder.getInt32(7),
11444 Builder.getInt32(10), Builder.getInt32(5)};
11445 return Builder.CreateCall(MCR, args);
11447 // Instead of using barriers, atomic accesses on these subtargets use
11449 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11452 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11453 // Only a full system barrier exists in the M-class architectures.
11454 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11455 Constant *CDomain = Builder.getInt32(Domain);
11456 return Builder.CreateCall(DMB, CDomain);
11460 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11461 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11462 AtomicOrdering Ord, bool IsStore,
11463 bool IsLoad) const {
11464 if (!getInsertFencesForAtomic())
11470 llvm_unreachable("Invalid fence: unordered/non-atomic");
11473 return nullptr; // Nothing to do
11474 case SequentiallyConsistent:
11476 return nullptr; // Nothing to do
11479 case AcquireRelease:
11480 if (Subtarget->isSwift())
11481 return makeDMB(Builder, ARM_MB::ISHST);
11482 // FIXME: add a comment with a link to documentation justifying this.
11484 return makeDMB(Builder, ARM_MB::ISH);
11486 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11489 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11490 AtomicOrdering Ord, bool IsStore,
11491 bool IsLoad) const {
11492 if (!getInsertFencesForAtomic())
11498 llvm_unreachable("Invalid fence: unordered/not-atomic");
11501 return nullptr; // Nothing to do
11503 case AcquireRelease:
11504 case SequentiallyConsistent:
11505 return makeDMB(Builder, ARM_MB::ISH);
11507 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11510 // Loads and stores less than 64-bits are already atomic; ones above that
11511 // are doomed anyway, so defer to the default libcall and blame the OS when
11512 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11513 // anything for those.
11514 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11515 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11516 return (Size == 64) && !Subtarget->isMClass();
11519 // Loads and stores less than 64-bits are already atomic; ones above that
11520 // are doomed anyway, so defer to the default libcall and blame the OS when
11521 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11522 // anything for those.
11523 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11524 // guarantee, see DDI0406C ARM architecture reference manual,
11525 // sections A8.8.72-74 LDRD)
11526 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11527 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11528 return (Size == 64) && !Subtarget->isMClass();
11531 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11532 // and up to 64 bits on the non-M profiles
11533 TargetLoweringBase::AtomicRMWExpansionKind
11534 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11535 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11536 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11537 ? AtomicRMWExpansionKind::LLSC
11538 : AtomicRMWExpansionKind::None;
11541 // This has so far only been implemented for MachO.
11542 bool ARMTargetLowering::useLoadStackGuardNode() const {
11543 return Subtarget->isTargetMachO();
11546 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11547 unsigned &Cost) const {
11548 // If we do not have NEON, vector types are not natively supported.
11549 if (!Subtarget->hasNEON())
11552 // Floating point values and vector values map to the same register file.
11553 // Therefore, although we could do a store extract of a vector type, this is
11554 // better to leave at float as we have more freedom in the addressing mode for
11556 if (VectorTy->isFPOrFPVectorTy())
11559 // If the index is unknown at compile time, this is very expensive to lower
11560 // and it is not possible to combine the store with the extract.
11561 if (!isa<ConstantInt>(Idx))
11564 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11565 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11566 // We can do a store + vector extract on any vector that fits perfectly in a D
11568 if (BitWidth == 64 || BitWidth == 128) {
11575 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11576 AtomicOrdering Ord) const {
11577 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11578 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11579 bool IsAcquire = isAtLeastAcquire(Ord);
11581 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11582 // intrinsic must return {i32, i32} and we have to recombine them into a
11583 // single i64 here.
11584 if (ValTy->getPrimitiveSizeInBits() == 64) {
11585 Intrinsic::ID Int =
11586 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11587 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11589 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11590 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11592 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11593 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11594 if (!Subtarget->isLittle())
11595 std::swap (Lo, Hi);
11596 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11597 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11598 return Builder.CreateOr(
11599 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11602 Type *Tys[] = { Addr->getType() };
11603 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11604 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11606 return Builder.CreateTruncOrBitCast(
11607 Builder.CreateCall(Ldrex, Addr),
11608 cast<PointerType>(Addr->getType())->getElementType());
11611 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11613 AtomicOrdering Ord) const {
11614 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11615 bool IsRelease = isAtLeastRelease(Ord);
11617 // Since the intrinsics must have legal type, the i64 intrinsics take two
11618 // parameters: "i32, i32". We must marshal Val into the appropriate form
11619 // before the call.
11620 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11621 Intrinsic::ID Int =
11622 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11623 Function *Strex = Intrinsic::getDeclaration(M, Int);
11624 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11626 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11627 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11628 if (!Subtarget->isLittle())
11629 std::swap (Lo, Hi);
11630 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11631 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11634 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11635 Type *Tys[] = { Addr->getType() };
11636 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11638 return Builder.CreateCall(
11639 Strex, {Builder.CreateZExtOrBitCast(
11640 Val, Strex->getFunctionType()->getParamType(0)),
11644 /// \brief Lower an interleaved load into a vldN intrinsic.
11646 /// E.g. Lower an interleaved load (Factor = 2):
11647 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11648 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11649 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11652 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11653 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11654 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11655 bool ARMTargetLowering::lowerInterleavedLoad(
11656 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11657 ArrayRef<unsigned> Indices, unsigned Factor) const {
11658 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11659 "Invalid interleave factor");
11660 assert(!Shuffles.empty() && "Empty shufflevector input");
11661 assert(Shuffles.size() == Indices.size() &&
11662 "Unmatched number of shufflevectors and indices");
11664 VectorType *VecTy = Shuffles[0]->getType();
11665 Type *EltTy = VecTy->getVectorElementType();
11667 const DataLayout &DL = LI->getModule()->getDataLayout();
11668 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11669 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11671 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11672 // support i64/f64 element).
11673 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11676 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11677 // load integer vectors first and then convert to pointer vectors.
11678 if (EltTy->isPointerTy())
11680 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11682 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11683 Intrinsic::arm_neon_vld3,
11684 Intrinsic::arm_neon_vld4};
11686 Function *VldnFunc =
11687 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11689 IRBuilder<> Builder(LI);
11690 SmallVector<Value *, 2> Ops;
11692 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11693 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11694 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11696 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11698 // Replace uses of each shufflevector with the corresponding vector loaded
11700 for (unsigned i = 0; i < Shuffles.size(); i++) {
11701 ShuffleVectorInst *SV = Shuffles[i];
11702 unsigned Index = Indices[i];
11704 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11706 // Convert the integer vector to pointer vector if the element is pointer.
11707 if (EltTy->isPointerTy())
11708 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11710 SV->replaceAllUsesWith(SubVec);
11716 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11718 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11719 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11720 unsigned NumElts) {
11721 SmallVector<Constant *, 16> Mask;
11722 for (unsigned i = 0; i < NumElts; i++)
11723 Mask.push_back(Builder.getInt32(Start + i));
11725 return ConstantVector::get(Mask);
11728 /// \brief Lower an interleaved store into a vstN intrinsic.
11730 /// E.g. Lower an interleaved store (Factor = 3):
11731 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11732 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11733 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11736 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11737 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11738 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11739 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11741 /// Note that the new shufflevectors will be removed and we'll only generate one
11742 /// vst3 instruction in CodeGen.
11743 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11744 ShuffleVectorInst *SVI,
11745 unsigned Factor) const {
11746 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11747 "Invalid interleave factor");
11749 VectorType *VecTy = SVI->getType();
11750 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11751 "Invalid interleaved store");
11753 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11754 Type *EltTy = VecTy->getVectorElementType();
11755 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11757 const DataLayout &DL = SI->getModule()->getDataLayout();
11758 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11759 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11761 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11762 // doesn't support i64/f64 element).
11763 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11766 Value *Op0 = SVI->getOperand(0);
11767 Value *Op1 = SVI->getOperand(1);
11768 IRBuilder<> Builder(SI);
11770 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11771 // vectors to integer vectors.
11772 if (EltTy->isPointerTy()) {
11773 Type *IntTy = DL.getIntPtrType(EltTy);
11775 // Convert to the corresponding integer vector.
11777 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11778 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11779 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11781 SubVecTy = VectorType::get(IntTy, NumSubElts);
11784 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11785 Intrinsic::arm_neon_vst3,
11786 Intrinsic::arm_neon_vst4};
11787 Function *VstNFunc = Intrinsic::getDeclaration(
11788 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11790 SmallVector<Value *, 6> Ops;
11792 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11793 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11795 // Split the shufflevector operands into sub vectors for the new vstN call.
11796 for (unsigned i = 0; i < Factor; i++)
11797 Ops.push_back(Builder.CreateShuffleVector(
11798 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11800 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11801 Builder.CreateCall(VstNFunc, Ops);
11813 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11814 uint64_t &Members) {
11815 if (auto *ST = dyn_cast<StructType>(Ty)) {
11816 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11817 uint64_t SubMembers = 0;
11818 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11820 Members += SubMembers;
11822 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11823 uint64_t SubMembers = 0;
11824 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11826 Members += SubMembers * AT->getNumElements();
11827 } else if (Ty->isFloatTy()) {
11828 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11832 } else if (Ty->isDoubleTy()) {
11833 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11837 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11844 return VT->getBitWidth() == 64;
11846 return VT->getBitWidth() == 128;
11848 switch (VT->getBitWidth()) {
11861 return (Members > 0 && Members <= 4);
11864 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11865 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11866 /// passing according to AAPCS rules.
11867 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11868 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11869 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11870 CallingConv::ARM_AAPCS_VFP)
11873 HABaseType Base = HA_UNKNOWN;
11874 uint64_t Members = 0;
11875 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11876 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11878 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11879 return IsHA || IsIntArray;