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 },
373 for (const auto &LC : LibraryCalls) {
374 setLibcallName(LC.Op, LC.Name);
375 setLibcallCallingConv(LC.Op, LC.CC);
379 // Use divmod compiler-rt calls for iOS 5.0 and later.
380 if (Subtarget->getTargetTriple().isiOS() &&
381 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
386 // The half <-> float conversion functions are always soft-float, but are
387 // needed for some targets which use a hard-float calling convention by
389 if (Subtarget->isAAPCS_ABI()) {
390 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
399 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
400 // a __gnu_ prefix (which is the default).
401 if (Subtarget->isTargetAEABI()) {
402 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
403 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
404 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f");
407 if (Subtarget->isThumb1Only())
408 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
410 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
411 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
412 !Subtarget->isThumb1Only()) {
413 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
414 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
417 for (MVT VT : MVT::vector_valuetypes()) {
418 for (MVT InnerVT : MVT::vector_valuetypes()) {
419 setTruncStoreAction(VT, InnerVT, Expand);
420 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
421 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
422 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
425 setOperationAction(ISD::MULHS, VT, Expand);
426 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
427 setOperationAction(ISD::MULHU, VT, Expand);
428 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
430 setOperationAction(ISD::BSWAP, VT, Expand);
433 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
436 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
437 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
439 if (Subtarget->hasNEON()) {
440 addDRTypeForNEON(MVT::v2f32);
441 addDRTypeForNEON(MVT::v8i8);
442 addDRTypeForNEON(MVT::v4i16);
443 addDRTypeForNEON(MVT::v2i32);
444 addDRTypeForNEON(MVT::v1i64);
446 addQRTypeForNEON(MVT::v4f32);
447 addQRTypeForNEON(MVT::v2f64);
448 addQRTypeForNEON(MVT::v16i8);
449 addQRTypeForNEON(MVT::v8i16);
450 addQRTypeForNEON(MVT::v4i32);
451 addQRTypeForNEON(MVT::v2i64);
453 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
454 // neither Neon nor VFP support any arithmetic operations on it.
455 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
456 // supported for v4f32.
457 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
458 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
459 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
460 // FIXME: Code duplication: FDIV and FREM are expanded always, see
461 // ARMTargetLowering::addTypeForNEON method for details.
462 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
463 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
464 // FIXME: Create unittest.
465 // In another words, find a way when "copysign" appears in DAG with vector
467 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
468 // FIXME: Code duplication: SETCC has custom operation action, see
469 // ARMTargetLowering::addTypeForNEON method for details.
470 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
471 // FIXME: Create unittest for FNEG and for FABS.
472 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
473 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
474 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
475 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
476 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
477 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
478 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
479 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
480 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
481 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
482 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
483 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
484 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
485 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
486 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
487 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
488 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
489 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
490 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
493 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
494 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
495 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
496 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
497 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
498 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
499 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
500 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
501 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
502 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
503 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
504 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
505 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
506 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
508 // Mark v2f32 intrinsics.
509 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
510 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
511 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
512 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
513 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
514 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
515 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
516 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
517 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
518 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
519 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
520 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
521 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
522 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
523 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
525 // Neon does not support some operations on v1i64 and v2i64 types.
526 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
527 // Custom handling for some quad-vector types to detect VMULL.
528 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
529 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
530 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
531 // Custom handling for some vector types to avoid expensive expansions
532 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
533 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
534 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
535 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
536 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
537 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
538 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
539 // a destination type that is wider than the source, and nor does
540 // it have a FP_TO_[SU]INT instruction with a narrower destination than
542 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
543 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
544 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
545 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
547 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
548 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
550 // NEON does not have single instruction CTPOP for vectors with element
551 // types wider than 8-bits. However, custom lowering can leverage the
552 // v8i8/v16i8 vcnt instruction.
553 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
554 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
555 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
556 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
558 // NEON does not have single instruction CTTZ for vectors.
559 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
560 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
561 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
562 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
564 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
565 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
566 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
567 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
570 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
571 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
572 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
574 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
575 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
576 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
577 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
579 // NEON only has FMA instructions as of VFP4.
580 if (!Subtarget->hasVFP4()) {
581 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
582 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
585 setTargetDAGCombine(ISD::INTRINSIC_VOID);
586 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
587 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
588 setTargetDAGCombine(ISD::SHL);
589 setTargetDAGCombine(ISD::SRL);
590 setTargetDAGCombine(ISD::SRA);
591 setTargetDAGCombine(ISD::SIGN_EXTEND);
592 setTargetDAGCombine(ISD::ZERO_EXTEND);
593 setTargetDAGCombine(ISD::ANY_EXTEND);
594 setTargetDAGCombine(ISD::BUILD_VECTOR);
595 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597 setTargetDAGCombine(ISD::STORE);
598 setTargetDAGCombine(ISD::FP_TO_SINT);
599 setTargetDAGCombine(ISD::FP_TO_UINT);
600 setTargetDAGCombine(ISD::FDIV);
601 setTargetDAGCombine(ISD::LOAD);
603 // It is legal to extload from v4i8 to v4i16 or v4i32.
604 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
606 for (MVT VT : MVT::integer_vector_valuetypes()) {
607 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
608 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
609 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
614 // ARM and Thumb2 support UMLAL/SMLAL.
615 if (!Subtarget->isThumb1Only())
616 setTargetDAGCombine(ISD::ADDC);
618 if (Subtarget->isFPOnlySP()) {
619 // When targeting a floating-point unit with only single-precision
620 // operations, f64 is legal for the few double-precision instructions which
621 // are present However, no double-precision operations other than moves,
622 // loads and stores are provided by the hardware.
623 setOperationAction(ISD::FADD, MVT::f64, Expand);
624 setOperationAction(ISD::FSUB, MVT::f64, Expand);
625 setOperationAction(ISD::FMUL, MVT::f64, Expand);
626 setOperationAction(ISD::FMA, MVT::f64, Expand);
627 setOperationAction(ISD::FDIV, MVT::f64, Expand);
628 setOperationAction(ISD::FREM, MVT::f64, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
630 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
631 setOperationAction(ISD::FNEG, MVT::f64, Expand);
632 setOperationAction(ISD::FABS, MVT::f64, Expand);
633 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
634 setOperationAction(ISD::FSIN, MVT::f64, Expand);
635 setOperationAction(ISD::FCOS, MVT::f64, Expand);
636 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
637 setOperationAction(ISD::FPOW, MVT::f64, Expand);
638 setOperationAction(ISD::FLOG, MVT::f64, Expand);
639 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
640 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
641 setOperationAction(ISD::FEXP, MVT::f64, Expand);
642 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
643 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
644 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
645 setOperationAction(ISD::FRINT, MVT::f64, Expand);
646 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
647 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
648 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
649 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
650 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
651 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
652 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
653 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
654 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
655 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
658 computeRegisterProperties(Subtarget->getRegisterInfo());
660 // ARM does not have floating-point extending loads.
661 for (MVT VT : MVT::fp_valuetypes()) {
662 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
663 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
666 // ... or truncating stores
667 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
668 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
669 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
671 // ARM does not have i1 sign extending load.
672 for (MVT VT : MVT::integer_valuetypes())
673 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
675 // ARM supports all 4 flavors of integer indexed load / store.
676 if (!Subtarget->isThumb1Only()) {
677 for (unsigned im = (unsigned)ISD::PRE_INC;
678 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
679 setIndexedLoadAction(im, MVT::i1, Legal);
680 setIndexedLoadAction(im, MVT::i8, Legal);
681 setIndexedLoadAction(im, MVT::i16, Legal);
682 setIndexedLoadAction(im, MVT::i32, Legal);
683 setIndexedStoreAction(im, MVT::i1, Legal);
684 setIndexedStoreAction(im, MVT::i8, Legal);
685 setIndexedStoreAction(im, MVT::i16, Legal);
686 setIndexedStoreAction(im, MVT::i32, Legal);
690 setOperationAction(ISD::SADDO, MVT::i32, Custom);
691 setOperationAction(ISD::UADDO, MVT::i32, Custom);
692 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
693 setOperationAction(ISD::USUBO, MVT::i32, Custom);
695 // i64 operation support.
696 setOperationAction(ISD::MUL, MVT::i64, Expand);
697 setOperationAction(ISD::MULHU, MVT::i32, Expand);
698 if (Subtarget->isThumb1Only()) {
699 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
700 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
702 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
703 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
704 setOperationAction(ISD::MULHS, MVT::i32, Expand);
706 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
707 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
708 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
709 setOperationAction(ISD::SRL, MVT::i64, Custom);
710 setOperationAction(ISD::SRA, MVT::i64, Custom);
712 if (!Subtarget->isThumb1Only()) {
713 // FIXME: We should do this for Thumb1 as well.
714 setOperationAction(ISD::ADDC, MVT::i32, Custom);
715 setOperationAction(ISD::ADDE, MVT::i32, Custom);
716 setOperationAction(ISD::SUBC, MVT::i32, Custom);
717 setOperationAction(ISD::SUBE, MVT::i32, Custom);
720 // ARM does not have ROTL.
721 setOperationAction(ISD::ROTL, MVT::i32, Expand);
722 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
723 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
724 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
725 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
727 // These just redirect to CTTZ and CTLZ on ARM.
728 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
729 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
731 // @llvm.readcyclecounter requires the Performance Monitors extension.
732 // Default to the 0 expansion on unsupported platforms.
733 // FIXME: Technically there are older ARM CPUs that have
734 // implementation-specific ways of obtaining this information.
735 if (Subtarget->hasPerfMon())
736 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
738 // Only ARMv6 has BSWAP.
739 if (!Subtarget->hasV6Ops())
740 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
742 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
743 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
744 // These are expanded into libcalls if the cpu doesn't have HW divider.
745 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
746 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
749 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
750 setOperationAction(ISD::SDIV, MVT::i32, Custom);
751 setOperationAction(ISD::UDIV, MVT::i32, Custom);
753 setOperationAction(ISD::SDIV, MVT::i64, Custom);
754 setOperationAction(ISD::UDIV, MVT::i64, Custom);
757 setOperationAction(ISD::SREM, MVT::i32, Expand);
758 setOperationAction(ISD::UREM, MVT::i32, Expand);
759 // Register based DivRem for AEABI (RTABI 4.2)
760 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
761 setOperationAction(ISD::SREM, MVT::i64, Custom);
762 setOperationAction(ISD::UREM, MVT::i64, Custom);
764 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
765 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
766 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
767 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
768 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
769 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
770 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
771 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
773 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
774 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
775 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
776 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
777 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
778 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
779 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
780 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
782 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
783 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
785 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
786 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
789 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
790 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
791 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
792 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
794 setOperationAction(ISD::TRAP, MVT::Other, Legal);
796 // Use the default implementation.
797 setOperationAction(ISD::VASTART, MVT::Other, Custom);
798 setOperationAction(ISD::VAARG, MVT::Other, Expand);
799 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
800 setOperationAction(ISD::VAEND, MVT::Other, Expand);
801 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
802 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
804 if (!Subtarget->isTargetMachO()) {
805 // Non-MachO platforms may return values in these registers via the
806 // personality function.
807 setExceptionPointerRegister(ARM::R0);
808 setExceptionSelectorRegister(ARM::R1);
811 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
812 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
814 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
816 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
817 // the default expansion. If we are targeting a single threaded system,
818 // then set them all for expand so we can lower them later into their
820 if (TM.Options.ThreadModel == ThreadModel::Single)
821 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
822 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
823 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
824 // to ldrex/strex loops already.
825 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
827 // On v8, we have particularly efficient implementations of atomic fences
828 // if they can be combined with nearby atomic loads and stores.
829 if (!Subtarget->hasV8Ops()) {
830 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
831 setInsertFencesForAtomic(true);
834 // If there's anything we can use as a barrier, go through custom lowering
836 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
837 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
839 // Set them all for expansion, which will force libcalls.
840 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
841 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
842 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
843 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
844 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
845 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
846 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
847 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
848 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
849 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
850 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
851 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
852 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
853 // Unordered/Monotonic case.
854 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
855 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
858 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
860 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
861 if (!Subtarget->hasV6Ops()) {
862 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
863 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
865 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
867 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
868 !Subtarget->isThumb1Only()) {
869 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
870 // iff target supports vfp2.
871 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
872 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
875 // We want to custom lower some of our intrinsics.
876 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
877 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
878 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
879 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
880 if (Subtarget->isTargetDarwin())
881 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
883 setOperationAction(ISD::SETCC, MVT::i32, Expand);
884 setOperationAction(ISD::SETCC, MVT::f32, Expand);
885 setOperationAction(ISD::SETCC, MVT::f64, Expand);
886 setOperationAction(ISD::SELECT, MVT::i32, Custom);
887 setOperationAction(ISD::SELECT, MVT::f32, Custom);
888 setOperationAction(ISD::SELECT, MVT::f64, Custom);
889 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
890 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
891 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
893 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
894 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
895 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
896 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
897 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
899 // We don't support sin/cos/fmod/copysign/pow
900 setOperationAction(ISD::FSIN, MVT::f64, Expand);
901 setOperationAction(ISD::FSIN, MVT::f32, Expand);
902 setOperationAction(ISD::FCOS, MVT::f32, Expand);
903 setOperationAction(ISD::FCOS, MVT::f64, Expand);
904 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
905 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
906 setOperationAction(ISD::FREM, MVT::f64, Expand);
907 setOperationAction(ISD::FREM, MVT::f32, Expand);
908 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
909 !Subtarget->isThumb1Only()) {
910 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
911 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
913 setOperationAction(ISD::FPOW, MVT::f64, Expand);
914 setOperationAction(ISD::FPOW, MVT::f32, Expand);
916 if (!Subtarget->hasVFP4()) {
917 setOperationAction(ISD::FMA, MVT::f64, Expand);
918 setOperationAction(ISD::FMA, MVT::f32, Expand);
921 // Various VFP goodness
922 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
923 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
924 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
925 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
926 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
929 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
930 if (!Subtarget->hasFP16()) {
931 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
932 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
936 // Combine sin / cos into one node or libcall if possible.
937 if (Subtarget->hasSinCos()) {
938 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
939 setLibcallName(RTLIB::SINCOS_F64, "sincos");
940 if (Subtarget->getTargetTriple().isiOS()) {
941 // For iOS, we don't want to the normal expansion of a libcall to
942 // sincos. We want to issue a libcall to __sincos_stret.
943 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
944 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
948 // FP-ARMv8 implements a lot of rounding-like FP operations.
949 if (Subtarget->hasFPARMv8()) {
950 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
951 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
952 setOperationAction(ISD::FROUND, MVT::f32, Legal);
953 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
954 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
955 setOperationAction(ISD::FRINT, MVT::f32, Legal);
956 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
957 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
958 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
959 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
960 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
961 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
963 if (!Subtarget->isFPOnlySP()) {
964 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
965 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
966 setOperationAction(ISD::FROUND, MVT::f64, Legal);
967 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
968 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
969 setOperationAction(ISD::FRINT, MVT::f64, Legal);
970 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
971 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
975 if (Subtarget->hasNEON()) {
976 // vmin and vmax aren't available in a scalar form, so we use
977 // a NEON instruction with an undef lane instead.
978 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
979 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
980 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
981 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
982 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
983 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
986 // We have target-specific dag combine patterns for the following nodes:
987 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
988 setTargetDAGCombine(ISD::ADD);
989 setTargetDAGCombine(ISD::SUB);
990 setTargetDAGCombine(ISD::MUL);
991 setTargetDAGCombine(ISD::AND);
992 setTargetDAGCombine(ISD::OR);
993 setTargetDAGCombine(ISD::XOR);
995 if (Subtarget->hasV6Ops())
996 setTargetDAGCombine(ISD::SRL);
998 setStackPointerRegisterToSaveRestore(ARM::SP);
1000 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1001 !Subtarget->hasVFP2())
1002 setSchedulingPreference(Sched::RegPressure);
1004 setSchedulingPreference(Sched::Hybrid);
1006 //// temporary - rewrite interface to use type
1007 MaxStoresPerMemset = 8;
1008 MaxStoresPerMemsetOptSize = 4;
1009 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1010 MaxStoresPerMemcpyOptSize = 2;
1011 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1012 MaxStoresPerMemmoveOptSize = 2;
1014 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1015 // are at least 4 bytes aligned.
1016 setMinStackArgumentAlignment(4);
1018 // Prefer likely predicted branches to selects on out-of-order cores.
1019 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1021 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1024 bool ARMTargetLowering::useSoftFloat() const {
1025 return Subtarget->useSoftFloat();
1028 // FIXME: It might make sense to define the representative register class as the
1029 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1030 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1031 // SPR's representative would be DPR_VFP2. This should work well if register
1032 // pressure tracking were modified such that a register use would increment the
1033 // pressure of the register class's representative and all of it's super
1034 // classes' representatives transitively. We have not implemented this because
1035 // of the difficulty prior to coalescing of modeling operand register classes
1036 // due to the common occurrence of cross class copies and subregister insertions
1038 std::pair<const TargetRegisterClass *, uint8_t>
1039 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1041 const TargetRegisterClass *RRC = nullptr;
1043 switch (VT.SimpleTy) {
1045 return TargetLowering::findRepresentativeClass(TRI, VT);
1046 // Use DPR as representative register class for all floating point
1047 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1048 // the cost is 1 for both f32 and f64.
1049 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1050 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1051 RRC = &ARM::DPRRegClass;
1052 // When NEON is used for SP, only half of the register file is available
1053 // because operations that define both SP and DP results will be constrained
1054 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1055 // coalescing by double-counting the SP regs. See the FIXME above.
1056 if (Subtarget->useNEONForSinglePrecisionFP())
1059 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1060 case MVT::v4f32: case MVT::v2f64:
1061 RRC = &ARM::DPRRegClass;
1065 RRC = &ARM::DPRRegClass;
1069 RRC = &ARM::DPRRegClass;
1073 return std::make_pair(RRC, Cost);
1076 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1077 switch ((ARMISD::NodeType)Opcode) {
1078 case ARMISD::FIRST_NUMBER: break;
1079 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1080 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1081 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1082 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1083 case ARMISD::CALL: return "ARMISD::CALL";
1084 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1085 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1086 case ARMISD::tCALL: return "ARMISD::tCALL";
1087 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1088 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1089 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1090 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1091 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1092 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1093 case ARMISD::CMP: return "ARMISD::CMP";
1094 case ARMISD::CMN: return "ARMISD::CMN";
1095 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1096 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1097 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1098 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1099 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1101 case ARMISD::CMOV: return "ARMISD::CMOV";
1103 case ARMISD::RBIT: return "ARMISD::RBIT";
1105 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1106 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1107 case ARMISD::RRX: return "ARMISD::RRX";
1109 case ARMISD::ADDC: return "ARMISD::ADDC";
1110 case ARMISD::ADDE: return "ARMISD::ADDE";
1111 case ARMISD::SUBC: return "ARMISD::SUBC";
1112 case ARMISD::SUBE: return "ARMISD::SUBE";
1114 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1115 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1117 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1118 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1119 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1121 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1123 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1125 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1127 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1129 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1131 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1132 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1134 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1135 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1136 case ARMISD::VCGE: return "ARMISD::VCGE";
1137 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1138 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1139 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1140 case ARMISD::VCGT: return "ARMISD::VCGT";
1141 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1142 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1143 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1144 case ARMISD::VTST: return "ARMISD::VTST";
1146 case ARMISD::VSHL: return "ARMISD::VSHL";
1147 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1148 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1149 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1150 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1151 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1152 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1153 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1154 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1155 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1156 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1157 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1158 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1159 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1160 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1161 case ARMISD::VSLI: return "ARMISD::VSLI";
1162 case ARMISD::VSRI: return "ARMISD::VSRI";
1163 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1164 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1165 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1166 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1167 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1168 case ARMISD::VDUP: return "ARMISD::VDUP";
1169 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1170 case ARMISD::VEXT: return "ARMISD::VEXT";
1171 case ARMISD::VREV64: return "ARMISD::VREV64";
1172 case ARMISD::VREV32: return "ARMISD::VREV32";
1173 case ARMISD::VREV16: return "ARMISD::VREV16";
1174 case ARMISD::VZIP: return "ARMISD::VZIP";
1175 case ARMISD::VUZP: return "ARMISD::VUZP";
1176 case ARMISD::VTRN: return "ARMISD::VTRN";
1177 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1178 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1179 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1180 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1181 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1182 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1183 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1184 case ARMISD::BFI: return "ARMISD::BFI";
1185 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1186 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1187 case ARMISD::VBSL: return "ARMISD::VBSL";
1188 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1189 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1190 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1191 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1192 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1193 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1194 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1195 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1196 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1197 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1198 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1199 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1200 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1201 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1202 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1203 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1204 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1205 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1206 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1207 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1208 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1213 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1216 return getPointerTy(DL);
1217 return VT.changeVectorElementTypeToInteger();
1220 /// getRegClassFor - Return the register class that should be used for the
1221 /// specified value type.
1222 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1223 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1224 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1225 // load / store 4 to 8 consecutive D registers.
1226 if (Subtarget->hasNEON()) {
1227 if (VT == MVT::v4i64)
1228 return &ARM::QQPRRegClass;
1229 if (VT == MVT::v8i64)
1230 return &ARM::QQQQPRRegClass;
1232 return TargetLowering::getRegClassFor(VT);
1235 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1236 // source/dest is aligned and the copy size is large enough. We therefore want
1237 // to align such objects passed to memory intrinsics.
1238 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1239 unsigned &PrefAlign) const {
1240 if (!isa<MemIntrinsic>(CI))
1243 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1244 // cycle faster than 4-byte aligned LDM.
1245 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1249 // Create a fast isel object.
1251 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1252 const TargetLibraryInfo *libInfo) const {
1253 return ARM::createFastISel(funcInfo, libInfo);
1256 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1257 unsigned NumVals = N->getNumValues();
1259 return Sched::RegPressure;
1261 for (unsigned i = 0; i != NumVals; ++i) {
1262 EVT VT = N->getValueType(i);
1263 if (VT == MVT::Glue || VT == MVT::Other)
1265 if (VT.isFloatingPoint() || VT.isVector())
1269 if (!N->isMachineOpcode())
1270 return Sched::RegPressure;
1272 // Load are scheduled for latency even if there instruction itinerary
1273 // is not available.
1274 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1275 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1277 if (MCID.getNumDefs() == 0)
1278 return Sched::RegPressure;
1279 if (!Itins->isEmpty() &&
1280 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1283 return Sched::RegPressure;
1286 //===----------------------------------------------------------------------===//
1288 //===----------------------------------------------------------------------===//
1290 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1291 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1293 default: llvm_unreachable("Unknown condition code!");
1294 case ISD::SETNE: return ARMCC::NE;
1295 case ISD::SETEQ: return ARMCC::EQ;
1296 case ISD::SETGT: return ARMCC::GT;
1297 case ISD::SETGE: return ARMCC::GE;
1298 case ISD::SETLT: return ARMCC::LT;
1299 case ISD::SETLE: return ARMCC::LE;
1300 case ISD::SETUGT: return ARMCC::HI;
1301 case ISD::SETUGE: return ARMCC::HS;
1302 case ISD::SETULT: return ARMCC::LO;
1303 case ISD::SETULE: return ARMCC::LS;
1307 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1308 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1309 ARMCC::CondCodes &CondCode2) {
1310 CondCode2 = ARMCC::AL;
1312 default: llvm_unreachable("Unknown FP condition!");
1314 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1316 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1318 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1319 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1320 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1321 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1322 case ISD::SETO: CondCode = ARMCC::VC; break;
1323 case ISD::SETUO: CondCode = ARMCC::VS; break;
1324 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1325 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1326 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1328 case ISD::SETULT: CondCode = ARMCC::LT; break;
1330 case ISD::SETULE: CondCode = ARMCC::LE; break;
1332 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1336 //===----------------------------------------------------------------------===//
1337 // Calling Convention Implementation
1338 //===----------------------------------------------------------------------===//
1340 #include "ARMGenCallingConv.inc"
1342 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1343 /// account presence of floating point hardware and calling convention
1344 /// limitations, such as support for variadic functions.
1346 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1347 bool isVarArg) const {
1350 llvm_unreachable("Unsupported calling convention");
1351 case CallingConv::ARM_AAPCS:
1352 case CallingConv::ARM_APCS:
1353 case CallingConv::GHC:
1355 case CallingConv::ARM_AAPCS_VFP:
1356 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1357 case CallingConv::C:
1358 if (!Subtarget->isAAPCS_ABI())
1359 return CallingConv::ARM_APCS;
1360 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1361 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1363 return CallingConv::ARM_AAPCS_VFP;
1365 return CallingConv::ARM_AAPCS;
1366 case CallingConv::Fast:
1367 if (!Subtarget->isAAPCS_ABI()) {
1368 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1369 return CallingConv::Fast;
1370 return CallingConv::ARM_APCS;
1371 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1372 return CallingConv::ARM_AAPCS_VFP;
1374 return CallingConv::ARM_AAPCS;
1378 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1379 /// CallingConvention.
1380 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1382 bool isVarArg) const {
1383 switch (getEffectiveCallingConv(CC, isVarArg)) {
1385 llvm_unreachable("Unsupported calling convention");
1386 case CallingConv::ARM_APCS:
1387 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1388 case CallingConv::ARM_AAPCS:
1389 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1390 case CallingConv::ARM_AAPCS_VFP:
1391 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1392 case CallingConv::Fast:
1393 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1394 case CallingConv::GHC:
1395 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1399 /// LowerCallResult - Lower the result values of a call into the
1400 /// appropriate copies out of appropriate physical registers.
1402 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1403 CallingConv::ID CallConv, bool isVarArg,
1404 const SmallVectorImpl<ISD::InputArg> &Ins,
1405 SDLoc dl, SelectionDAG &DAG,
1406 SmallVectorImpl<SDValue> &InVals,
1407 bool isThisReturn, SDValue ThisVal) const {
1409 // Assign locations to each value returned by this call.
1410 SmallVector<CCValAssign, 16> RVLocs;
1411 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1412 *DAG.getContext(), Call);
1413 CCInfo.AnalyzeCallResult(Ins,
1414 CCAssignFnForNode(CallConv, /* Return*/ true,
1417 // Copy all of the result registers out of their specified physreg.
1418 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1419 CCValAssign VA = RVLocs[i];
1421 // Pass 'this' value directly from the argument to return value, to avoid
1422 // reg unit interference
1423 if (i == 0 && isThisReturn) {
1424 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1425 "unexpected return calling convention register assignment");
1426 InVals.push_back(ThisVal);
1431 if (VA.needsCustom()) {
1432 // Handle f64 or half of a v2f64.
1433 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1435 Chain = Lo.getValue(1);
1436 InFlag = Lo.getValue(2);
1437 VA = RVLocs[++i]; // skip ahead to next loc
1438 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
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);
1446 if (VA.getLocVT() == MVT::v2f64) {
1447 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1448 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1449 DAG.getConstant(0, dl, MVT::i32));
1451 VA = RVLocs[++i]; // skip ahead to next loc
1452 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1453 Chain = Lo.getValue(1);
1454 InFlag = Lo.getValue(2);
1455 VA = RVLocs[++i]; // skip ahead to next loc
1456 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1457 Chain = Hi.getValue(1);
1458 InFlag = Hi.getValue(2);
1459 if (!Subtarget->isLittle())
1461 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1462 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1463 DAG.getConstant(1, dl, MVT::i32));
1466 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1468 Chain = Val.getValue(1);
1469 InFlag = Val.getValue(2);
1472 switch (VA.getLocInfo()) {
1473 default: llvm_unreachable("Unknown loc info!");
1474 case CCValAssign::Full: break;
1475 case CCValAssign::BCvt:
1476 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1480 InVals.push_back(Val);
1486 /// LowerMemOpCallTo - Store the argument to the stack.
1488 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1489 SDValue StackPtr, SDValue Arg,
1490 SDLoc dl, SelectionDAG &DAG,
1491 const CCValAssign &VA,
1492 ISD::ArgFlagsTy Flags) const {
1493 unsigned LocMemOffset = VA.getLocMemOffset();
1494 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1495 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1497 return DAG.getStore(
1498 Chain, dl, Arg, PtrOff,
1499 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1503 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1504 SDValue Chain, SDValue &Arg,
1505 RegsToPassVector &RegsToPass,
1506 CCValAssign &VA, CCValAssign &NextVA,
1508 SmallVectorImpl<SDValue> &MemOpChains,
1509 ISD::ArgFlagsTy Flags) const {
1511 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1512 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1513 unsigned id = Subtarget->isLittle() ? 0 : 1;
1514 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1516 if (NextVA.isRegLoc())
1517 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1519 assert(NextVA.isMemLoc());
1520 if (!StackPtr.getNode())
1521 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1522 getPointerTy(DAG.getDataLayout()));
1524 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1530 /// LowerCall - Lowering a call into a callseq_start <-
1531 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1534 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1535 SmallVectorImpl<SDValue> &InVals) const {
1536 SelectionDAG &DAG = CLI.DAG;
1538 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1539 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1540 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1541 SDValue Chain = CLI.Chain;
1542 SDValue Callee = CLI.Callee;
1543 bool &isTailCall = CLI.IsTailCall;
1544 CallingConv::ID CallConv = CLI.CallConv;
1545 bool doesNotRet = CLI.DoesNotReturn;
1546 bool isVarArg = CLI.IsVarArg;
1548 MachineFunction &MF = DAG.getMachineFunction();
1549 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1550 bool isThisReturn = false;
1551 bool isSibCall = false;
1552 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1554 // Disable tail calls if they're not supported.
1555 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1559 // Check if it's really possible to do a tail call.
1560 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1561 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1562 Outs, OutVals, Ins, DAG);
1563 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1564 report_fatal_error("failed to perform tail call elimination on a call "
1565 "site marked musttail");
1566 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1567 // detected sibcalls.
1574 // Analyze operands of the call, assigning locations to each operand.
1575 SmallVector<CCValAssign, 16> ArgLocs;
1576 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1577 *DAG.getContext(), Call);
1578 CCInfo.AnalyzeCallOperands(Outs,
1579 CCAssignFnForNode(CallConv, /* Return*/ false,
1582 // Get a count of how many bytes are to be pushed on the stack.
1583 unsigned NumBytes = CCInfo.getNextStackOffset();
1585 // For tail calls, memory operands are available in our caller's stack.
1589 // Adjust the stack pointer for the new arguments...
1590 // These operations are automatically eliminated by the prolog/epilog pass
1592 Chain = DAG.getCALLSEQ_START(Chain,
1593 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1596 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1598 RegsToPassVector RegsToPass;
1599 SmallVector<SDValue, 8> MemOpChains;
1601 // Walk the register/memloc assignments, inserting copies/loads. In the case
1602 // of tail call optimization, arguments are handled later.
1603 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1605 ++i, ++realArgIdx) {
1606 CCValAssign &VA = ArgLocs[i];
1607 SDValue Arg = OutVals[realArgIdx];
1608 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1609 bool isByVal = Flags.isByVal();
1611 // Promote the value if needed.
1612 switch (VA.getLocInfo()) {
1613 default: llvm_unreachable("Unknown loc info!");
1614 case CCValAssign::Full: break;
1615 case CCValAssign::SExt:
1616 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1618 case CCValAssign::ZExt:
1619 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1621 case CCValAssign::AExt:
1622 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1624 case CCValAssign::BCvt:
1625 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1629 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1630 if (VA.needsCustom()) {
1631 if (VA.getLocVT() == MVT::v2f64) {
1632 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1633 DAG.getConstant(0, dl, MVT::i32));
1634 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1635 DAG.getConstant(1, dl, MVT::i32));
1637 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1638 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1640 VA = ArgLocs[++i]; // skip ahead to next loc
1641 if (VA.isRegLoc()) {
1642 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1643 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1645 assert(VA.isMemLoc());
1647 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1648 dl, DAG, VA, Flags));
1651 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1652 StackPtr, MemOpChains, Flags);
1654 } else if (VA.isRegLoc()) {
1655 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1656 assert(VA.getLocVT() == MVT::i32 &&
1657 "unexpected calling convention register assignment");
1658 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1659 "unexpected use of 'returned'");
1660 isThisReturn = true;
1662 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1663 } else if (isByVal) {
1664 assert(VA.isMemLoc());
1665 unsigned offset = 0;
1667 // True if this byval aggregate will be split between registers
1669 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1670 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1672 if (CurByValIdx < ByValArgsCount) {
1674 unsigned RegBegin, RegEnd;
1675 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1678 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1680 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1681 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1682 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1683 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1684 MachinePointerInfo(),
1685 false, false, false,
1686 DAG.InferPtrAlignment(AddArg));
1687 MemOpChains.push_back(Load.getValue(1));
1688 RegsToPass.push_back(std::make_pair(j, Load));
1691 // If parameter size outsides register area, "offset" value
1692 // helps us to calculate stack slot for remained part properly.
1693 offset = RegEnd - RegBegin;
1695 CCInfo.nextInRegsParam();
1698 if (Flags.getByValSize() > 4*offset) {
1699 auto PtrVT = getPointerTy(DAG.getDataLayout());
1700 unsigned LocMemOffset = VA.getLocMemOffset();
1701 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1702 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1703 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1704 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1705 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1707 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1710 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1711 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1712 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1715 } else if (!isSibCall) {
1716 assert(VA.isMemLoc());
1718 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1719 dl, DAG, VA, Flags));
1723 if (!MemOpChains.empty())
1724 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1726 // Build a sequence of copy-to-reg nodes chained together with token chain
1727 // and flag operands which copy the outgoing args into the appropriate regs.
1729 // Tail call byval lowering might overwrite argument registers so in case of
1730 // tail call optimization the copies to registers are lowered later.
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);
1738 // For tail calls lower the arguments to the 'real' stack slot.
1740 // Force all the incoming stack arguments to be loaded from the stack
1741 // before any new outgoing arguments are stored to the stack, because the
1742 // outgoing stack slots may alias the incoming argument stack slots, and
1743 // the alias isn't otherwise explicit. This is slightly more conservative
1744 // than necessary, because it means that each store effectively depends
1745 // on every argument instead of just those arguments it would clobber.
1747 // Do not flag preceding copytoreg stuff together with the following stuff.
1749 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1750 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1751 RegsToPass[i].second, InFlag);
1752 InFlag = Chain.getValue(1);
1757 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1758 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1759 // node so that legalize doesn't hack it.
1760 bool isDirect = false;
1761 bool isARMFunc = false;
1762 bool isLocalARMFunc = false;
1763 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1764 auto PtrVt = getPointerTy(DAG.getDataLayout());
1766 if (Subtarget->genLongCalls()) {
1767 assert((Subtarget->isTargetWindows() ||
1768 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1769 "long-calls with non-static relocation model!");
1770 // Handle a global address or an external symbol. If it's not one of
1771 // those, the target's already in a register, so we don't need to do
1773 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1774 const GlobalValue *GV = G->getGlobal();
1775 // Create a constant pool entry for the callee address
1776 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1777 ARMConstantPoolValue *CPV =
1778 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1780 // Get the address of the callee into a register
1781 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1782 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1783 Callee = DAG.getLoad(
1784 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1785 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1787 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1788 const char *Sym = S->getSymbol();
1790 // Create a constant pool entry for the callee address
1791 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1792 ARMConstantPoolValue *CPV =
1793 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1794 ARMPCLabelIndex, 0);
1795 // Get the address of the callee into a register
1796 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1797 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1798 Callee = DAG.getLoad(
1799 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1800 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1803 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1804 const GlobalValue *GV = G->getGlobal();
1806 bool isDef = GV->isStrongDefinitionForLinker();
1807 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1808 getTargetMachine().getRelocationModel() != Reloc::Static;
1809 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1810 // ARM call to a local ARM function is predicable.
1811 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1812 // tBX takes a register source operand.
1813 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1814 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1815 Callee = DAG.getNode(
1816 ARMISD::WrapperPIC, dl, PtrVt,
1817 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1818 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1819 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1820 false, false, true, 0);
1821 } else if (Subtarget->isTargetCOFF()) {
1822 assert(Subtarget->isTargetWindows() &&
1823 "Windows is the only supported COFF target");
1824 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1825 ? ARMII::MO_DLLIMPORT
1826 : ARMII::MO_NO_FLAG;
1828 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1829 if (GV->hasDLLImportStorageClass())
1831 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1832 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1833 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1834 false, false, false, 0);
1836 // On ELF targets for PIC code, direct calls should go through the PLT
1837 unsigned OpFlags = 0;
1838 if (Subtarget->isTargetELF() &&
1839 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1840 OpFlags = ARMII::MO_PLT;
1841 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1843 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1845 bool isStub = Subtarget->isTargetMachO() &&
1846 getTargetMachine().getRelocationModel() != Reloc::Static;
1847 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1848 // tBX takes a register source operand.
1849 const char *Sym = S->getSymbol();
1850 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1851 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1852 ARMConstantPoolValue *CPV =
1853 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1854 ARMPCLabelIndex, 4);
1855 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1856 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1857 Callee = DAG.getLoad(
1858 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1859 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1861 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1862 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1864 unsigned OpFlags = 0;
1865 // On ELF targets for PIC code, direct calls should go through the PLT
1866 if (Subtarget->isTargetELF() &&
1867 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1868 OpFlags = ARMII::MO_PLT;
1869 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1873 // FIXME: handle tail calls differently.
1875 if (Subtarget->isThumb()) {
1876 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1877 CallOpc = ARMISD::CALL_NOLINK;
1879 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1881 if (!isDirect && !Subtarget->hasV5TOps())
1882 CallOpc = ARMISD::CALL_NOLINK;
1883 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1884 // Emit regular call when code size is the priority
1885 !MF.getFunction()->optForMinSize())
1886 // "mov lr, pc; b _foo" to avoid confusing the RSP
1887 CallOpc = ARMISD::CALL_NOLINK;
1889 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1892 std::vector<SDValue> Ops;
1893 Ops.push_back(Chain);
1894 Ops.push_back(Callee);
1896 // Add argument registers to the end of the list so that they are known live
1898 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1899 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1900 RegsToPass[i].second.getValueType()));
1902 // Add a register mask operand representing the call-preserved registers.
1904 const uint32_t *Mask;
1905 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1907 // For 'this' returns, use the R0-preserving mask if applicable
1908 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1910 // Set isThisReturn to false if the calling convention is not one that
1911 // allows 'returned' to be modeled in this way, so LowerCallResult does
1912 // not try to pass 'this' straight through
1913 isThisReturn = false;
1914 Mask = ARI->getCallPreservedMask(MF, CallConv);
1917 Mask = ARI->getCallPreservedMask(MF, CallConv);
1919 assert(Mask && "Missing call preserved mask for calling convention");
1920 Ops.push_back(DAG.getRegisterMask(Mask));
1923 if (InFlag.getNode())
1924 Ops.push_back(InFlag);
1926 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1928 MF.getFrameInfo()->setHasTailCall();
1929 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1932 // Returns a chain and a flag for retval copy to use.
1933 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1934 InFlag = Chain.getValue(1);
1936 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1937 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1939 InFlag = Chain.getValue(1);
1941 // Handle result values, copying them out of physregs into vregs that we
1943 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1944 InVals, isThisReturn,
1945 isThisReturn ? OutVals[0] : SDValue());
1948 /// HandleByVal - Every parameter *after* a byval parameter is passed
1949 /// on the stack. Remember the next parameter register to allocate,
1950 /// and then confiscate the rest of the parameter registers to insure
1952 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1953 unsigned Align) const {
1954 assert((State->getCallOrPrologue() == Prologue ||
1955 State->getCallOrPrologue() == Call) &&
1956 "unhandled ParmContext");
1958 // Byval (as with any stack) slots are always at least 4 byte aligned.
1959 Align = std::max(Align, 4U);
1961 unsigned Reg = State->AllocateReg(GPRArgRegs);
1965 unsigned AlignInRegs = Align / 4;
1966 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1967 for (unsigned i = 0; i < Waste; ++i)
1968 Reg = State->AllocateReg(GPRArgRegs);
1973 unsigned Excess = 4 * (ARM::R4 - Reg);
1975 // Special case when NSAA != SP and parameter size greater than size of
1976 // all remained GPR regs. In that case we can't split parameter, we must
1977 // send it to stack. We also must set NCRN to R4, so waste all
1978 // remained registers.
1979 const unsigned NSAAOffset = State->getNextStackOffset();
1980 if (NSAAOffset != 0 && Size > Excess) {
1981 while (State->AllocateReg(GPRArgRegs))
1986 // First register for byval parameter is the first register that wasn't
1987 // allocated before this method call, so it would be "reg".
1988 // If parameter is small enough to be saved in range [reg, r4), then
1989 // the end (first after last) register would be reg + param-size-in-regs,
1990 // else parameter would be splitted between registers and stack,
1991 // end register would be r4 in this case.
1992 unsigned ByValRegBegin = Reg;
1993 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1994 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1995 // Note, first register is allocated in the beginning of function already,
1996 // allocate remained amount of registers we need.
1997 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1998 State->AllocateReg(GPRArgRegs);
1999 // A byval parameter that is split between registers and memory needs its
2000 // size truncated here.
2001 // In the case where the entire structure fits in registers, we set the
2002 // size in memory to zero.
2003 Size = std::max<int>(Size - Excess, 0);
2006 /// MatchingStackOffset - Return true if the given stack call argument is
2007 /// already available in the same position (relatively) of the caller's
2008 /// incoming argument stack.
2010 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2011 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2012 const TargetInstrInfo *TII) {
2013 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2015 if (Arg.getOpcode() == ISD::CopyFromReg) {
2016 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2017 if (!TargetRegisterInfo::isVirtualRegister(VR))
2019 MachineInstr *Def = MRI->getVRegDef(VR);
2022 if (!Flags.isByVal()) {
2023 if (!TII->isLoadFromStackSlot(Def, FI))
2028 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2029 if (Flags.isByVal())
2030 // ByVal argument is passed in as a pointer but it's now being
2031 // dereferenced. e.g.
2032 // define @foo(%struct.X* %A) {
2033 // tail call @bar(%struct.X* byval %A)
2036 SDValue Ptr = Ld->getBasePtr();
2037 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2040 FI = FINode->getIndex();
2044 assert(FI != INT_MAX);
2045 if (!MFI->isFixedObjectIndex(FI))
2047 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2050 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2051 /// for tail call optimization. Targets which want to do tail call
2052 /// optimization should implement this function.
2054 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2055 CallingConv::ID CalleeCC,
2057 bool isCalleeStructRet,
2058 bool isCallerStructRet,
2059 const SmallVectorImpl<ISD::OutputArg> &Outs,
2060 const SmallVectorImpl<SDValue> &OutVals,
2061 const SmallVectorImpl<ISD::InputArg> &Ins,
2062 SelectionDAG& DAG) const {
2063 const Function *CallerF = DAG.getMachineFunction().getFunction();
2064 CallingConv::ID CallerCC = CallerF->getCallingConv();
2065 bool CCMatch = CallerCC == CalleeCC;
2067 assert(Subtarget->supportsTailCall());
2069 // Look for obvious safe cases to perform tail call optimization that do not
2070 // require ABI changes. This is what gcc calls sibcall.
2072 // Do not sibcall optimize vararg calls unless the call site is not passing
2074 if (isVarArg && !Outs.empty())
2077 // Exception-handling functions need a special set of instructions to indicate
2078 // a return to the hardware. Tail-calling another function would probably
2080 if (CallerF->hasFnAttribute("interrupt"))
2083 // Also avoid sibcall optimization if either caller or callee uses struct
2084 // return semantics.
2085 if (isCalleeStructRet || isCallerStructRet)
2088 // Externally-defined functions with weak linkage should not be
2089 // tail-called on ARM when the OS does not support dynamic
2090 // pre-emption of symbols, as the AAELF spec requires normal calls
2091 // to undefined weak functions to be replaced with a NOP or jump to the
2092 // next instruction. The behaviour of branch instructions in this
2093 // situation (as used for tail calls) is implementation-defined, so we
2094 // cannot rely on the linker replacing the tail call with a return.
2095 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2096 const GlobalValue *GV = G->getGlobal();
2097 const Triple &TT = getTargetMachine().getTargetTriple();
2098 if (GV->hasExternalWeakLinkage() &&
2099 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2103 // If the calling conventions do not match, then we'd better make sure the
2104 // results are returned in the same way as what the caller expects.
2106 SmallVector<CCValAssign, 16> RVLocs1;
2107 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2108 *DAG.getContext(), Call);
2109 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2111 SmallVector<CCValAssign, 16> RVLocs2;
2112 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2113 *DAG.getContext(), Call);
2114 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2116 if (RVLocs1.size() != RVLocs2.size())
2118 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2119 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2121 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2123 if (RVLocs1[i].isRegLoc()) {
2124 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2127 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2133 // If Caller's vararg or byval argument has been split between registers and
2134 // stack, do not perform tail call, since part of the argument is in caller's
2136 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2137 getInfo<ARMFunctionInfo>();
2138 if (AFI_Caller->getArgRegsSaveSize())
2141 // If the callee takes no arguments then go on to check the results of the
2143 if (!Outs.empty()) {
2144 // Check if stack adjustment is needed. For now, do not do this if any
2145 // argument is passed on the stack.
2146 SmallVector<CCValAssign, 16> ArgLocs;
2147 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2148 *DAG.getContext(), Call);
2149 CCInfo.AnalyzeCallOperands(Outs,
2150 CCAssignFnForNode(CalleeCC, false, isVarArg));
2151 if (CCInfo.getNextStackOffset()) {
2152 MachineFunction &MF = DAG.getMachineFunction();
2154 // Check if the arguments are already laid out in the right way as
2155 // the caller's fixed stack objects.
2156 MachineFrameInfo *MFI = MF.getFrameInfo();
2157 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2158 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2159 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2161 ++i, ++realArgIdx) {
2162 CCValAssign &VA = ArgLocs[i];
2163 EVT RegVT = VA.getLocVT();
2164 SDValue Arg = OutVals[realArgIdx];
2165 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2166 if (VA.getLocInfo() == CCValAssign::Indirect)
2168 if (VA.needsCustom()) {
2169 // f64 and vector types are split into multiple registers or
2170 // register/stack-slot combinations. The types will not match
2171 // the registers; give up on memory f64 refs until we figure
2172 // out what to do about this.
2175 if (!ArgLocs[++i].isRegLoc())
2177 if (RegVT == MVT::v2f64) {
2178 if (!ArgLocs[++i].isRegLoc())
2180 if (!ArgLocs[++i].isRegLoc())
2183 } else if (!VA.isRegLoc()) {
2184 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2196 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2197 MachineFunction &MF, bool isVarArg,
2198 const SmallVectorImpl<ISD::OutputArg> &Outs,
2199 LLVMContext &Context) const {
2200 SmallVector<CCValAssign, 16> RVLocs;
2201 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2202 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2206 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2207 SDLoc DL, SelectionDAG &DAG) {
2208 const MachineFunction &MF = DAG.getMachineFunction();
2209 const Function *F = MF.getFunction();
2211 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2213 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2214 // version of the "preferred return address". These offsets affect the return
2215 // instruction if this is a return from PL1 without hypervisor extensions.
2216 // IRQ/FIQ: +4 "subs pc, lr, #4"
2217 // SWI: 0 "subs pc, lr, #0"
2218 // ABORT: +4 "subs pc, lr, #4"
2219 // UNDEF: +4/+2 "subs pc, lr, #0"
2220 // UNDEF varies depending on where the exception came from ARM or Thumb
2221 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2224 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2227 else if (IntKind == "SWI" || IntKind == "UNDEF")
2230 report_fatal_error("Unsupported interrupt attribute. If present, value "
2231 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2233 RetOps.insert(RetOps.begin() + 1,
2234 DAG.getConstant(LROffset, DL, MVT::i32, false));
2236 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2240 ARMTargetLowering::LowerReturn(SDValue Chain,
2241 CallingConv::ID CallConv, bool isVarArg,
2242 const SmallVectorImpl<ISD::OutputArg> &Outs,
2243 const SmallVectorImpl<SDValue> &OutVals,
2244 SDLoc dl, SelectionDAG &DAG) const {
2246 // CCValAssign - represent the assignment of the return value to a location.
2247 SmallVector<CCValAssign, 16> RVLocs;
2249 // CCState - Info about the registers and stack slots.
2250 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2251 *DAG.getContext(), Call);
2253 // Analyze outgoing return values.
2254 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2258 SmallVector<SDValue, 4> RetOps;
2259 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2260 bool isLittleEndian = Subtarget->isLittle();
2262 MachineFunction &MF = DAG.getMachineFunction();
2263 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2264 AFI->setReturnRegsCount(RVLocs.size());
2266 // Copy the result values into the output registers.
2267 for (unsigned i = 0, realRVLocIdx = 0;
2269 ++i, ++realRVLocIdx) {
2270 CCValAssign &VA = RVLocs[i];
2271 assert(VA.isRegLoc() && "Can only return in registers!");
2273 SDValue Arg = OutVals[realRVLocIdx];
2275 switch (VA.getLocInfo()) {
2276 default: llvm_unreachable("Unknown loc info!");
2277 case CCValAssign::Full: break;
2278 case CCValAssign::BCvt:
2279 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2283 if (VA.needsCustom()) {
2284 if (VA.getLocVT() == MVT::v2f64) {
2285 // Extract the first half and return it in two registers.
2286 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2287 DAG.getConstant(0, dl, MVT::i32));
2288 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2289 DAG.getVTList(MVT::i32, MVT::i32), Half);
2291 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2292 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2294 Flag = Chain.getValue(1);
2295 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2296 VA = RVLocs[++i]; // skip ahead to next loc
2297 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2298 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2300 Flag = Chain.getValue(1);
2301 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2302 VA = RVLocs[++i]; // skip ahead to next loc
2304 // Extract the 2nd half and fall through to handle it as an f64 value.
2305 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2306 DAG.getConstant(1, dl, MVT::i32));
2308 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2310 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2311 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2312 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2313 fmrrd.getValue(isLittleEndian ? 0 : 1),
2315 Flag = Chain.getValue(1);
2316 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2317 VA = RVLocs[++i]; // skip ahead to next loc
2318 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2319 fmrrd.getValue(isLittleEndian ? 1 : 0),
2322 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2324 // Guarantee that all emitted copies are
2325 // stuck together, avoiding something bad.
2326 Flag = Chain.getValue(1);
2327 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2330 // Update chain and glue.
2333 RetOps.push_back(Flag);
2335 // CPUs which aren't M-class use a special sequence to return from
2336 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2337 // though we use "subs pc, lr, #N").
2339 // M-class CPUs actually use a normal return sequence with a special
2340 // (hardware-provided) value in LR, so the normal code path works.
2341 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2342 !Subtarget->isMClass()) {
2343 if (Subtarget->isThumb1Only())
2344 report_fatal_error("interrupt attribute is not supported in Thumb1");
2345 return LowerInterruptReturn(RetOps, dl, DAG);
2348 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2351 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2352 if (N->getNumValues() != 1)
2354 if (!N->hasNUsesOfValue(1, 0))
2357 SDValue TCChain = Chain;
2358 SDNode *Copy = *N->use_begin();
2359 if (Copy->getOpcode() == ISD::CopyToReg) {
2360 // If the copy has a glue operand, we conservatively assume it isn't safe to
2361 // perform a tail call.
2362 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2364 TCChain = Copy->getOperand(0);
2365 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2366 SDNode *VMov = Copy;
2367 // f64 returned in a pair of GPRs.
2368 SmallPtrSet<SDNode*, 2> Copies;
2369 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2371 if (UI->getOpcode() != ISD::CopyToReg)
2375 if (Copies.size() > 2)
2378 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2380 SDValue UseChain = UI->getOperand(0);
2381 if (Copies.count(UseChain.getNode()))
2385 // We are at the top of this chain.
2386 // If the copy has a glue operand, we conservatively assume it
2387 // isn't safe to perform a tail call.
2388 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2394 } else if (Copy->getOpcode() == ISD::BITCAST) {
2395 // f32 returned in a single GPR.
2396 if (!Copy->hasOneUse())
2398 Copy = *Copy->use_begin();
2399 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2401 // If the copy has a glue operand, we conservatively assume it isn't safe to
2402 // perform a tail call.
2403 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2405 TCChain = Copy->getOperand(0);
2410 bool HasRet = false;
2411 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2413 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2414 UI->getOpcode() != ARMISD::INTRET_FLAG)
2426 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2427 if (!Subtarget->supportsTailCall())
2431 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2432 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2438 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2439 // and pass the lower and high parts through.
2440 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2442 SDValue WriteValue = Op->getOperand(2);
2444 // This function is only supposed to be called for i64 type argument.
2445 assert(WriteValue.getValueType() == MVT::i64
2446 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2448 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2449 DAG.getConstant(0, DL, MVT::i32));
2450 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2451 DAG.getConstant(1, DL, MVT::i32));
2452 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2453 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2456 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2457 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2458 // one of the above mentioned nodes. It has to be wrapped because otherwise
2459 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2460 // be used to form addressing mode. These wrapped nodes will be selected
2462 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2463 EVT PtrVT = Op.getValueType();
2464 // FIXME there is no actual debug info here
2466 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2468 if (CP->isMachineConstantPoolEntry())
2469 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2470 CP->getAlignment());
2472 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2473 CP->getAlignment());
2474 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2477 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2478 return MachineJumpTableInfo::EK_Inline;
2481 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2482 SelectionDAG &DAG) const {
2483 MachineFunction &MF = DAG.getMachineFunction();
2484 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2485 unsigned ARMPCLabelIndex = 0;
2487 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2488 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2489 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2491 if (RelocM == Reloc::Static) {
2492 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2494 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2495 ARMPCLabelIndex = AFI->createPICLabelUId();
2496 ARMConstantPoolValue *CPV =
2497 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2498 ARMCP::CPBlockAddress, PCAdj);
2499 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2501 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2503 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2504 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2505 false, false, false, 0);
2506 if (RelocM == Reloc::Static)
2508 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2509 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2512 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2514 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2515 SelectionDAG &DAG) const {
2517 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2518 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2519 MachineFunction &MF = DAG.getMachineFunction();
2520 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2521 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2522 ARMConstantPoolValue *CPV =
2523 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2524 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2525 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2526 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2528 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2529 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2530 false, false, false, 0);
2531 SDValue Chain = Argument.getValue(1);
2533 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2534 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2536 // call __tls_get_addr.
2539 Entry.Node = Argument;
2540 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2541 Args.push_back(Entry);
2543 // FIXME: is there useful debug info available here?
2544 TargetLowering::CallLoweringInfo CLI(DAG);
2545 CLI.setDebugLoc(dl).setChain(Chain)
2546 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2547 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2550 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2551 return CallResult.first;
2554 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2555 // "local exec" model.
2557 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2559 TLSModel::Model model) const {
2560 const GlobalValue *GV = GA->getGlobal();
2563 SDValue Chain = DAG.getEntryNode();
2564 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2565 // Get the Thread Pointer
2566 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2568 if (model == TLSModel::InitialExec) {
2569 MachineFunction &MF = DAG.getMachineFunction();
2570 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2571 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2572 // Initial exec model.
2573 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2574 ARMConstantPoolValue *CPV =
2575 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2576 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2578 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2579 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2580 Offset = DAG.getLoad(
2581 PtrVT, dl, Chain, Offset,
2582 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2584 Chain = Offset.getValue(1);
2586 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2587 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2589 Offset = DAG.getLoad(
2590 PtrVT, dl, Chain, Offset,
2591 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2595 assert(model == TLSModel::LocalExec);
2596 ARMConstantPoolValue *CPV =
2597 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2598 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2599 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2600 Offset = DAG.getLoad(
2601 PtrVT, dl, Chain, Offset,
2602 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2606 // The address of the thread local variable is the add of the thread
2607 // pointer with the offset of the variable.
2608 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2612 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2613 // TODO: implement the "local dynamic" model
2614 assert(Subtarget->isTargetELF() &&
2615 "TLS not implemented for non-ELF targets");
2616 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2617 if (DAG.getTarget().Options.EmulatedTLS)
2618 return LowerToTLSEmulatedModel(GA, DAG);
2620 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2623 case TLSModel::GeneralDynamic:
2624 case TLSModel::LocalDynamic:
2625 return LowerToTLSGeneralDynamicModel(GA, DAG);
2626 case TLSModel::InitialExec:
2627 case TLSModel::LocalExec:
2628 return LowerToTLSExecModels(GA, DAG, model);
2630 llvm_unreachable("bogus TLS model");
2633 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2634 SelectionDAG &DAG) const {
2635 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2637 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2638 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2640 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2642 MachineFunction &MF = DAG.getMachineFunction();
2643 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2644 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2645 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2647 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2648 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2649 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2650 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2651 /*AddCurrentAddress=*/UseGOT_PREL);
2652 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2653 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2654 SDValue Result = DAG.getLoad(
2655 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2656 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2658 SDValue Chain = Result.getValue(1);
2659 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2660 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2662 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2663 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2664 false, false, false, 0);
2668 // If we have T2 ops, we can materialize the address directly via movt/movw
2669 // pair. This is always cheaper.
2670 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2672 // FIXME: Once remat is capable of dealing with instructions with register
2673 // operands, expand this into two nodes.
2674 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2675 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2677 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2678 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2680 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2681 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2686 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2687 SelectionDAG &DAG) const {
2688 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2690 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2691 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2693 if (Subtarget->useMovt(DAG.getMachineFunction()))
2696 // FIXME: Once remat is capable of dealing with instructions with register
2697 // operands, expand this into multiple nodes
2699 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2701 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2702 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2704 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2705 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2706 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2707 false, false, false, 0);
2711 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2712 SelectionDAG &DAG) const {
2713 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2714 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2715 "Windows on ARM expects to use movw/movt");
2717 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2718 const ARMII::TOF TargetFlags =
2719 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2720 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2726 // FIXME: Once remat is capable of dealing with instructions with register
2727 // operands, expand this into two nodes.
2728 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2729 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2731 if (GV->hasDLLImportStorageClass())
2732 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2733 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2734 false, false, false, 0);
2739 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2741 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2742 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2743 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2744 Op.getOperand(1), Val);
2748 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2750 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2751 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2754 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2755 SelectionDAG &DAG) const {
2757 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2762 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2763 const ARMSubtarget *Subtarget) const {
2764 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2767 default: return SDValue(); // Don't custom lower most intrinsics.
2768 case Intrinsic::arm_rbit: {
2769 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2770 "RBIT intrinsic must have i32 type!");
2771 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2773 case Intrinsic::arm_thread_pointer: {
2774 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2775 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2777 case Intrinsic::eh_sjlj_lsda: {
2778 MachineFunction &MF = DAG.getMachineFunction();
2779 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2780 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2781 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2782 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2784 unsigned PCAdj = (RelocM != Reloc::PIC_)
2785 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2786 ARMConstantPoolValue *CPV =
2787 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2788 ARMCP::CPLSDA, PCAdj);
2789 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2790 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2791 SDValue Result = DAG.getLoad(
2792 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2793 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2796 if (RelocM == Reloc::PIC_) {
2797 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2798 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2802 case Intrinsic::arm_neon_vmulls:
2803 case Intrinsic::arm_neon_vmullu: {
2804 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2805 ? ARMISD::VMULLs : ARMISD::VMULLu;
2806 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2807 Op.getOperand(1), Op.getOperand(2));
2809 case Intrinsic::arm_neon_vminnm:
2810 case Intrinsic::arm_neon_vmaxnm: {
2811 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2812 ? ISD::FMINNUM : ISD::FMAXNUM;
2813 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2814 Op.getOperand(1), Op.getOperand(2));
2816 case Intrinsic::arm_neon_vminu:
2817 case Intrinsic::arm_neon_vmaxu: {
2818 if (Op.getValueType().isFloatingPoint())
2820 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2821 ? ISD::UMIN : ISD::UMAX;
2822 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2823 Op.getOperand(1), Op.getOperand(2));
2825 case Intrinsic::arm_neon_vmins:
2826 case Intrinsic::arm_neon_vmaxs: {
2827 // v{min,max}s is overloaded between signed integers and floats.
2828 if (!Op.getValueType().isFloatingPoint()) {
2829 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2830 ? ISD::SMIN : ISD::SMAX;
2831 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2832 Op.getOperand(1), Op.getOperand(2));
2834 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2835 ? ISD::FMINNAN : ISD::FMAXNAN;
2836 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2837 Op.getOperand(1), Op.getOperand(2));
2842 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2843 const ARMSubtarget *Subtarget) {
2844 // FIXME: handle "fence singlethread" more efficiently.
2846 if (!Subtarget->hasDataBarrier()) {
2847 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2848 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2850 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2851 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2852 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2853 DAG.getConstant(0, dl, MVT::i32));
2856 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2857 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2858 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2859 if (Subtarget->isMClass()) {
2860 // Only a full system barrier exists in the M-class architectures.
2861 Domain = ARM_MB::SY;
2862 } else if (Subtarget->isSwift() && Ord == Release) {
2863 // Swift happens to implement ISHST barriers in a way that's compatible with
2864 // Release semantics but weaker than ISH so we'd be fools not to use
2865 // it. Beware: other processors probably don't!
2866 Domain = ARM_MB::ISHST;
2869 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2870 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2871 DAG.getConstant(Domain, dl, MVT::i32));
2874 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2875 const ARMSubtarget *Subtarget) {
2876 // ARM pre v5TE and Thumb1 does not have preload instructions.
2877 if (!(Subtarget->isThumb2() ||
2878 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2879 // Just preserve the chain.
2880 return Op.getOperand(0);
2883 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2885 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2886 // ARMv7 with MP extension has PLDW.
2887 return Op.getOperand(0);
2889 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2890 if (Subtarget->isThumb()) {
2892 isRead = ~isRead & 1;
2893 isData = ~isData & 1;
2896 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2897 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2898 DAG.getConstant(isData, dl, MVT::i32));
2901 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2902 MachineFunction &MF = DAG.getMachineFunction();
2903 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2905 // vastart just stores the address of the VarArgsFrameIndex slot into the
2906 // memory location argument.
2908 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2909 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2910 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2911 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2912 MachinePointerInfo(SV), false, false, 0);
2916 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2917 SDValue &Root, SelectionDAG &DAG,
2919 MachineFunction &MF = DAG.getMachineFunction();
2920 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2922 const TargetRegisterClass *RC;
2923 if (AFI->isThumb1OnlyFunction())
2924 RC = &ARM::tGPRRegClass;
2926 RC = &ARM::GPRRegClass;
2928 // Transform the arguments stored in physical registers into virtual ones.
2929 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2930 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2933 if (NextVA.isMemLoc()) {
2934 MachineFrameInfo *MFI = MF.getFrameInfo();
2935 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2937 // Create load node to retrieve arguments from the stack.
2938 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2939 ArgValue2 = DAG.getLoad(
2940 MVT::i32, dl, Root, FIN,
2941 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2944 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2945 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2947 if (!Subtarget->isLittle())
2948 std::swap (ArgValue, ArgValue2);
2949 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2952 // The remaining GPRs hold either the beginning of variable-argument
2953 // data, or the beginning of an aggregate passed by value (usually
2954 // byval). Either way, we allocate stack slots adjacent to the data
2955 // provided by our caller, and store the unallocated registers there.
2956 // If this is a variadic function, the va_list pointer will begin with
2957 // these values; otherwise, this reassembles a (byval) structure that
2958 // was split between registers and memory.
2959 // Return: The frame index registers were stored into.
2961 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2962 SDLoc dl, SDValue &Chain,
2963 const Value *OrigArg,
2964 unsigned InRegsParamRecordIdx,
2966 unsigned ArgSize) const {
2967 // Currently, two use-cases possible:
2968 // Case #1. Non-var-args function, and we meet first byval parameter.
2969 // Setup first unallocated register as first byval register;
2970 // eat all remained registers
2971 // (these two actions are performed by HandleByVal method).
2972 // Then, here, we initialize stack frame with
2973 // "store-reg" instructions.
2974 // Case #2. Var-args function, that doesn't contain byval parameters.
2975 // The same: eat all remained unallocated registers,
2976 // initialize stack frame.
2978 MachineFunction &MF = DAG.getMachineFunction();
2979 MachineFrameInfo *MFI = MF.getFrameInfo();
2980 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2981 unsigned RBegin, REnd;
2982 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2983 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2985 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2986 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2991 ArgOffset = -4 * (ARM::R4 - RBegin);
2993 auto PtrVT = getPointerTy(DAG.getDataLayout());
2994 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2995 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2997 SmallVector<SDValue, 4> MemOps;
2998 const TargetRegisterClass *RC =
2999 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3001 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3002 unsigned VReg = MF.addLiveIn(Reg, RC);
3003 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3005 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3006 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3007 MemOps.push_back(Store);
3008 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3011 if (!MemOps.empty())
3012 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3016 // Setup stack frame, the va_list pointer will start from.
3018 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3019 SDLoc dl, SDValue &Chain,
3021 unsigned TotalArgRegsSaveSize,
3022 bool ForceMutable) const {
3023 MachineFunction &MF = DAG.getMachineFunction();
3024 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3026 // Try to store any remaining integer argument regs
3027 // to their spots on the stack so that they may be loaded by deferencing
3028 // the result of va_next.
3029 // If there is no regs to be stored, just point address after last
3030 // argument passed via stack.
3031 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3032 CCInfo.getInRegsParamsCount(),
3033 CCInfo.getNextStackOffset(), 4);
3034 AFI->setVarArgsFrameIndex(FrameIndex);
3038 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3039 CallingConv::ID CallConv, bool isVarArg,
3040 const SmallVectorImpl<ISD::InputArg>
3042 SDLoc dl, SelectionDAG &DAG,
3043 SmallVectorImpl<SDValue> &InVals)
3045 MachineFunction &MF = DAG.getMachineFunction();
3046 MachineFrameInfo *MFI = MF.getFrameInfo();
3048 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3050 // Assign locations to all of the incoming arguments.
3051 SmallVector<CCValAssign, 16> ArgLocs;
3052 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3053 *DAG.getContext(), Prologue);
3054 CCInfo.AnalyzeFormalArguments(Ins,
3055 CCAssignFnForNode(CallConv, /* Return*/ false,
3058 SmallVector<SDValue, 16> ArgValues;
3060 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3061 unsigned CurArgIdx = 0;
3063 // Initially ArgRegsSaveSize is zero.
3064 // Then we increase this value each time we meet byval parameter.
3065 // We also increase this value in case of varargs function.
3066 AFI->setArgRegsSaveSize(0);
3068 // Calculate the amount of stack space that we need to allocate to store
3069 // byval and variadic arguments that are passed in registers.
3070 // We need to know this before we allocate the first byval or variadic
3071 // argument, as they will be allocated a stack slot below the CFA (Canonical
3072 // Frame Address, the stack pointer at entry to the function).
3073 unsigned ArgRegBegin = ARM::R4;
3074 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3075 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3078 CCValAssign &VA = ArgLocs[i];
3079 unsigned Index = VA.getValNo();
3080 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3081 if (!Flags.isByVal())
3084 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3085 unsigned RBegin, REnd;
3086 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3087 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3089 CCInfo.nextInRegsParam();
3091 CCInfo.rewindByValRegsInfo();
3093 int lastInsIndex = -1;
3094 if (isVarArg && MFI->hasVAStart()) {
3095 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3096 if (RegIdx != array_lengthof(GPRArgRegs))
3097 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3100 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3101 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3102 auto PtrVT = getPointerTy(DAG.getDataLayout());
3104 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3105 CCValAssign &VA = ArgLocs[i];
3106 if (Ins[VA.getValNo()].isOrigArg()) {
3107 std::advance(CurOrigArg,
3108 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3109 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3111 // Arguments stored in registers.
3112 if (VA.isRegLoc()) {
3113 EVT RegVT = VA.getLocVT();
3115 if (VA.needsCustom()) {
3116 // f64 and vector types are split up into multiple registers or
3117 // combinations of registers and stack slots.
3118 if (VA.getLocVT() == MVT::v2f64) {
3119 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3121 VA = ArgLocs[++i]; // skip ahead to next loc
3123 if (VA.isMemLoc()) {
3124 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3125 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3126 ArgValue2 = DAG.getLoad(
3127 MVT::f64, dl, Chain, FIN,
3128 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3129 false, false, false, 0);
3131 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3134 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3135 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3136 ArgValue, ArgValue1,
3137 DAG.getIntPtrConstant(0, dl));
3138 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3139 ArgValue, ArgValue2,
3140 DAG.getIntPtrConstant(1, dl));
3142 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3145 const TargetRegisterClass *RC;
3147 if (RegVT == MVT::f32)
3148 RC = &ARM::SPRRegClass;
3149 else if (RegVT == MVT::f64)
3150 RC = &ARM::DPRRegClass;
3151 else if (RegVT == MVT::v2f64)
3152 RC = &ARM::QPRRegClass;
3153 else if (RegVT == MVT::i32)
3154 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3155 : &ARM::GPRRegClass;
3157 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3159 // Transform the arguments in physical registers into virtual ones.
3160 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3161 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3164 // If this is an 8 or 16-bit value, it is really passed promoted
3165 // to 32 bits. Insert an assert[sz]ext to capture this, then
3166 // truncate to the right size.
3167 switch (VA.getLocInfo()) {
3168 default: llvm_unreachable("Unknown loc info!");
3169 case CCValAssign::Full: break;
3170 case CCValAssign::BCvt:
3171 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3173 case CCValAssign::SExt:
3174 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3175 DAG.getValueType(VA.getValVT()));
3176 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3178 case CCValAssign::ZExt:
3179 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3180 DAG.getValueType(VA.getValVT()));
3181 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3185 InVals.push_back(ArgValue);
3187 } else { // VA.isRegLoc()
3190 assert(VA.isMemLoc());
3191 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3193 int index = VA.getValNo();
3195 // Some Ins[] entries become multiple ArgLoc[] entries.
3196 // Process them only once.
3197 if (index != lastInsIndex)
3199 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3200 // FIXME: For now, all byval parameter objects are marked mutable.
3201 // This can be changed with more analysis.
3202 // In case of tail call optimization mark all arguments mutable.
3203 // Since they could be overwritten by lowering of arguments in case of
3205 if (Flags.isByVal()) {
3206 assert(Ins[index].isOrigArg() &&
3207 "Byval arguments cannot be implicit");
3208 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3210 int FrameIndex = StoreByValRegs(
3211 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3212 VA.getLocMemOffset(), Flags.getByValSize());
3213 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3214 CCInfo.nextInRegsParam();
3216 unsigned FIOffset = VA.getLocMemOffset();
3217 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3220 // Create load nodes to retrieve arguments from the stack.
3221 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3222 InVals.push_back(DAG.getLoad(
3223 VA.getValVT(), dl, Chain, FIN,
3224 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3225 false, false, false, 0));
3227 lastInsIndex = index;
3233 if (isVarArg && MFI->hasVAStart())
3234 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3235 CCInfo.getNextStackOffset(),
3236 TotalArgRegsSaveSize);
3238 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3243 /// isFloatingPointZero - Return true if this is +0.0.
3244 static bool isFloatingPointZero(SDValue Op) {
3245 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3246 return CFP->getValueAPF().isPosZero();
3247 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3248 // Maybe this has already been legalized into the constant pool?
3249 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3250 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3251 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3252 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3253 return CFP->getValueAPF().isPosZero();
3255 } else if (Op->getOpcode() == ISD::BITCAST &&
3256 Op->getValueType(0) == MVT::f64) {
3257 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3258 // created by LowerConstantFP().
3259 SDValue BitcastOp = Op->getOperand(0);
3260 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3261 SDValue MoveOp = BitcastOp->getOperand(0);
3262 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3263 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3271 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3272 /// the given operands.
3274 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3275 SDValue &ARMcc, SelectionDAG &DAG,
3277 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3278 unsigned C = RHSC->getZExtValue();
3279 if (!isLegalICmpImmediate(C)) {
3280 // Constant does not fit, try adjusting it by one?
3285 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3286 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3287 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3292 if (C != 0 && isLegalICmpImmediate(C-1)) {
3293 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3294 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3299 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3300 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3301 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3306 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3307 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3308 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3315 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3316 ARMISD::NodeType CompareType;
3319 CompareType = ARMISD::CMP;
3324 CompareType = ARMISD::CMPZ;
3327 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3328 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3331 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3333 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3335 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3337 if (!isFloatingPointZero(RHS))
3338 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3340 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3341 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3344 /// duplicateCmp - Glue values can have only one use, so this function
3345 /// duplicates a comparison node.
3347 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3348 unsigned Opc = Cmp.getOpcode();
3350 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3351 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3353 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3354 Cmp = Cmp.getOperand(0);
3355 Opc = Cmp.getOpcode();
3356 if (Opc == ARMISD::CMPFP)
3357 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3359 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3360 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3362 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3365 std::pair<SDValue, SDValue>
3366 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3367 SDValue &ARMcc) const {
3368 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3370 SDValue Value, OverflowCmp;
3371 SDValue LHS = Op.getOperand(0);
3372 SDValue RHS = Op.getOperand(1);
3375 // FIXME: We are currently always generating CMPs because we don't support
3376 // generating CMN through the backend. This is not as good as the natural
3377 // CMP case because it causes a register dependency and cannot be folded
3380 switch (Op.getOpcode()) {
3382 llvm_unreachable("Unknown overflow instruction!");
3384 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3385 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3386 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3389 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3390 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3391 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3394 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3395 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3396 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3399 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3400 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3401 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3405 return std::make_pair(Value, OverflowCmp);
3410 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3411 // Let legalize expand this if it isn't a legal type yet.
3412 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3415 SDValue Value, OverflowCmp;
3417 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3418 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3420 // We use 0 and 1 as false and true values.
3421 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3422 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3423 EVT VT = Op.getValueType();
3425 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3426 ARMcc, CCR, OverflowCmp);
3428 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3429 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3433 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3434 SDValue Cond = Op.getOperand(0);
3435 SDValue SelectTrue = Op.getOperand(1);
3436 SDValue SelectFalse = Op.getOperand(2);
3438 unsigned Opc = Cond.getOpcode();
3440 if (Cond.getResNo() == 1 &&
3441 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3442 Opc == ISD::USUBO)) {
3443 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3446 SDValue Value, OverflowCmp;
3448 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3449 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3450 EVT VT = Op.getValueType();
3452 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3458 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3459 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3461 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3462 const ConstantSDNode *CMOVTrue =
3463 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3464 const ConstantSDNode *CMOVFalse =
3465 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3467 if (CMOVTrue && CMOVFalse) {
3468 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3469 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3473 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3475 False = SelectFalse;
3476 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3481 if (True.getNode() && False.getNode()) {
3482 EVT VT = Op.getValueType();
3483 SDValue ARMcc = Cond.getOperand(2);
3484 SDValue CCR = Cond.getOperand(3);
3485 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3486 assert(True.getValueType() == VT);
3487 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3492 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3493 // undefined bits before doing a full-word comparison with zero.
3494 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3495 DAG.getConstant(1, dl, Cond.getValueType()));
3497 return DAG.getSelectCC(dl, Cond,
3498 DAG.getConstant(0, dl, Cond.getValueType()),
3499 SelectTrue, SelectFalse, ISD::SETNE);
3502 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3503 bool &swpCmpOps, bool &swpVselOps) {
3504 // Start by selecting the GE condition code for opcodes that return true for
3506 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3508 CondCode = ARMCC::GE;
3510 // and GT for opcodes that return false for 'equality'.
3511 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3513 CondCode = ARMCC::GT;
3515 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3516 // to swap the compare operands.
3517 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3521 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3522 // If we have an unordered opcode, we need to swap the operands to the VSEL
3523 // instruction (effectively negating the condition).
3525 // This also has the effect of swapping which one of 'less' or 'greater'
3526 // returns true, so we also swap the compare operands. It also switches
3527 // whether we return true for 'equality', so we compensate by picking the
3528 // opposite condition code to our original choice.
3529 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3530 CC == ISD::SETUGT) {
3531 swpCmpOps = !swpCmpOps;
3532 swpVselOps = !swpVselOps;
3533 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3536 // 'ordered' is 'anything but unordered', so use the VS condition code and
3537 // swap the VSEL operands.
3538 if (CC == ISD::SETO) {
3539 CondCode = ARMCC::VS;
3543 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3544 // code and swap the VSEL operands.
3545 if (CC == ISD::SETUNE) {
3546 CondCode = ARMCC::EQ;
3551 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3552 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3553 SDValue Cmp, SelectionDAG &DAG) const {
3554 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3555 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3556 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3557 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3558 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3560 SDValue TrueLow = TrueVal.getValue(0);
3561 SDValue TrueHigh = TrueVal.getValue(1);
3562 SDValue FalseLow = FalseVal.getValue(0);
3563 SDValue FalseHigh = FalseVal.getValue(1);
3565 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3567 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3568 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3570 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3572 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3577 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3578 EVT VT = Op.getValueType();
3579 SDValue LHS = Op.getOperand(0);
3580 SDValue RHS = Op.getOperand(1);
3581 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3582 SDValue TrueVal = Op.getOperand(2);
3583 SDValue FalseVal = Op.getOperand(3);
3586 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3587 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3590 // If softenSetCCOperands only returned one value, we should compare it to
3592 if (!RHS.getNode()) {
3593 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3598 if (LHS.getValueType() == MVT::i32) {
3599 // Try to generate VSEL on ARMv8.
3600 // The VSEL instruction can't use all the usual ARM condition
3601 // codes: it only has two bits to select the condition code, so it's
3602 // constrained to use only GE, GT, VS and EQ.
3604 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3605 // swap the operands of the previous compare instruction (effectively
3606 // inverting the compare condition, swapping 'less' and 'greater') and
3607 // sometimes need to swap the operands to the VSEL (which inverts the
3608 // condition in the sense of firing whenever the previous condition didn't)
3609 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3610 TrueVal.getValueType() == MVT::f64)) {
3611 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3612 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3613 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3614 CC = ISD::getSetCCInverse(CC, true);
3615 std::swap(TrueVal, FalseVal);
3620 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3621 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3622 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3625 ARMCC::CondCodes CondCode, CondCode2;
3626 FPCCToARMCC(CC, CondCode, CondCode2);
3628 // Try to generate VMAXNM/VMINNM on ARMv8.
3629 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3630 TrueVal.getValueType() == MVT::f64)) {
3631 bool swpCmpOps = false;
3632 bool swpVselOps = false;
3633 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3635 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3636 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3638 std::swap(LHS, RHS);
3640 std::swap(TrueVal, FalseVal);
3644 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3645 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3646 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3647 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3648 if (CondCode2 != ARMCC::AL) {
3649 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3650 // FIXME: Needs another CMP because flag can have but one use.
3651 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3652 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3657 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3658 /// to morph to an integer compare sequence.
3659 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3660 const ARMSubtarget *Subtarget) {
3661 SDNode *N = Op.getNode();
3662 if (!N->hasOneUse())
3663 // Otherwise it requires moving the value from fp to integer registers.
3665 if (!N->getNumValues())
3667 EVT VT = Op.getValueType();
3668 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3669 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3670 // vmrs are very slow, e.g. cortex-a8.
3673 if (isFloatingPointZero(Op)) {
3677 return ISD::isNormalLoad(N);
3680 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3681 if (isFloatingPointZero(Op))
3682 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3684 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3685 return DAG.getLoad(MVT::i32, SDLoc(Op),
3686 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3687 Ld->isVolatile(), Ld->isNonTemporal(),
3688 Ld->isInvariant(), Ld->getAlignment());
3690 llvm_unreachable("Unknown VFP cmp argument!");
3693 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3694 SDValue &RetVal1, SDValue &RetVal2) {
3697 if (isFloatingPointZero(Op)) {
3698 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3699 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3703 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3704 SDValue Ptr = Ld->getBasePtr();
3705 RetVal1 = DAG.getLoad(MVT::i32, dl,
3706 Ld->getChain(), Ptr,
3707 Ld->getPointerInfo(),
3708 Ld->isVolatile(), Ld->isNonTemporal(),
3709 Ld->isInvariant(), Ld->getAlignment());
3711 EVT PtrType = Ptr.getValueType();
3712 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3713 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3714 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3715 RetVal2 = DAG.getLoad(MVT::i32, dl,
3716 Ld->getChain(), NewPtr,
3717 Ld->getPointerInfo().getWithOffset(4),
3718 Ld->isVolatile(), Ld->isNonTemporal(),
3719 Ld->isInvariant(), NewAlign);
3723 llvm_unreachable("Unknown VFP cmp argument!");
3726 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3727 /// f32 and even f64 comparisons to integer ones.
3729 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3730 SDValue Chain = Op.getOperand(0);
3731 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3732 SDValue LHS = Op.getOperand(2);
3733 SDValue RHS = Op.getOperand(3);
3734 SDValue Dest = Op.getOperand(4);
3737 bool LHSSeenZero = false;
3738 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3739 bool RHSSeenZero = false;
3740 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3741 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3742 // If unsafe fp math optimization is enabled and there are no other uses of
3743 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3744 // to an integer comparison.
3745 if (CC == ISD::SETOEQ)
3747 else if (CC == ISD::SETUNE)
3750 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3752 if (LHS.getValueType() == MVT::f32) {
3753 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3754 bitcastf32Toi32(LHS, DAG), Mask);
3755 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3756 bitcastf32Toi32(RHS, DAG), Mask);
3757 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3758 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3759 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3760 Chain, Dest, ARMcc, CCR, Cmp);
3765 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3766 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3767 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3768 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3769 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3770 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3771 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3772 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3773 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3779 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3780 SDValue Chain = Op.getOperand(0);
3781 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3782 SDValue LHS = Op.getOperand(2);
3783 SDValue RHS = Op.getOperand(3);
3784 SDValue Dest = Op.getOperand(4);
3787 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3788 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3791 // If softenSetCCOperands only returned one value, we should compare it to
3793 if (!RHS.getNode()) {
3794 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3799 if (LHS.getValueType() == MVT::i32) {
3801 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3802 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3803 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3804 Chain, Dest, ARMcc, CCR, Cmp);
3807 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3809 if (getTargetMachine().Options.UnsafeFPMath &&
3810 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3811 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3812 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3813 if (Result.getNode())
3817 ARMCC::CondCodes CondCode, CondCode2;
3818 FPCCToARMCC(CC, CondCode, CondCode2);
3820 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3821 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3822 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3823 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3824 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3825 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3826 if (CondCode2 != ARMCC::AL) {
3827 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3828 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3829 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3834 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3835 SDValue Chain = Op.getOperand(0);
3836 SDValue Table = Op.getOperand(1);
3837 SDValue Index = Op.getOperand(2);
3840 EVT PTy = getPointerTy(DAG.getDataLayout());
3841 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3842 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3843 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3844 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3845 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3846 if (Subtarget->isThumb2()) {
3847 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3848 // which does another jump to the destination. This also makes it easier
3849 // to translate it to TBB / TBH later.
3850 // FIXME: This might not work if the function is extremely large.
3851 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3852 Addr, Op.getOperand(2), JTI);
3854 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3856 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3857 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3858 false, false, false, 0);
3859 Chain = Addr.getValue(1);
3860 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3861 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3864 DAG.getLoad(PTy, dl, Chain, Addr,
3865 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3866 false, false, false, 0);
3867 Chain = Addr.getValue(1);
3868 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3872 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3873 EVT VT = Op.getValueType();
3876 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3877 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3879 return DAG.UnrollVectorOp(Op.getNode());
3882 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3883 "Invalid type for custom lowering!");
3884 if (VT != MVT::v4i16)
3885 return DAG.UnrollVectorOp(Op.getNode());
3887 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3888 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3891 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3892 EVT VT = Op.getValueType();
3894 return LowerVectorFP_TO_INT(Op, DAG);
3895 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3897 if (Op.getOpcode() == ISD::FP_TO_SINT)
3898 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3901 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3903 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3904 /*isSigned*/ false, SDLoc(Op)).first;
3910 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3911 EVT VT = Op.getValueType();
3914 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3915 if (VT.getVectorElementType() == MVT::f32)
3917 return DAG.UnrollVectorOp(Op.getNode());
3920 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3921 "Invalid type for custom lowering!");
3922 if (VT != MVT::v4f32)
3923 return DAG.UnrollVectorOp(Op.getNode());
3927 switch (Op.getOpcode()) {
3928 default: llvm_unreachable("Invalid opcode!");
3929 case ISD::SINT_TO_FP:
3930 CastOpc = ISD::SIGN_EXTEND;
3931 Opc = ISD::SINT_TO_FP;
3933 case ISD::UINT_TO_FP:
3934 CastOpc = ISD::ZERO_EXTEND;
3935 Opc = ISD::UINT_TO_FP;
3939 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3940 return DAG.getNode(Opc, dl, VT, Op);
3943 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3944 EVT VT = Op.getValueType();
3946 return LowerVectorINT_TO_FP(Op, DAG);
3947 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3949 if (Op.getOpcode() == ISD::SINT_TO_FP)
3950 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3953 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3955 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3956 /*isSigned*/ false, SDLoc(Op)).first;
3962 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3963 // Implement fcopysign with a fabs and a conditional fneg.
3964 SDValue Tmp0 = Op.getOperand(0);
3965 SDValue Tmp1 = Op.getOperand(1);
3967 EVT VT = Op.getValueType();
3968 EVT SrcVT = Tmp1.getValueType();
3969 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3970 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3971 bool UseNEON = !InGPR && Subtarget->hasNEON();
3974 // Use VBSL to copy the sign bit.
3975 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3976 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3977 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3978 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3980 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3981 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3982 DAG.getConstant(32, dl, MVT::i32));
3983 else /*if (VT == MVT::f32)*/
3984 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3985 if (SrcVT == MVT::f32) {
3986 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3988 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3989 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3990 DAG.getConstant(32, dl, MVT::i32));
3991 } else if (VT == MVT::f32)
3992 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3993 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3994 DAG.getConstant(32, dl, MVT::i32));
3995 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3996 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3998 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4000 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4001 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4002 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4004 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4005 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4006 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4007 if (VT == MVT::f32) {
4008 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4009 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4010 DAG.getConstant(0, dl, MVT::i32));
4012 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4018 // Bitcast operand 1 to i32.
4019 if (SrcVT == MVT::f64)
4020 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4022 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4024 // Or in the signbit with integer operations.
4025 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4026 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4027 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4028 if (VT == MVT::f32) {
4029 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4030 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4031 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4032 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4035 // f64: Or the high part with signbit and then combine two parts.
4036 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4038 SDValue Lo = Tmp0.getValue(0);
4039 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4040 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4041 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4044 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4045 MachineFunction &MF = DAG.getMachineFunction();
4046 MachineFrameInfo *MFI = MF.getFrameInfo();
4047 MFI->setReturnAddressIsTaken(true);
4049 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4052 EVT VT = Op.getValueType();
4054 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4056 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4057 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4058 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4059 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4060 MachinePointerInfo(), false, false, false, 0);
4063 // Return LR, which contains the return address. Mark it an implicit live-in.
4064 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4065 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4068 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4069 const ARMBaseRegisterInfo &ARI =
4070 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4071 MachineFunction &MF = DAG.getMachineFunction();
4072 MachineFrameInfo *MFI = MF.getFrameInfo();
4073 MFI->setFrameAddressIsTaken(true);
4075 EVT VT = Op.getValueType();
4076 SDLoc dl(Op); // FIXME probably not meaningful
4077 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4078 unsigned FrameReg = ARI.getFrameRegister(MF);
4079 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4081 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4082 MachinePointerInfo(),
4083 false, false, false, 0);
4087 // FIXME? Maybe this could be a TableGen attribute on some registers and
4088 // this table could be generated automatically from RegInfo.
4089 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4090 SelectionDAG &DAG) const {
4091 unsigned Reg = StringSwitch<unsigned>(RegName)
4092 .Case("sp", ARM::SP)
4096 report_fatal_error(Twine("Invalid register name \""
4097 + StringRef(RegName) + "\"."));
4100 // Result is 64 bit value so split into two 32 bit values and return as a
4102 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4103 SelectionDAG &DAG) {
4106 // This function is only supposed to be called for i64 type destination.
4107 assert(N->getValueType(0) == MVT::i64
4108 && "ExpandREAD_REGISTER called for non-i64 type result.");
4110 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4111 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4115 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4117 Results.push_back(Read.getOperand(0));
4120 /// ExpandBITCAST - If the target supports VFP, this function is called to
4121 /// expand a bit convert where either the source or destination type is i64 to
4122 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4123 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4124 /// vectors), since the legalizer won't know what to do with that.
4125 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4126 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4128 SDValue Op = N->getOperand(0);
4130 // This function is only supposed to be called for i64 types, either as the
4131 // source or destination of the bit convert.
4132 EVT SrcVT = Op.getValueType();
4133 EVT DstVT = N->getValueType(0);
4134 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4135 "ExpandBITCAST called for non-i64 type");
4137 // Turn i64->f64 into VMOVDRR.
4138 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4139 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4140 DAG.getConstant(0, dl, MVT::i32));
4141 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4142 DAG.getConstant(1, dl, MVT::i32));
4143 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4144 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4147 // Turn f64->i64 into VMOVRRD.
4148 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4150 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4151 SrcVT.getVectorNumElements() > 1)
4152 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4153 DAG.getVTList(MVT::i32, MVT::i32),
4154 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4156 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4157 DAG.getVTList(MVT::i32, MVT::i32), Op);
4158 // Merge the pieces into a single i64 value.
4159 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4165 /// getZeroVector - Returns a vector of specified type with all zero elements.
4166 /// Zero vectors are used to represent vector negation and in those cases
4167 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4168 /// not support i64 elements, so sometimes the zero vectors will need to be
4169 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4171 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4172 assert(VT.isVector() && "Expected a vector type");
4173 // The canonical modified immediate encoding of a zero vector is....0!
4174 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4175 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4176 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4177 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4180 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4181 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4182 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4183 SelectionDAG &DAG) const {
4184 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4185 EVT VT = Op.getValueType();
4186 unsigned VTBits = VT.getSizeInBits();
4188 SDValue ShOpLo = Op.getOperand(0);
4189 SDValue ShOpHi = Op.getOperand(1);
4190 SDValue ShAmt = Op.getOperand(2);
4192 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4194 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4196 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4197 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4198 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4199 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4200 DAG.getConstant(VTBits, dl, MVT::i32));
4201 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4202 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4203 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4205 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4206 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4207 ISD::SETGE, ARMcc, DAG, dl);
4208 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4209 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4212 SDValue Ops[2] = { Lo, Hi };
4213 return DAG.getMergeValues(Ops, dl);
4216 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4217 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4218 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4219 SelectionDAG &DAG) const {
4220 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4221 EVT VT = Op.getValueType();
4222 unsigned VTBits = VT.getSizeInBits();
4224 SDValue ShOpLo = Op.getOperand(0);
4225 SDValue ShOpHi = Op.getOperand(1);
4226 SDValue ShAmt = Op.getOperand(2);
4229 assert(Op.getOpcode() == ISD::SHL_PARTS);
4230 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4231 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4232 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4233 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4234 DAG.getConstant(VTBits, dl, MVT::i32));
4235 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4236 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4238 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4239 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4240 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4241 ISD::SETGE, ARMcc, DAG, dl);
4242 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4243 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4246 SDValue Ops[2] = { Lo, Hi };
4247 return DAG.getMergeValues(Ops, dl);
4250 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4251 SelectionDAG &DAG) const {
4252 // The rounding mode is in bits 23:22 of the FPSCR.
4253 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4254 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4255 // so that the shift + and get folded into a bitfield extract.
4257 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4258 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4260 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4261 DAG.getConstant(1U << 22, dl, MVT::i32));
4262 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4263 DAG.getConstant(22, dl, MVT::i32));
4264 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4265 DAG.getConstant(3, dl, MVT::i32));
4268 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4269 const ARMSubtarget *ST) {
4271 EVT VT = N->getValueType(0);
4272 if (VT.isVector()) {
4273 assert(ST->hasNEON());
4275 // Compute the least significant set bit: LSB = X & -X
4276 SDValue X = N->getOperand(0);
4277 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4278 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4280 EVT ElemTy = VT.getVectorElementType();
4282 if (ElemTy == MVT::i8) {
4283 // Compute with: cttz(x) = ctpop(lsb - 1)
4284 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4285 DAG.getTargetConstant(1, dl, ElemTy));
4286 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4287 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4290 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4291 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4292 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4293 unsigned NumBits = ElemTy.getSizeInBits();
4294 SDValue WidthMinus1 =
4295 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4296 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4297 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4298 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4301 // Compute with: cttz(x) = ctpop(lsb - 1)
4303 // Since we can only compute the number of bits in a byte with vcnt.8, we
4304 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4309 if (ElemTy == MVT::i64) {
4310 // Load constant 0xffff'ffff'ffff'ffff to register.
4311 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4312 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4313 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4315 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4316 DAG.getTargetConstant(1, dl, ElemTy));
4317 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4320 // Count #bits with vcnt.8.
4321 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4322 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4323 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4325 // Gather the #bits with vpaddl (pairwise add.)
4326 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4327 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4328 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4330 if (ElemTy == MVT::i16)
4333 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4334 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4335 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4337 if (ElemTy == MVT::i32)
4340 assert(ElemTy == MVT::i64);
4341 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4342 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4347 if (!ST->hasV6T2Ops())
4350 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4351 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4354 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4355 /// for each 16-bit element from operand, repeated. The basic idea is to
4356 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4358 /// Trace for v4i16:
4359 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4360 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4361 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4362 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4363 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4364 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4365 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4366 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4367 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4368 EVT VT = N->getValueType(0);
4371 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4372 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4373 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4374 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4375 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4376 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4379 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4380 /// bit-count for each 16-bit element from the operand. We need slightly
4381 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4382 /// 64/128-bit registers.
4384 /// Trace for v4i16:
4385 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4386 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4387 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4388 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4389 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4390 EVT VT = N->getValueType(0);
4393 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4394 if (VT.is64BitVector()) {
4395 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4396 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4397 DAG.getIntPtrConstant(0, DL));
4399 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4400 BitCounts, DAG.getIntPtrConstant(0, DL));
4401 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4405 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4406 /// bit-count for each 32-bit element from the operand. The idea here is
4407 /// to split the vector into 16-bit elements, leverage the 16-bit count
4408 /// routine, and then combine the results.
4410 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4411 /// input = [v0 v1 ] (vi: 32-bit elements)
4412 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4413 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4414 /// vrev: N0 = [k1 k0 k3 k2 ]
4416 /// N1 =+[k1 k0 k3 k2 ]
4418 /// N2 =+[k1 k3 k0 k2 ]
4420 /// Extended =+[k1 k3 k0 k2 ]
4422 /// Extracted=+[k1 k3 ]
4424 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4425 EVT VT = N->getValueType(0);
4428 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4430 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4431 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4432 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4433 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4434 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4436 if (VT.is64BitVector()) {
4437 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4438 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4439 DAG.getIntPtrConstant(0, DL));
4441 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4442 DAG.getIntPtrConstant(0, DL));
4443 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4447 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4448 const ARMSubtarget *ST) {
4449 EVT VT = N->getValueType(0);
4451 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4452 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4453 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4454 "Unexpected type for custom ctpop lowering");
4456 if (VT.getVectorElementType() == MVT::i32)
4457 return lowerCTPOP32BitElements(N, DAG);
4459 return lowerCTPOP16BitElements(N, DAG);
4462 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4463 const ARMSubtarget *ST) {
4464 EVT VT = N->getValueType(0);
4470 // Lower vector shifts on NEON to use VSHL.
4471 assert(ST->hasNEON() && "unexpected vector shift");
4473 // Left shifts translate directly to the vshiftu intrinsic.
4474 if (N->getOpcode() == ISD::SHL)
4475 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4476 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4478 N->getOperand(0), N->getOperand(1));
4480 assert((N->getOpcode() == ISD::SRA ||
4481 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4483 // NEON uses the same intrinsics for both left and right shifts. For
4484 // right shifts, the shift amounts are negative, so negate the vector of
4486 EVT ShiftVT = N->getOperand(1).getValueType();
4487 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4488 getZeroVector(ShiftVT, DAG, dl),
4490 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4491 Intrinsic::arm_neon_vshifts :
4492 Intrinsic::arm_neon_vshiftu);
4493 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4494 DAG.getConstant(vshiftInt, dl, MVT::i32),
4495 N->getOperand(0), NegatedCount);
4498 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4499 const ARMSubtarget *ST) {
4500 EVT VT = N->getValueType(0);
4503 // We can get here for a node like i32 = ISD::SHL i32, i64
4507 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4508 "Unknown shift to lower!");
4510 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4511 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4512 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4515 // If we are in thumb mode, we don't have RRX.
4516 if (ST->isThumb1Only()) return SDValue();
4518 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4519 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4520 DAG.getConstant(0, dl, MVT::i32));
4521 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4522 DAG.getConstant(1, dl, MVT::i32));
4524 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4525 // captures the result into a carry flag.
4526 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4527 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4529 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4530 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4532 // Merge the pieces into a single i64 value.
4533 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4536 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4537 SDValue TmpOp0, TmpOp1;
4538 bool Invert = false;
4542 SDValue Op0 = Op.getOperand(0);
4543 SDValue Op1 = Op.getOperand(1);
4544 SDValue CC = Op.getOperand(2);
4545 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4546 EVT VT = Op.getValueType();
4547 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4550 if (CmpVT.getVectorElementType() == MVT::i64)
4551 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4552 // but it's possible that our operands are 64-bit but our result is 32-bit.
4553 // Bail in this case.
4556 if (Op1.getValueType().isFloatingPoint()) {
4557 switch (SetCCOpcode) {
4558 default: llvm_unreachable("Illegal FP comparison");
4560 case ISD::SETNE: Invert = true; // Fallthrough
4562 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4564 case ISD::SETLT: Swap = true; // Fallthrough
4566 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4568 case ISD::SETLE: Swap = true; // Fallthrough
4570 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4571 case ISD::SETUGE: Swap = true; // Fallthrough
4572 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4573 case ISD::SETUGT: Swap = true; // Fallthrough
4574 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4575 case ISD::SETUEQ: Invert = true; // Fallthrough
4577 // Expand this to (OLT | OGT).
4581 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4582 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4584 case ISD::SETUO: Invert = true; // Fallthrough
4586 // Expand this to (OLT | OGE).
4590 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4591 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4595 // Integer comparisons.
4596 switch (SetCCOpcode) {
4597 default: llvm_unreachable("Illegal integer comparison");
4598 case ISD::SETNE: Invert = true;
4599 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4600 case ISD::SETLT: Swap = true;
4601 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4602 case ISD::SETLE: Swap = true;
4603 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4604 case ISD::SETULT: Swap = true;
4605 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4606 case ISD::SETULE: Swap = true;
4607 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4610 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4611 if (Opc == ARMISD::VCEQ) {
4614 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4616 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4619 // Ignore bitconvert.
4620 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4621 AndOp = AndOp.getOperand(0);
4623 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4625 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4626 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4633 std::swap(Op0, Op1);
4635 // If one of the operands is a constant vector zero, attempt to fold the
4636 // comparison to a specialized compare-against-zero form.
4638 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4640 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4641 if (Opc == ARMISD::VCGE)
4642 Opc = ARMISD::VCLEZ;
4643 else if (Opc == ARMISD::VCGT)
4644 Opc = ARMISD::VCLTZ;
4649 if (SingleOp.getNode()) {
4652 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4654 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4656 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4658 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4660 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4662 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4665 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4668 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4671 Result = DAG.getNOT(dl, Result, VT);
4676 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4677 /// valid vector constant for a NEON instruction with a "modified immediate"
4678 /// operand (e.g., VMOV). If so, return the encoded value.
4679 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4680 unsigned SplatBitSize, SelectionDAG &DAG,
4681 SDLoc dl, EVT &VT, bool is128Bits,
4682 NEONModImmType type) {
4683 unsigned OpCmode, Imm;
4685 // SplatBitSize is set to the smallest size that splats the vector, so a
4686 // zero vector will always have SplatBitSize == 8. However, NEON modified
4687 // immediate instructions others than VMOV do not support the 8-bit encoding
4688 // of a zero vector, and the default encoding of zero is supposed to be the
4693 switch (SplatBitSize) {
4695 if (type != VMOVModImm)
4697 // Any 1-byte value is OK. Op=0, Cmode=1110.
4698 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4701 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4705 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4706 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4707 if ((SplatBits & ~0xff) == 0) {
4708 // Value = 0x00nn: Op=x, Cmode=100x.
4713 if ((SplatBits & ~0xff00) == 0) {
4714 // Value = 0xnn00: Op=x, Cmode=101x.
4716 Imm = SplatBits >> 8;
4722 // NEON's 32-bit VMOV supports splat values where:
4723 // * only one byte is nonzero, or
4724 // * the least significant byte is 0xff and the second byte is nonzero, or
4725 // * the least significant 2 bytes are 0xff and the third is nonzero.
4726 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4727 if ((SplatBits & ~0xff) == 0) {
4728 // Value = 0x000000nn: Op=x, Cmode=000x.
4733 if ((SplatBits & ~0xff00) == 0) {
4734 // Value = 0x0000nn00: Op=x, Cmode=001x.
4736 Imm = SplatBits >> 8;
4739 if ((SplatBits & ~0xff0000) == 0) {
4740 // Value = 0x00nn0000: Op=x, Cmode=010x.
4742 Imm = SplatBits >> 16;
4745 if ((SplatBits & ~0xff000000) == 0) {
4746 // Value = 0xnn000000: Op=x, Cmode=011x.
4748 Imm = SplatBits >> 24;
4752 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4753 if (type == OtherModImm) return SDValue();
4755 if ((SplatBits & ~0xffff) == 0 &&
4756 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4757 // Value = 0x0000nnff: Op=x, Cmode=1100.
4759 Imm = SplatBits >> 8;
4763 if ((SplatBits & ~0xffffff) == 0 &&
4764 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4765 // Value = 0x00nnffff: Op=x, Cmode=1101.
4767 Imm = SplatBits >> 16;
4771 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4772 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4773 // VMOV.I32. A (very) minor optimization would be to replicate the value
4774 // and fall through here to test for a valid 64-bit splat. But, then the
4775 // caller would also need to check and handle the change in size.
4779 if (type != VMOVModImm)
4781 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4782 uint64_t BitMask = 0xff;
4784 unsigned ImmMask = 1;
4786 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4787 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4790 } else if ((SplatBits & BitMask) != 0) {
4797 if (DAG.getDataLayout().isBigEndian())
4798 // swap higher and lower 32 bit word
4799 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4801 // Op=1, Cmode=1110.
4803 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4808 llvm_unreachable("unexpected size for isNEONModifiedImm");
4811 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4812 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4815 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4816 const ARMSubtarget *ST) const {
4820 bool IsDouble = Op.getValueType() == MVT::f64;
4821 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4823 // Use the default (constant pool) lowering for double constants when we have
4825 if (IsDouble && Subtarget->isFPOnlySP())
4828 // Try splatting with a VMOV.f32...
4829 APFloat FPVal = CFP->getValueAPF();
4830 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4833 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4834 // We have code in place to select a valid ConstantFP already, no need to
4839 // It's a float and we are trying to use NEON operations where
4840 // possible. Lower it to a splat followed by an extract.
4842 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4843 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4845 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4846 DAG.getConstant(0, DL, MVT::i32));
4849 // The rest of our options are NEON only, make sure that's allowed before
4851 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4855 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4857 // It wouldn't really be worth bothering for doubles except for one very
4858 // important value, which does happen to match: 0.0. So make sure we don't do
4860 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4863 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4864 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4865 VMovVT, false, VMOVModImm);
4866 if (NewVal != SDValue()) {
4868 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4871 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4873 // It's a float: cast and extract a vector element.
4874 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4876 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4877 DAG.getConstant(0, DL, MVT::i32));
4880 // Finally, try a VMVN.i32
4881 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4883 if (NewVal != SDValue()) {
4885 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4888 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4890 // It's a float: cast and extract a vector element.
4891 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4894 DAG.getConstant(0, DL, MVT::i32));
4900 // check if an VEXT instruction can handle the shuffle mask when the
4901 // vector sources of the shuffle are the same.
4902 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4903 unsigned NumElts = VT.getVectorNumElements();
4905 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4911 // If this is a VEXT shuffle, the immediate value is the index of the first
4912 // element. The other shuffle indices must be the successive elements after
4914 unsigned ExpectedElt = Imm;
4915 for (unsigned i = 1; i < NumElts; ++i) {
4916 // Increment the expected index. If it wraps around, just follow it
4917 // back to index zero and keep going.
4919 if (ExpectedElt == NumElts)
4922 if (M[i] < 0) continue; // ignore UNDEF indices
4923 if (ExpectedElt != static_cast<unsigned>(M[i]))
4931 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4932 bool &ReverseVEXT, unsigned &Imm) {
4933 unsigned NumElts = VT.getVectorNumElements();
4934 ReverseVEXT = false;
4936 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4942 // If this is a VEXT shuffle, the immediate value is the index of the first
4943 // element. The other shuffle indices must be the successive elements after
4945 unsigned ExpectedElt = Imm;
4946 for (unsigned i = 1; i < NumElts; ++i) {
4947 // Increment the expected index. If it wraps around, it may still be
4948 // a VEXT but the source vectors must be swapped.
4950 if (ExpectedElt == NumElts * 2) {
4955 if (M[i] < 0) continue; // ignore UNDEF indices
4956 if (ExpectedElt != static_cast<unsigned>(M[i]))
4960 // Adjust the index value if the source operands will be swapped.
4967 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4968 /// instruction with the specified blocksize. (The order of the elements
4969 /// within each block of the vector is reversed.)
4970 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4971 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4972 "Only possible block sizes for VREV are: 16, 32, 64");
4974 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4978 unsigned NumElts = VT.getVectorNumElements();
4979 unsigned BlockElts = M[0] + 1;
4980 // If the first shuffle index is UNDEF, be optimistic.
4982 BlockElts = BlockSize / EltSz;
4984 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4987 for (unsigned i = 0; i < NumElts; ++i) {
4988 if (M[i] < 0) continue; // ignore UNDEF indices
4989 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4996 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4997 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4998 // range, then 0 is placed into the resulting vector. So pretty much any mask
4999 // of 8 elements can work here.
5000 return VT == MVT::v8i8 && M.size() == 8;
5003 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5004 // checking that pairs of elements in the shuffle mask represent the same index
5005 // in each vector, incrementing the expected index by 2 at each step.
5006 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5007 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5009 // WhichResult gives the offset for each element in the mask based on which
5010 // of the two results it belongs to.
5012 // The transpose can be represented either as:
5013 // result1 = shufflevector v1, v2, result1_shuffle_mask
5014 // result2 = shufflevector v1, v2, result2_shuffle_mask
5015 // where v1/v2 and the shuffle masks have the same number of elements
5016 // (here WhichResult (see below) indicates which result is being checked)
5019 // results = shufflevector v1, v2, shuffle_mask
5020 // where both results are returned in one vector and the shuffle mask has twice
5021 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5022 // want to check the low half and high half of the shuffle mask as if it were
5024 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5025 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5029 unsigned NumElts = VT.getVectorNumElements();
5030 if (M.size() != NumElts && M.size() != NumElts*2)
5033 // If the mask is twice as long as the input vector then we need to check the
5034 // upper and lower parts of the mask with a matching value for WhichResult
5035 // FIXME: A mask with only even values will be rejected in case the first
5036 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5037 // M[0] is used to determine WhichResult
5038 for (unsigned i = 0; i < M.size(); i += NumElts) {
5039 if (M.size() == NumElts * 2)
5040 WhichResult = i / NumElts;
5042 WhichResult = M[i] == 0 ? 0 : 1;
5043 for (unsigned j = 0; j < NumElts; j += 2) {
5044 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5045 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5050 if (M.size() == NumElts*2)
5056 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5057 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5058 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5059 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5060 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5064 unsigned NumElts = VT.getVectorNumElements();
5065 if (M.size() != NumElts && M.size() != NumElts*2)
5068 for (unsigned i = 0; i < M.size(); i += NumElts) {
5069 if (M.size() == NumElts * 2)
5070 WhichResult = i / NumElts;
5072 WhichResult = M[i] == 0 ? 0 : 1;
5073 for (unsigned j = 0; j < NumElts; j += 2) {
5074 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5075 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5080 if (M.size() == NumElts*2)
5086 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5087 // that the mask elements are either all even and in steps of size 2 or all odd
5088 // and in steps of size 2.
5089 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5090 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5092 // Requires similar checks to that of isVTRNMask with
5093 // respect the how results are returned.
5094 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5095 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5099 unsigned NumElts = VT.getVectorNumElements();
5100 if (M.size() != NumElts && M.size() != NumElts*2)
5103 for (unsigned i = 0; i < M.size(); i += NumElts) {
5104 WhichResult = M[i] == 0 ? 0 : 1;
5105 for (unsigned j = 0; j < NumElts; ++j) {
5106 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5111 if (M.size() == NumElts*2)
5114 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5115 if (VT.is64BitVector() && EltSz == 32)
5121 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5122 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5123 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5124 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5125 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5129 unsigned NumElts = VT.getVectorNumElements();
5130 if (M.size() != NumElts && M.size() != NumElts*2)
5133 unsigned Half = NumElts / 2;
5134 for (unsigned i = 0; i < M.size(); i += NumElts) {
5135 WhichResult = M[i] == 0 ? 0 : 1;
5136 for (unsigned j = 0; j < NumElts; j += Half) {
5137 unsigned Idx = WhichResult;
5138 for (unsigned k = 0; k < Half; ++k) {
5139 int MIdx = M[i + j + k];
5140 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5147 if (M.size() == NumElts*2)
5150 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5151 if (VT.is64BitVector() && EltSz == 32)
5157 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5158 // that pairs of elements of the shufflemask represent the same index in each
5159 // vector incrementing sequentially through the vectors.
5160 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5161 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5163 // Requires similar checks to that of isVTRNMask with respect the how results
5165 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5166 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5170 unsigned NumElts = VT.getVectorNumElements();
5171 if (M.size() != NumElts && M.size() != NumElts*2)
5174 for (unsigned i = 0; i < M.size(); i += NumElts) {
5175 WhichResult = M[i] == 0 ? 0 : 1;
5176 unsigned Idx = WhichResult * NumElts / 2;
5177 for (unsigned j = 0; j < NumElts; j += 2) {
5178 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5179 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5185 if (M.size() == NumElts*2)
5188 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5189 if (VT.is64BitVector() && EltSz == 32)
5195 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5196 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5197 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5198 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5199 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5203 unsigned NumElts = VT.getVectorNumElements();
5204 if (M.size() != NumElts && M.size() != NumElts*2)
5207 for (unsigned i = 0; i < M.size(); i += NumElts) {
5208 WhichResult = M[i] == 0 ? 0 : 1;
5209 unsigned Idx = WhichResult * NumElts / 2;
5210 for (unsigned j = 0; j < NumElts; j += 2) {
5211 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5212 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5218 if (M.size() == NumElts*2)
5221 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5222 if (VT.is64BitVector() && EltSz == 32)
5228 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5229 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5230 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5231 unsigned &WhichResult,
5234 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5235 return ARMISD::VTRN;
5236 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5237 return ARMISD::VUZP;
5238 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5239 return ARMISD::VZIP;
5242 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5243 return ARMISD::VTRN;
5244 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5245 return ARMISD::VUZP;
5246 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5247 return ARMISD::VZIP;
5252 /// \return true if this is a reverse operation on an vector.
5253 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5254 unsigned NumElts = VT.getVectorNumElements();
5255 // Make sure the mask has the right size.
5256 if (NumElts != M.size())
5259 // Look for <15, ..., 3, -1, 1, 0>.
5260 for (unsigned i = 0; i != NumElts; ++i)
5261 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5267 // If N is an integer constant that can be moved into a register in one
5268 // instruction, return an SDValue of such a constant (will become a MOV
5269 // instruction). Otherwise return null.
5270 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5271 const ARMSubtarget *ST, SDLoc dl) {
5273 if (!isa<ConstantSDNode>(N))
5275 Val = cast<ConstantSDNode>(N)->getZExtValue();
5277 if (ST->isThumb1Only()) {
5278 if (Val <= 255 || ~Val <= 255)
5279 return DAG.getConstant(Val, dl, MVT::i32);
5281 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5282 return DAG.getConstant(Val, dl, MVT::i32);
5287 // If this is a case we can't handle, return null and let the default
5288 // expansion code take care of it.
5289 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5290 const ARMSubtarget *ST) const {
5291 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5293 EVT VT = Op.getValueType();
5295 APInt SplatBits, SplatUndef;
5296 unsigned SplatBitSize;
5298 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5299 if (SplatBitSize <= 64) {
5300 // Check if an immediate VMOV works.
5302 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5303 SplatUndef.getZExtValue(), SplatBitSize,
5304 DAG, dl, VmovVT, VT.is128BitVector(),
5306 if (Val.getNode()) {
5307 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5308 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5311 // Try an immediate VMVN.
5312 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5313 Val = isNEONModifiedImm(NegatedImm,
5314 SplatUndef.getZExtValue(), SplatBitSize,
5315 DAG, dl, VmovVT, VT.is128BitVector(),
5317 if (Val.getNode()) {
5318 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5319 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5322 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5323 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5324 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5326 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5327 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5333 // Scan through the operands to see if only one value is used.
5335 // As an optimisation, even if more than one value is used it may be more
5336 // profitable to splat with one value then change some lanes.
5338 // Heuristically we decide to do this if the vector has a "dominant" value,
5339 // defined as splatted to more than half of the lanes.
5340 unsigned NumElts = VT.getVectorNumElements();
5341 bool isOnlyLowElement = true;
5342 bool usesOnlyOneValue = true;
5343 bool hasDominantValue = false;
5344 bool isConstant = true;
5346 // Map of the number of times a particular SDValue appears in the
5348 DenseMap<SDValue, unsigned> ValueCounts;
5350 for (unsigned i = 0; i < NumElts; ++i) {
5351 SDValue V = Op.getOperand(i);
5352 if (V.getOpcode() == ISD::UNDEF)
5355 isOnlyLowElement = false;
5356 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5359 ValueCounts.insert(std::make_pair(V, 0));
5360 unsigned &Count = ValueCounts[V];
5362 // Is this value dominant? (takes up more than half of the lanes)
5363 if (++Count > (NumElts / 2)) {
5364 hasDominantValue = true;
5368 if (ValueCounts.size() != 1)
5369 usesOnlyOneValue = false;
5370 if (!Value.getNode() && ValueCounts.size() > 0)
5371 Value = ValueCounts.begin()->first;
5373 if (ValueCounts.size() == 0)
5374 return DAG.getUNDEF(VT);
5376 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5377 // Keep going if we are hitting this case.
5378 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5379 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5381 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5383 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5384 // i32 and try again.
5385 if (hasDominantValue && EltSize <= 32) {
5389 // If we are VDUPing a value that comes directly from a vector, that will
5390 // cause an unnecessary move to and from a GPR, where instead we could
5391 // just use VDUPLANE. We can only do this if the lane being extracted
5392 // is at a constant index, as the VDUP from lane instructions only have
5393 // constant-index forms.
5394 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5395 isa<ConstantSDNode>(Value->getOperand(1))) {
5396 // We need to create a new undef vector to use for the VDUPLANE if the
5397 // size of the vector from which we get the value is different than the
5398 // size of the vector that we need to create. We will insert the element
5399 // such that the register coalescer will remove unnecessary copies.
5400 if (VT != Value->getOperand(0).getValueType()) {
5401 ConstantSDNode *constIndex;
5402 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5403 assert(constIndex && "The index is not a constant!");
5404 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5405 VT.getVectorNumElements();
5406 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5407 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5408 Value, DAG.getConstant(index, dl, MVT::i32)),
5409 DAG.getConstant(index, dl, MVT::i32));
5411 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5412 Value->getOperand(0), Value->getOperand(1));
5414 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5416 if (!usesOnlyOneValue) {
5417 // The dominant value was splatted as 'N', but we now have to insert
5418 // all differing elements.
5419 for (unsigned I = 0; I < NumElts; ++I) {
5420 if (Op.getOperand(I) == Value)
5422 SmallVector<SDValue, 3> Ops;
5424 Ops.push_back(Op.getOperand(I));
5425 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5426 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5431 if (VT.getVectorElementType().isFloatingPoint()) {
5432 SmallVector<SDValue, 8> Ops;
5433 for (unsigned i = 0; i < NumElts; ++i)
5434 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5436 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5437 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5438 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5440 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5442 if (usesOnlyOneValue) {
5443 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5444 if (isConstant && Val.getNode())
5445 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5449 // If all elements are constants and the case above didn't get hit, fall back
5450 // to the default expansion, which will generate a load from the constant
5455 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5457 SDValue shuffle = ReconstructShuffle(Op, DAG);
5458 if (shuffle != SDValue())
5462 // Vectors with 32- or 64-bit elements can be built by directly assigning
5463 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5464 // will be legalized.
5465 if (EltSize >= 32) {
5466 // Do the expansion with floating-point types, since that is what the VFP
5467 // registers are defined to use, and since i64 is not legal.
5468 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5469 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5470 SmallVector<SDValue, 8> Ops;
5471 for (unsigned i = 0; i < NumElts; ++i)
5472 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5473 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5474 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5477 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5478 // know the default expansion would otherwise fall back on something even
5479 // worse. For a vector with one or two non-undef values, that's
5480 // scalar_to_vector for the elements followed by a shuffle (provided the
5481 // shuffle is valid for the target) and materialization element by element
5482 // on the stack followed by a load for everything else.
5483 if (!isConstant && !usesOnlyOneValue) {
5484 SDValue Vec = DAG.getUNDEF(VT);
5485 for (unsigned i = 0 ; i < NumElts; ++i) {
5486 SDValue V = Op.getOperand(i);
5487 if (V.getOpcode() == ISD::UNDEF)
5489 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5490 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5498 // Gather data to see if the operation can be modelled as a
5499 // shuffle in combination with VEXTs.
5500 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5501 SelectionDAG &DAG) const {
5502 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5504 EVT VT = Op.getValueType();
5505 unsigned NumElts = VT.getVectorNumElements();
5507 struct ShuffleSourceInfo {
5512 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5513 // be compatible with the shuffle we intend to construct. As a result
5514 // ShuffleVec will be some sliding window into the original Vec.
5517 // Code should guarantee that element i in Vec starts at element "WindowBase
5518 // + i * WindowScale in ShuffleVec".
5522 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5523 ShuffleSourceInfo(SDValue Vec)
5524 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5528 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5530 SmallVector<ShuffleSourceInfo, 2> Sources;
5531 for (unsigned i = 0; i < NumElts; ++i) {
5532 SDValue V = Op.getOperand(i);
5533 if (V.getOpcode() == ISD::UNDEF)
5535 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5536 // A shuffle can only come from building a vector from various
5537 // elements of other vectors.
5539 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5540 // Furthermore, shuffles require a constant mask, whereas extractelts
5541 // accept variable indices.
5545 // Add this element source to the list if it's not already there.
5546 SDValue SourceVec = V.getOperand(0);
5547 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5548 if (Source == Sources.end())
5549 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5551 // Update the minimum and maximum lane number seen.
5552 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5553 Source->MinElt = std::min(Source->MinElt, EltNo);
5554 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5557 // Currently only do something sane when at most two source vectors
5559 if (Sources.size() > 2)
5562 // Find out the smallest element size among result and two sources, and use
5563 // it as element size to build the shuffle_vector.
5564 EVT SmallestEltTy = VT.getVectorElementType();
5565 for (auto &Source : Sources) {
5566 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5567 if (SrcEltTy.bitsLT(SmallestEltTy))
5568 SmallestEltTy = SrcEltTy;
5570 unsigned ResMultiplier =
5571 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5572 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5573 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5575 // If the source vector is too wide or too narrow, we may nevertheless be able
5576 // to construct a compatible shuffle either by concatenating it with UNDEF or
5577 // extracting a suitable range of elements.
5578 for (auto &Src : Sources) {
5579 EVT SrcVT = Src.ShuffleVec.getValueType();
5581 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5584 // This stage of the search produces a source with the same element type as
5585 // the original, but with a total width matching the BUILD_VECTOR output.
5586 EVT EltVT = SrcVT.getVectorElementType();
5587 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5588 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5590 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5591 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5593 // We can pad out the smaller vector for free, so if it's part of a
5596 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5597 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5601 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5604 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5605 // Span too large for a VEXT to cope
5609 if (Src.MinElt >= NumSrcElts) {
5610 // The extraction can just take the second half
5612 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5613 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5614 Src.WindowBase = -NumSrcElts;
5615 } else if (Src.MaxElt < NumSrcElts) {
5616 // The extraction can just take the first half
5618 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5619 DAG.getConstant(0, dl, MVT::i32));
5621 // An actual VEXT is needed
5623 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5624 DAG.getConstant(0, dl, MVT::i32));
5626 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5627 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5629 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5631 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5632 Src.WindowBase = -Src.MinElt;
5636 // Another possible incompatibility occurs from the vector element types. We
5637 // can fix this by bitcasting the source vectors to the same type we intend
5639 for (auto &Src : Sources) {
5640 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5641 if (SrcEltTy == SmallestEltTy)
5643 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5644 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5645 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5646 Src.WindowBase *= Src.WindowScale;
5649 // Final sanity check before we try to actually produce a shuffle.
5651 for (auto Src : Sources)
5652 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5655 // The stars all align, our next step is to produce the mask for the shuffle.
5656 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5657 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5658 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5659 SDValue Entry = Op.getOperand(i);
5660 if (Entry.getOpcode() == ISD::UNDEF)
5663 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5664 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5666 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5667 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5669 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5670 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5671 VT.getVectorElementType().getSizeInBits());
5672 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5674 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5675 // starting at the appropriate offset.
5676 int *LaneMask = &Mask[i * ResMultiplier];
5678 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5679 ExtractBase += NumElts * (Src - Sources.begin());
5680 for (int j = 0; j < LanesDefined; ++j)
5681 LaneMask[j] = ExtractBase + j;
5684 // Final check before we try to produce nonsense...
5685 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5688 // We can't handle more than two sources. This should have already
5689 // been checked before this point.
5690 assert(Sources.size() <= 2 && "Too many sources!");
5692 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5693 for (unsigned i = 0; i < Sources.size(); ++i)
5694 ShuffleOps[i] = Sources[i].ShuffleVec;
5696 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5697 ShuffleOps[1], &Mask[0]);
5698 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5701 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5702 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5703 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5704 /// are assumed to be legal.
5706 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5708 if (VT.getVectorNumElements() == 4 &&
5709 (VT.is128BitVector() || VT.is64BitVector())) {
5710 unsigned PFIndexes[4];
5711 for (unsigned i = 0; i != 4; ++i) {
5715 PFIndexes[i] = M[i];
5718 // Compute the index in the perfect shuffle table.
5719 unsigned PFTableIndex =
5720 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5721 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5722 unsigned Cost = (PFEntry >> 30);
5728 bool ReverseVEXT, isV_UNDEF;
5729 unsigned Imm, WhichResult;
5731 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5732 return (EltSize >= 32 ||
5733 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5734 isVREVMask(M, VT, 64) ||
5735 isVREVMask(M, VT, 32) ||
5736 isVREVMask(M, VT, 16) ||
5737 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5738 isVTBLMask(M, VT) ||
5739 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5740 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5743 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5744 /// the specified operations to build the shuffle.
5745 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5746 SDValue RHS, SelectionDAG &DAG,
5748 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5749 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5750 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5753 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5762 OP_VUZPL, // VUZP, left result
5763 OP_VUZPR, // VUZP, right result
5764 OP_VZIPL, // VZIP, left result
5765 OP_VZIPR, // VZIP, right result
5766 OP_VTRNL, // VTRN, left result
5767 OP_VTRNR // VTRN, right result
5770 if (OpNum == OP_COPY) {
5771 if (LHSID == (1*9+2)*9+3) return LHS;
5772 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5776 SDValue OpLHS, OpRHS;
5777 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5778 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5779 EVT VT = OpLHS.getValueType();
5782 default: llvm_unreachable("Unknown shuffle opcode!");
5784 // VREV divides the vector in half and swaps within the half.
5785 if (VT.getVectorElementType() == MVT::i32 ||
5786 VT.getVectorElementType() == MVT::f32)
5787 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5788 // vrev <4 x i16> -> VREV32
5789 if (VT.getVectorElementType() == MVT::i16)
5790 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5791 // vrev <4 x i8> -> VREV16
5792 assert(VT.getVectorElementType() == MVT::i8);
5793 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5798 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5799 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5803 return DAG.getNode(ARMISD::VEXT, dl, VT,
5805 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5808 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5809 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5812 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5813 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5816 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5817 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5821 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5822 ArrayRef<int> ShuffleMask,
5823 SelectionDAG &DAG) {
5824 // Check to see if we can use the VTBL instruction.
5825 SDValue V1 = Op.getOperand(0);
5826 SDValue V2 = Op.getOperand(1);
5829 SmallVector<SDValue, 8> VTBLMask;
5830 for (ArrayRef<int>::iterator
5831 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5832 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5834 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5835 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5836 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5838 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5839 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5842 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5843 SelectionDAG &DAG) {
5845 SDValue OpLHS = Op.getOperand(0);
5846 EVT VT = OpLHS.getValueType();
5848 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5849 "Expect an v8i16/v16i8 type");
5850 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5851 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5852 // extract the first 8 bytes into the top double word and the last 8 bytes
5853 // into the bottom double word. The v8i16 case is similar.
5854 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5855 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5856 DAG.getConstant(ExtractNum, DL, MVT::i32));
5859 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5860 SDValue V1 = Op.getOperand(0);
5861 SDValue V2 = Op.getOperand(1);
5863 EVT VT = Op.getValueType();
5864 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5866 // Convert shuffles that are directly supported on NEON to target-specific
5867 // DAG nodes, instead of keeping them as shuffles and matching them again
5868 // during code selection. This is more efficient and avoids the possibility
5869 // of inconsistencies between legalization and selection.
5870 // FIXME: floating-point vectors should be canonicalized to integer vectors
5871 // of the same time so that they get CSEd properly.
5872 ArrayRef<int> ShuffleMask = SVN->getMask();
5874 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5875 if (EltSize <= 32) {
5876 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5877 int Lane = SVN->getSplatIndex();
5878 // If this is undef splat, generate it via "just" vdup, if possible.
5879 if (Lane == -1) Lane = 0;
5881 // Test if V1 is a SCALAR_TO_VECTOR.
5882 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5883 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5885 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5886 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5888 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5889 !isa<ConstantSDNode>(V1.getOperand(0))) {
5890 bool IsScalarToVector = true;
5891 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5892 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5893 IsScalarToVector = false;
5896 if (IsScalarToVector)
5897 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5899 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5900 DAG.getConstant(Lane, dl, MVT::i32));
5905 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5908 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5909 DAG.getConstant(Imm, dl, MVT::i32));
5912 if (isVREVMask(ShuffleMask, VT, 64))
5913 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5914 if (isVREVMask(ShuffleMask, VT, 32))
5915 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5916 if (isVREVMask(ShuffleMask, VT, 16))
5917 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5919 if (V2->getOpcode() == ISD::UNDEF &&
5920 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5921 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5922 DAG.getConstant(Imm, dl, MVT::i32));
5925 // Check for Neon shuffles that modify both input vectors in place.
5926 // If both results are used, i.e., if there are two shuffles with the same
5927 // source operands and with masks corresponding to both results of one of
5928 // these operations, DAG memoization will ensure that a single node is
5929 // used for both shuffles.
5930 unsigned WhichResult;
5932 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5933 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5936 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5937 .getValue(WhichResult);
5940 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5941 // shuffles that produce a result larger than their operands with:
5942 // shuffle(concat(v1, undef), concat(v2, undef))
5944 // shuffle(concat(v1, v2), undef)
5945 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5947 // This is useful in the general case, but there are special cases where
5948 // native shuffles produce larger results: the two-result ops.
5950 // Look through the concat when lowering them:
5951 // shuffle(concat(v1, v2), undef)
5953 // concat(VZIP(v1, v2):0, :1)
5955 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5956 V2->getOpcode() == ISD::UNDEF) {
5957 SDValue SubV1 = V1->getOperand(0);
5958 SDValue SubV2 = V1->getOperand(1);
5959 EVT SubVT = SubV1.getValueType();
5961 // We expect these to have been canonicalized to -1.
5962 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5963 return i < (int)VT.getVectorNumElements();
5964 }) && "Unexpected shuffle index into UNDEF operand!");
5966 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5967 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5970 assert((WhichResult == 0) &&
5971 "In-place shuffle of concat can only have one result!");
5972 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5974 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5980 // If the shuffle is not directly supported and it has 4 elements, use
5981 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5982 unsigned NumElts = VT.getVectorNumElements();
5984 unsigned PFIndexes[4];
5985 for (unsigned i = 0; i != 4; ++i) {
5986 if (ShuffleMask[i] < 0)
5989 PFIndexes[i] = ShuffleMask[i];
5992 // Compute the index in the perfect shuffle table.
5993 unsigned PFTableIndex =
5994 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5995 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5996 unsigned Cost = (PFEntry >> 30);
5999 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6002 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6003 if (EltSize >= 32) {
6004 // Do the expansion with floating-point types, since that is what the VFP
6005 // registers are defined to use, and since i64 is not legal.
6006 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6007 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6008 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6009 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6010 SmallVector<SDValue, 8> Ops;
6011 for (unsigned i = 0; i < NumElts; ++i) {
6012 if (ShuffleMask[i] < 0)
6013 Ops.push_back(DAG.getUNDEF(EltVT));
6015 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6016 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6017 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6020 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6021 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6024 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6025 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6027 if (VT == MVT::v8i8) {
6028 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6029 if (NewOp.getNode())
6036 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6037 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6038 SDValue Lane = Op.getOperand(2);
6039 if (!isa<ConstantSDNode>(Lane))
6045 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6046 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6047 SDValue Lane = Op.getOperand(1);
6048 if (!isa<ConstantSDNode>(Lane))
6051 SDValue Vec = Op.getOperand(0);
6052 if (Op.getValueType() == MVT::i32 &&
6053 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6055 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6061 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6062 // The only time a CONCAT_VECTORS operation can have legal types is when
6063 // two 64-bit vectors are concatenated to a 128-bit vector.
6064 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6065 "unexpected CONCAT_VECTORS");
6067 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6068 SDValue Op0 = Op.getOperand(0);
6069 SDValue Op1 = Op.getOperand(1);
6070 if (Op0.getOpcode() != ISD::UNDEF)
6071 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6072 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6073 DAG.getIntPtrConstant(0, dl));
6074 if (Op1.getOpcode() != ISD::UNDEF)
6075 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6076 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6077 DAG.getIntPtrConstant(1, dl));
6078 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6081 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6082 /// element has been zero/sign-extended, depending on the isSigned parameter,
6083 /// from an integer type half its size.
6084 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6086 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6087 EVT VT = N->getValueType(0);
6088 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6089 SDNode *BVN = N->getOperand(0).getNode();
6090 if (BVN->getValueType(0) != MVT::v4i32 ||
6091 BVN->getOpcode() != ISD::BUILD_VECTOR)
6093 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6094 unsigned HiElt = 1 - LoElt;
6095 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6096 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6097 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6098 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6099 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6102 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6103 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6106 if (Hi0->isNullValue() && Hi1->isNullValue())
6112 if (N->getOpcode() != ISD::BUILD_VECTOR)
6115 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6116 SDNode *Elt = N->getOperand(i).getNode();
6117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6118 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6119 unsigned HalfSize = EltSize / 2;
6121 if (!isIntN(HalfSize, C->getSExtValue()))
6124 if (!isUIntN(HalfSize, C->getZExtValue()))
6135 /// isSignExtended - Check if a node is a vector value that is sign-extended
6136 /// or a constant BUILD_VECTOR with sign-extended elements.
6137 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6138 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6140 if (isExtendedBUILD_VECTOR(N, DAG, true))
6145 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6146 /// or a constant BUILD_VECTOR with zero-extended elements.
6147 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6148 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6150 if (isExtendedBUILD_VECTOR(N, DAG, false))
6155 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6156 if (OrigVT.getSizeInBits() >= 64)
6159 assert(OrigVT.isSimple() && "Expecting a simple value type");
6161 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6162 switch (OrigSimpleTy) {
6163 default: llvm_unreachable("Unexpected Vector Type");
6172 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6173 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6174 /// We insert the required extension here to get the vector to fill a D register.
6175 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6178 unsigned ExtOpcode) {
6179 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6180 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6181 // 64-bits we need to insert a new extension so that it will be 64-bits.
6182 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6183 if (OrigTy.getSizeInBits() >= 64)
6186 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6187 EVT NewVT = getExtensionTo64Bits(OrigTy);
6189 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6192 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6193 /// does not do any sign/zero extension. If the original vector is less
6194 /// than 64 bits, an appropriate extension will be added after the load to
6195 /// reach a total size of 64 bits. We have to add the extension separately
6196 /// because ARM does not have a sign/zero extending load for vectors.
6197 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6198 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6200 // The load already has the right type.
6201 if (ExtendedTy == LD->getMemoryVT())
6202 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6203 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6204 LD->isNonTemporal(), LD->isInvariant(),
6205 LD->getAlignment());
6207 // We need to create a zextload/sextload. We cannot just create a load
6208 // followed by a zext/zext node because LowerMUL is also run during normal
6209 // operation legalization where we can't create illegal types.
6210 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6211 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6212 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6213 LD->isNonTemporal(), LD->getAlignment());
6216 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6217 /// extending load, or BUILD_VECTOR with extended elements, return the
6218 /// unextended value. The unextended vector should be 64 bits so that it can
6219 /// be used as an operand to a VMULL instruction. If the original vector size
6220 /// before extension is less than 64 bits we add a an extension to resize
6221 /// the vector to 64 bits.
6222 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6223 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6224 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6225 N->getOperand(0)->getValueType(0),
6229 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6230 return SkipLoadExtensionForVMULL(LD, DAG);
6232 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6233 // have been legalized as a BITCAST from v4i32.
6234 if (N->getOpcode() == ISD::BITCAST) {
6235 SDNode *BVN = N->getOperand(0).getNode();
6236 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6237 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6238 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6239 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6240 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6242 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6243 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6244 EVT VT = N->getValueType(0);
6245 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6246 unsigned NumElts = VT.getVectorNumElements();
6247 MVT TruncVT = MVT::getIntegerVT(EltSize);
6248 SmallVector<SDValue, 8> Ops;
6250 for (unsigned i = 0; i != NumElts; ++i) {
6251 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6252 const APInt &CInt = C->getAPIntValue();
6253 // Element types smaller than 32 bits are not legal, so use i32 elements.
6254 // The values are implicitly truncated so sext vs. zext doesn't matter.
6255 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6257 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6258 MVT::getVectorVT(TruncVT, NumElts), Ops);
6261 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6262 unsigned Opcode = N->getOpcode();
6263 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6264 SDNode *N0 = N->getOperand(0).getNode();
6265 SDNode *N1 = N->getOperand(1).getNode();
6266 return N0->hasOneUse() && N1->hasOneUse() &&
6267 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6272 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6273 unsigned Opcode = N->getOpcode();
6274 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6275 SDNode *N0 = N->getOperand(0).getNode();
6276 SDNode *N1 = N->getOperand(1).getNode();
6277 return N0->hasOneUse() && N1->hasOneUse() &&
6278 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6283 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6284 // Multiplications are only custom-lowered for 128-bit vectors so that
6285 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6286 EVT VT = Op.getValueType();
6287 assert(VT.is128BitVector() && VT.isInteger() &&
6288 "unexpected type for custom-lowering ISD::MUL");
6289 SDNode *N0 = Op.getOperand(0).getNode();
6290 SDNode *N1 = Op.getOperand(1).getNode();
6291 unsigned NewOpc = 0;
6293 bool isN0SExt = isSignExtended(N0, DAG);
6294 bool isN1SExt = isSignExtended(N1, DAG);
6295 if (isN0SExt && isN1SExt)
6296 NewOpc = ARMISD::VMULLs;
6298 bool isN0ZExt = isZeroExtended(N0, DAG);
6299 bool isN1ZExt = isZeroExtended(N1, DAG);
6300 if (isN0ZExt && isN1ZExt)
6301 NewOpc = ARMISD::VMULLu;
6302 else if (isN1SExt || isN1ZExt) {
6303 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6304 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6305 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6306 NewOpc = ARMISD::VMULLs;
6308 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6309 NewOpc = ARMISD::VMULLu;
6311 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6313 NewOpc = ARMISD::VMULLu;
6319 if (VT == MVT::v2i64)
6320 // Fall through to expand this. It is not legal.
6323 // Other vector multiplications are legal.
6328 // Legalize to a VMULL instruction.
6331 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6333 Op0 = SkipExtensionForVMULL(N0, DAG);
6334 assert(Op0.getValueType().is64BitVector() &&
6335 Op1.getValueType().is64BitVector() &&
6336 "unexpected types for extended operands to VMULL");
6337 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6340 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6341 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6348 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6349 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6350 EVT Op1VT = Op1.getValueType();
6351 return DAG.getNode(N0->getOpcode(), DL, VT,
6352 DAG.getNode(NewOpc, DL, VT,
6353 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6354 DAG.getNode(NewOpc, DL, VT,
6355 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6359 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6360 // TODO: Should this propagate fast-math-flags?
6363 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6364 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6365 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6366 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6367 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6368 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6369 // Get reciprocal estimate.
6370 // float4 recip = vrecpeq_f32(yf);
6371 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6372 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6374 // Because char has a smaller range than uchar, we can actually get away
6375 // without any newton steps. This requires that we use a weird bias
6376 // of 0xb000, however (again, this has been exhaustively tested).
6377 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6378 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6379 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6380 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6381 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6382 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6383 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6384 // Convert back to short.
6385 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6386 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6391 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6392 // TODO: Should this propagate fast-math-flags?
6395 // Convert to float.
6396 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6397 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6398 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6399 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6400 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6401 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6403 // Use reciprocal estimate and one refinement step.
6404 // float4 recip = vrecpeq_f32(yf);
6405 // recip *= vrecpsq_f32(yf, recip);
6406 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6407 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6409 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6410 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6412 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6413 // Because short has a smaller range than ushort, we can actually get away
6414 // with only a single newton step. This requires that we use a weird bias
6415 // of 89, however (again, this has been exhaustively tested).
6416 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6417 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6418 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6419 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6420 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6421 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6422 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6423 // Convert back to integer and return.
6424 // return vmovn_s32(vcvt_s32_f32(result));
6425 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6426 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6430 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6431 EVT VT = Op.getValueType();
6432 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6433 "unexpected type for custom-lowering ISD::SDIV");
6436 SDValue N0 = Op.getOperand(0);
6437 SDValue N1 = Op.getOperand(1);
6440 if (VT == MVT::v8i8) {
6441 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6442 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6444 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6445 DAG.getIntPtrConstant(4, dl));
6446 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6447 DAG.getIntPtrConstant(4, dl));
6448 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6449 DAG.getIntPtrConstant(0, dl));
6450 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6451 DAG.getIntPtrConstant(0, dl));
6453 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6454 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6456 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6457 N0 = LowerCONCAT_VECTORS(N0, DAG);
6459 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6462 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6465 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6466 // TODO: Should this propagate fast-math-flags?
6467 EVT VT = Op.getValueType();
6468 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6469 "unexpected type for custom-lowering ISD::UDIV");
6472 SDValue N0 = Op.getOperand(0);
6473 SDValue N1 = Op.getOperand(1);
6476 if (VT == MVT::v8i8) {
6477 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6478 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6480 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6481 DAG.getIntPtrConstant(4, dl));
6482 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6483 DAG.getIntPtrConstant(4, dl));
6484 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6485 DAG.getIntPtrConstant(0, dl));
6486 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6487 DAG.getIntPtrConstant(0, dl));
6489 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6490 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6492 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6493 N0 = LowerCONCAT_VECTORS(N0, DAG);
6495 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6496 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6502 // v4i16 sdiv ... Convert to float.
6503 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6504 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6505 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6506 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6507 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6508 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6510 // Use reciprocal estimate and two refinement steps.
6511 // float4 recip = vrecpeq_f32(yf);
6512 // recip *= vrecpsq_f32(yf, recip);
6513 // recip *= vrecpsq_f32(yf, recip);
6514 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6515 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6517 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6518 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6520 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6521 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6522 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6524 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6525 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6526 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6527 // and that it will never cause us to return an answer too large).
6528 // float4 result = as_float4(as_int4(xf*recip) + 2);
6529 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6530 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6531 N1 = DAG.getConstant(2, dl, MVT::i32);
6532 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6533 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6534 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6535 // Convert back to integer and return.
6536 // return vmovn_u32(vcvt_s32_f32(result));
6537 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6538 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6542 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6543 EVT VT = Op.getNode()->getValueType(0);
6544 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6547 bool ExtraOp = false;
6548 switch (Op.getOpcode()) {
6549 default: llvm_unreachable("Invalid code");
6550 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6551 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6552 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6553 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6557 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6559 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6560 Op.getOperand(1), Op.getOperand(2));
6563 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6564 assert(Subtarget->isTargetDarwin());
6566 // For iOS, we want to call an alternative entry point: __sincos_stret,
6567 // return values are passed via sret.
6569 SDValue Arg = Op.getOperand(0);
6570 EVT ArgVT = Arg.getValueType();
6571 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6572 auto PtrVT = getPointerTy(DAG.getDataLayout());
6574 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6576 // Pair of floats / doubles used to pass the result.
6577 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6579 // Create stack object for sret.
6580 auto &DL = DAG.getDataLayout();
6581 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6582 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6583 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6584 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6590 Entry.Ty = RetTy->getPointerTo();
6591 Entry.isSExt = false;
6592 Entry.isZExt = false;
6593 Entry.isSRet = true;
6594 Args.push_back(Entry);
6598 Entry.isSExt = false;
6599 Entry.isZExt = false;
6600 Args.push_back(Entry);
6602 const char *LibcallName =
6603 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6604 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6606 TargetLowering::CallLoweringInfo CLI(DAG);
6607 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6608 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6610 .setDiscardResult();
6612 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6614 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6615 MachinePointerInfo(), false, false, false, 0);
6617 // Address of cos field.
6618 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6619 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6620 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6621 MachinePointerInfo(), false, false, false, 0);
6623 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6624 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6625 LoadSin.getValue(0), LoadCos.getValue(0));
6628 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6630 SDValue &Chain) const {
6631 EVT VT = Op.getValueType();
6632 assert((VT == MVT::i32 || VT == MVT::i64) &&
6633 "unexpected type for custom lowering DIV");
6636 const auto &DL = DAG.getDataLayout();
6637 const auto &TLI = DAG.getTargetLoweringInfo();
6639 const char *Name = nullptr;
6641 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6643 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6645 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6647 ARMTargetLowering::ArgListTy Args;
6649 for (auto AI : {1, 0}) {
6651 Arg.Node = Op.getOperand(AI);
6652 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6653 Args.push_back(Arg);
6656 CallLoweringInfo CLI(DAG);
6659 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6660 ES, std::move(Args), 0);
6662 return LowerCallTo(CLI).first;
6665 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6666 bool Signed) const {
6667 assert(Op.getValueType() == MVT::i32 &&
6668 "unexpected type for custom lowering DIV");
6671 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6672 DAG.getEntryNode(), Op.getOperand(1));
6674 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6677 void ARMTargetLowering::ExpandDIV_Windows(
6678 SDValue Op, SelectionDAG &DAG, bool Signed,
6679 SmallVectorImpl<SDValue> &Results) const {
6680 const auto &DL = DAG.getDataLayout();
6681 const auto &TLI = DAG.getTargetLoweringInfo();
6683 assert(Op.getValueType() == MVT::i64 &&
6684 "unexpected type for custom lowering DIV");
6687 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6688 DAG.getConstant(0, dl, MVT::i32));
6689 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6690 DAG.getConstant(1, dl, MVT::i32));
6691 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6694 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6696 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6698 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6699 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6700 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6701 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6703 Results.push_back(Lower);
6704 Results.push_back(Upper);
6707 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6708 // Monotonic load/store is legal for all targets
6709 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6712 // Acquire/Release load/store is not legal for targets without a
6713 // dmb or equivalent available.
6717 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6718 SmallVectorImpl<SDValue> &Results,
6720 const ARMSubtarget *Subtarget) {
6722 // Under Power Management extensions, the cycle-count is:
6723 // mrc p15, #0, <Rt>, c9, c13, #0
6724 SDValue Ops[] = { N->getOperand(0), // Chain
6725 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6726 DAG.getConstant(15, DL, MVT::i32),
6727 DAG.getConstant(0, DL, MVT::i32),
6728 DAG.getConstant(9, DL, MVT::i32),
6729 DAG.getConstant(13, DL, MVT::i32),
6730 DAG.getConstant(0, DL, MVT::i32)
6733 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6734 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6735 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6736 DAG.getConstant(0, DL, MVT::i32)));
6737 Results.push_back(Cycles32.getValue(1));
6740 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6741 switch (Op.getOpcode()) {
6742 default: llvm_unreachable("Don't know how to custom lower this!");
6743 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6744 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6745 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6746 case ISD::GlobalAddress:
6747 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6748 default: llvm_unreachable("unknown object format");
6750 return LowerGlobalAddressWindows(Op, DAG);
6752 return LowerGlobalAddressELF(Op, DAG);
6754 return LowerGlobalAddressDarwin(Op, DAG);
6756 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6757 case ISD::SELECT: return LowerSELECT(Op, DAG);
6758 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6759 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6760 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6761 case ISD::VASTART: return LowerVASTART(Op, DAG);
6762 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6763 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6764 case ISD::SINT_TO_FP:
6765 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6766 case ISD::FP_TO_SINT:
6767 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6768 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6769 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6770 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6771 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6772 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6773 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6774 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6776 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6779 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6780 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6781 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6782 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6783 case ISD::SRL_PARTS:
6784 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6786 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6787 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6788 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6789 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6790 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6791 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6792 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6793 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6794 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6795 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6796 case ISD::MUL: return LowerMUL(Op, DAG);
6798 if (Subtarget->isTargetWindows())
6799 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6800 return LowerSDIV(Op, DAG);
6802 if (Subtarget->isTargetWindows())
6803 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6804 return LowerUDIV(Op, DAG);
6808 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6813 return LowerXALUO(Op, DAG);
6814 case ISD::ATOMIC_LOAD:
6815 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6816 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6818 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6819 case ISD::DYNAMIC_STACKALLOC:
6820 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6821 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6822 llvm_unreachable("Don't know how to custom lower this!");
6823 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6824 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6825 case ARMISD::WIN__DBZCHK: return SDValue();
6829 /// ReplaceNodeResults - Replace the results of node with an illegal result
6830 /// type with new values built out of custom code.
6831 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6832 SmallVectorImpl<SDValue> &Results,
6833 SelectionDAG &DAG) const {
6835 switch (N->getOpcode()) {
6837 llvm_unreachable("Don't know how to custom expand this!");
6838 case ISD::READ_REGISTER:
6839 ExpandREAD_REGISTER(N, Results, DAG);
6842 Res = ExpandBITCAST(N, DAG);
6846 Res = Expand64BitShift(N, DAG, Subtarget);
6850 Res = LowerREM(N, DAG);
6852 case ISD::READCYCLECOUNTER:
6853 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6857 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6858 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6862 Results.push_back(Res);
6865 //===----------------------------------------------------------------------===//
6866 // ARM Scheduler Hooks
6867 //===----------------------------------------------------------------------===//
6869 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6870 /// registers the function context.
6871 void ARMTargetLowering::
6872 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6873 MachineBasicBlock *DispatchBB, int FI) const {
6874 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6875 DebugLoc dl = MI->getDebugLoc();
6876 MachineFunction *MF = MBB->getParent();
6877 MachineRegisterInfo *MRI = &MF->getRegInfo();
6878 MachineConstantPool *MCP = MF->getConstantPool();
6879 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6880 const Function *F = MF->getFunction();
6882 bool isThumb = Subtarget->isThumb();
6883 bool isThumb2 = Subtarget->isThumb2();
6885 unsigned PCLabelId = AFI->createPICLabelUId();
6886 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6887 ARMConstantPoolValue *CPV =
6888 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6889 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6891 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6892 : &ARM::GPRRegClass;
6894 // Grab constant pool and fixed stack memory operands.
6895 MachineMemOperand *CPMMO =
6896 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6897 MachineMemOperand::MOLoad, 4, 4);
6899 MachineMemOperand *FIMMOSt =
6900 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6901 MachineMemOperand::MOStore, 4, 4);
6903 // Load the address of the dispatch MBB into the jump buffer.
6905 // Incoming value: jbuf
6906 // ldr.n r5, LCPI1_1
6909 // str r5, [$jbuf, #+4] ; &jbuf[1]
6910 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6911 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6912 .addConstantPoolIndex(CPI)
6913 .addMemOperand(CPMMO));
6914 // Set the low bit because of thumb mode.
6915 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6917 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6918 .addReg(NewVReg1, RegState::Kill)
6920 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6921 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6922 .addReg(NewVReg2, RegState::Kill)
6924 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6925 .addReg(NewVReg3, RegState::Kill)
6927 .addImm(36) // &jbuf[1] :: pc
6928 .addMemOperand(FIMMOSt));
6929 } else if (isThumb) {
6930 // Incoming value: jbuf
6931 // ldr.n r1, LCPI1_4
6935 // add r2, $jbuf, #+4 ; &jbuf[1]
6937 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6938 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6939 .addConstantPoolIndex(CPI)
6940 .addMemOperand(CPMMO));
6941 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6942 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6943 .addReg(NewVReg1, RegState::Kill)
6945 // Set the low bit because of thumb mode.
6946 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6947 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6948 .addReg(ARM::CPSR, RegState::Define)
6950 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6951 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6952 .addReg(ARM::CPSR, RegState::Define)
6953 .addReg(NewVReg2, RegState::Kill)
6954 .addReg(NewVReg3, RegState::Kill));
6955 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6956 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6958 .addImm(36); // &jbuf[1] :: pc
6959 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6960 .addReg(NewVReg4, RegState::Kill)
6961 .addReg(NewVReg5, RegState::Kill)
6963 .addMemOperand(FIMMOSt));
6965 // Incoming value: jbuf
6968 // str r1, [$jbuf, #+4] ; &jbuf[1]
6969 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6970 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6971 .addConstantPoolIndex(CPI)
6973 .addMemOperand(CPMMO));
6974 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6975 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6976 .addReg(NewVReg1, RegState::Kill)
6977 .addImm(PCLabelId));
6978 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6979 .addReg(NewVReg2, RegState::Kill)
6981 .addImm(36) // &jbuf[1] :: pc
6982 .addMemOperand(FIMMOSt));
6986 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6987 MachineBasicBlock *MBB) const {
6988 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6989 DebugLoc dl = MI->getDebugLoc();
6990 MachineFunction *MF = MBB->getParent();
6991 MachineRegisterInfo *MRI = &MF->getRegInfo();
6992 MachineFrameInfo *MFI = MF->getFrameInfo();
6993 int FI = MFI->getFunctionContextIndex();
6995 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6996 : &ARM::GPRnopcRegClass;
6998 // Get a mapping of the call site numbers to all of the landing pads they're
7000 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7001 unsigned MaxCSNum = 0;
7002 MachineModuleInfo &MMI = MF->getMMI();
7003 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7005 if (!BB->isEHPad()) continue;
7007 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7009 for (MachineBasicBlock::iterator
7010 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7011 if (!II->isEHLabel()) continue;
7013 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7014 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7016 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7017 for (SmallVectorImpl<unsigned>::iterator
7018 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7019 CSI != CSE; ++CSI) {
7020 CallSiteNumToLPad[*CSI].push_back(&*BB);
7021 MaxCSNum = std::max(MaxCSNum, *CSI);
7027 // Get an ordered list of the machine basic blocks for the jump table.
7028 std::vector<MachineBasicBlock*> LPadList;
7029 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7030 LPadList.reserve(CallSiteNumToLPad.size());
7031 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7032 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7033 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7034 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7035 LPadList.push_back(*II);
7036 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7040 assert(!LPadList.empty() &&
7041 "No landing pad destinations for the dispatch jump table!");
7043 // Create the jump table and associated information.
7044 MachineJumpTableInfo *JTI =
7045 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7046 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7047 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7049 // Create the MBBs for the dispatch code.
7051 // Shove the dispatch's address into the return slot in the function context.
7052 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7053 DispatchBB->setIsEHPad();
7055 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7056 unsigned trap_opcode;
7057 if (Subtarget->isThumb())
7058 trap_opcode = ARM::tTRAP;
7060 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7062 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7063 DispatchBB->addSuccessor(TrapBB);
7065 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7066 DispatchBB->addSuccessor(DispContBB);
7069 MF->insert(MF->end(), DispatchBB);
7070 MF->insert(MF->end(), DispContBB);
7071 MF->insert(MF->end(), TrapBB);
7073 // Insert code into the entry block that creates and registers the function
7075 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7077 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7078 MachinePointerInfo::getFixedStack(*MF, FI),
7079 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7081 MachineInstrBuilder MIB;
7082 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7084 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7085 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7087 // Add a register mask with no preserved registers. This results in all
7088 // registers being marked as clobbered.
7089 MIB.addRegMask(RI.getNoPreservedMask());
7091 unsigned NumLPads = LPadList.size();
7092 if (Subtarget->isThumb2()) {
7093 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7094 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7097 .addMemOperand(FIMMOLd));
7099 if (NumLPads < 256) {
7100 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7102 .addImm(LPadList.size()));
7104 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7105 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7106 .addImm(NumLPads & 0xFFFF));
7108 unsigned VReg2 = VReg1;
7109 if ((NumLPads & 0xFFFF0000) != 0) {
7110 VReg2 = MRI->createVirtualRegister(TRC);
7111 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7113 .addImm(NumLPads >> 16));
7116 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7121 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7126 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7127 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7128 .addJumpTableIndex(MJTI));
7130 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7133 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7134 .addReg(NewVReg3, RegState::Kill)
7136 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7138 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7139 .addReg(NewVReg4, RegState::Kill)
7141 .addJumpTableIndex(MJTI);
7142 } else if (Subtarget->isThumb()) {
7143 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7144 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7147 .addMemOperand(FIMMOLd));
7149 if (NumLPads < 256) {
7150 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7154 MachineConstantPool *ConstantPool = MF->getConstantPool();
7155 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7156 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7158 // MachineConstantPool wants an explicit alignment.
7159 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7161 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7162 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7164 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7165 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7166 .addReg(VReg1, RegState::Define)
7167 .addConstantPoolIndex(Idx));
7168 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7173 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7178 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7179 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7180 .addReg(ARM::CPSR, RegState::Define)
7184 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7185 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7186 .addJumpTableIndex(MJTI));
7188 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7189 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7190 .addReg(ARM::CPSR, RegState::Define)
7191 .addReg(NewVReg2, RegState::Kill)
7194 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7195 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7197 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7198 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7199 .addReg(NewVReg4, RegState::Kill)
7201 .addMemOperand(JTMMOLd));
7203 unsigned NewVReg6 = NewVReg5;
7204 if (RelocM == Reloc::PIC_) {
7205 NewVReg6 = MRI->createVirtualRegister(TRC);
7206 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7207 .addReg(ARM::CPSR, RegState::Define)
7208 .addReg(NewVReg5, RegState::Kill)
7212 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7213 .addReg(NewVReg6, RegState::Kill)
7214 .addJumpTableIndex(MJTI);
7216 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7217 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7220 .addMemOperand(FIMMOLd));
7222 if (NumLPads < 256) {
7223 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7226 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7227 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7228 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7229 .addImm(NumLPads & 0xFFFF));
7231 unsigned VReg2 = VReg1;
7232 if ((NumLPads & 0xFFFF0000) != 0) {
7233 VReg2 = MRI->createVirtualRegister(TRC);
7234 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7236 .addImm(NumLPads >> 16));
7239 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7243 MachineConstantPool *ConstantPool = MF->getConstantPool();
7244 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7245 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7247 // MachineConstantPool wants an explicit alignment.
7248 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7250 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7251 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7253 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7254 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7255 .addReg(VReg1, RegState::Define)
7256 .addConstantPoolIndex(Idx)
7258 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7260 .addReg(VReg1, RegState::Kill));
7263 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7268 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7270 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7272 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7273 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7274 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7275 .addJumpTableIndex(MJTI));
7277 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7278 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7279 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7281 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7282 .addReg(NewVReg3, RegState::Kill)
7285 .addMemOperand(JTMMOLd));
7287 if (RelocM == Reloc::PIC_) {
7288 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7289 .addReg(NewVReg5, RegState::Kill)
7291 .addJumpTableIndex(MJTI);
7293 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7294 .addReg(NewVReg5, RegState::Kill)
7295 .addJumpTableIndex(MJTI);
7299 // Add the jump table entries as successors to the MBB.
7300 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7301 for (std::vector<MachineBasicBlock*>::iterator
7302 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7303 MachineBasicBlock *CurMBB = *I;
7304 if (SeenMBBs.insert(CurMBB).second)
7305 DispContBB->addSuccessor(CurMBB);
7308 // N.B. the order the invoke BBs are processed in doesn't matter here.
7309 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7310 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7311 for (MachineBasicBlock *BB : InvokeBBs) {
7313 // Remove the landing pad successor from the invoke block and replace it
7314 // with the new dispatch block.
7315 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7317 while (!Successors.empty()) {
7318 MachineBasicBlock *SMBB = Successors.pop_back_val();
7319 if (SMBB->isEHPad()) {
7320 BB->removeSuccessor(SMBB);
7321 MBBLPads.push_back(SMBB);
7325 BB->addSuccessor(DispatchBB);
7327 // Find the invoke call and mark all of the callee-saved registers as
7328 // 'implicit defined' so that they're spilled. This prevents code from
7329 // moving instructions to before the EH block, where they will never be
7331 for (MachineBasicBlock::reverse_iterator
7332 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7333 if (!II->isCall()) continue;
7335 DenseMap<unsigned, bool> DefRegs;
7336 for (MachineInstr::mop_iterator
7337 OI = II->operands_begin(), OE = II->operands_end();
7339 if (!OI->isReg()) continue;
7340 DefRegs[OI->getReg()] = true;
7343 MachineInstrBuilder MIB(*MF, &*II);
7345 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7346 unsigned Reg = SavedRegs[i];
7347 if (Subtarget->isThumb2() &&
7348 !ARM::tGPRRegClass.contains(Reg) &&
7349 !ARM::hGPRRegClass.contains(Reg))
7351 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7353 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7356 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7363 // Mark all former landing pads as non-landing pads. The dispatch is the only
7365 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7366 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7367 (*I)->setIsEHPad(false);
7369 // The instruction is gone now.
7370 MI->eraseFromParent();
7374 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7375 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7376 E = MBB->succ_end(); I != E; ++I)
7379 llvm_unreachable("Expecting a BB with two successors!");
7382 /// Return the load opcode for a given load size. If load size >= 8,
7383 /// neon opcode will be returned.
7384 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7386 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7387 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7389 return LdSize == 4 ? ARM::tLDRi
7390 : LdSize == 2 ? ARM::tLDRHi
7391 : LdSize == 1 ? ARM::tLDRBi : 0;
7393 return LdSize == 4 ? ARM::t2LDR_POST
7394 : LdSize == 2 ? ARM::t2LDRH_POST
7395 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7396 return LdSize == 4 ? ARM::LDR_POST_IMM
7397 : LdSize == 2 ? ARM::LDRH_POST
7398 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7401 /// Return the store opcode for a given store size. If store size >= 8,
7402 /// neon opcode will be returned.
7403 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7405 return StSize == 16 ? ARM::VST1q32wb_fixed
7406 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7408 return StSize == 4 ? ARM::tSTRi
7409 : StSize == 2 ? ARM::tSTRHi
7410 : StSize == 1 ? ARM::tSTRBi : 0;
7412 return StSize == 4 ? ARM::t2STR_POST
7413 : StSize == 2 ? ARM::t2STRH_POST
7414 : StSize == 1 ? ARM::t2STRB_POST : 0;
7415 return StSize == 4 ? ARM::STR_POST_IMM
7416 : StSize == 2 ? ARM::STRH_POST
7417 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7420 /// Emit a post-increment load operation with given size. The instructions
7421 /// will be added to BB at Pos.
7422 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7423 const TargetInstrInfo *TII, DebugLoc dl,
7424 unsigned LdSize, unsigned Data, unsigned AddrIn,
7425 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7426 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7427 assert(LdOpc != 0 && "Should have a load opcode");
7429 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7430 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7432 } else if (IsThumb1) {
7433 // load + update AddrIn
7434 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7435 .addReg(AddrIn).addImm(0));
7436 MachineInstrBuilder MIB =
7437 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7438 MIB = AddDefaultT1CC(MIB);
7439 MIB.addReg(AddrIn).addImm(LdSize);
7440 AddDefaultPred(MIB);
7441 } else if (IsThumb2) {
7442 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7443 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7446 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7447 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7448 .addReg(0).addImm(LdSize));
7452 /// Emit a post-increment store operation with given size. The instructions
7453 /// will be added to BB at Pos.
7454 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7455 const TargetInstrInfo *TII, DebugLoc dl,
7456 unsigned StSize, unsigned Data, unsigned AddrIn,
7457 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7458 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7459 assert(StOpc != 0 && "Should have a store opcode");
7461 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7462 .addReg(AddrIn).addImm(0).addReg(Data));
7463 } else if (IsThumb1) {
7464 // store + update AddrIn
7465 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7466 .addReg(AddrIn).addImm(0));
7467 MachineInstrBuilder MIB =
7468 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7469 MIB = AddDefaultT1CC(MIB);
7470 MIB.addReg(AddrIn).addImm(StSize);
7471 AddDefaultPred(MIB);
7472 } else if (IsThumb2) {
7473 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7474 .addReg(Data).addReg(AddrIn).addImm(StSize));
7476 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7477 .addReg(Data).addReg(AddrIn).addReg(0)
7483 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7484 MachineBasicBlock *BB) const {
7485 // This pseudo instruction has 3 operands: dst, src, size
7486 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7487 // Otherwise, we will generate unrolled scalar copies.
7488 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7489 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7490 MachineFunction::iterator It = ++BB->getIterator();
7492 unsigned dest = MI->getOperand(0).getReg();
7493 unsigned src = MI->getOperand(1).getReg();
7494 unsigned SizeVal = MI->getOperand(2).getImm();
7495 unsigned Align = MI->getOperand(3).getImm();
7496 DebugLoc dl = MI->getDebugLoc();
7498 MachineFunction *MF = BB->getParent();
7499 MachineRegisterInfo &MRI = MF->getRegInfo();
7500 unsigned UnitSize = 0;
7501 const TargetRegisterClass *TRC = nullptr;
7502 const TargetRegisterClass *VecTRC = nullptr;
7504 bool IsThumb1 = Subtarget->isThumb1Only();
7505 bool IsThumb2 = Subtarget->isThumb2();
7509 } else if (Align & 2) {
7512 // Check whether we can use NEON instructions.
7513 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7514 Subtarget->hasNEON()) {
7515 if ((Align % 16 == 0) && SizeVal >= 16)
7517 else if ((Align % 8 == 0) && SizeVal >= 8)
7520 // Can't use NEON instructions.
7525 // Select the correct opcode and register class for unit size load/store
7526 bool IsNeon = UnitSize >= 8;
7527 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7529 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7530 : UnitSize == 8 ? &ARM::DPRRegClass
7533 unsigned BytesLeft = SizeVal % UnitSize;
7534 unsigned LoopSize = SizeVal - BytesLeft;
7536 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7537 // Use LDR and STR to copy.
7538 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7539 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7540 unsigned srcIn = src;
7541 unsigned destIn = dest;
7542 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7543 unsigned srcOut = MRI.createVirtualRegister(TRC);
7544 unsigned destOut = MRI.createVirtualRegister(TRC);
7545 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7546 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7547 IsThumb1, IsThumb2);
7548 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7549 IsThumb1, IsThumb2);
7554 // Handle the leftover bytes with LDRB and STRB.
7555 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7556 // [destOut] = STRB_POST(scratch, destIn, 1)
7557 for (unsigned i = 0; i < BytesLeft; i++) {
7558 unsigned srcOut = MRI.createVirtualRegister(TRC);
7559 unsigned destOut = MRI.createVirtualRegister(TRC);
7560 unsigned scratch = MRI.createVirtualRegister(TRC);
7561 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7562 IsThumb1, IsThumb2);
7563 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7564 IsThumb1, IsThumb2);
7568 MI->eraseFromParent(); // The instruction is gone now.
7572 // Expand the pseudo op to a loop.
7575 // movw varEnd, # --> with thumb2
7577 // ldrcp varEnd, idx --> without thumb2
7578 // fallthrough --> loopMBB
7580 // PHI varPhi, varEnd, varLoop
7581 // PHI srcPhi, src, srcLoop
7582 // PHI destPhi, dst, destLoop
7583 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7584 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7585 // subs varLoop, varPhi, #UnitSize
7587 // fallthrough --> exitMBB
7589 // epilogue to handle left-over bytes
7590 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7591 // [destOut] = STRB_POST(scratch, destLoop, 1)
7592 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7593 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7594 MF->insert(It, loopMBB);
7595 MF->insert(It, exitMBB);
7597 // Transfer the remainder of BB and its successor edges to exitMBB.
7598 exitMBB->splice(exitMBB->begin(), BB,
7599 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7600 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7602 // Load an immediate to varEnd.
7603 unsigned varEnd = MRI.createVirtualRegister(TRC);
7604 if (Subtarget->useMovt(*MF)) {
7605 unsigned Vtmp = varEnd;
7606 if ((LoopSize & 0xFFFF0000) != 0)
7607 Vtmp = MRI.createVirtualRegister(TRC);
7608 AddDefaultPred(BuildMI(BB, dl,
7609 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7610 Vtmp).addImm(LoopSize & 0xFFFF));
7612 if ((LoopSize & 0xFFFF0000) != 0)
7613 AddDefaultPred(BuildMI(BB, dl,
7614 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7617 .addImm(LoopSize >> 16));
7619 MachineConstantPool *ConstantPool = MF->getConstantPool();
7620 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7621 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7623 // MachineConstantPool wants an explicit alignment.
7624 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7626 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7627 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7630 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7631 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7633 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7634 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7636 BB->addSuccessor(loopMBB);
7638 // Generate the loop body:
7639 // varPhi = PHI(varLoop, varEnd)
7640 // srcPhi = PHI(srcLoop, src)
7641 // destPhi = PHI(destLoop, dst)
7642 MachineBasicBlock *entryBB = BB;
7644 unsigned varLoop = MRI.createVirtualRegister(TRC);
7645 unsigned varPhi = MRI.createVirtualRegister(TRC);
7646 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7647 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7648 unsigned destLoop = MRI.createVirtualRegister(TRC);
7649 unsigned destPhi = MRI.createVirtualRegister(TRC);
7651 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7652 .addReg(varLoop).addMBB(loopMBB)
7653 .addReg(varEnd).addMBB(entryBB);
7654 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7655 .addReg(srcLoop).addMBB(loopMBB)
7656 .addReg(src).addMBB(entryBB);
7657 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7658 .addReg(destLoop).addMBB(loopMBB)
7659 .addReg(dest).addMBB(entryBB);
7661 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7662 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7663 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7664 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7665 IsThumb1, IsThumb2);
7666 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7667 IsThumb1, IsThumb2);
7669 // Decrement loop variable by UnitSize.
7671 MachineInstrBuilder MIB =
7672 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7673 MIB = AddDefaultT1CC(MIB);
7674 MIB.addReg(varPhi).addImm(UnitSize);
7675 AddDefaultPred(MIB);
7677 MachineInstrBuilder MIB =
7678 BuildMI(*BB, BB->end(), dl,
7679 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7680 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7681 MIB->getOperand(5).setReg(ARM::CPSR);
7682 MIB->getOperand(5).setIsDef(true);
7684 BuildMI(*BB, BB->end(), dl,
7685 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7686 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7688 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7689 BB->addSuccessor(loopMBB);
7690 BB->addSuccessor(exitMBB);
7692 // Add epilogue to handle BytesLeft.
7694 MachineInstr *StartOfExit = exitMBB->begin();
7696 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7697 // [destOut] = STRB_POST(scratch, destLoop, 1)
7698 unsigned srcIn = srcLoop;
7699 unsigned destIn = destLoop;
7700 for (unsigned i = 0; i < BytesLeft; i++) {
7701 unsigned srcOut = MRI.createVirtualRegister(TRC);
7702 unsigned destOut = MRI.createVirtualRegister(TRC);
7703 unsigned scratch = MRI.createVirtualRegister(TRC);
7704 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7705 IsThumb1, IsThumb2);
7706 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7707 IsThumb1, IsThumb2);
7712 MI->eraseFromParent(); // The instruction is gone now.
7717 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7718 MachineBasicBlock *MBB) const {
7719 const TargetMachine &TM = getTargetMachine();
7720 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7721 DebugLoc DL = MI->getDebugLoc();
7723 assert(Subtarget->isTargetWindows() &&
7724 "__chkstk is only supported on Windows");
7725 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7727 // __chkstk takes the number of words to allocate on the stack in R4, and
7728 // returns the stack adjustment in number of bytes in R4. This will not
7729 // clober any other registers (other than the obvious lr).
7731 // Although, technically, IP should be considered a register which may be
7732 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7733 // thumb-2 environment, so there is no interworking required. As a result, we
7734 // do not expect a veneer to be emitted by the linker, clobbering IP.
7736 // Each module receives its own copy of __chkstk, so no import thunk is
7737 // required, again, ensuring that IP is not clobbered.
7739 // Finally, although some linkers may theoretically provide a trampoline for
7740 // out of range calls (which is quite common due to a 32M range limitation of
7741 // branches for Thumb), we can generate the long-call version via
7742 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7745 switch (TM.getCodeModel()) {
7746 case CodeModel::Small:
7747 case CodeModel::Medium:
7748 case CodeModel::Default:
7749 case CodeModel::Kernel:
7750 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7751 .addImm((unsigned)ARMCC::AL).addReg(0)
7752 .addExternalSymbol("__chkstk")
7753 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7754 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7755 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7757 case CodeModel::Large:
7758 case CodeModel::JITDefault: {
7759 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7760 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7762 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7763 .addExternalSymbol("__chkstk");
7764 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7765 .addImm((unsigned)ARMCC::AL).addReg(0)
7766 .addReg(Reg, RegState::Kill)
7767 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7768 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7769 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7774 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7776 .addReg(ARM::SP).addReg(ARM::R4)));
7778 MI->eraseFromParent();
7783 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7784 MachineBasicBlock *MBB) const {
7785 DebugLoc DL = MI->getDebugLoc();
7786 MachineFunction *MF = MBB->getParent();
7787 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7789 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7790 MF->push_back(ContBB);
7791 ContBB->splice(ContBB->begin(), MBB,
7792 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7793 MBB->addSuccessor(ContBB);
7795 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7796 MF->push_back(TrapBB);
7797 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7798 MBB->addSuccessor(TrapBB);
7800 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7801 .addReg(MI->getOperand(0).getReg())
7804 MI->eraseFromParent();
7809 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7810 MachineBasicBlock *BB) const {
7811 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7812 DebugLoc dl = MI->getDebugLoc();
7813 bool isThumb2 = Subtarget->isThumb2();
7814 switch (MI->getOpcode()) {
7817 llvm_unreachable("Unexpected instr type to insert");
7819 // The Thumb2 pre-indexed stores have the same MI operands, they just
7820 // define them differently in the .td files from the isel patterns, so
7821 // they need pseudos.
7822 case ARM::t2STR_preidx:
7823 MI->setDesc(TII->get(ARM::t2STR_PRE));
7825 case ARM::t2STRB_preidx:
7826 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7828 case ARM::t2STRH_preidx:
7829 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7832 case ARM::STRi_preidx:
7833 case ARM::STRBi_preidx: {
7834 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7835 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7836 // Decode the offset.
7837 unsigned Offset = MI->getOperand(4).getImm();
7838 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7839 Offset = ARM_AM::getAM2Offset(Offset);
7843 MachineMemOperand *MMO = *MI->memoperands_begin();
7844 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7845 .addOperand(MI->getOperand(0)) // Rn_wb
7846 .addOperand(MI->getOperand(1)) // Rt
7847 .addOperand(MI->getOperand(2)) // Rn
7848 .addImm(Offset) // offset (skip GPR==zero_reg)
7849 .addOperand(MI->getOperand(5)) // pred
7850 .addOperand(MI->getOperand(6))
7851 .addMemOperand(MMO);
7852 MI->eraseFromParent();
7855 case ARM::STRr_preidx:
7856 case ARM::STRBr_preidx:
7857 case ARM::STRH_preidx: {
7859 switch (MI->getOpcode()) {
7860 default: llvm_unreachable("unexpected opcode!");
7861 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7862 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7863 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7865 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7866 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7867 MIB.addOperand(MI->getOperand(i));
7868 MI->eraseFromParent();
7872 case ARM::tMOVCCr_pseudo: {
7873 // To "insert" a SELECT_CC instruction, we actually have to insert the
7874 // diamond control-flow pattern. The incoming instruction knows the
7875 // destination vreg to set, the condition code register to branch on, the
7876 // true/false values to select between, and a branch opcode to use.
7877 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7878 MachineFunction::iterator It = ++BB->getIterator();
7883 // cmpTY ccX, r1, r2
7885 // fallthrough --> copy0MBB
7886 MachineBasicBlock *thisMBB = BB;
7887 MachineFunction *F = BB->getParent();
7888 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7889 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7890 F->insert(It, copy0MBB);
7891 F->insert(It, sinkMBB);
7893 // Transfer the remainder of BB and its successor edges to sinkMBB.
7894 sinkMBB->splice(sinkMBB->begin(), BB,
7895 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7896 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7898 BB->addSuccessor(copy0MBB);
7899 BB->addSuccessor(sinkMBB);
7901 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7902 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7905 // %FalseValue = ...
7906 // # fallthrough to sinkMBB
7909 // Update machine-CFG edges
7910 BB->addSuccessor(sinkMBB);
7913 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7916 BuildMI(*BB, BB->begin(), dl,
7917 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7918 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7919 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7921 MI->eraseFromParent(); // The pseudo instruction is gone now.
7926 case ARM::BCCZi64: {
7927 // If there is an unconditional branch to the other successor, remove it.
7928 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7930 // Compare both parts that make up the double comparison separately for
7932 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7934 unsigned LHS1 = MI->getOperand(1).getReg();
7935 unsigned LHS2 = MI->getOperand(2).getReg();
7937 AddDefaultPred(BuildMI(BB, dl,
7938 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7939 .addReg(LHS1).addImm(0));
7940 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7941 .addReg(LHS2).addImm(0)
7942 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7944 unsigned RHS1 = MI->getOperand(3).getReg();
7945 unsigned RHS2 = MI->getOperand(4).getReg();
7946 AddDefaultPred(BuildMI(BB, dl,
7947 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7948 .addReg(LHS1).addReg(RHS1));
7949 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7950 .addReg(LHS2).addReg(RHS2)
7951 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7954 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7955 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7956 if (MI->getOperand(0).getImm() == ARMCC::NE)
7957 std::swap(destMBB, exitMBB);
7959 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7960 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7962 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7964 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7966 MI->eraseFromParent(); // The pseudo instruction is gone now.
7970 case ARM::Int_eh_sjlj_setjmp:
7971 case ARM::Int_eh_sjlj_setjmp_nofp:
7972 case ARM::tInt_eh_sjlj_setjmp:
7973 case ARM::t2Int_eh_sjlj_setjmp:
7974 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7977 case ARM::Int_eh_sjlj_setup_dispatch:
7978 EmitSjLjDispatchBlock(MI, BB);
7983 // To insert an ABS instruction, we have to insert the
7984 // diamond control-flow pattern. The incoming instruction knows the
7985 // source vreg to test against 0, the destination vreg to set,
7986 // the condition code register to branch on, the
7987 // true/false values to select between, and a branch opcode to use.
7992 // BCC (branch to SinkBB if V0 >= 0)
7993 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7994 // SinkBB: V1 = PHI(V2, V3)
7995 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7996 MachineFunction::iterator BBI = ++BB->getIterator();
7997 MachineFunction *Fn = BB->getParent();
7998 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7999 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8000 Fn->insert(BBI, RSBBB);
8001 Fn->insert(BBI, SinkBB);
8003 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8004 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8005 bool ABSSrcKIll = MI->getOperand(1).isKill();
8006 bool isThumb2 = Subtarget->isThumb2();
8007 MachineRegisterInfo &MRI = Fn->getRegInfo();
8008 // In Thumb mode S must not be specified if source register is the SP or
8009 // PC and if destination register is the SP, so restrict register class
8010 unsigned NewRsbDstReg =
8011 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8013 // Transfer the remainder of BB and its successor edges to sinkMBB.
8014 SinkBB->splice(SinkBB->begin(), BB,
8015 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8016 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8018 BB->addSuccessor(RSBBB);
8019 BB->addSuccessor(SinkBB);
8021 // fall through to SinkMBB
8022 RSBBB->addSuccessor(SinkBB);
8024 // insert a cmp at the end of BB
8025 AddDefaultPred(BuildMI(BB, dl,
8026 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8027 .addReg(ABSSrcReg).addImm(0));
8029 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8031 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8032 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8034 // insert rsbri in RSBBB
8035 // Note: BCC and rsbri will be converted into predicated rsbmi
8036 // by if-conversion pass
8037 BuildMI(*RSBBB, RSBBB->begin(), dl,
8038 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8039 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8040 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8042 // insert PHI in SinkBB,
8043 // reuse ABSDstReg to not change uses of ABS instruction
8044 BuildMI(*SinkBB, SinkBB->begin(), dl,
8045 TII->get(ARM::PHI), ABSDstReg)
8046 .addReg(NewRsbDstReg).addMBB(RSBBB)
8047 .addReg(ABSSrcReg).addMBB(BB);
8049 // remove ABS instruction
8050 MI->eraseFromParent();
8052 // return last added BB
8055 case ARM::COPY_STRUCT_BYVAL_I32:
8057 return EmitStructByval(MI, BB);
8058 case ARM::WIN__CHKSTK:
8059 return EmitLowered__chkstk(MI, BB);
8060 case ARM::WIN__DBZCHK:
8061 return EmitLowered__dbzchk(MI, BB);
8065 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8066 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8067 /// instead of as a custom inserter because we need the use list from the SDNode.
8068 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8069 MachineInstr *MI, const SDNode *Node) {
8070 bool isThumb1 = Subtarget->isThumb1Only();
8072 DebugLoc DL = MI->getDebugLoc();
8073 MachineFunction *MF = MI->getParent()->getParent();
8074 MachineRegisterInfo &MRI = MF->getRegInfo();
8075 MachineInstrBuilder MIB(*MF, MI);
8077 // If the new dst/src is unused mark it as dead.
8078 if (!Node->hasAnyUseOfValue(0)) {
8079 MI->getOperand(0).setIsDead(true);
8081 if (!Node->hasAnyUseOfValue(1)) {
8082 MI->getOperand(1).setIsDead(true);
8085 // The MEMCPY both defines and kills the scratch registers.
8086 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8087 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8088 : &ARM::GPRRegClass);
8089 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8093 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8094 SDNode *Node) const {
8095 if (MI->getOpcode() == ARM::MEMCPY) {
8096 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8100 const MCInstrDesc *MCID = &MI->getDesc();
8101 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8102 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8103 // operand is still set to noreg. If needed, set the optional operand's
8104 // register to CPSR, and remove the redundant implicit def.
8106 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8108 // Rename pseudo opcodes.
8109 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8111 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8112 MCID = &TII->get(NewOpc);
8114 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8115 "converted opcode should be the same except for cc_out");
8119 // Add the optional cc_out operand
8120 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8122 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8124 // Any ARM instruction that sets the 's' bit should specify an optional
8125 // "cc_out" operand in the last operand position.
8126 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8127 assert(!NewOpc && "Optional cc_out operand required");
8130 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8131 // since we already have an optional CPSR def.
8132 bool definesCPSR = false;
8133 bool deadCPSR = false;
8134 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8136 const MachineOperand &MO = MI->getOperand(i);
8137 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8141 MI->RemoveOperand(i);
8146 assert(!NewOpc && "Optional cc_out operand required");
8149 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8151 assert(!MI->getOperand(ccOutIdx).getReg() &&
8152 "expect uninitialized optional cc_out operand");
8156 // If this instruction was defined with an optional CPSR def and its dag node
8157 // had a live implicit CPSR def, then activate the optional CPSR def.
8158 MachineOperand &MO = MI->getOperand(ccOutIdx);
8159 MO.setReg(ARM::CPSR);
8163 //===----------------------------------------------------------------------===//
8164 // ARM Optimization Hooks
8165 //===----------------------------------------------------------------------===//
8167 // Helper function that checks if N is a null or all ones constant.
8168 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8169 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8172 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8175 // Return true if N is conditionally 0 or all ones.
8176 // Detects these expressions where cc is an i1 value:
8178 // (select cc 0, y) [AllOnes=0]
8179 // (select cc y, 0) [AllOnes=0]
8180 // (zext cc) [AllOnes=0]
8181 // (sext cc) [AllOnes=0/1]
8182 // (select cc -1, y) [AllOnes=1]
8183 // (select cc y, -1) [AllOnes=1]
8185 // Invert is set when N is the null/all ones constant when CC is false.
8186 // OtherOp is set to the alternative value of N.
8187 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8188 SDValue &CC, bool &Invert,
8190 SelectionDAG &DAG) {
8191 switch (N->getOpcode()) {
8192 default: return false;
8194 CC = N->getOperand(0);
8195 SDValue N1 = N->getOperand(1);
8196 SDValue N2 = N->getOperand(2);
8197 if (isZeroOrAllOnes(N1, AllOnes)) {
8202 if (isZeroOrAllOnes(N2, AllOnes)) {
8209 case ISD::ZERO_EXTEND:
8210 // (zext cc) can never be the all ones value.
8214 case ISD::SIGN_EXTEND: {
8216 EVT VT = N->getValueType(0);
8217 CC = N->getOperand(0);
8218 if (CC.getValueType() != MVT::i1)
8222 // When looking for an AllOnes constant, N is an sext, and the 'other'
8224 OtherOp = DAG.getConstant(0, dl, VT);
8225 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8226 // When looking for a 0 constant, N can be zext or sext.
8227 OtherOp = DAG.getConstant(1, dl, VT);
8229 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8236 // Combine a constant select operand into its use:
8238 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8239 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8240 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8241 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8242 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8244 // The transform is rejected if the select doesn't have a constant operand that
8245 // is null, or all ones when AllOnes is set.
8247 // Also recognize sext/zext from i1:
8249 // (add (zext cc), x) -> (select cc (add x, 1), x)
8250 // (add (sext cc), x) -> (select cc (add x, -1), x)
8252 // These transformations eventually create predicated instructions.
8254 // @param N The node to transform.
8255 // @param Slct The N operand that is a select.
8256 // @param OtherOp The other N operand (x above).
8257 // @param DCI Context.
8258 // @param AllOnes Require the select constant to be all ones instead of null.
8259 // @returns The new node, or SDValue() on failure.
8261 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8262 TargetLowering::DAGCombinerInfo &DCI,
8263 bool AllOnes = false) {
8264 SelectionDAG &DAG = DCI.DAG;
8265 EVT VT = N->getValueType(0);
8266 SDValue NonConstantVal;
8269 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8270 NonConstantVal, DAG))
8273 // Slct is now know to be the desired identity constant when CC is true.
8274 SDValue TrueVal = OtherOp;
8275 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8276 OtherOp, NonConstantVal);
8277 // Unless SwapSelectOps says CC should be false.
8279 std::swap(TrueVal, FalseVal);
8281 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8282 CCOp, TrueVal, FalseVal);
8285 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8287 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8288 TargetLowering::DAGCombinerInfo &DCI) {
8289 SDValue N0 = N->getOperand(0);
8290 SDValue N1 = N->getOperand(1);
8291 if (N0.getNode()->hasOneUse()) {
8292 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8293 if (Result.getNode())
8296 if (N1.getNode()->hasOneUse()) {
8297 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8298 if (Result.getNode())
8304 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8305 // (only after legalization).
8306 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8307 TargetLowering::DAGCombinerInfo &DCI,
8308 const ARMSubtarget *Subtarget) {
8310 // Only perform optimization if after legalize, and if NEON is available. We
8311 // also expected both operands to be BUILD_VECTORs.
8312 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8313 || N0.getOpcode() != ISD::BUILD_VECTOR
8314 || N1.getOpcode() != ISD::BUILD_VECTOR)
8317 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8318 EVT VT = N->getValueType(0);
8319 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8322 // Check that the vector operands are of the right form.
8323 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8324 // operands, where N is the size of the formed vector.
8325 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8326 // index such that we have a pair wise add pattern.
8328 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8329 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8331 SDValue Vec = N0->getOperand(0)->getOperand(0);
8332 SDNode *V = Vec.getNode();
8333 unsigned nextIndex = 0;
8335 // For each operands to the ADD which are BUILD_VECTORs,
8336 // check to see if each of their operands are an EXTRACT_VECTOR with
8337 // the same vector and appropriate index.
8338 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8339 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8340 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8342 SDValue ExtVec0 = N0->getOperand(i);
8343 SDValue ExtVec1 = N1->getOperand(i);
8345 // First operand is the vector, verify its the same.
8346 if (V != ExtVec0->getOperand(0).getNode() ||
8347 V != ExtVec1->getOperand(0).getNode())
8350 // Second is the constant, verify its correct.
8351 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8352 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8354 // For the constant, we want to see all the even or all the odd.
8355 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8356 || C1->getZExtValue() != nextIndex+1)
8365 // Create VPADDL node.
8366 SelectionDAG &DAG = DCI.DAG;
8367 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8371 // Build operand list.
8372 SmallVector<SDValue, 8> Ops;
8373 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8374 TLI.getPointerTy(DAG.getDataLayout())));
8376 // Input is the vector.
8379 // Get widened type and narrowed type.
8381 unsigned numElem = VT.getVectorNumElements();
8383 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8384 switch (inputLaneType.getSimpleVT().SimpleTy) {
8385 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8386 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8387 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8389 llvm_unreachable("Invalid vector element type for padd optimization.");
8392 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8393 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8394 return DAG.getNode(ExtOp, dl, VT, tmp);
8397 static SDValue findMUL_LOHI(SDValue V) {
8398 if (V->getOpcode() == ISD::UMUL_LOHI ||
8399 V->getOpcode() == ISD::SMUL_LOHI)
8404 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8405 TargetLowering::DAGCombinerInfo &DCI,
8406 const ARMSubtarget *Subtarget) {
8408 if (Subtarget->isThumb1Only()) return SDValue();
8410 // Only perform the checks after legalize when the pattern is available.
8411 if (DCI.isBeforeLegalize()) return SDValue();
8413 // Look for multiply add opportunities.
8414 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8415 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8416 // a glue link from the first add to the second add.
8417 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8418 // a S/UMLAL instruction.
8421 // / \ [no multiline comment]
8427 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8428 SDValue AddcOp0 = AddcNode->getOperand(0);
8429 SDValue AddcOp1 = AddcNode->getOperand(1);
8431 // Check if the two operands are from the same mul_lohi node.
8432 if (AddcOp0.getNode() == AddcOp1.getNode())
8435 assert(AddcNode->getNumValues() == 2 &&
8436 AddcNode->getValueType(0) == MVT::i32 &&
8437 "Expect ADDC with two result values. First: i32");
8439 // Check that we have a glued ADDC node.
8440 if (AddcNode->getValueType(1) != MVT::Glue)
8443 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8444 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8445 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8446 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8447 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8450 // Look for the glued ADDE.
8451 SDNode* AddeNode = AddcNode->getGluedUser();
8455 // Make sure it is really an ADDE.
8456 if (AddeNode->getOpcode() != ISD::ADDE)
8459 assert(AddeNode->getNumOperands() == 3 &&
8460 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8461 "ADDE node has the wrong inputs");
8463 // Check for the triangle shape.
8464 SDValue AddeOp0 = AddeNode->getOperand(0);
8465 SDValue AddeOp1 = AddeNode->getOperand(1);
8467 // Make sure that the ADDE operands are not coming from the same node.
8468 if (AddeOp0.getNode() == AddeOp1.getNode())
8471 // Find the MUL_LOHI node walking up ADDE's operands.
8472 bool IsLeftOperandMUL = false;
8473 SDValue MULOp = findMUL_LOHI(AddeOp0);
8474 if (MULOp == SDValue())
8475 MULOp = findMUL_LOHI(AddeOp1);
8477 IsLeftOperandMUL = true;
8478 if (MULOp == SDValue())
8481 // Figure out the right opcode.
8482 unsigned Opc = MULOp->getOpcode();
8483 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8485 // Figure out the high and low input values to the MLAL node.
8486 SDValue* HiAdd = nullptr;
8487 SDValue* LoMul = nullptr;
8488 SDValue* LowAdd = nullptr;
8490 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8491 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8494 if (IsLeftOperandMUL)
8500 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8501 // whose low result is fed to the ADDC we are checking.
8503 if (AddcOp0 == MULOp.getValue(0)) {
8507 if (AddcOp1 == MULOp.getValue(0)) {
8515 // Create the merged node.
8516 SelectionDAG &DAG = DCI.DAG;
8518 // Build operand list.
8519 SmallVector<SDValue, 8> Ops;
8520 Ops.push_back(LoMul->getOperand(0));
8521 Ops.push_back(LoMul->getOperand(1));
8522 Ops.push_back(*LowAdd);
8523 Ops.push_back(*HiAdd);
8525 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8526 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8528 // Replace the ADDs' nodes uses by the MLA node's values.
8529 SDValue HiMLALResult(MLALNode.getNode(), 1);
8530 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8532 SDValue LoMLALResult(MLALNode.getNode(), 0);
8533 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8535 // Return original node to notify the driver to stop replacing.
8536 SDValue resNode(AddcNode, 0);
8540 /// PerformADDCCombine - Target-specific dag combine transform from
8541 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8542 static SDValue PerformADDCCombine(SDNode *N,
8543 TargetLowering::DAGCombinerInfo &DCI,
8544 const ARMSubtarget *Subtarget) {
8546 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8550 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8551 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8552 /// called with the default operands, and if that fails, with commuted
8554 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8555 TargetLowering::DAGCombinerInfo &DCI,
8556 const ARMSubtarget *Subtarget){
8558 // Attempt to create vpaddl for this add.
8559 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8560 if (Result.getNode())
8563 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8564 if (N0.getNode()->hasOneUse()) {
8565 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8566 if (Result.getNode()) return Result;
8571 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8573 static SDValue PerformADDCombine(SDNode *N,
8574 TargetLowering::DAGCombinerInfo &DCI,
8575 const ARMSubtarget *Subtarget) {
8576 SDValue N0 = N->getOperand(0);
8577 SDValue N1 = N->getOperand(1);
8579 // First try with the default operand order.
8580 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8581 if (Result.getNode())
8584 // If that didn't work, try again with the operands commuted.
8585 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8588 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8590 static SDValue PerformSUBCombine(SDNode *N,
8591 TargetLowering::DAGCombinerInfo &DCI) {
8592 SDValue N0 = N->getOperand(0);
8593 SDValue N1 = N->getOperand(1);
8595 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8596 if (N1.getNode()->hasOneUse()) {
8597 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8598 if (Result.getNode()) return Result;
8604 /// PerformVMULCombine
8605 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8606 /// special multiplier accumulator forwarding.
8612 // However, for (A + B) * (A + B),
8619 static SDValue PerformVMULCombine(SDNode *N,
8620 TargetLowering::DAGCombinerInfo &DCI,
8621 const ARMSubtarget *Subtarget) {
8622 if (!Subtarget->hasVMLxForwarding())
8625 SelectionDAG &DAG = DCI.DAG;
8626 SDValue N0 = N->getOperand(0);
8627 SDValue N1 = N->getOperand(1);
8628 unsigned Opcode = N0.getOpcode();
8629 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8630 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8631 Opcode = N1.getOpcode();
8632 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8633 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8641 EVT VT = N->getValueType(0);
8643 SDValue N00 = N0->getOperand(0);
8644 SDValue N01 = N0->getOperand(1);
8645 return DAG.getNode(Opcode, DL, VT,
8646 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8647 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8650 static SDValue PerformMULCombine(SDNode *N,
8651 TargetLowering::DAGCombinerInfo &DCI,
8652 const ARMSubtarget *Subtarget) {
8653 SelectionDAG &DAG = DCI.DAG;
8655 if (Subtarget->isThumb1Only())
8658 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8661 EVT VT = N->getValueType(0);
8662 if (VT.is64BitVector() || VT.is128BitVector())
8663 return PerformVMULCombine(N, DCI, Subtarget);
8667 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8671 int64_t MulAmt = C->getSExtValue();
8672 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8674 ShiftAmt = ShiftAmt & (32 - 1);
8675 SDValue V = N->getOperand(0);
8679 MulAmt >>= ShiftAmt;
8682 if (isPowerOf2_32(MulAmt - 1)) {
8683 // (mul x, 2^N + 1) => (add (shl x, N), x)
8684 Res = DAG.getNode(ISD::ADD, DL, VT,
8686 DAG.getNode(ISD::SHL, DL, VT,
8688 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8690 } else if (isPowerOf2_32(MulAmt + 1)) {
8691 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8692 Res = DAG.getNode(ISD::SUB, DL, VT,
8693 DAG.getNode(ISD::SHL, DL, VT,
8695 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8701 uint64_t MulAmtAbs = -MulAmt;
8702 if (isPowerOf2_32(MulAmtAbs + 1)) {
8703 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8704 Res = DAG.getNode(ISD::SUB, DL, VT,
8706 DAG.getNode(ISD::SHL, DL, VT,
8708 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8710 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8711 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8712 Res = DAG.getNode(ISD::ADD, DL, VT,
8714 DAG.getNode(ISD::SHL, DL, VT,
8716 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8718 Res = DAG.getNode(ISD::SUB, DL, VT,
8719 DAG.getConstant(0, DL, MVT::i32), Res);
8726 Res = DAG.getNode(ISD::SHL, DL, VT,
8727 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8729 // Do not add new nodes to DAG combiner worklist.
8730 DCI.CombineTo(N, Res, false);
8734 static SDValue PerformANDCombine(SDNode *N,
8735 TargetLowering::DAGCombinerInfo &DCI,
8736 const ARMSubtarget *Subtarget) {
8738 // Attempt to use immediate-form VBIC
8739 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8741 EVT VT = N->getValueType(0);
8742 SelectionDAG &DAG = DCI.DAG;
8744 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8747 APInt SplatBits, SplatUndef;
8748 unsigned SplatBitSize;
8751 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8752 if (SplatBitSize <= 64) {
8754 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8755 SplatUndef.getZExtValue(), SplatBitSize,
8756 DAG, dl, VbicVT, VT.is128BitVector(),
8758 if (Val.getNode()) {
8760 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8761 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8762 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8767 if (!Subtarget->isThumb1Only()) {
8768 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8769 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8770 if (Result.getNode())
8777 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8778 static SDValue PerformORCombine(SDNode *N,
8779 TargetLowering::DAGCombinerInfo &DCI,
8780 const ARMSubtarget *Subtarget) {
8781 // Attempt to use immediate-form VORR
8782 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8784 EVT VT = N->getValueType(0);
8785 SelectionDAG &DAG = DCI.DAG;
8787 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8790 APInt SplatBits, SplatUndef;
8791 unsigned SplatBitSize;
8793 if (BVN && Subtarget->hasNEON() &&
8794 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8795 if (SplatBitSize <= 64) {
8797 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8798 SplatUndef.getZExtValue(), SplatBitSize,
8799 DAG, dl, VorrVT, VT.is128BitVector(),
8801 if (Val.getNode()) {
8803 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8804 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8805 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8810 if (!Subtarget->isThumb1Only()) {
8811 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8812 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8813 if (Result.getNode())
8817 // The code below optimizes (or (and X, Y), Z).
8818 // The AND operand needs to have a single user to make these optimizations
8820 SDValue N0 = N->getOperand(0);
8821 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8823 SDValue N1 = N->getOperand(1);
8825 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8826 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8827 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8829 unsigned SplatBitSize;
8832 APInt SplatBits0, SplatBits1;
8833 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8834 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8835 // Ensure that the second operand of both ands are constants
8836 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8837 HasAnyUndefs) && !HasAnyUndefs) {
8838 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8839 HasAnyUndefs) && !HasAnyUndefs) {
8840 // Ensure that the bit width of the constants are the same and that
8841 // the splat arguments are logical inverses as per the pattern we
8842 // are trying to simplify.
8843 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8844 SplatBits0 == ~SplatBits1) {
8845 // Canonicalize the vector type to make instruction selection
8847 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8848 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8852 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8858 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8861 // BFI is only available on V6T2+
8862 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8866 // 1) or (and A, mask), val => ARMbfi A, val, mask
8867 // iff (val & mask) == val
8869 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8870 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8871 // && mask == ~mask2
8872 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8873 // && ~mask == mask2
8874 // (i.e., copy a bitfield value into another bitfield of the same width)
8879 SDValue N00 = N0.getOperand(0);
8881 // The value and the mask need to be constants so we can verify this is
8882 // actually a bitfield set. If the mask is 0xffff, we can do better
8883 // via a movt instruction, so don't use BFI in that case.
8884 SDValue MaskOp = N0.getOperand(1);
8885 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8888 unsigned Mask = MaskC->getZExtValue();
8892 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8893 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8895 unsigned Val = N1C->getZExtValue();
8896 if ((Val & ~Mask) != Val)
8899 if (ARM::isBitFieldInvertedMask(Mask)) {
8900 Val >>= countTrailingZeros(~Mask);
8902 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8903 DAG.getConstant(Val, DL, MVT::i32),
8904 DAG.getConstant(Mask, DL, MVT::i32));
8906 // Do not add new nodes to DAG combiner worklist.
8907 DCI.CombineTo(N, Res, false);
8910 } else if (N1.getOpcode() == ISD::AND) {
8911 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8912 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8915 unsigned Mask2 = N11C->getZExtValue();
8917 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8919 if (ARM::isBitFieldInvertedMask(Mask) &&
8921 // The pack halfword instruction works better for masks that fit it,
8922 // so use that when it's available.
8923 if (Subtarget->hasT2ExtractPack() &&
8924 (Mask == 0xffff || Mask == 0xffff0000))
8927 unsigned amt = countTrailingZeros(Mask2);
8928 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8929 DAG.getConstant(amt, DL, MVT::i32));
8930 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8931 DAG.getConstant(Mask, DL, MVT::i32));
8932 // Do not add new nodes to DAG combiner worklist.
8933 DCI.CombineTo(N, Res, false);
8935 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8937 // The pack halfword instruction works better for masks that fit it,
8938 // so use that when it's available.
8939 if (Subtarget->hasT2ExtractPack() &&
8940 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8943 unsigned lsb = countTrailingZeros(Mask);
8944 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8945 DAG.getConstant(lsb, DL, MVT::i32));
8946 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8947 DAG.getConstant(Mask2, DL, MVT::i32));
8948 // Do not add new nodes to DAG combiner worklist.
8949 DCI.CombineTo(N, Res, false);
8954 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8955 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8956 ARM::isBitFieldInvertedMask(~Mask)) {
8957 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8958 // where lsb(mask) == #shamt and masked bits of B are known zero.
8959 SDValue ShAmt = N00.getOperand(1);
8960 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8961 unsigned LSB = countTrailingZeros(Mask);
8965 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8966 DAG.getConstant(~Mask, DL, MVT::i32));
8968 // Do not add new nodes to DAG combiner worklist.
8969 DCI.CombineTo(N, Res, false);
8975 static SDValue PerformXORCombine(SDNode *N,
8976 TargetLowering::DAGCombinerInfo &DCI,
8977 const ARMSubtarget *Subtarget) {
8978 EVT VT = N->getValueType(0);
8979 SelectionDAG &DAG = DCI.DAG;
8981 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8984 if (!Subtarget->isThumb1Only()) {
8985 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8986 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8987 if (Result.getNode())
8994 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8995 /// the bits being cleared by the AND are not demanded by the BFI.
8996 static SDValue PerformBFICombine(SDNode *N,
8997 TargetLowering::DAGCombinerInfo &DCI) {
8998 SDValue N1 = N->getOperand(1);
8999 if (N1.getOpcode() == ISD::AND) {
9000 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9003 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9004 unsigned LSB = countTrailingZeros(~InvMask);
9005 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9007 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9008 "undefined behavior");
9009 unsigned Mask = (1u << Width) - 1;
9010 unsigned Mask2 = N11C->getZExtValue();
9011 if ((Mask & (~Mask2)) == 0)
9012 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9013 N->getOperand(0), N1.getOperand(0),
9019 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9020 /// ARMISD::VMOVRRD.
9021 static SDValue PerformVMOVRRDCombine(SDNode *N,
9022 TargetLowering::DAGCombinerInfo &DCI,
9023 const ARMSubtarget *Subtarget) {
9024 // vmovrrd(vmovdrr x, y) -> x,y
9025 SDValue InDouble = N->getOperand(0);
9026 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9027 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9029 // vmovrrd(load f64) -> (load i32), (load i32)
9030 SDNode *InNode = InDouble.getNode();
9031 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9032 InNode->getValueType(0) == MVT::f64 &&
9033 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9034 !cast<LoadSDNode>(InNode)->isVolatile()) {
9035 // TODO: Should this be done for non-FrameIndex operands?
9036 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9038 SelectionDAG &DAG = DCI.DAG;
9040 SDValue BasePtr = LD->getBasePtr();
9041 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9042 LD->getPointerInfo(), LD->isVolatile(),
9043 LD->isNonTemporal(), LD->isInvariant(),
9044 LD->getAlignment());
9046 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9047 DAG.getConstant(4, DL, MVT::i32));
9048 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9049 LD->getPointerInfo(), LD->isVolatile(),
9050 LD->isNonTemporal(), LD->isInvariant(),
9051 std::min(4U, LD->getAlignment() / 2));
9053 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9054 if (DCI.DAG.getDataLayout().isBigEndian())
9055 std::swap (NewLD1, NewLD2);
9056 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9063 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9064 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9065 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9066 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9067 SDValue Op0 = N->getOperand(0);
9068 SDValue Op1 = N->getOperand(1);
9069 if (Op0.getOpcode() == ISD::BITCAST)
9070 Op0 = Op0.getOperand(0);
9071 if (Op1.getOpcode() == ISD::BITCAST)
9072 Op1 = Op1.getOperand(0);
9073 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9074 Op0.getNode() == Op1.getNode() &&
9075 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9076 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9077 N->getValueType(0), Op0.getOperand(0));
9081 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9082 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9083 /// i64 vector to have f64 elements, since the value can then be loaded
9084 /// directly into a VFP register.
9085 static bool hasNormalLoadOperand(SDNode *N) {
9086 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9087 for (unsigned i = 0; i < NumElts; ++i) {
9088 SDNode *Elt = N->getOperand(i).getNode();
9089 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9095 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9096 /// ISD::BUILD_VECTOR.
9097 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9098 TargetLowering::DAGCombinerInfo &DCI,
9099 const ARMSubtarget *Subtarget) {
9100 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9101 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9102 // into a pair of GPRs, which is fine when the value is used as a scalar,
9103 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9104 SelectionDAG &DAG = DCI.DAG;
9105 if (N->getNumOperands() == 2) {
9106 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9111 // Load i64 elements as f64 values so that type legalization does not split
9112 // them up into i32 values.
9113 EVT VT = N->getValueType(0);
9114 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9117 SmallVector<SDValue, 8> Ops;
9118 unsigned NumElts = VT.getVectorNumElements();
9119 for (unsigned i = 0; i < NumElts; ++i) {
9120 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9122 // Make the DAGCombiner fold the bitcast.
9123 DCI.AddToWorklist(V.getNode());
9125 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9126 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9127 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9130 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9132 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9133 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9134 // At that time, we may have inserted bitcasts from integer to float.
9135 // If these bitcasts have survived DAGCombine, change the lowering of this
9136 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9137 // force to use floating point types.
9139 // Make sure we can change the type of the vector.
9140 // This is possible iff:
9141 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9142 // 1.1. Vector is used only once.
9143 // 1.2. Use is a bit convert to an integer type.
9144 // 2. The size of its operands are 32-bits (64-bits are not legal).
9145 EVT VT = N->getValueType(0);
9146 EVT EltVT = VT.getVectorElementType();
9148 // Check 1.1. and 2.
9149 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9152 // By construction, the input type must be float.
9153 assert(EltVT == MVT::f32 && "Unexpected type!");
9156 SDNode *Use = *N->use_begin();
9157 if (Use->getOpcode() != ISD::BITCAST ||
9158 Use->getValueType(0).isFloatingPoint())
9161 // Check profitability.
9162 // Model is, if more than half of the relevant operands are bitcast from
9163 // i32, turn the build_vector into a sequence of insert_vector_elt.
9164 // Relevant operands are everything that is not statically
9165 // (i.e., at compile time) bitcasted.
9166 unsigned NumOfBitCastedElts = 0;
9167 unsigned NumElts = VT.getVectorNumElements();
9168 unsigned NumOfRelevantElts = NumElts;
9169 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9170 SDValue Elt = N->getOperand(Idx);
9171 if (Elt->getOpcode() == ISD::BITCAST) {
9172 // Assume only bit cast to i32 will go away.
9173 if (Elt->getOperand(0).getValueType() == MVT::i32)
9174 ++NumOfBitCastedElts;
9175 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9176 // Constants are statically casted, thus do not count them as
9177 // relevant operands.
9178 --NumOfRelevantElts;
9181 // Check if more than half of the elements require a non-free bitcast.
9182 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9185 SelectionDAG &DAG = DCI.DAG;
9186 // Create the new vector type.
9187 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9188 // Check if the type is legal.
9189 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9190 if (!TLI.isTypeLegal(VecVT))
9194 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9195 // => BITCAST INSERT_VECTOR_ELT
9196 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9198 SDValue Vec = DAG.getUNDEF(VecVT);
9200 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9201 SDValue V = N->getOperand(Idx);
9202 if (V.getOpcode() == ISD::UNDEF)
9204 if (V.getOpcode() == ISD::BITCAST &&
9205 V->getOperand(0).getValueType() == MVT::i32)
9206 // Fold obvious case.
9207 V = V.getOperand(0);
9209 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9210 // Make the DAGCombiner fold the bitcasts.
9211 DCI.AddToWorklist(V.getNode());
9213 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9214 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9216 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9217 // Make the DAGCombiner fold the bitcasts.
9218 DCI.AddToWorklist(Vec.getNode());
9222 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9223 /// ISD::INSERT_VECTOR_ELT.
9224 static SDValue PerformInsertEltCombine(SDNode *N,
9225 TargetLowering::DAGCombinerInfo &DCI) {
9226 // Bitcast an i64 load inserted into a vector to f64.
9227 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9228 EVT VT = N->getValueType(0);
9229 SDNode *Elt = N->getOperand(1).getNode();
9230 if (VT.getVectorElementType() != MVT::i64 ||
9231 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9234 SelectionDAG &DAG = DCI.DAG;
9236 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9237 VT.getVectorNumElements());
9238 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9239 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9240 // Make the DAGCombiner fold the bitcasts.
9241 DCI.AddToWorklist(Vec.getNode());
9242 DCI.AddToWorklist(V.getNode());
9243 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9244 Vec, V, N->getOperand(2));
9245 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9248 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9249 /// ISD::VECTOR_SHUFFLE.
9250 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9251 // The LLVM shufflevector instruction does not require the shuffle mask
9252 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9253 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9254 // operands do not match the mask length, they are extended by concatenating
9255 // them with undef vectors. That is probably the right thing for other
9256 // targets, but for NEON it is better to concatenate two double-register
9257 // size vector operands into a single quad-register size vector. Do that
9258 // transformation here:
9259 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9260 // shuffle(concat(v1, v2), undef)
9261 SDValue Op0 = N->getOperand(0);
9262 SDValue Op1 = N->getOperand(1);
9263 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9264 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9265 Op0.getNumOperands() != 2 ||
9266 Op1.getNumOperands() != 2)
9268 SDValue Concat0Op1 = Op0.getOperand(1);
9269 SDValue Concat1Op1 = Op1.getOperand(1);
9270 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9271 Concat1Op1.getOpcode() != ISD::UNDEF)
9273 // Skip the transformation if any of the types are illegal.
9274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9275 EVT VT = N->getValueType(0);
9276 if (!TLI.isTypeLegal(VT) ||
9277 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9278 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9281 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9282 Op0.getOperand(0), Op1.getOperand(0));
9283 // Translate the shuffle mask.
9284 SmallVector<int, 16> NewMask;
9285 unsigned NumElts = VT.getVectorNumElements();
9286 unsigned HalfElts = NumElts/2;
9287 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9288 for (unsigned n = 0; n < NumElts; ++n) {
9289 int MaskElt = SVN->getMaskElt(n);
9291 if (MaskElt < (int)HalfElts)
9293 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9294 NewElt = HalfElts + MaskElt - NumElts;
9295 NewMask.push_back(NewElt);
9297 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9298 DAG.getUNDEF(VT), NewMask.data());
9301 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9302 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9303 /// base address updates.
9304 /// For generic load/stores, the memory type is assumed to be a vector.
9305 /// The caller is assumed to have checked legality.
9306 static SDValue CombineBaseUpdate(SDNode *N,
9307 TargetLowering::DAGCombinerInfo &DCI) {
9308 SelectionDAG &DAG = DCI.DAG;
9309 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9310 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9311 const bool isStore = N->getOpcode() == ISD::STORE;
9312 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9313 SDValue Addr = N->getOperand(AddrOpIdx);
9314 MemSDNode *MemN = cast<MemSDNode>(N);
9317 // Search for a use of the address operand that is an increment.
9318 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9319 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9321 if (User->getOpcode() != ISD::ADD ||
9322 UI.getUse().getResNo() != Addr.getResNo())
9325 // Check that the add is independent of the load/store. Otherwise, folding
9326 // it would create a cycle.
9327 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9330 // Find the new opcode for the updating load/store.
9331 bool isLoadOp = true;
9332 bool isLaneOp = false;
9333 unsigned NewOpc = 0;
9334 unsigned NumVecs = 0;
9336 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9338 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9339 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9341 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9343 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9345 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9347 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9348 NumVecs = 2; isLaneOp = true; break;
9349 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9350 NumVecs = 3; isLaneOp = true; break;
9351 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9352 NumVecs = 4; isLaneOp = true; break;
9353 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9354 NumVecs = 1; isLoadOp = false; break;
9355 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9356 NumVecs = 2; isLoadOp = false; break;
9357 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9358 NumVecs = 3; isLoadOp = false; break;
9359 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9360 NumVecs = 4; isLoadOp = false; break;
9361 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9362 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9363 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9364 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9365 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9366 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9370 switch (N->getOpcode()) {
9371 default: llvm_unreachable("unexpected opcode for Neon base update");
9372 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9373 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9374 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9375 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9376 NumVecs = 1; isLaneOp = false; break;
9377 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9378 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9382 // Find the size of memory referenced by the load/store.
9385 VecTy = N->getValueType(0);
9386 } else if (isIntrinsic) {
9387 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9389 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9390 VecTy = N->getOperand(1).getValueType();
9393 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9395 NumBytes /= VecTy.getVectorNumElements();
9397 // If the increment is a constant, it must match the memory ref size.
9398 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9399 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9400 uint64_t IncVal = CInc->getZExtValue();
9401 if (IncVal != NumBytes)
9403 } else if (NumBytes >= 3 * 16) {
9404 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9405 // separate instructions that make it harder to use a non-constant update.
9409 // OK, we found an ADD we can fold into the base update.
9410 // Now, create a _UPD node, taking care of not breaking alignment.
9412 EVT AlignedVecTy = VecTy;
9413 unsigned Alignment = MemN->getAlignment();
9415 // If this is a less-than-standard-aligned load/store, change the type to
9416 // match the standard alignment.
9417 // The alignment is overlooked when selecting _UPD variants; and it's
9418 // easier to introduce bitcasts here than fix that.
9419 // There are 3 ways to get to this base-update combine:
9420 // - intrinsics: they are assumed to be properly aligned (to the standard
9421 // alignment of the memory type), so we don't need to do anything.
9422 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9423 // intrinsics, so, likewise, there's nothing to do.
9424 // - generic load/store instructions: the alignment is specified as an
9425 // explicit operand, rather than implicitly as the standard alignment
9426 // of the memory type (like the intrisics). We need to change the
9427 // memory type to match the explicit alignment. That way, we don't
9428 // generate non-standard-aligned ARMISD::VLDx nodes.
9429 if (isa<LSBaseSDNode>(N)) {
9432 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9433 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9434 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9435 assert(!isLaneOp && "Unexpected generic load/store lane.");
9436 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9437 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9439 // Don't set an explicit alignment on regular load/stores that we want
9440 // to transform to VLD/VST 1_UPD nodes.
9441 // This matches the behavior of regular load/stores, which only get an
9442 // explicit alignment if the MMO alignment is larger than the standard
9443 // alignment of the memory type.
9444 // Intrinsics, however, always get an explicit alignment, set to the
9445 // alignment of the MMO.
9449 // Create the new updating load/store node.
9450 // First, create an SDVTList for the new updating node's results.
9452 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9454 for (n = 0; n < NumResultVecs; ++n)
9455 Tys[n] = AlignedVecTy;
9456 Tys[n++] = MVT::i32;
9457 Tys[n] = MVT::Other;
9458 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9460 // Then, gather the new node's operands.
9461 SmallVector<SDValue, 8> Ops;
9462 Ops.push_back(N->getOperand(0)); // incoming chain
9463 Ops.push_back(N->getOperand(AddrOpIdx));
9466 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9467 // Try to match the intrinsic's signature
9468 Ops.push_back(StN->getValue());
9470 // Loads (and of course intrinsics) match the intrinsics' signature,
9471 // so just add all but the alignment operand.
9472 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9473 Ops.push_back(N->getOperand(i));
9476 // For all node types, the alignment operand is always the last one.
9477 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9479 // If this is a non-standard-aligned STORE, the penultimate operand is the
9480 // stored value. Bitcast it to the aligned type.
9481 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9482 SDValue &StVal = Ops[Ops.size()-2];
9483 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9486 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9488 MemN->getMemOperand());
9491 SmallVector<SDValue, 5> NewResults;
9492 for (unsigned i = 0; i < NumResultVecs; ++i)
9493 NewResults.push_back(SDValue(UpdN.getNode(), i));
9495 // If this is an non-standard-aligned LOAD, the first result is the loaded
9496 // value. Bitcast it to the expected result type.
9497 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9498 SDValue &LdVal = NewResults[0];
9499 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9502 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9503 DCI.CombineTo(N, NewResults);
9504 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9511 static SDValue PerformVLDCombine(SDNode *N,
9512 TargetLowering::DAGCombinerInfo &DCI) {
9513 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9516 return CombineBaseUpdate(N, DCI);
9519 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9520 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9521 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9523 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9524 SelectionDAG &DAG = DCI.DAG;
9525 EVT VT = N->getValueType(0);
9526 // vldN-dup instructions only support 64-bit vectors for N > 1.
9527 if (!VT.is64BitVector())
9530 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9531 SDNode *VLD = N->getOperand(0).getNode();
9532 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9534 unsigned NumVecs = 0;
9535 unsigned NewOpc = 0;
9536 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9537 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9539 NewOpc = ARMISD::VLD2DUP;
9540 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9542 NewOpc = ARMISD::VLD3DUP;
9543 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9545 NewOpc = ARMISD::VLD4DUP;
9550 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9551 // numbers match the load.
9552 unsigned VLDLaneNo =
9553 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9554 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9556 // Ignore uses of the chain result.
9557 if (UI.getUse().getResNo() == NumVecs)
9560 if (User->getOpcode() != ARMISD::VDUPLANE ||
9561 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9565 // Create the vldN-dup node.
9568 for (n = 0; n < NumVecs; ++n)
9570 Tys[n] = MVT::Other;
9571 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9572 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9573 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9574 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9575 Ops, VLDMemInt->getMemoryVT(),
9576 VLDMemInt->getMemOperand());
9579 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9581 unsigned ResNo = UI.getUse().getResNo();
9582 // Ignore uses of the chain result.
9583 if (ResNo == NumVecs)
9586 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9589 // Now the vldN-lane intrinsic is dead except for its chain result.
9590 // Update uses of the chain.
9591 std::vector<SDValue> VLDDupResults;
9592 for (unsigned n = 0; n < NumVecs; ++n)
9593 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9594 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9595 DCI.CombineTo(VLD, VLDDupResults);
9600 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9601 /// ARMISD::VDUPLANE.
9602 static SDValue PerformVDUPLANECombine(SDNode *N,
9603 TargetLowering::DAGCombinerInfo &DCI) {
9604 SDValue Op = N->getOperand(0);
9606 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9607 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9608 if (CombineVLDDUP(N, DCI))
9609 return SDValue(N, 0);
9611 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9612 // redundant. Ignore bit_converts for now; element sizes are checked below.
9613 while (Op.getOpcode() == ISD::BITCAST)
9614 Op = Op.getOperand(0);
9615 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9618 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9619 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9620 // The canonical VMOV for a zero vector uses a 32-bit element size.
9621 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9623 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9625 EVT VT = N->getValueType(0);
9626 if (EltSize > VT.getVectorElementType().getSizeInBits())
9629 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9632 static SDValue PerformLOADCombine(SDNode *N,
9633 TargetLowering::DAGCombinerInfo &DCI) {
9634 EVT VT = N->getValueType(0);
9636 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9637 if (ISD::isNormalLoad(N) && VT.isVector() &&
9638 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9639 return CombineBaseUpdate(N, DCI);
9644 /// PerformSTORECombine - Target-specific dag combine xforms for
9646 static SDValue PerformSTORECombine(SDNode *N,
9647 TargetLowering::DAGCombinerInfo &DCI) {
9648 StoreSDNode *St = cast<StoreSDNode>(N);
9649 if (St->isVolatile())
9652 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9653 // pack all of the elements in one place. Next, store to memory in fewer
9655 SDValue StVal = St->getValue();
9656 EVT VT = StVal.getValueType();
9657 if (St->isTruncatingStore() && VT.isVector()) {
9658 SelectionDAG &DAG = DCI.DAG;
9659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9660 EVT StVT = St->getMemoryVT();
9661 unsigned NumElems = VT.getVectorNumElements();
9662 assert(StVT != VT && "Cannot truncate to the same type");
9663 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9664 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9666 // From, To sizes and ElemCount must be pow of two
9667 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9669 // We are going to use the original vector elt for storing.
9670 // Accumulated smaller vector elements must be a multiple of the store size.
9671 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9673 unsigned SizeRatio = FromEltSz / ToEltSz;
9674 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9676 // Create a type on which we perform the shuffle.
9677 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9678 NumElems*SizeRatio);
9679 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9682 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9683 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9684 for (unsigned i = 0; i < NumElems; ++i)
9685 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9686 ? (i + 1) * SizeRatio - 1
9689 // Can't shuffle using an illegal type.
9690 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9692 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9693 DAG.getUNDEF(WideVec.getValueType()),
9695 // At this point all of the data is stored at the bottom of the
9696 // register. We now need to save it to mem.
9698 // Find the largest store unit
9699 MVT StoreType = MVT::i8;
9700 for (MVT Tp : MVT::integer_valuetypes()) {
9701 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9704 // Didn't find a legal store type.
9705 if (!TLI.isTypeLegal(StoreType))
9708 // Bitcast the original vector into a vector of store-size units
9709 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9710 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9711 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9712 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9713 SmallVector<SDValue, 8> Chains;
9714 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9715 TLI.getPointerTy(DAG.getDataLayout()));
9716 SDValue BasePtr = St->getBasePtr();
9718 // Perform one or more big stores into memory.
9719 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9720 for (unsigned I = 0; I < E; I++) {
9721 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9722 StoreType, ShuffWide,
9723 DAG.getIntPtrConstant(I, DL));
9724 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9725 St->getPointerInfo(), St->isVolatile(),
9726 St->isNonTemporal(), St->getAlignment());
9727 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9729 Chains.push_back(Ch);
9731 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9734 if (!ISD::isNormalStore(St))
9737 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9738 // ARM stores of arguments in the same cache line.
9739 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9740 StVal.getNode()->hasOneUse()) {
9741 SelectionDAG &DAG = DCI.DAG;
9742 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9744 SDValue BasePtr = St->getBasePtr();
9745 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9746 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9747 BasePtr, St->getPointerInfo(), St->isVolatile(),
9748 St->isNonTemporal(), St->getAlignment());
9750 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9751 DAG.getConstant(4, DL, MVT::i32));
9752 return DAG.getStore(NewST1.getValue(0), DL,
9753 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9754 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9755 St->isNonTemporal(),
9756 std::min(4U, St->getAlignment() / 2));
9759 if (StVal.getValueType() == MVT::i64 &&
9760 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9762 // Bitcast an i64 store extracted from a vector to f64.
9763 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9764 SelectionDAG &DAG = DCI.DAG;
9766 SDValue IntVec = StVal.getOperand(0);
9767 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9768 IntVec.getValueType().getVectorNumElements());
9769 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9770 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9771 Vec, StVal.getOperand(1));
9773 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9774 // Make the DAGCombiner fold the bitcasts.
9775 DCI.AddToWorklist(Vec.getNode());
9776 DCI.AddToWorklist(ExtElt.getNode());
9777 DCI.AddToWorklist(V.getNode());
9778 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9779 St->getPointerInfo(), St->isVolatile(),
9780 St->isNonTemporal(), St->getAlignment(),
9784 // If this is a legal vector store, try to combine it into a VST1_UPD.
9785 if (ISD::isNormalStore(N) && VT.isVector() &&
9786 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9787 return CombineBaseUpdate(N, DCI);
9792 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9793 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9794 /// when the VMUL has a constant operand that is a power of 2.
9796 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9797 /// vmul.f32 d16, d17, d16
9798 /// vcvt.s32.f32 d16, d16
9800 /// vcvt.s32.f32 d16, d16, #3
9801 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9802 const ARMSubtarget *Subtarget) {
9803 if (!Subtarget->hasNEON())
9806 SDValue Op = N->getOperand(0);
9807 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9810 SDValue ConstVec = Op->getOperand(1);
9811 if (!isa<BuildVectorSDNode>(ConstVec))
9814 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9815 uint32_t FloatBits = FloatTy.getSizeInBits();
9816 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9817 uint32_t IntBits = IntTy.getSizeInBits();
9818 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9819 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9820 // These instructions only exist converting from f32 to i32. We can handle
9821 // smaller integers by generating an extra truncate, but larger ones would
9822 // be lossy. We also can't handle more then 4 lanes, since these intructions
9823 // only support v2i32/v4i32 types.
9827 BitVector UndefElements;
9828 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9829 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9830 if (C == -1 || C == 0 || C > 32)
9834 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9835 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9836 Intrinsic::arm_neon_vcvtfp2fxu;
9837 SDValue FixConv = DAG.getNode(
9838 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9839 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9840 DAG.getConstant(C, dl, MVT::i32));
9842 if (IntBits < FloatBits)
9843 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9848 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9849 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9850 /// when the VDIV has a constant operand that is a power of 2.
9852 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9853 /// vcvt.f32.s32 d16, d16
9854 /// vdiv.f32 d16, d17, d16
9856 /// vcvt.f32.s32 d16, d16, #3
9857 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9858 const ARMSubtarget *Subtarget) {
9859 if (!Subtarget->hasNEON())
9862 SDValue Op = N->getOperand(0);
9863 unsigned OpOpcode = Op.getNode()->getOpcode();
9864 if (!N->getValueType(0).isVector() ||
9865 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9868 SDValue ConstVec = N->getOperand(1);
9869 if (!isa<BuildVectorSDNode>(ConstVec))
9872 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9873 uint32_t FloatBits = FloatTy.getSizeInBits();
9874 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9875 uint32_t IntBits = IntTy.getSizeInBits();
9876 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9877 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9878 // These instructions only exist converting from i32 to f32. We can handle
9879 // smaller integers by generating an extra extend, but larger ones would
9880 // be lossy. We also can't handle more then 4 lanes, since these intructions
9881 // only support v2i32/v4i32 types.
9885 BitVector UndefElements;
9886 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9887 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9888 if (C == -1 || C == 0 || C > 32)
9892 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9893 SDValue ConvInput = Op.getOperand(0);
9894 if (IntBits < FloatBits)
9895 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9896 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9899 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9900 Intrinsic::arm_neon_vcvtfxu2fp;
9901 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9903 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9904 ConvInput, DAG.getConstant(C, dl, MVT::i32));
9907 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9908 /// operand of a vector shift operation, where all the elements of the
9909 /// build_vector must have the same constant integer value.
9910 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9911 // Ignore bit_converts.
9912 while (Op.getOpcode() == ISD::BITCAST)
9913 Op = Op.getOperand(0);
9914 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9915 APInt SplatBits, SplatUndef;
9916 unsigned SplatBitSize;
9918 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9919 HasAnyUndefs, ElementBits) ||
9920 SplatBitSize > ElementBits)
9922 Cnt = SplatBits.getSExtValue();
9926 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9927 /// operand of a vector shift left operation. That value must be in the range:
9928 /// 0 <= Value < ElementBits for a left shift; or
9929 /// 0 <= Value <= ElementBits for a long left shift.
9930 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9931 assert(VT.isVector() && "vector shift count is not a vector type");
9932 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9933 if (! getVShiftImm(Op, ElementBits, Cnt))
9935 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9938 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9939 /// operand of a vector shift right operation. For a shift opcode, the value
9940 /// is positive, but for an intrinsic the value count must be negative. The
9941 /// absolute value must be in the range:
9942 /// 1 <= |Value| <= ElementBits for a right shift; or
9943 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9944 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9946 assert(VT.isVector() && "vector shift count is not a vector type");
9947 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9948 if (! getVShiftImm(Op, ElementBits, Cnt))
9951 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9952 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9959 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9960 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9961 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9964 // Don't do anything for most intrinsics.
9967 case Intrinsic::arm_neon_vabds:
9968 if (!N->getValueType(0).isInteger())
9970 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9971 N->getOperand(1), N->getOperand(2));
9972 case Intrinsic::arm_neon_vabdu:
9973 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9974 N->getOperand(1), N->getOperand(2));
9976 // Vector shifts: check for immediate versions and lower them.
9977 // Note: This is done during DAG combining instead of DAG legalizing because
9978 // the build_vectors for 64-bit vector element shift counts are generally
9979 // not legal, and it is hard to see their values after they get legalized to
9980 // loads from a constant pool.
9981 case Intrinsic::arm_neon_vshifts:
9982 case Intrinsic::arm_neon_vshiftu:
9983 case Intrinsic::arm_neon_vrshifts:
9984 case Intrinsic::arm_neon_vrshiftu:
9985 case Intrinsic::arm_neon_vrshiftn:
9986 case Intrinsic::arm_neon_vqshifts:
9987 case Intrinsic::arm_neon_vqshiftu:
9988 case Intrinsic::arm_neon_vqshiftsu:
9989 case Intrinsic::arm_neon_vqshiftns:
9990 case Intrinsic::arm_neon_vqshiftnu:
9991 case Intrinsic::arm_neon_vqshiftnsu:
9992 case Intrinsic::arm_neon_vqrshiftns:
9993 case Intrinsic::arm_neon_vqrshiftnu:
9994 case Intrinsic::arm_neon_vqrshiftnsu: {
9995 EVT VT = N->getOperand(1).getValueType();
9997 unsigned VShiftOpc = 0;
10000 case Intrinsic::arm_neon_vshifts:
10001 case Intrinsic::arm_neon_vshiftu:
10002 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10003 VShiftOpc = ARMISD::VSHL;
10006 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10007 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10008 ARMISD::VSHRs : ARMISD::VSHRu);
10013 case Intrinsic::arm_neon_vrshifts:
10014 case Intrinsic::arm_neon_vrshiftu:
10015 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10019 case Intrinsic::arm_neon_vqshifts:
10020 case Intrinsic::arm_neon_vqshiftu:
10021 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10025 case Intrinsic::arm_neon_vqshiftsu:
10026 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10028 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10030 case Intrinsic::arm_neon_vrshiftn:
10031 case Intrinsic::arm_neon_vqshiftns:
10032 case Intrinsic::arm_neon_vqshiftnu:
10033 case Intrinsic::arm_neon_vqshiftnsu:
10034 case Intrinsic::arm_neon_vqrshiftns:
10035 case Intrinsic::arm_neon_vqrshiftnu:
10036 case Intrinsic::arm_neon_vqrshiftnsu:
10037 // Narrowing shifts require an immediate right shift.
10038 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10040 llvm_unreachable("invalid shift count for narrowing vector shift "
10044 llvm_unreachable("unhandled vector shift");
10048 case Intrinsic::arm_neon_vshifts:
10049 case Intrinsic::arm_neon_vshiftu:
10050 // Opcode already set above.
10052 case Intrinsic::arm_neon_vrshifts:
10053 VShiftOpc = ARMISD::VRSHRs; break;
10054 case Intrinsic::arm_neon_vrshiftu:
10055 VShiftOpc = ARMISD::VRSHRu; break;
10056 case Intrinsic::arm_neon_vrshiftn:
10057 VShiftOpc = ARMISD::VRSHRN; break;
10058 case Intrinsic::arm_neon_vqshifts:
10059 VShiftOpc = ARMISD::VQSHLs; break;
10060 case Intrinsic::arm_neon_vqshiftu:
10061 VShiftOpc = ARMISD::VQSHLu; break;
10062 case Intrinsic::arm_neon_vqshiftsu:
10063 VShiftOpc = ARMISD::VQSHLsu; break;
10064 case Intrinsic::arm_neon_vqshiftns:
10065 VShiftOpc = ARMISD::VQSHRNs; break;
10066 case Intrinsic::arm_neon_vqshiftnu:
10067 VShiftOpc = ARMISD::VQSHRNu; break;
10068 case Intrinsic::arm_neon_vqshiftnsu:
10069 VShiftOpc = ARMISD::VQSHRNsu; break;
10070 case Intrinsic::arm_neon_vqrshiftns:
10071 VShiftOpc = ARMISD::VQRSHRNs; break;
10072 case Intrinsic::arm_neon_vqrshiftnu:
10073 VShiftOpc = ARMISD::VQRSHRNu; break;
10074 case Intrinsic::arm_neon_vqrshiftnsu:
10075 VShiftOpc = ARMISD::VQRSHRNsu; break;
10079 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10080 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10083 case Intrinsic::arm_neon_vshiftins: {
10084 EVT VT = N->getOperand(1).getValueType();
10086 unsigned VShiftOpc = 0;
10088 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10089 VShiftOpc = ARMISD::VSLI;
10090 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10091 VShiftOpc = ARMISD::VSRI;
10093 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10097 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10098 N->getOperand(1), N->getOperand(2),
10099 DAG.getConstant(Cnt, dl, MVT::i32));
10102 case Intrinsic::arm_neon_vqrshifts:
10103 case Intrinsic::arm_neon_vqrshiftu:
10104 // No immediate versions of these to check for.
10111 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10112 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10113 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10114 /// vector element shift counts are generally not legal, and it is hard to see
10115 /// their values after they get legalized to loads from a constant pool.
10116 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10117 const ARMSubtarget *ST) {
10118 EVT VT = N->getValueType(0);
10119 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10120 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10121 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10122 SDValue N1 = N->getOperand(1);
10123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10124 SDValue N0 = N->getOperand(0);
10125 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10126 DAG.MaskedValueIsZero(N0.getOperand(0),
10127 APInt::getHighBitsSet(32, 16)))
10128 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10132 // Nothing to be done for scalar shifts.
10133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10134 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10137 assert(ST->hasNEON() && "unexpected vector shift");
10140 switch (N->getOpcode()) {
10141 default: llvm_unreachable("unexpected shift opcode");
10144 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10146 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10147 DAG.getConstant(Cnt, dl, MVT::i32));
10153 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10154 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10155 ARMISD::VSHRs : ARMISD::VSHRu);
10157 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10158 DAG.getConstant(Cnt, dl, MVT::i32));
10164 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10165 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10166 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10167 const ARMSubtarget *ST) {
10168 SDValue N0 = N->getOperand(0);
10170 // Check for sign- and zero-extensions of vector extract operations of 8-
10171 // and 16-bit vector elements. NEON supports these directly. They are
10172 // handled during DAG combining because type legalization will promote them
10173 // to 32-bit types and it is messy to recognize the operations after that.
10174 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10175 SDValue Vec = N0.getOperand(0);
10176 SDValue Lane = N0.getOperand(1);
10177 EVT VT = N->getValueType(0);
10178 EVT EltVT = N0.getValueType();
10179 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10181 if (VT == MVT::i32 &&
10182 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10183 TLI.isTypeLegal(Vec.getValueType()) &&
10184 isa<ConstantSDNode>(Lane)) {
10187 switch (N->getOpcode()) {
10188 default: llvm_unreachable("unexpected opcode");
10189 case ISD::SIGN_EXTEND:
10190 Opc = ARMISD::VGETLANEs;
10192 case ISD::ZERO_EXTEND:
10193 case ISD::ANY_EXTEND:
10194 Opc = ARMISD::VGETLANEu;
10197 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10204 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10206 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10207 SDValue Cmp = N->getOperand(4);
10208 if (Cmp.getOpcode() != ARMISD::CMPZ)
10209 // Only looking at EQ and NE cases.
10212 EVT VT = N->getValueType(0);
10214 SDValue LHS = Cmp.getOperand(0);
10215 SDValue RHS = Cmp.getOperand(1);
10216 SDValue FalseVal = N->getOperand(0);
10217 SDValue TrueVal = N->getOperand(1);
10218 SDValue ARMcc = N->getOperand(2);
10219 ARMCC::CondCodes CC =
10220 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10238 /// FIXME: Turn this into a target neutral optimization?
10240 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10241 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10242 N->getOperand(3), Cmp);
10243 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10245 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10246 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10247 N->getOperand(3), NewCmp);
10250 if (Res.getNode()) {
10251 APInt KnownZero, KnownOne;
10252 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10253 // Capture demanded bits information that would be otherwise lost.
10254 if (KnownZero == 0xfffffffe)
10255 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10256 DAG.getValueType(MVT::i1));
10257 else if (KnownZero == 0xffffff00)
10258 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10259 DAG.getValueType(MVT::i8));
10260 else if (KnownZero == 0xffff0000)
10261 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10262 DAG.getValueType(MVT::i16));
10268 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10269 DAGCombinerInfo &DCI) const {
10270 switch (N->getOpcode()) {
10272 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10273 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10274 case ISD::SUB: return PerformSUBCombine(N, DCI);
10275 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10276 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10277 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10278 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10279 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10280 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10281 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10282 case ISD::STORE: return PerformSTORECombine(N, DCI);
10283 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10284 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10285 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10286 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10287 case ISD::FP_TO_SINT:
10288 case ISD::FP_TO_UINT:
10289 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10291 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10292 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10295 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10296 case ISD::SIGN_EXTEND:
10297 case ISD::ZERO_EXTEND:
10298 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10299 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10300 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10301 case ARMISD::VLD2DUP:
10302 case ARMISD::VLD3DUP:
10303 case ARMISD::VLD4DUP:
10304 return PerformVLDCombine(N, DCI);
10305 case ARMISD::BUILD_VECTOR:
10306 return PerformARMBUILD_VECTORCombine(N, DCI);
10307 case ISD::INTRINSIC_VOID:
10308 case ISD::INTRINSIC_W_CHAIN:
10309 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10310 case Intrinsic::arm_neon_vld1:
10311 case Intrinsic::arm_neon_vld2:
10312 case Intrinsic::arm_neon_vld3:
10313 case Intrinsic::arm_neon_vld4:
10314 case Intrinsic::arm_neon_vld2lane:
10315 case Intrinsic::arm_neon_vld3lane:
10316 case Intrinsic::arm_neon_vld4lane:
10317 case Intrinsic::arm_neon_vst1:
10318 case Intrinsic::arm_neon_vst2:
10319 case Intrinsic::arm_neon_vst3:
10320 case Intrinsic::arm_neon_vst4:
10321 case Intrinsic::arm_neon_vst2lane:
10322 case Intrinsic::arm_neon_vst3lane:
10323 case Intrinsic::arm_neon_vst4lane:
10324 return PerformVLDCombine(N, DCI);
10332 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10334 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10337 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10340 bool *Fast) const {
10341 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10342 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10344 switch (VT.getSimpleVT().SimpleTy) {
10350 // Unaligned access can use (for example) LRDB, LRDH, LDR
10351 if (AllowsUnaligned) {
10353 *Fast = Subtarget->hasV7Ops();
10360 // For any little-endian targets with neon, we can support unaligned ld/st
10361 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10362 // A big-endian target may also explicitly support unaligned accesses
10363 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10373 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10374 unsigned AlignCheck) {
10375 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10376 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10379 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10380 unsigned DstAlign, unsigned SrcAlign,
10381 bool IsMemset, bool ZeroMemset,
10383 MachineFunction &MF) const {
10384 const Function *F = MF.getFunction();
10386 // See if we can use NEON instructions for this...
10387 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10388 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10391 (memOpAlign(SrcAlign, DstAlign, 16) ||
10392 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10394 } else if (Size >= 8 &&
10395 (memOpAlign(SrcAlign, DstAlign, 8) ||
10396 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10402 // Lowering to i32/i16 if the size permits.
10405 else if (Size >= 2)
10408 // Let the target-independent logic figure it out.
10412 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10413 if (Val.getOpcode() != ISD::LOAD)
10416 EVT VT1 = Val.getValueType();
10417 if (!VT1.isSimple() || !VT1.isInteger() ||
10418 !VT2.isSimple() || !VT2.isInteger())
10421 switch (VT1.getSimpleVT().SimpleTy) {
10426 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10433 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10434 EVT VT = ExtVal.getValueType();
10436 if (!isTypeLegal(VT))
10439 // Don't create a loadext if we can fold the extension into a wide/long
10441 // If there's more than one user instruction, the loadext is desirable no
10442 // matter what. There can be two uses by the same instruction.
10443 if (ExtVal->use_empty() ||
10444 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10447 SDNode *U = *ExtVal->use_begin();
10448 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10449 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10455 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10456 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10459 if (!isTypeLegal(EVT::getEVT(Ty1)))
10462 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10464 // Assuming the caller doesn't have a zeroext or signext return parameter,
10465 // truncation all the way down to i1 is valid.
10470 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10474 unsigned Scale = 1;
10475 switch (VT.getSimpleVT().SimpleTy) {
10476 default: return false;
10491 if ((V & (Scale - 1)) != 0)
10494 return V == (V & ((1LL << 5) - 1));
10497 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10498 const ARMSubtarget *Subtarget) {
10499 bool isNeg = false;
10505 switch (VT.getSimpleVT().SimpleTy) {
10506 default: return false;
10511 // + imm12 or - imm8
10513 return V == (V & ((1LL << 8) - 1));
10514 return V == (V & ((1LL << 12) - 1));
10517 // Same as ARM mode. FIXME: NEON?
10518 if (!Subtarget->hasVFP2())
10523 return V == (V & ((1LL << 8) - 1));
10527 /// isLegalAddressImmediate - Return true if the integer value can be used
10528 /// as the offset of the target addressing mode for load / store of the
10530 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10531 const ARMSubtarget *Subtarget) {
10535 if (!VT.isSimple())
10538 if (Subtarget->isThumb1Only())
10539 return isLegalT1AddressImmediate(V, VT);
10540 else if (Subtarget->isThumb2())
10541 return isLegalT2AddressImmediate(V, VT, Subtarget);
10546 switch (VT.getSimpleVT().SimpleTy) {
10547 default: return false;
10552 return V == (V & ((1LL << 12) - 1));
10555 return V == (V & ((1LL << 8) - 1));
10558 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10563 return V == (V & ((1LL << 8) - 1));
10567 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10569 int Scale = AM.Scale;
10573 switch (VT.getSimpleVT().SimpleTy) {
10574 default: return false;
10582 Scale = Scale & ~1;
10583 return Scale == 2 || Scale == 4 || Scale == 8;
10586 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10590 // Note, we allow "void" uses (basically, uses that aren't loads or
10591 // stores), because arm allows folding a scale into many arithmetic
10592 // operations. This should be made more precise and revisited later.
10594 // Allow r << imm, but the imm has to be a multiple of two.
10595 if (Scale & 1) return false;
10596 return isPowerOf2_32(Scale);
10600 /// isLegalAddressingMode - Return true if the addressing mode represented
10601 /// by AM is legal for this target, for a load/store of the specified type.
10602 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10603 const AddrMode &AM, Type *Ty,
10604 unsigned AS) const {
10605 EVT VT = getValueType(DL, Ty, true);
10606 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10609 // Can never fold addr of global into load/store.
10613 switch (AM.Scale) {
10614 case 0: // no scale reg, must be "r+i" or "r", or "i".
10617 if (Subtarget->isThumb1Only())
10621 // ARM doesn't support any R+R*scale+imm addr modes.
10625 if (!VT.isSimple())
10628 if (Subtarget->isThumb2())
10629 return isLegalT2ScaledAddressingMode(AM, VT);
10631 int Scale = AM.Scale;
10632 switch (VT.getSimpleVT().SimpleTy) {
10633 default: return false;
10637 if (Scale < 0) Scale = -Scale;
10641 return isPowerOf2_32(Scale & ~1);
10645 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10650 // Note, we allow "void" uses (basically, uses that aren't loads or
10651 // stores), because arm allows folding a scale into many arithmetic
10652 // operations. This should be made more precise and revisited later.
10654 // Allow r << imm, but the imm has to be a multiple of two.
10655 if (Scale & 1) return false;
10656 return isPowerOf2_32(Scale);
10662 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10663 /// icmp immediate, that is the target has icmp instructions which can compare
10664 /// a register against the immediate without having to materialize the
10665 /// immediate into a register.
10666 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10667 // Thumb2 and ARM modes can use cmn for negative immediates.
10668 if (!Subtarget->isThumb())
10669 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10670 if (Subtarget->isThumb2())
10671 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10672 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10673 return Imm >= 0 && Imm <= 255;
10676 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10677 /// *or sub* immediate, that is the target has add or sub instructions which can
10678 /// add a register with the immediate without having to materialize the
10679 /// immediate into a register.
10680 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10681 // Same encoding for add/sub, just flip the sign.
10682 int64_t AbsImm = std::abs(Imm);
10683 if (!Subtarget->isThumb())
10684 return ARM_AM::getSOImmVal(AbsImm) != -1;
10685 if (Subtarget->isThumb2())
10686 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10687 // Thumb1 only has 8-bit unsigned immediate.
10688 return AbsImm >= 0 && AbsImm <= 255;
10691 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10692 bool isSEXTLoad, SDValue &Base,
10693 SDValue &Offset, bool &isInc,
10694 SelectionDAG &DAG) {
10695 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10698 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10699 // AddressingMode 3
10700 Base = Ptr->getOperand(0);
10701 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10702 int RHSC = (int)RHS->getZExtValue();
10703 if (RHSC < 0 && RHSC > -256) {
10704 assert(Ptr->getOpcode() == ISD::ADD);
10706 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10710 isInc = (Ptr->getOpcode() == ISD::ADD);
10711 Offset = Ptr->getOperand(1);
10713 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10714 // AddressingMode 2
10715 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10716 int RHSC = (int)RHS->getZExtValue();
10717 if (RHSC < 0 && RHSC > -0x1000) {
10718 assert(Ptr->getOpcode() == ISD::ADD);
10720 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10721 Base = Ptr->getOperand(0);
10726 if (Ptr->getOpcode() == ISD::ADD) {
10728 ARM_AM::ShiftOpc ShOpcVal=
10729 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10730 if (ShOpcVal != ARM_AM::no_shift) {
10731 Base = Ptr->getOperand(1);
10732 Offset = Ptr->getOperand(0);
10734 Base = Ptr->getOperand(0);
10735 Offset = Ptr->getOperand(1);
10740 isInc = (Ptr->getOpcode() == ISD::ADD);
10741 Base = Ptr->getOperand(0);
10742 Offset = Ptr->getOperand(1);
10746 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10750 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10751 bool isSEXTLoad, SDValue &Base,
10752 SDValue &Offset, bool &isInc,
10753 SelectionDAG &DAG) {
10754 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10757 Base = Ptr->getOperand(0);
10758 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10759 int RHSC = (int)RHS->getZExtValue();
10760 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10761 assert(Ptr->getOpcode() == ISD::ADD);
10763 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10765 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10766 isInc = Ptr->getOpcode() == ISD::ADD;
10767 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10775 /// getPreIndexedAddressParts - returns true by value, base pointer and
10776 /// offset pointer and addressing mode by reference if the node's address
10777 /// can be legally represented as pre-indexed load / store address.
10779 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10781 ISD::MemIndexedMode &AM,
10782 SelectionDAG &DAG) const {
10783 if (Subtarget->isThumb1Only())
10788 bool isSEXTLoad = false;
10789 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10790 Ptr = LD->getBasePtr();
10791 VT = LD->getMemoryVT();
10792 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10793 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10794 Ptr = ST->getBasePtr();
10795 VT = ST->getMemoryVT();
10800 bool isLegal = false;
10801 if (Subtarget->isThumb2())
10802 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10803 Offset, isInc, DAG);
10805 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10806 Offset, isInc, DAG);
10810 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10814 /// getPostIndexedAddressParts - returns true by value, base pointer and
10815 /// offset pointer and addressing mode by reference if this node can be
10816 /// combined with a load / store to form a post-indexed load / store.
10817 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10820 ISD::MemIndexedMode &AM,
10821 SelectionDAG &DAG) const {
10822 if (Subtarget->isThumb1Only())
10827 bool isSEXTLoad = false;
10828 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10829 VT = LD->getMemoryVT();
10830 Ptr = LD->getBasePtr();
10831 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10832 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10833 VT = ST->getMemoryVT();
10834 Ptr = ST->getBasePtr();
10839 bool isLegal = false;
10840 if (Subtarget->isThumb2())
10841 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10844 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10850 // Swap base ptr and offset to catch more post-index load / store when
10851 // it's legal. In Thumb2 mode, offset must be an immediate.
10852 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10853 !Subtarget->isThumb2())
10854 std::swap(Base, Offset);
10856 // Post-indexed load / store update the base pointer.
10861 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10865 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10868 const SelectionDAG &DAG,
10869 unsigned Depth) const {
10870 unsigned BitWidth = KnownOne.getBitWidth();
10871 KnownZero = KnownOne = APInt(BitWidth, 0);
10872 switch (Op.getOpcode()) {
10878 // These nodes' second result is a boolean
10879 if (Op.getResNo() == 0)
10881 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10883 case ARMISD::CMOV: {
10884 // Bits are known zero/one if known on the LHS and RHS.
10885 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10886 if (KnownZero == 0 && KnownOne == 0) return;
10888 APInt KnownZeroRHS, KnownOneRHS;
10889 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10890 KnownZero &= KnownZeroRHS;
10891 KnownOne &= KnownOneRHS;
10894 case ISD::INTRINSIC_W_CHAIN: {
10895 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10896 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10899 case Intrinsic::arm_ldaex:
10900 case Intrinsic::arm_ldrex: {
10901 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10902 unsigned MemBits = VT.getScalarType().getSizeInBits();
10903 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10911 //===----------------------------------------------------------------------===//
10912 // ARM Inline Assembly Support
10913 //===----------------------------------------------------------------------===//
10915 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10916 // Looking for "rev" which is V6+.
10917 if (!Subtarget->hasV6Ops())
10920 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10921 std::string AsmStr = IA->getAsmString();
10922 SmallVector<StringRef, 4> AsmPieces;
10923 SplitString(AsmStr, AsmPieces, ";\n");
10925 switch (AsmPieces.size()) {
10926 default: return false;
10928 AsmStr = AsmPieces[0];
10930 SplitString(AsmStr, AsmPieces, " \t,");
10933 if (AsmPieces.size() == 3 &&
10934 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10935 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10936 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10937 if (Ty && Ty->getBitWidth() == 32)
10938 return IntrinsicLowering::LowerToByteSwap(CI);
10946 /// getConstraintType - Given a constraint letter, return the type of
10947 /// constraint it is for this target.
10948 ARMTargetLowering::ConstraintType
10949 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10950 if (Constraint.size() == 1) {
10951 switch (Constraint[0]) {
10953 case 'l': return C_RegisterClass;
10954 case 'w': return C_RegisterClass;
10955 case 'h': return C_RegisterClass;
10956 case 'x': return C_RegisterClass;
10957 case 't': return C_RegisterClass;
10958 case 'j': return C_Other; // Constant for movw.
10959 // An address with a single base register. Due to the way we
10960 // currently handle addresses it is the same as an 'r' memory constraint.
10961 case 'Q': return C_Memory;
10963 } else if (Constraint.size() == 2) {
10964 switch (Constraint[0]) {
10966 // All 'U+' constraints are addresses.
10967 case 'U': return C_Memory;
10970 return TargetLowering::getConstraintType(Constraint);
10973 /// Examine constraint type and operand type and determine a weight value.
10974 /// This object must already have been set up with the operand type
10975 /// and the current alternative constraint selected.
10976 TargetLowering::ConstraintWeight
10977 ARMTargetLowering::getSingleConstraintMatchWeight(
10978 AsmOperandInfo &info, const char *constraint) const {
10979 ConstraintWeight weight = CW_Invalid;
10980 Value *CallOperandVal = info.CallOperandVal;
10981 // If we don't have a value, we can't do a match,
10982 // but allow it at the lowest weight.
10983 if (!CallOperandVal)
10985 Type *type = CallOperandVal->getType();
10986 // Look at the constraint type.
10987 switch (*constraint) {
10989 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10992 if (type->isIntegerTy()) {
10993 if (Subtarget->isThumb())
10994 weight = CW_SpecificReg;
10996 weight = CW_Register;
11000 if (type->isFloatingPointTy())
11001 weight = CW_Register;
11007 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11008 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11009 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11010 if (Constraint.size() == 1) {
11011 // GCC ARM Constraint Letters
11012 switch (Constraint[0]) {
11013 case 'l': // Low regs or general regs.
11014 if (Subtarget->isThumb())
11015 return RCPair(0U, &ARM::tGPRRegClass);
11016 return RCPair(0U, &ARM::GPRRegClass);
11017 case 'h': // High regs or no regs.
11018 if (Subtarget->isThumb())
11019 return RCPair(0U, &ARM::hGPRRegClass);
11022 if (Subtarget->isThumb1Only())
11023 return RCPair(0U, &ARM::tGPRRegClass);
11024 return RCPair(0U, &ARM::GPRRegClass);
11026 if (VT == MVT::Other)
11028 if (VT == MVT::f32)
11029 return RCPair(0U, &ARM::SPRRegClass);
11030 if (VT.getSizeInBits() == 64)
11031 return RCPair(0U, &ARM::DPRRegClass);
11032 if (VT.getSizeInBits() == 128)
11033 return RCPair(0U, &ARM::QPRRegClass);
11036 if (VT == MVT::Other)
11038 if (VT == MVT::f32)
11039 return RCPair(0U, &ARM::SPR_8RegClass);
11040 if (VT.getSizeInBits() == 64)
11041 return RCPair(0U, &ARM::DPR_8RegClass);
11042 if (VT.getSizeInBits() == 128)
11043 return RCPair(0U, &ARM::QPR_8RegClass);
11046 if (VT == MVT::f32)
11047 return RCPair(0U, &ARM::SPRRegClass);
11051 if (StringRef("{cc}").equals_lower(Constraint))
11052 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11054 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11057 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11058 /// vector. If it is invalid, don't add anything to Ops.
11059 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11060 std::string &Constraint,
11061 std::vector<SDValue>&Ops,
11062 SelectionDAG &DAG) const {
11065 // Currently only support length 1 constraints.
11066 if (Constraint.length() != 1) return;
11068 char ConstraintLetter = Constraint[0];
11069 switch (ConstraintLetter) {
11072 case 'I': case 'J': case 'K': case 'L':
11073 case 'M': case 'N': case 'O':
11074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11078 int64_t CVal64 = C->getSExtValue();
11079 int CVal = (int) CVal64;
11080 // None of these constraints allow values larger than 32 bits. Check
11081 // that the value fits in an int.
11082 if (CVal != CVal64)
11085 switch (ConstraintLetter) {
11087 // Constant suitable for movw, must be between 0 and
11089 if (Subtarget->hasV6T2Ops())
11090 if (CVal >= 0 && CVal <= 65535)
11094 if (Subtarget->isThumb1Only()) {
11095 // This must be a constant between 0 and 255, for ADD
11097 if (CVal >= 0 && CVal <= 255)
11099 } else if (Subtarget->isThumb2()) {
11100 // A constant that can be used as an immediate value in a
11101 // data-processing instruction.
11102 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11105 // A constant that can be used as an immediate value in a
11106 // data-processing instruction.
11107 if (ARM_AM::getSOImmVal(CVal) != -1)
11113 if (Subtarget->isThumb()) { // FIXME thumb2
11114 // This must be a constant between -255 and -1, for negated ADD
11115 // immediates. This can be used in GCC with an "n" modifier that
11116 // prints the negated value, for use with SUB instructions. It is
11117 // not useful otherwise but is implemented for compatibility.
11118 if (CVal >= -255 && CVal <= -1)
11121 // This must be a constant between -4095 and 4095. It is not clear
11122 // what this constraint is intended for. Implemented for
11123 // compatibility with GCC.
11124 if (CVal >= -4095 && CVal <= 4095)
11130 if (Subtarget->isThumb1Only()) {
11131 // A 32-bit value where only one byte has a nonzero value. Exclude
11132 // zero to match GCC. This constraint is used by GCC internally for
11133 // constants that can be loaded with a move/shift combination.
11134 // It is not useful otherwise but is implemented for compatibility.
11135 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11137 } else if (Subtarget->isThumb2()) {
11138 // A constant whose bitwise inverse can be used as an immediate
11139 // value in a data-processing instruction. This can be used in GCC
11140 // with a "B" modifier that prints the inverted value, for use with
11141 // BIC and MVN instructions. It is not useful otherwise but is
11142 // implemented for compatibility.
11143 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11146 // A constant whose bitwise inverse can be used as an immediate
11147 // value in a data-processing instruction. This can be used in GCC
11148 // with a "B" modifier that prints the inverted value, for use with
11149 // BIC and MVN instructions. It is not useful otherwise but is
11150 // implemented for compatibility.
11151 if (ARM_AM::getSOImmVal(~CVal) != -1)
11157 if (Subtarget->isThumb1Only()) {
11158 // This must be a constant between -7 and 7,
11159 // for 3-operand ADD/SUB immediate instructions.
11160 if (CVal >= -7 && CVal < 7)
11162 } else if (Subtarget->isThumb2()) {
11163 // A constant whose negation can be used as an immediate value in a
11164 // data-processing instruction. This can be used in GCC with an "n"
11165 // modifier that prints the negated value, for use with SUB
11166 // instructions. It is not useful otherwise but is implemented for
11168 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11171 // A constant whose negation can be used as an immediate value in a
11172 // data-processing instruction. This can be used in GCC with an "n"
11173 // modifier that prints the negated value, for use with SUB
11174 // instructions. It is not useful otherwise but is implemented for
11176 if (ARM_AM::getSOImmVal(-CVal) != -1)
11182 if (Subtarget->isThumb()) { // FIXME thumb2
11183 // This must be a multiple of 4 between 0 and 1020, for
11184 // ADD sp + immediate.
11185 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11188 // A power of two or a constant between 0 and 32. This is used in
11189 // GCC for the shift amount on shifted register operands, but it is
11190 // useful in general for any shift amounts.
11191 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11197 if (Subtarget->isThumb()) { // FIXME thumb2
11198 // This must be a constant between 0 and 31, for shift amounts.
11199 if (CVal >= 0 && CVal <= 31)
11205 if (Subtarget->isThumb()) { // FIXME thumb2
11206 // This must be a multiple of 4 between -508 and 508, for
11207 // ADD/SUB sp = sp + immediate.
11208 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11213 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11217 if (Result.getNode()) {
11218 Ops.push_back(Result);
11221 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11224 static RTLIB::Libcall getDivRemLibcall(
11225 const SDNode *N, MVT::SimpleValueType SVT) {
11226 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11227 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11228 "Unhandled Opcode in getDivRemLibcall");
11229 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11230 N->getOpcode() == ISD::SREM;
11233 default: llvm_unreachable("Unexpected request for libcall!");
11234 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11235 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11236 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11237 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11242 static TargetLowering::ArgListTy getDivRemArgList(
11243 const SDNode *N, LLVMContext *Context) {
11244 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11245 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11246 "Unhandled Opcode in getDivRemArgList");
11247 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11248 N->getOpcode() == ISD::SREM;
11249 TargetLowering::ArgListTy Args;
11250 TargetLowering::ArgListEntry Entry;
11251 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11252 EVT ArgVT = N->getOperand(i).getValueType();
11253 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11254 Entry.Node = N->getOperand(i);
11256 Entry.isSExt = isSigned;
11257 Entry.isZExt = !isSigned;
11258 Args.push_back(Entry);
11263 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11264 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11265 "Register-based DivRem lowering only");
11266 unsigned Opcode = Op->getOpcode();
11267 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11268 "Invalid opcode for Div/Rem lowering");
11269 bool isSigned = (Opcode == ISD::SDIVREM);
11270 EVT VT = Op->getValueType(0);
11271 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11273 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11274 VT.getSimpleVT().SimpleTy);
11275 SDValue InChain = DAG.getEntryNode();
11277 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11280 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11281 getPointerTy(DAG.getDataLayout()));
11283 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11286 TargetLowering::CallLoweringInfo CLI(DAG);
11287 CLI.setDebugLoc(dl).setChain(InChain)
11288 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11289 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11291 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11292 return CallInfo.first;
11295 // Lowers REM using divmod helpers
11296 // see RTABI section 4.2/4.3
11297 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11298 // Build return types (div and rem)
11299 std::vector<Type*> RetTyParams;
11300 Type *RetTyElement;
11302 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11303 default: llvm_unreachable("Unexpected request for libcall!");
11304 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11305 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11306 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11307 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11310 RetTyParams.push_back(RetTyElement);
11311 RetTyParams.push_back(RetTyElement);
11312 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11313 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11315 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11317 SDValue InChain = DAG.getEntryNode();
11318 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11319 bool isSigned = N->getOpcode() == ISD::SREM;
11320 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11321 getPointerTy(DAG.getDataLayout()));
11324 CallLoweringInfo CLI(DAG);
11325 CLI.setChain(InChain)
11326 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11327 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11328 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11330 // Return second (rem) result operand (first contains div)
11331 SDNode *ResNode = CallResult.first.getNode();
11332 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11333 return ResNode->getOperand(1);
11337 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11338 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11342 SDValue Chain = Op.getOperand(0);
11343 SDValue Size = Op.getOperand(1);
11345 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11346 DAG.getConstant(2, DL, MVT::i32));
11349 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11350 Flag = Chain.getValue(1);
11352 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11353 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11355 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11356 Chain = NewSP.getValue(1);
11358 SDValue Ops[2] = { NewSP, Chain };
11359 return DAG.getMergeValues(Ops, DL);
11362 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11363 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11364 "Unexpected type for custom-lowering FP_EXTEND");
11367 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11369 SDValue SrcVal = Op.getOperand(0);
11370 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11374 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11375 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11376 Subtarget->isFPOnlySP() &&
11377 "Unexpected type for custom-lowering FP_ROUND");
11380 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11382 SDValue SrcVal = Op.getOperand(0);
11383 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11388 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11389 // The ARM target isn't yet aware of offsets.
11393 bool ARM::isBitFieldInvertedMask(unsigned v) {
11394 if (v == 0xffffffff)
11397 // there can be 1's on either or both "outsides", all the "inside"
11398 // bits must be 0's
11399 return isShiftedMask_32(~v);
11402 /// isFPImmLegal - Returns true if the target can instruction select the
11403 /// specified FP immediate natively. If false, the legalizer will
11404 /// materialize the FP immediate as a load from a constant pool.
11405 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11406 if (!Subtarget->hasVFP3())
11408 if (VT == MVT::f32)
11409 return ARM_AM::getFP32Imm(Imm) != -1;
11410 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11411 return ARM_AM::getFP64Imm(Imm) != -1;
11415 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11416 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11417 /// specified in the intrinsic calls.
11418 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11420 unsigned Intrinsic) const {
11421 switch (Intrinsic) {
11422 case Intrinsic::arm_neon_vld1:
11423 case Intrinsic::arm_neon_vld2:
11424 case Intrinsic::arm_neon_vld3:
11425 case Intrinsic::arm_neon_vld4:
11426 case Intrinsic::arm_neon_vld2lane:
11427 case Intrinsic::arm_neon_vld3lane:
11428 case Intrinsic::arm_neon_vld4lane: {
11429 Info.opc = ISD::INTRINSIC_W_CHAIN;
11430 // Conservatively set memVT to the entire set of vectors loaded.
11431 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11432 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11433 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11434 Info.ptrVal = I.getArgOperand(0);
11436 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11437 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11438 Info.vol = false; // volatile loads with NEON intrinsics not supported
11439 Info.readMem = true;
11440 Info.writeMem = false;
11443 case Intrinsic::arm_neon_vst1:
11444 case Intrinsic::arm_neon_vst2:
11445 case Intrinsic::arm_neon_vst3:
11446 case Intrinsic::arm_neon_vst4:
11447 case Intrinsic::arm_neon_vst2lane:
11448 case Intrinsic::arm_neon_vst3lane:
11449 case Intrinsic::arm_neon_vst4lane: {
11450 Info.opc = ISD::INTRINSIC_VOID;
11451 // Conservatively set memVT to the entire set of vectors stored.
11452 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11453 unsigned NumElts = 0;
11454 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11455 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11456 if (!ArgTy->isVectorTy())
11458 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11460 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11461 Info.ptrVal = I.getArgOperand(0);
11463 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11464 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11465 Info.vol = false; // volatile stores with NEON intrinsics not supported
11466 Info.readMem = false;
11467 Info.writeMem = true;
11470 case Intrinsic::arm_ldaex:
11471 case Intrinsic::arm_ldrex: {
11472 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11473 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11474 Info.opc = ISD::INTRINSIC_W_CHAIN;
11475 Info.memVT = MVT::getVT(PtrTy->getElementType());
11476 Info.ptrVal = I.getArgOperand(0);
11478 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11480 Info.readMem = true;
11481 Info.writeMem = false;
11484 case Intrinsic::arm_stlex:
11485 case Intrinsic::arm_strex: {
11486 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11487 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11488 Info.opc = ISD::INTRINSIC_W_CHAIN;
11489 Info.memVT = MVT::getVT(PtrTy->getElementType());
11490 Info.ptrVal = I.getArgOperand(1);
11492 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11494 Info.readMem = false;
11495 Info.writeMem = true;
11498 case Intrinsic::arm_stlexd:
11499 case Intrinsic::arm_strexd: {
11500 Info.opc = ISD::INTRINSIC_W_CHAIN;
11501 Info.memVT = MVT::i64;
11502 Info.ptrVal = I.getArgOperand(2);
11506 Info.readMem = false;
11507 Info.writeMem = true;
11510 case Intrinsic::arm_ldaexd:
11511 case Intrinsic::arm_ldrexd: {
11512 Info.opc = ISD::INTRINSIC_W_CHAIN;
11513 Info.memVT = MVT::i64;
11514 Info.ptrVal = I.getArgOperand(0);
11518 Info.readMem = true;
11519 Info.writeMem = false;
11529 /// \brief Returns true if it is beneficial to convert a load of a constant
11530 /// to just the constant itself.
11531 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11533 assert(Ty->isIntegerTy());
11535 unsigned Bits = Ty->getPrimitiveSizeInBits();
11536 if (Bits == 0 || Bits > 32)
11541 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11542 ARM_MB::MemBOpt Domain) const {
11543 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11545 // First, if the target has no DMB, see what fallback we can use.
11546 if (!Subtarget->hasDataBarrier()) {
11547 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11548 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11550 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11551 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11552 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11553 Builder.getInt32(0), Builder.getInt32(7),
11554 Builder.getInt32(10), Builder.getInt32(5)};
11555 return Builder.CreateCall(MCR, args);
11557 // Instead of using barriers, atomic accesses on these subtargets use
11559 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11562 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11563 // Only a full system barrier exists in the M-class architectures.
11564 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11565 Constant *CDomain = Builder.getInt32(Domain);
11566 return Builder.CreateCall(DMB, CDomain);
11570 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11571 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11572 AtomicOrdering Ord, bool IsStore,
11573 bool IsLoad) const {
11574 if (!getInsertFencesForAtomic())
11580 llvm_unreachable("Invalid fence: unordered/non-atomic");
11583 return nullptr; // Nothing to do
11584 case SequentiallyConsistent:
11586 return nullptr; // Nothing to do
11589 case AcquireRelease:
11590 if (Subtarget->isSwift())
11591 return makeDMB(Builder, ARM_MB::ISHST);
11592 // FIXME: add a comment with a link to documentation justifying this.
11594 return makeDMB(Builder, ARM_MB::ISH);
11596 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11599 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11600 AtomicOrdering Ord, bool IsStore,
11601 bool IsLoad) const {
11602 if (!getInsertFencesForAtomic())
11608 llvm_unreachable("Invalid fence: unordered/not-atomic");
11611 return nullptr; // Nothing to do
11613 case AcquireRelease:
11614 case SequentiallyConsistent:
11615 return makeDMB(Builder, ARM_MB::ISH);
11617 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11620 // Loads and stores less than 64-bits are already atomic; ones above that
11621 // are doomed anyway, so defer to the default libcall and blame the OS when
11622 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11623 // anything for those.
11624 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11625 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11626 return (Size == 64) && !Subtarget->isMClass();
11629 // Loads and stores less than 64-bits are already atomic; ones above that
11630 // are doomed anyway, so defer to the default libcall and blame the OS when
11631 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11632 // anything for those.
11633 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11634 // guarantee, see DDI0406C ARM architecture reference manual,
11635 // sections A8.8.72-74 LDRD)
11636 TargetLowering::AtomicExpansionKind
11637 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11638 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11639 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11640 : AtomicExpansionKind::None;
11643 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11644 // and up to 64 bits on the non-M profiles
11645 TargetLowering::AtomicExpansionKind
11646 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11647 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11648 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11649 ? AtomicExpansionKind::LLSC
11650 : AtomicExpansionKind::None;
11653 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11654 AtomicCmpXchgInst *AI) const {
11658 // This has so far only been implemented for MachO.
11659 bool ARMTargetLowering::useLoadStackGuardNode() const {
11660 return Subtarget->isTargetMachO();
11663 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11664 unsigned &Cost) const {
11665 // If we do not have NEON, vector types are not natively supported.
11666 if (!Subtarget->hasNEON())
11669 // Floating point values and vector values map to the same register file.
11670 // Therefore, although we could do a store extract of a vector type, this is
11671 // better to leave at float as we have more freedom in the addressing mode for
11673 if (VectorTy->isFPOrFPVectorTy())
11676 // If the index is unknown at compile time, this is very expensive to lower
11677 // and it is not possible to combine the store with the extract.
11678 if (!isa<ConstantInt>(Idx))
11681 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11682 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11683 // We can do a store + vector extract on any vector that fits perfectly in a D
11685 if (BitWidth == 64 || BitWidth == 128) {
11692 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11693 AtomicOrdering Ord) const {
11694 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11695 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11696 bool IsAcquire = isAtLeastAcquire(Ord);
11698 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11699 // intrinsic must return {i32, i32} and we have to recombine them into a
11700 // single i64 here.
11701 if (ValTy->getPrimitiveSizeInBits() == 64) {
11702 Intrinsic::ID Int =
11703 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11704 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11706 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11707 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11709 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11710 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11711 if (!Subtarget->isLittle())
11712 std::swap (Lo, Hi);
11713 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11714 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11715 return Builder.CreateOr(
11716 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11719 Type *Tys[] = { Addr->getType() };
11720 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11721 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11723 return Builder.CreateTruncOrBitCast(
11724 Builder.CreateCall(Ldrex, Addr),
11725 cast<PointerType>(Addr->getType())->getElementType());
11728 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11729 IRBuilder<> &Builder) const {
11730 if (!Subtarget->hasV7Ops())
11732 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11733 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11736 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11738 AtomicOrdering Ord) const {
11739 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11740 bool IsRelease = isAtLeastRelease(Ord);
11742 // Since the intrinsics must have legal type, the i64 intrinsics take two
11743 // parameters: "i32, i32". We must marshal Val into the appropriate form
11744 // before the call.
11745 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11746 Intrinsic::ID Int =
11747 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11748 Function *Strex = Intrinsic::getDeclaration(M, Int);
11749 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11751 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11752 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11753 if (!Subtarget->isLittle())
11754 std::swap (Lo, Hi);
11755 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11756 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11759 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11760 Type *Tys[] = { Addr->getType() };
11761 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11763 return Builder.CreateCall(
11764 Strex, {Builder.CreateZExtOrBitCast(
11765 Val, Strex->getFunctionType()->getParamType(0)),
11769 /// \brief Lower an interleaved load into a vldN intrinsic.
11771 /// E.g. Lower an interleaved load (Factor = 2):
11772 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11773 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11774 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11777 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11778 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11779 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11780 bool ARMTargetLowering::lowerInterleavedLoad(
11781 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11782 ArrayRef<unsigned> Indices, unsigned Factor) const {
11783 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11784 "Invalid interleave factor");
11785 assert(!Shuffles.empty() && "Empty shufflevector input");
11786 assert(Shuffles.size() == Indices.size() &&
11787 "Unmatched number of shufflevectors and indices");
11789 VectorType *VecTy = Shuffles[0]->getType();
11790 Type *EltTy = VecTy->getVectorElementType();
11792 const DataLayout &DL = LI->getModule()->getDataLayout();
11793 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11794 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11796 // Skip if we do not have NEON and skip illegal vector types and vector types
11797 // with i64/f64 elements (vldN doesn't support i64/f64 elements).
11798 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
11801 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11802 // load integer vectors first and then convert to pointer vectors.
11803 if (EltTy->isPointerTy())
11805 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11807 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11808 Intrinsic::arm_neon_vld3,
11809 Intrinsic::arm_neon_vld4};
11811 IRBuilder<> Builder(LI);
11812 SmallVector<Value *, 2> Ops;
11814 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11815 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11816 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11818 Type *Tys[] = { VecTy, Int8Ptr };
11819 Function *VldnFunc =
11820 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11821 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11823 // Replace uses of each shufflevector with the corresponding vector loaded
11825 for (unsigned i = 0; i < Shuffles.size(); i++) {
11826 ShuffleVectorInst *SV = Shuffles[i];
11827 unsigned Index = Indices[i];
11829 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11831 // Convert the integer vector to pointer vector if the element is pointer.
11832 if (EltTy->isPointerTy())
11833 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11835 SV->replaceAllUsesWith(SubVec);
11841 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11843 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11844 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11845 unsigned NumElts) {
11846 SmallVector<Constant *, 16> Mask;
11847 for (unsigned i = 0; i < NumElts; i++)
11848 Mask.push_back(Builder.getInt32(Start + i));
11850 return ConstantVector::get(Mask);
11853 /// \brief Lower an interleaved store into a vstN intrinsic.
11855 /// E.g. Lower an interleaved store (Factor = 3):
11856 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11857 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11858 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11861 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11862 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11863 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11864 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11866 /// Note that the new shufflevectors will be removed and we'll only generate one
11867 /// vst3 instruction in CodeGen.
11868 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11869 ShuffleVectorInst *SVI,
11870 unsigned Factor) const {
11871 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11872 "Invalid interleave factor");
11874 VectorType *VecTy = SVI->getType();
11875 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11876 "Invalid interleaved store");
11878 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11879 Type *EltTy = VecTy->getVectorElementType();
11880 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11882 const DataLayout &DL = SI->getModule()->getDataLayout();
11883 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11884 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11886 // Skip if we do not have NEON and skip illegal vector types and vector types
11887 // with i64/f64 elements (vstN doesn't support i64/f64 elements).
11888 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
11892 Value *Op0 = SVI->getOperand(0);
11893 Value *Op1 = SVI->getOperand(1);
11894 IRBuilder<> Builder(SI);
11896 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11897 // vectors to integer vectors.
11898 if (EltTy->isPointerTy()) {
11899 Type *IntTy = DL.getIntPtrType(EltTy);
11901 // Convert to the corresponding integer vector.
11903 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11904 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11905 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11907 SubVecTy = VectorType::get(IntTy, NumSubElts);
11910 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11911 Intrinsic::arm_neon_vst3,
11912 Intrinsic::arm_neon_vst4};
11913 SmallVector<Value *, 6> Ops;
11915 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11916 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11918 Type *Tys[] = { Int8Ptr, SubVecTy };
11919 Function *VstNFunc = Intrinsic::getDeclaration(
11920 SI->getModule(), StoreInts[Factor - 2], Tys);
11922 // Split the shufflevector operands into sub vectors for the new vstN call.
11923 for (unsigned i = 0; i < Factor; i++)
11924 Ops.push_back(Builder.CreateShuffleVector(
11925 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11927 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11928 Builder.CreateCall(VstNFunc, Ops);
11940 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11941 uint64_t &Members) {
11942 if (auto *ST = dyn_cast<StructType>(Ty)) {
11943 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11944 uint64_t SubMembers = 0;
11945 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11947 Members += SubMembers;
11949 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11950 uint64_t SubMembers = 0;
11951 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11953 Members += SubMembers * AT->getNumElements();
11954 } else if (Ty->isFloatTy()) {
11955 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11959 } else if (Ty->isDoubleTy()) {
11960 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11964 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11971 return VT->getBitWidth() == 64;
11973 return VT->getBitWidth() == 128;
11975 switch (VT->getBitWidth()) {
11988 return (Members > 0 && Members <= 4);
11991 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11992 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11993 /// passing according to AAPCS rules.
11994 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11995 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11996 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11997 CallingConv::ARM_AAPCS_VFP)
12000 HABaseType Base = HA_UNKNOWN;
12001 uint64_t Members = 0;
12002 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12003 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12005 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12006 return IsHA || IsIntArray;