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);
246 // Set the correct calling convention for ARMv7k WatchOS. It's just
247 // AAPCS_VFP for functions as simple as libcalls.
248 if (Subtarget->isTargetWatchOS()) {
249 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
250 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, nullptr);
256 setLibcallName(RTLIB::SRL_I128, nullptr);
257 setLibcallName(RTLIB::SRA_I128, nullptr);
260 if (Subtarget->isAAPCS_ABI() &&
261 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
262 Subtarget->isTargetAndroid())) {
263 static const struct {
264 const RTLIB::Libcall Op;
265 const char * const Name;
266 const CallingConv::ID CC;
267 const ISD::CondCode Cond;
269 // Double-precision floating-point arithmetic helper functions
270 // RTABI chapter 4.1.2, Table 2
271 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
274 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 // Double-precision floating-point comparison helper functions
277 // RTABI chapter 4.1.2, Table 3
278 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
280 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
282 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
284 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
287 // Single-precision floating-point arithmetic helper functions
288 // RTABI chapter 4.1.2, Table 4
289 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 // Single-precision floating-point comparison helper functions
295 // RTABI chapter 4.1.2, Table 5
296 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
298 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
300 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
301 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
302 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
303 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
305 // Floating-point to integer conversions.
306 // RTABI chapter 4.1.2, Table 6
307 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 // Conversions between floating types.
317 // RTABI chapter 4.1.2, Table 7
318 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 // Integer to floating-point conversions.
323 // RTABI chapter 4.1.2, Table 8
324 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 // Long long helper functions
334 // RTABI chapter 4.2, Table 9
335 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 // Integer division functions
341 // RTABI chapter 4.3.1
342 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 for (const auto &LC : LibraryCalls) {
353 setLibcallName(LC.Op, LC.Name);
354 setLibcallCallingConv(LC.Op, LC.CC);
355 if (LC.Cond != ISD::SETCC_INVALID)
356 setCmpLibcallCC(LC.Op, LC.Cond);
359 // EABI dependent RTLIB
360 if (TM.Options.EABIVersion == EABI::EABI4 ||
361 TM.Options.EABIVersion == EABI::EABI5) {
362 static const struct {
363 const RTLIB::Libcall Op;
364 const char *const Name;
365 const CallingConv::ID CC;
366 const ISD::CondCode Cond;
367 } MemOpsLibraryCalls[] = {
369 // RTABI chapter 4.3.4
370 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375 for (const auto &LC : MemOpsLibraryCalls) {
376 setLibcallName(LC.Op, LC.Name);
377 setLibcallCallingConv(LC.Op, LC.CC);
378 if (LC.Cond != ISD::SETCC_INVALID)
379 setCmpLibcallCC(LC.Op, LC.Cond);
384 if (Subtarget->isTargetWindows()) {
385 static const struct {
386 const RTLIB::Libcall Op;
387 const char * const Name;
388 const CallingConv::ID CC;
390 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
391 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
392 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
393 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
394 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
395 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
396 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
397 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
398 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
399 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
400 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
401 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
404 for (const auto &LC : LibraryCalls) {
405 setLibcallName(LC.Op, LC.Name);
406 setLibcallCallingConv(LC.Op, LC.CC);
410 // Use divmod compiler-rt calls for iOS 5.0 and later.
411 if (Subtarget->isTargetWatchOS() ||
412 (Subtarget->isTargetIOS() &&
413 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
414 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
415 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
418 // The half <-> float conversion functions are always soft-float, but are
419 // needed for some targets which use a hard-float calling convention by
421 if (Subtarget->isAAPCS_ABI()) {
422 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
424 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
426 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
427 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
428 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
431 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
432 // a __gnu_ prefix (which is the default).
433 if (Subtarget->isTargetAEABI()) {
434 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
435 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
436 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f");
439 if (Subtarget->isThumb1Only())
440 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
442 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
443 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
444 !Subtarget->isThumb1Only()) {
445 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
446 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
449 for (MVT VT : MVT::vector_valuetypes()) {
450 for (MVT InnerVT : MVT::vector_valuetypes()) {
451 setTruncStoreAction(VT, InnerVT, Expand);
452 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
453 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
454 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
457 setOperationAction(ISD::MULHS, VT, Expand);
458 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
459 setOperationAction(ISD::MULHU, VT, Expand);
460 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
462 setOperationAction(ISD::BSWAP, VT, Expand);
465 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
466 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
468 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
469 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
471 if (Subtarget->hasNEON()) {
472 addDRTypeForNEON(MVT::v2f32);
473 addDRTypeForNEON(MVT::v8i8);
474 addDRTypeForNEON(MVT::v4i16);
475 addDRTypeForNEON(MVT::v2i32);
476 addDRTypeForNEON(MVT::v1i64);
478 addQRTypeForNEON(MVT::v4f32);
479 addQRTypeForNEON(MVT::v2f64);
480 addQRTypeForNEON(MVT::v16i8);
481 addQRTypeForNEON(MVT::v8i16);
482 addQRTypeForNEON(MVT::v4i32);
483 addQRTypeForNEON(MVT::v2i64);
485 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
486 // neither Neon nor VFP support any arithmetic operations on it.
487 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
488 // supported for v4f32.
489 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
490 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
491 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
492 // FIXME: Code duplication: FDIV and FREM are expanded always, see
493 // ARMTargetLowering::addTypeForNEON method for details.
494 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
495 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
496 // FIXME: Create unittest.
497 // In another words, find a way when "copysign" appears in DAG with vector
499 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
500 // FIXME: Code duplication: SETCC has custom operation action, see
501 // ARMTargetLowering::addTypeForNEON method for details.
502 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
503 // FIXME: Create unittest for FNEG and for FABS.
504 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
505 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
506 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
507 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
508 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
510 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
511 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
514 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
516 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
517 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
518 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
519 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
520 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
521 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
522 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
524 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
526 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
527 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
528 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
529 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
530 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
531 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
532 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
533 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
534 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
535 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
536 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
537 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
538 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
540 // Mark v2f32 intrinsics.
541 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
543 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
544 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
545 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
546 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
547 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
548 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
549 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
550 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
551 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
552 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
553 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
554 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
555 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
557 // Neon does not support some operations on v1i64 and v2i64 types.
558 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
559 // Custom handling for some quad-vector types to detect VMULL.
560 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
561 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
562 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
563 // Custom handling for some vector types to avoid expensive expansions
564 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
565 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
566 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
567 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
568 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
569 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
570 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
571 // a destination type that is wider than the source, and nor does
572 // it have a FP_TO_[SU]INT instruction with a narrower destination than
574 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
576 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
577 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
579 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
580 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
582 // NEON does not have single instruction CTPOP for vectors with element
583 // types wider than 8-bits. However, custom lowering can leverage the
584 // v8i8/v16i8 vcnt instruction.
585 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
586 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
587 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
588 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
590 // NEON does not have single instruction CTTZ for vectors.
591 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
592 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
593 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
594 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
596 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
597 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
598 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
599 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
608 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
609 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
611 // NEON only has FMA instructions as of VFP4.
612 if (!Subtarget->hasVFP4()) {
613 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
614 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
617 setTargetDAGCombine(ISD::INTRINSIC_VOID);
618 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
619 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
620 setTargetDAGCombine(ISD::SHL);
621 setTargetDAGCombine(ISD::SRL);
622 setTargetDAGCombine(ISD::SRA);
623 setTargetDAGCombine(ISD::SIGN_EXTEND);
624 setTargetDAGCombine(ISD::ZERO_EXTEND);
625 setTargetDAGCombine(ISD::ANY_EXTEND);
626 setTargetDAGCombine(ISD::BUILD_VECTOR);
627 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
628 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
629 setTargetDAGCombine(ISD::STORE);
630 setTargetDAGCombine(ISD::FP_TO_SINT);
631 setTargetDAGCombine(ISD::FP_TO_UINT);
632 setTargetDAGCombine(ISD::FDIV);
633 setTargetDAGCombine(ISD::LOAD);
635 // It is legal to extload from v4i8 to v4i16 or v4i32.
636 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
638 for (MVT VT : MVT::integer_vector_valuetypes()) {
639 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
640 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
641 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
646 // ARM and Thumb2 support UMLAL/SMLAL.
647 if (!Subtarget->isThumb1Only())
648 setTargetDAGCombine(ISD::ADDC);
650 if (Subtarget->isFPOnlySP()) {
651 // When targeting a floating-point unit with only single-precision
652 // operations, f64 is legal for the few double-precision instructions which
653 // are present However, no double-precision operations other than moves,
654 // loads and stores are provided by the hardware.
655 setOperationAction(ISD::FADD, MVT::f64, Expand);
656 setOperationAction(ISD::FSUB, MVT::f64, Expand);
657 setOperationAction(ISD::FMUL, MVT::f64, Expand);
658 setOperationAction(ISD::FMA, MVT::f64, Expand);
659 setOperationAction(ISD::FDIV, MVT::f64, Expand);
660 setOperationAction(ISD::FREM, MVT::f64, Expand);
661 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
662 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
663 setOperationAction(ISD::FNEG, MVT::f64, Expand);
664 setOperationAction(ISD::FABS, MVT::f64, Expand);
665 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
666 setOperationAction(ISD::FSIN, MVT::f64, Expand);
667 setOperationAction(ISD::FCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
669 setOperationAction(ISD::FPOW, MVT::f64, Expand);
670 setOperationAction(ISD::FLOG, MVT::f64, Expand);
671 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
672 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
673 setOperationAction(ISD::FEXP, MVT::f64, Expand);
674 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
675 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
676 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
677 setOperationAction(ISD::FRINT, MVT::f64, Expand);
678 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
679 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
680 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
682 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
683 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
684 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
685 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
686 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
687 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
690 computeRegisterProperties(Subtarget->getRegisterInfo());
692 // ARM does not have floating-point extending loads.
693 for (MVT VT : MVT::fp_valuetypes()) {
694 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
695 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
698 // ... or truncating stores
699 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
700 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
701 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
703 // ARM does not have i1 sign extending load.
704 for (MVT VT : MVT::integer_valuetypes())
705 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
707 // ARM supports all 4 flavors of integer indexed load / store.
708 if (!Subtarget->isThumb1Only()) {
709 for (unsigned im = (unsigned)ISD::PRE_INC;
710 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
711 setIndexedLoadAction(im, MVT::i1, Legal);
712 setIndexedLoadAction(im, MVT::i8, Legal);
713 setIndexedLoadAction(im, MVT::i16, Legal);
714 setIndexedLoadAction(im, MVT::i32, Legal);
715 setIndexedStoreAction(im, MVT::i1, Legal);
716 setIndexedStoreAction(im, MVT::i8, Legal);
717 setIndexedStoreAction(im, MVT::i16, Legal);
718 setIndexedStoreAction(im, MVT::i32, Legal);
722 setOperationAction(ISD::SADDO, MVT::i32, Custom);
723 setOperationAction(ISD::UADDO, MVT::i32, Custom);
724 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
725 setOperationAction(ISD::USUBO, MVT::i32, Custom);
727 // i64 operation support.
728 setOperationAction(ISD::MUL, MVT::i64, Expand);
729 setOperationAction(ISD::MULHU, MVT::i32, Expand);
730 if (Subtarget->isThumb1Only()) {
731 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
732 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
734 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
735 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
736 setOperationAction(ISD::MULHS, MVT::i32, Expand);
738 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
739 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
740 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
741 setOperationAction(ISD::SRL, MVT::i64, Custom);
742 setOperationAction(ISD::SRA, MVT::i64, Custom);
744 if (!Subtarget->isThumb1Only()) {
745 // FIXME: We should do this for Thumb1 as well.
746 setOperationAction(ISD::ADDC, MVT::i32, Custom);
747 setOperationAction(ISD::ADDE, MVT::i32, Custom);
748 setOperationAction(ISD::SUBC, MVT::i32, Custom);
749 setOperationAction(ISD::SUBE, MVT::i32, Custom);
752 if (!Subtarget->isThumb1Only())
753 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
755 // ARM does not have ROTL.
756 setOperationAction(ISD::ROTL, MVT::i32, Expand);
757 for (MVT VT : MVT::vector_valuetypes()) {
758 setOperationAction(ISD::ROTL, VT, Expand);
759 setOperationAction(ISD::ROTR, VT, Expand);
761 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
762 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
763 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
764 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
766 // These just redirect to CTTZ and CTLZ on ARM.
767 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
768 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
770 // @llvm.readcyclecounter requires the Performance Monitors extension.
771 // Default to the 0 expansion on unsupported platforms.
772 // FIXME: Technically there are older ARM CPUs that have
773 // implementation-specific ways of obtaining this information.
774 if (Subtarget->hasPerfMon())
775 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
777 // Only ARMv6 has BSWAP.
778 if (!Subtarget->hasV6Ops())
779 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
781 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
782 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
783 // These are expanded into libcalls if the cpu doesn't have HW divider.
784 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
785 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
788 setOperationAction(ISD::SREM, MVT::i32, Expand);
789 setOperationAction(ISD::UREM, MVT::i32, Expand);
790 // Register based DivRem for AEABI (RTABI 4.2)
791 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
792 setOperationAction(ISD::SREM, MVT::i64, Custom);
793 setOperationAction(ISD::UREM, MVT::i64, Custom);
795 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
796 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
797 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
798 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
799 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
800 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
801 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
802 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
804 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
805 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
806 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
807 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
808 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
809 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
810 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
811 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
813 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
814 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
816 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
817 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
820 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
821 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
822 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
823 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
825 setOperationAction(ISD::TRAP, MVT::Other, Legal);
827 // Use the default implementation.
828 setOperationAction(ISD::VASTART, MVT::Other, Custom);
829 setOperationAction(ISD::VAARG, MVT::Other, Expand);
830 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
831 setOperationAction(ISD::VAEND, MVT::Other, Expand);
832 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
833 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
835 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
836 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
838 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
840 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
841 // the default expansion. If we are targeting a single threaded system,
842 // then set them all for expand so we can lower them later into their
844 if (TM.Options.ThreadModel == ThreadModel::Single)
845 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
846 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
847 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
848 // to ldrex/strex loops already.
849 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
851 // On v8, we have particularly efficient implementations of atomic fences
852 // if they can be combined with nearby atomic loads and stores.
853 if (!Subtarget->hasV8Ops()) {
854 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
855 setInsertFencesForAtomic(true);
858 // If there's anything we can use as a barrier, go through custom lowering
860 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
861 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
863 // Set them all for expansion, which will force libcalls.
864 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
865 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
866 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
867 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
868 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
869 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
870 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
871 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
872 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
873 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
874 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
875 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
876 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
877 // Unordered/Monotonic case.
878 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
879 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
882 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
884 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
885 if (!Subtarget->hasV6Ops()) {
886 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
887 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
889 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
891 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892 !Subtarget->isThumb1Only()) {
893 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
894 // iff target supports vfp2.
895 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
896 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
899 // We want to custom lower some of our intrinsics.
900 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
901 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
902 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
903 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
904 if (Subtarget->useSjLjEH())
905 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
907 setOperationAction(ISD::SETCC, MVT::i32, Expand);
908 setOperationAction(ISD::SETCC, MVT::f32, Expand);
909 setOperationAction(ISD::SETCC, MVT::f64, Expand);
910 setOperationAction(ISD::SELECT, MVT::i32, Custom);
911 setOperationAction(ISD::SELECT, MVT::f32, Custom);
912 setOperationAction(ISD::SELECT, MVT::f64, Custom);
913 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
914 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
915 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
917 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
918 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
919 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
920 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
921 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
923 // We don't support sin/cos/fmod/copysign/pow
924 setOperationAction(ISD::FSIN, MVT::f64, Expand);
925 setOperationAction(ISD::FSIN, MVT::f32, Expand);
926 setOperationAction(ISD::FCOS, MVT::f32, Expand);
927 setOperationAction(ISD::FCOS, MVT::f64, Expand);
928 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
929 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
930 setOperationAction(ISD::FREM, MVT::f64, Expand);
931 setOperationAction(ISD::FREM, MVT::f32, Expand);
932 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
933 !Subtarget->isThumb1Only()) {
934 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
935 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
937 setOperationAction(ISD::FPOW, MVT::f64, Expand);
938 setOperationAction(ISD::FPOW, MVT::f32, Expand);
940 if (!Subtarget->hasVFP4()) {
941 setOperationAction(ISD::FMA, MVT::f64, Expand);
942 setOperationAction(ISD::FMA, MVT::f32, Expand);
945 // Various VFP goodness
946 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
947 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
948 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
949 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
950 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
953 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
954 if (!Subtarget->hasFP16()) {
955 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
956 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
960 // Combine sin / cos into one node or libcall if possible.
961 if (Subtarget->hasSinCos()) {
962 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
963 setLibcallName(RTLIB::SINCOS_F64, "sincos");
964 if (Subtarget->isTargetWatchOS()) {
965 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
966 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
968 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
969 // For iOS, we don't want to the normal expansion of a libcall to
970 // sincos. We want to issue a libcall to __sincos_stret.
971 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
972 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
976 // FP-ARMv8 implements a lot of rounding-like FP operations.
977 if (Subtarget->hasFPARMv8()) {
978 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
979 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
980 setOperationAction(ISD::FROUND, MVT::f32, Legal);
981 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
982 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
983 setOperationAction(ISD::FRINT, MVT::f32, Legal);
984 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
985 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
986 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
987 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
988 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
989 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
991 if (!Subtarget->isFPOnlySP()) {
992 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
993 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
994 setOperationAction(ISD::FROUND, MVT::f64, Legal);
995 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
996 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
997 setOperationAction(ISD::FRINT, MVT::f64, Legal);
998 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
999 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1003 if (Subtarget->hasNEON()) {
1004 // vmin and vmax aren't available in a scalar form, so we use
1005 // a NEON instruction with an undef lane instead.
1006 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1007 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1008 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1009 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1010 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1011 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1014 // We have target-specific dag combine patterns for the following nodes:
1015 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1016 setTargetDAGCombine(ISD::ADD);
1017 setTargetDAGCombine(ISD::SUB);
1018 setTargetDAGCombine(ISD::MUL);
1019 setTargetDAGCombine(ISD::AND);
1020 setTargetDAGCombine(ISD::OR);
1021 setTargetDAGCombine(ISD::XOR);
1023 if (Subtarget->hasV6Ops())
1024 setTargetDAGCombine(ISD::SRL);
1026 setStackPointerRegisterToSaveRestore(ARM::SP);
1028 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1029 !Subtarget->hasVFP2())
1030 setSchedulingPreference(Sched::RegPressure);
1032 setSchedulingPreference(Sched::Hybrid);
1034 //// temporary - rewrite interface to use type
1035 MaxStoresPerMemset = 8;
1036 MaxStoresPerMemsetOptSize = 4;
1037 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1038 MaxStoresPerMemcpyOptSize = 2;
1039 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1040 MaxStoresPerMemmoveOptSize = 2;
1042 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1043 // are at least 4 bytes aligned.
1044 setMinStackArgumentAlignment(4);
1046 // Prefer likely predicted branches to selects on out-of-order cores.
1047 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1049 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1052 bool ARMTargetLowering::useSoftFloat() const {
1053 return Subtarget->useSoftFloat();
1056 // FIXME: It might make sense to define the representative register class as the
1057 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1058 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1059 // SPR's representative would be DPR_VFP2. This should work well if register
1060 // pressure tracking were modified such that a register use would increment the
1061 // pressure of the register class's representative and all of it's super
1062 // classes' representatives transitively. We have not implemented this because
1063 // of the difficulty prior to coalescing of modeling operand register classes
1064 // due to the common occurrence of cross class copies and subregister insertions
1066 std::pair<const TargetRegisterClass *, uint8_t>
1067 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1069 const TargetRegisterClass *RRC = nullptr;
1071 switch (VT.SimpleTy) {
1073 return TargetLowering::findRepresentativeClass(TRI, VT);
1074 // Use DPR as representative register class for all floating point
1075 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1076 // the cost is 1 for both f32 and f64.
1077 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1078 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1079 RRC = &ARM::DPRRegClass;
1080 // When NEON is used for SP, only half of the register file is available
1081 // because operations that define both SP and DP results will be constrained
1082 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1083 // coalescing by double-counting the SP regs. See the FIXME above.
1084 if (Subtarget->useNEONForSinglePrecisionFP())
1087 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1088 case MVT::v4f32: case MVT::v2f64:
1089 RRC = &ARM::DPRRegClass;
1093 RRC = &ARM::DPRRegClass;
1097 RRC = &ARM::DPRRegClass;
1101 return std::make_pair(RRC, Cost);
1104 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1105 switch ((ARMISD::NodeType)Opcode) {
1106 case ARMISD::FIRST_NUMBER: break;
1107 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1108 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1109 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1110 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1111 case ARMISD::CALL: return "ARMISD::CALL";
1112 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1113 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1114 case ARMISD::tCALL: return "ARMISD::tCALL";
1115 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1116 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1117 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1118 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1119 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1120 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1121 case ARMISD::CMP: return "ARMISD::CMP";
1122 case ARMISD::CMN: return "ARMISD::CMN";
1123 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1124 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1125 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1126 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1127 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1129 case ARMISD::CMOV: return "ARMISD::CMOV";
1131 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1132 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1133 case ARMISD::RRX: return "ARMISD::RRX";
1135 case ARMISD::ADDC: return "ARMISD::ADDC";
1136 case ARMISD::ADDE: return "ARMISD::ADDE";
1137 case ARMISD::SUBC: return "ARMISD::SUBC";
1138 case ARMISD::SUBE: return "ARMISD::SUBE";
1140 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1141 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1143 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1144 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1145 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1147 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1149 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1151 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1153 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1155 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1157 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1158 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1160 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1161 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1162 case ARMISD::VCGE: return "ARMISD::VCGE";
1163 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1164 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1165 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1166 case ARMISD::VCGT: return "ARMISD::VCGT";
1167 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1168 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1169 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1170 case ARMISD::VTST: return "ARMISD::VTST";
1172 case ARMISD::VSHL: return "ARMISD::VSHL";
1173 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1174 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1175 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1176 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1177 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1178 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1179 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1180 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1181 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1182 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1183 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1184 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1185 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1186 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1187 case ARMISD::VSLI: return "ARMISD::VSLI";
1188 case ARMISD::VSRI: return "ARMISD::VSRI";
1189 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1190 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1191 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1192 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1193 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1194 case ARMISD::VDUP: return "ARMISD::VDUP";
1195 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1196 case ARMISD::VEXT: return "ARMISD::VEXT";
1197 case ARMISD::VREV64: return "ARMISD::VREV64";
1198 case ARMISD::VREV32: return "ARMISD::VREV32";
1199 case ARMISD::VREV16: return "ARMISD::VREV16";
1200 case ARMISD::VZIP: return "ARMISD::VZIP";
1201 case ARMISD::VUZP: return "ARMISD::VUZP";
1202 case ARMISD::VTRN: return "ARMISD::VTRN";
1203 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1204 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1205 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1206 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1207 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1208 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1209 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1210 case ARMISD::BFI: return "ARMISD::BFI";
1211 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1212 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1213 case ARMISD::VBSL: return "ARMISD::VBSL";
1214 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1215 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1216 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1217 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1218 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1219 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1220 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1221 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1222 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1223 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1224 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1225 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1226 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1227 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1228 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1229 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1230 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1231 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1232 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1233 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1234 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1239 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1242 return getPointerTy(DL);
1243 return VT.changeVectorElementTypeToInteger();
1246 /// getRegClassFor - Return the register class that should be used for the
1247 /// specified value type.
1248 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1249 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1250 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1251 // load / store 4 to 8 consecutive D registers.
1252 if (Subtarget->hasNEON()) {
1253 if (VT == MVT::v4i64)
1254 return &ARM::QQPRRegClass;
1255 if (VT == MVT::v8i64)
1256 return &ARM::QQQQPRRegClass;
1258 return TargetLowering::getRegClassFor(VT);
1261 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1262 // source/dest is aligned and the copy size is large enough. We therefore want
1263 // to align such objects passed to memory intrinsics.
1264 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1265 unsigned &PrefAlign) const {
1266 if (!isa<MemIntrinsic>(CI))
1269 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1270 // cycle faster than 4-byte aligned LDM.
1271 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1275 // Create a fast isel object.
1277 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1278 const TargetLibraryInfo *libInfo) const {
1279 return ARM::createFastISel(funcInfo, libInfo);
1282 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1283 unsigned NumVals = N->getNumValues();
1285 return Sched::RegPressure;
1287 for (unsigned i = 0; i != NumVals; ++i) {
1288 EVT VT = N->getValueType(i);
1289 if (VT == MVT::Glue || VT == MVT::Other)
1291 if (VT.isFloatingPoint() || VT.isVector())
1295 if (!N->isMachineOpcode())
1296 return Sched::RegPressure;
1298 // Load are scheduled for latency even if there instruction itinerary
1299 // is not available.
1300 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1301 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1303 if (MCID.getNumDefs() == 0)
1304 return Sched::RegPressure;
1305 if (!Itins->isEmpty() &&
1306 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1309 return Sched::RegPressure;
1312 //===----------------------------------------------------------------------===//
1314 //===----------------------------------------------------------------------===//
1316 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1317 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1319 default: llvm_unreachable("Unknown condition code!");
1320 case ISD::SETNE: return ARMCC::NE;
1321 case ISD::SETEQ: return ARMCC::EQ;
1322 case ISD::SETGT: return ARMCC::GT;
1323 case ISD::SETGE: return ARMCC::GE;
1324 case ISD::SETLT: return ARMCC::LT;
1325 case ISD::SETLE: return ARMCC::LE;
1326 case ISD::SETUGT: return ARMCC::HI;
1327 case ISD::SETUGE: return ARMCC::HS;
1328 case ISD::SETULT: return ARMCC::LO;
1329 case ISD::SETULE: return ARMCC::LS;
1333 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1334 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1335 ARMCC::CondCodes &CondCode2) {
1336 CondCode2 = ARMCC::AL;
1338 default: llvm_unreachable("Unknown FP condition!");
1340 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1342 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1344 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1345 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1346 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1347 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1348 case ISD::SETO: CondCode = ARMCC::VC; break;
1349 case ISD::SETUO: CondCode = ARMCC::VS; break;
1350 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1351 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1352 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1354 case ISD::SETULT: CondCode = ARMCC::LT; break;
1356 case ISD::SETULE: CondCode = ARMCC::LE; break;
1358 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1362 //===----------------------------------------------------------------------===//
1363 // Calling Convention Implementation
1364 //===----------------------------------------------------------------------===//
1366 #include "ARMGenCallingConv.inc"
1368 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1369 /// account presence of floating point hardware and calling convention
1370 /// limitations, such as support for variadic functions.
1372 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1373 bool isVarArg) const {
1376 llvm_unreachable("Unsupported calling convention");
1377 case CallingConv::ARM_AAPCS:
1378 case CallingConv::ARM_APCS:
1379 case CallingConv::GHC:
1381 case CallingConv::ARM_AAPCS_VFP:
1382 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1383 case CallingConv::C:
1384 if (!Subtarget->isAAPCS_ABI())
1385 return CallingConv::ARM_APCS;
1386 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1387 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1389 return CallingConv::ARM_AAPCS_VFP;
1391 return CallingConv::ARM_AAPCS;
1392 case CallingConv::Fast:
1393 if (!Subtarget->isAAPCS_ABI()) {
1394 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1395 return CallingConv::Fast;
1396 return CallingConv::ARM_APCS;
1397 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1398 return CallingConv::ARM_AAPCS_VFP;
1400 return CallingConv::ARM_AAPCS;
1404 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1405 /// CallingConvention.
1406 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1408 bool isVarArg) const {
1409 switch (getEffectiveCallingConv(CC, isVarArg)) {
1411 llvm_unreachable("Unsupported calling convention");
1412 case CallingConv::ARM_APCS:
1413 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1414 case CallingConv::ARM_AAPCS:
1415 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1416 case CallingConv::ARM_AAPCS_VFP:
1417 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1418 case CallingConv::Fast:
1419 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1420 case CallingConv::GHC:
1421 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1425 /// LowerCallResult - Lower the result values of a call into the
1426 /// appropriate copies out of appropriate physical registers.
1428 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1429 CallingConv::ID CallConv, bool isVarArg,
1430 const SmallVectorImpl<ISD::InputArg> &Ins,
1431 SDLoc dl, SelectionDAG &DAG,
1432 SmallVectorImpl<SDValue> &InVals,
1433 bool isThisReturn, SDValue ThisVal) const {
1435 // Assign locations to each value returned by this call.
1436 SmallVector<CCValAssign, 16> RVLocs;
1437 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1438 *DAG.getContext(), Call);
1439 CCInfo.AnalyzeCallResult(Ins,
1440 CCAssignFnForNode(CallConv, /* Return*/ true,
1443 // Copy all of the result registers out of their specified physreg.
1444 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1445 CCValAssign VA = RVLocs[i];
1447 // Pass 'this' value directly from the argument to return value, to avoid
1448 // reg unit interference
1449 if (i == 0 && isThisReturn) {
1450 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1451 "unexpected return calling convention register assignment");
1452 InVals.push_back(ThisVal);
1457 if (VA.needsCustom()) {
1458 // Handle f64 or half of a v2f64.
1459 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1461 Chain = Lo.getValue(1);
1462 InFlag = Lo.getValue(2);
1463 VA = RVLocs[++i]; // skip ahead to next loc
1464 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1466 Chain = Hi.getValue(1);
1467 InFlag = Hi.getValue(2);
1468 if (!Subtarget->isLittle())
1470 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1472 if (VA.getLocVT() == MVT::v2f64) {
1473 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1474 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1475 DAG.getConstant(0, dl, MVT::i32));
1477 VA = RVLocs[++i]; // skip ahead to next loc
1478 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1479 Chain = Lo.getValue(1);
1480 InFlag = Lo.getValue(2);
1481 VA = RVLocs[++i]; // skip ahead to next loc
1482 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1483 Chain = Hi.getValue(1);
1484 InFlag = Hi.getValue(2);
1485 if (!Subtarget->isLittle())
1487 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1488 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1489 DAG.getConstant(1, dl, MVT::i32));
1492 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1494 Chain = Val.getValue(1);
1495 InFlag = Val.getValue(2);
1498 switch (VA.getLocInfo()) {
1499 default: llvm_unreachable("Unknown loc info!");
1500 case CCValAssign::Full: break;
1501 case CCValAssign::BCvt:
1502 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1506 InVals.push_back(Val);
1512 /// LowerMemOpCallTo - Store the argument to the stack.
1514 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1515 SDValue StackPtr, SDValue Arg,
1516 SDLoc dl, SelectionDAG &DAG,
1517 const CCValAssign &VA,
1518 ISD::ArgFlagsTy Flags) const {
1519 unsigned LocMemOffset = VA.getLocMemOffset();
1520 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1521 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1523 return DAG.getStore(
1524 Chain, dl, Arg, PtrOff,
1525 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1529 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1530 SDValue Chain, SDValue &Arg,
1531 RegsToPassVector &RegsToPass,
1532 CCValAssign &VA, CCValAssign &NextVA,
1534 SmallVectorImpl<SDValue> &MemOpChains,
1535 ISD::ArgFlagsTy Flags) const {
1537 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1538 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1539 unsigned id = Subtarget->isLittle() ? 0 : 1;
1540 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1542 if (NextVA.isRegLoc())
1543 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1545 assert(NextVA.isMemLoc());
1546 if (!StackPtr.getNode())
1547 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1548 getPointerTy(DAG.getDataLayout()));
1550 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1556 /// LowerCall - Lowering a call into a callseq_start <-
1557 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1560 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1561 SmallVectorImpl<SDValue> &InVals) const {
1562 SelectionDAG &DAG = CLI.DAG;
1564 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1565 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1566 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1567 SDValue Chain = CLI.Chain;
1568 SDValue Callee = CLI.Callee;
1569 bool &isTailCall = CLI.IsTailCall;
1570 CallingConv::ID CallConv = CLI.CallConv;
1571 bool doesNotRet = CLI.DoesNotReturn;
1572 bool isVarArg = CLI.IsVarArg;
1574 MachineFunction &MF = DAG.getMachineFunction();
1575 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1576 bool isThisReturn = false;
1577 bool isSibCall = false;
1578 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1580 // Disable tail calls if they're not supported.
1581 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1585 // Check if it's really possible to do a tail call.
1586 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1587 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1588 Outs, OutVals, Ins, DAG);
1589 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1590 report_fatal_error("failed to perform tail call elimination on a call "
1591 "site marked musttail");
1592 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1593 // detected sibcalls.
1600 // Analyze operands of the call, assigning locations to each operand.
1601 SmallVector<CCValAssign, 16> ArgLocs;
1602 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1603 *DAG.getContext(), Call);
1604 CCInfo.AnalyzeCallOperands(Outs,
1605 CCAssignFnForNode(CallConv, /* Return*/ false,
1608 // Get a count of how many bytes are to be pushed on the stack.
1609 unsigned NumBytes = CCInfo.getNextStackOffset();
1611 // For tail calls, memory operands are available in our caller's stack.
1615 // Adjust the stack pointer for the new arguments...
1616 // These operations are automatically eliminated by the prolog/epilog pass
1618 Chain = DAG.getCALLSEQ_START(Chain,
1619 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1622 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1624 RegsToPassVector RegsToPass;
1625 SmallVector<SDValue, 8> MemOpChains;
1627 // Walk the register/memloc assignments, inserting copies/loads. In the case
1628 // of tail call optimization, arguments are handled later.
1629 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1631 ++i, ++realArgIdx) {
1632 CCValAssign &VA = ArgLocs[i];
1633 SDValue Arg = OutVals[realArgIdx];
1634 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1635 bool isByVal = Flags.isByVal();
1637 // Promote the value if needed.
1638 switch (VA.getLocInfo()) {
1639 default: llvm_unreachable("Unknown loc info!");
1640 case CCValAssign::Full: break;
1641 case CCValAssign::SExt:
1642 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1644 case CCValAssign::ZExt:
1645 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1647 case CCValAssign::AExt:
1648 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1650 case CCValAssign::BCvt:
1651 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1655 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1656 if (VA.needsCustom()) {
1657 if (VA.getLocVT() == MVT::v2f64) {
1658 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1659 DAG.getConstant(0, dl, MVT::i32));
1660 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1661 DAG.getConstant(1, dl, MVT::i32));
1663 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1664 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1666 VA = ArgLocs[++i]; // skip ahead to next loc
1667 if (VA.isRegLoc()) {
1668 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1669 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1671 assert(VA.isMemLoc());
1673 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1674 dl, DAG, VA, Flags));
1677 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1678 StackPtr, MemOpChains, Flags);
1680 } else if (VA.isRegLoc()) {
1681 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1682 assert(VA.getLocVT() == MVT::i32 &&
1683 "unexpected calling convention register assignment");
1684 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1685 "unexpected use of 'returned'");
1686 isThisReturn = true;
1688 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1689 } else if (isByVal) {
1690 assert(VA.isMemLoc());
1691 unsigned offset = 0;
1693 // True if this byval aggregate will be split between registers
1695 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1696 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1698 if (CurByValIdx < ByValArgsCount) {
1700 unsigned RegBegin, RegEnd;
1701 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1704 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1706 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1707 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1708 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1709 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1710 MachinePointerInfo(),
1711 false, false, false,
1712 DAG.InferPtrAlignment(AddArg));
1713 MemOpChains.push_back(Load.getValue(1));
1714 RegsToPass.push_back(std::make_pair(j, Load));
1717 // If parameter size outsides register area, "offset" value
1718 // helps us to calculate stack slot for remained part properly.
1719 offset = RegEnd - RegBegin;
1721 CCInfo.nextInRegsParam();
1724 if (Flags.getByValSize() > 4*offset) {
1725 auto PtrVT = getPointerTy(DAG.getDataLayout());
1726 unsigned LocMemOffset = VA.getLocMemOffset();
1727 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1728 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1729 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1730 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1731 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1733 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1736 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1737 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1738 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1741 } else if (!isSibCall) {
1742 assert(VA.isMemLoc());
1744 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1745 dl, DAG, VA, Flags));
1749 if (!MemOpChains.empty())
1750 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1752 // Build a sequence of copy-to-reg nodes chained together with token chain
1753 // and flag operands which copy the outgoing args into the appropriate regs.
1755 // Tail call byval lowering might overwrite argument registers so in case of
1756 // tail call optimization the copies to registers are lowered later.
1758 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1759 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1760 RegsToPass[i].second, InFlag);
1761 InFlag = Chain.getValue(1);
1764 // For tail calls lower the arguments to the 'real' stack slot.
1766 // Force all the incoming stack arguments to be loaded from the stack
1767 // before any new outgoing arguments are stored to the stack, because the
1768 // outgoing stack slots may alias the incoming argument stack slots, and
1769 // the alias isn't otherwise explicit. This is slightly more conservative
1770 // than necessary, because it means that each store effectively depends
1771 // on every argument instead of just those arguments it would clobber.
1773 // Do not flag preceding copytoreg stuff together with the following stuff.
1775 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1776 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1777 RegsToPass[i].second, InFlag);
1778 InFlag = Chain.getValue(1);
1783 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1784 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1785 // node so that legalize doesn't hack it.
1786 bool isDirect = false;
1787 bool isARMFunc = false;
1788 bool isLocalARMFunc = false;
1789 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1790 auto PtrVt = getPointerTy(DAG.getDataLayout());
1792 if (Subtarget->genLongCalls()) {
1793 assert((Subtarget->isTargetWindows() ||
1794 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1795 "long-calls with non-static relocation model!");
1796 // Handle a global address or an external symbol. If it's not one of
1797 // those, the target's already in a register, so we don't need to do
1799 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1800 const GlobalValue *GV = G->getGlobal();
1801 // Create a constant pool entry for the callee address
1802 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1803 ARMConstantPoolValue *CPV =
1804 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1806 // Get the address of the callee into a register
1807 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1808 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1809 Callee = DAG.getLoad(
1810 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1811 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1813 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1814 const char *Sym = S->getSymbol();
1816 // Create a constant pool entry for the callee address
1817 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1818 ARMConstantPoolValue *CPV =
1819 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1820 ARMPCLabelIndex, 0);
1821 // Get the address of the callee into a register
1822 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1823 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1824 Callee = DAG.getLoad(
1825 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1826 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1829 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1830 const GlobalValue *GV = G->getGlobal();
1832 bool isDef = GV->isStrongDefinitionForLinker();
1833 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1834 getTargetMachine().getRelocationModel() != Reloc::Static;
1835 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1836 // ARM call to a local ARM function is predicable.
1837 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1838 // tBX takes a register source operand.
1839 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1840 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1841 Callee = DAG.getNode(
1842 ARMISD::WrapperPIC, dl, PtrVt,
1843 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1844 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1845 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1846 false, false, true, 0);
1847 } else if (Subtarget->isTargetCOFF()) {
1848 assert(Subtarget->isTargetWindows() &&
1849 "Windows is the only supported COFF target");
1850 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1851 ? ARMII::MO_DLLIMPORT
1852 : ARMII::MO_NO_FLAG;
1854 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1855 if (GV->hasDLLImportStorageClass())
1857 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1858 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1859 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1860 false, false, false, 0);
1862 // On ELF targets for PIC code, direct calls should go through the PLT
1863 unsigned OpFlags = 0;
1864 if (Subtarget->isTargetELF() &&
1865 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1866 OpFlags = ARMII::MO_PLT;
1867 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1869 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1871 bool isStub = Subtarget->isTargetMachO() &&
1872 getTargetMachine().getRelocationModel() != Reloc::Static;
1873 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1874 // tBX takes a register source operand.
1875 const char *Sym = S->getSymbol();
1876 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1877 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1878 ARMConstantPoolValue *CPV =
1879 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1880 ARMPCLabelIndex, 4);
1881 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1882 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1883 Callee = DAG.getLoad(
1884 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1885 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1887 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1888 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1890 unsigned OpFlags = 0;
1891 // On ELF targets for PIC code, direct calls should go through the PLT
1892 if (Subtarget->isTargetELF() &&
1893 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1894 OpFlags = ARMII::MO_PLT;
1895 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1899 // FIXME: handle tail calls differently.
1901 if (Subtarget->isThumb()) {
1902 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1903 CallOpc = ARMISD::CALL_NOLINK;
1905 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1907 if (!isDirect && !Subtarget->hasV5TOps())
1908 CallOpc = ARMISD::CALL_NOLINK;
1909 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1910 // Emit regular call when code size is the priority
1911 !MF.getFunction()->optForMinSize())
1912 // "mov lr, pc; b _foo" to avoid confusing the RSP
1913 CallOpc = ARMISD::CALL_NOLINK;
1915 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1918 std::vector<SDValue> Ops;
1919 Ops.push_back(Chain);
1920 Ops.push_back(Callee);
1922 // Add argument registers to the end of the list so that they are known live
1924 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1925 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1926 RegsToPass[i].second.getValueType()));
1928 // Add a register mask operand representing the call-preserved registers.
1930 const uint32_t *Mask;
1931 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1933 // For 'this' returns, use the R0-preserving mask if applicable
1934 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1936 // Set isThisReturn to false if the calling convention is not one that
1937 // allows 'returned' to be modeled in this way, so LowerCallResult does
1938 // not try to pass 'this' straight through
1939 isThisReturn = false;
1940 Mask = ARI->getCallPreservedMask(MF, CallConv);
1943 Mask = ARI->getCallPreservedMask(MF, CallConv);
1945 assert(Mask && "Missing call preserved mask for calling convention");
1946 Ops.push_back(DAG.getRegisterMask(Mask));
1949 if (InFlag.getNode())
1950 Ops.push_back(InFlag);
1952 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1954 MF.getFrameInfo()->setHasTailCall();
1955 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1958 // Returns a chain and a flag for retval copy to use.
1959 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1960 InFlag = Chain.getValue(1);
1962 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1963 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1965 InFlag = Chain.getValue(1);
1967 // Handle result values, copying them out of physregs into vregs that we
1969 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1970 InVals, isThisReturn,
1971 isThisReturn ? OutVals[0] : SDValue());
1974 /// HandleByVal - Every parameter *after* a byval parameter is passed
1975 /// on the stack. Remember the next parameter register to allocate,
1976 /// and then confiscate the rest of the parameter registers to insure
1978 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1979 unsigned Align) const {
1980 assert((State->getCallOrPrologue() == Prologue ||
1981 State->getCallOrPrologue() == Call) &&
1982 "unhandled ParmContext");
1984 // Byval (as with any stack) slots are always at least 4 byte aligned.
1985 Align = std::max(Align, 4U);
1987 unsigned Reg = State->AllocateReg(GPRArgRegs);
1991 unsigned AlignInRegs = Align / 4;
1992 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1993 for (unsigned i = 0; i < Waste; ++i)
1994 Reg = State->AllocateReg(GPRArgRegs);
1999 unsigned Excess = 4 * (ARM::R4 - Reg);
2001 // Special case when NSAA != SP and parameter size greater than size of
2002 // all remained GPR regs. In that case we can't split parameter, we must
2003 // send it to stack. We also must set NCRN to R4, so waste all
2004 // remained registers.
2005 const unsigned NSAAOffset = State->getNextStackOffset();
2006 if (NSAAOffset != 0 && Size > Excess) {
2007 while (State->AllocateReg(GPRArgRegs))
2012 // First register for byval parameter is the first register that wasn't
2013 // allocated before this method call, so it would be "reg".
2014 // If parameter is small enough to be saved in range [reg, r4), then
2015 // the end (first after last) register would be reg + param-size-in-regs,
2016 // else parameter would be splitted between registers and stack,
2017 // end register would be r4 in this case.
2018 unsigned ByValRegBegin = Reg;
2019 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2020 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2021 // Note, first register is allocated in the beginning of function already,
2022 // allocate remained amount of registers we need.
2023 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2024 State->AllocateReg(GPRArgRegs);
2025 // A byval parameter that is split between registers and memory needs its
2026 // size truncated here.
2027 // In the case where the entire structure fits in registers, we set the
2028 // size in memory to zero.
2029 Size = std::max<int>(Size - Excess, 0);
2032 /// MatchingStackOffset - Return true if the given stack call argument is
2033 /// already available in the same position (relatively) of the caller's
2034 /// incoming argument stack.
2036 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2037 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2038 const TargetInstrInfo *TII) {
2039 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2041 if (Arg.getOpcode() == ISD::CopyFromReg) {
2042 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2043 if (!TargetRegisterInfo::isVirtualRegister(VR))
2045 MachineInstr *Def = MRI->getVRegDef(VR);
2048 if (!Flags.isByVal()) {
2049 if (!TII->isLoadFromStackSlot(Def, FI))
2054 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2055 if (Flags.isByVal())
2056 // ByVal argument is passed in as a pointer but it's now being
2057 // dereferenced. e.g.
2058 // define @foo(%struct.X* %A) {
2059 // tail call @bar(%struct.X* byval %A)
2062 SDValue Ptr = Ld->getBasePtr();
2063 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2066 FI = FINode->getIndex();
2070 assert(FI != INT_MAX);
2071 if (!MFI->isFixedObjectIndex(FI))
2073 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2076 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2077 /// for tail call optimization. Targets which want to do tail call
2078 /// optimization should implement this function.
2080 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2081 CallingConv::ID CalleeCC,
2083 bool isCalleeStructRet,
2084 bool isCallerStructRet,
2085 const SmallVectorImpl<ISD::OutputArg> &Outs,
2086 const SmallVectorImpl<SDValue> &OutVals,
2087 const SmallVectorImpl<ISD::InputArg> &Ins,
2088 SelectionDAG& DAG) const {
2089 const Function *CallerF = DAG.getMachineFunction().getFunction();
2090 CallingConv::ID CallerCC = CallerF->getCallingConv();
2091 bool CCMatch = CallerCC == CalleeCC;
2093 assert(Subtarget->supportsTailCall());
2095 // Look for obvious safe cases to perform tail call optimization that do not
2096 // require ABI changes. This is what gcc calls sibcall.
2098 // Do not sibcall optimize vararg calls unless the call site is not passing
2100 if (isVarArg && !Outs.empty())
2103 // Exception-handling functions need a special set of instructions to indicate
2104 // a return to the hardware. Tail-calling another function would probably
2106 if (CallerF->hasFnAttribute("interrupt"))
2109 // Also avoid sibcall optimization if either caller or callee uses struct
2110 // return semantics.
2111 if (isCalleeStructRet || isCallerStructRet)
2114 // Externally-defined functions with weak linkage should not be
2115 // tail-called on ARM when the OS does not support dynamic
2116 // pre-emption of symbols, as the AAELF spec requires normal calls
2117 // to undefined weak functions to be replaced with a NOP or jump to the
2118 // next instruction. The behaviour of branch instructions in this
2119 // situation (as used for tail calls) is implementation-defined, so we
2120 // cannot rely on the linker replacing the tail call with a return.
2121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2122 const GlobalValue *GV = G->getGlobal();
2123 const Triple &TT = getTargetMachine().getTargetTriple();
2124 if (GV->hasExternalWeakLinkage() &&
2125 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2129 // If the calling conventions do not match, then we'd better make sure the
2130 // results are returned in the same way as what the caller expects.
2132 SmallVector<CCValAssign, 16> RVLocs1;
2133 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2134 *DAG.getContext(), Call);
2135 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2137 SmallVector<CCValAssign, 16> RVLocs2;
2138 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2139 *DAG.getContext(), Call);
2140 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2142 if (RVLocs1.size() != RVLocs2.size())
2144 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2145 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2147 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2149 if (RVLocs1[i].isRegLoc()) {
2150 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2153 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2159 // If Caller's vararg or byval argument has been split between registers and
2160 // stack, do not perform tail call, since part of the argument is in caller's
2162 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2163 getInfo<ARMFunctionInfo>();
2164 if (AFI_Caller->getArgRegsSaveSize())
2167 // If the callee takes no arguments then go on to check the results of the
2169 if (!Outs.empty()) {
2170 // Check if stack adjustment is needed. For now, do not do this if any
2171 // argument is passed on the stack.
2172 SmallVector<CCValAssign, 16> ArgLocs;
2173 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2174 *DAG.getContext(), Call);
2175 CCInfo.AnalyzeCallOperands(Outs,
2176 CCAssignFnForNode(CalleeCC, false, isVarArg));
2177 if (CCInfo.getNextStackOffset()) {
2178 MachineFunction &MF = DAG.getMachineFunction();
2180 // Check if the arguments are already laid out in the right way as
2181 // the caller's fixed stack objects.
2182 MachineFrameInfo *MFI = MF.getFrameInfo();
2183 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2184 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2185 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2187 ++i, ++realArgIdx) {
2188 CCValAssign &VA = ArgLocs[i];
2189 EVT RegVT = VA.getLocVT();
2190 SDValue Arg = OutVals[realArgIdx];
2191 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2192 if (VA.getLocInfo() == CCValAssign::Indirect)
2194 if (VA.needsCustom()) {
2195 // f64 and vector types are split into multiple registers or
2196 // register/stack-slot combinations. The types will not match
2197 // the registers; give up on memory f64 refs until we figure
2198 // out what to do about this.
2201 if (!ArgLocs[++i].isRegLoc())
2203 if (RegVT == MVT::v2f64) {
2204 if (!ArgLocs[++i].isRegLoc())
2206 if (!ArgLocs[++i].isRegLoc())
2209 } else if (!VA.isRegLoc()) {
2210 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2222 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2223 MachineFunction &MF, bool isVarArg,
2224 const SmallVectorImpl<ISD::OutputArg> &Outs,
2225 LLVMContext &Context) const {
2226 SmallVector<CCValAssign, 16> RVLocs;
2227 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2228 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2232 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2233 SDLoc DL, SelectionDAG &DAG) {
2234 const MachineFunction &MF = DAG.getMachineFunction();
2235 const Function *F = MF.getFunction();
2237 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2239 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2240 // version of the "preferred return address". These offsets affect the return
2241 // instruction if this is a return from PL1 without hypervisor extensions.
2242 // IRQ/FIQ: +4 "subs pc, lr, #4"
2243 // SWI: 0 "subs pc, lr, #0"
2244 // ABORT: +4 "subs pc, lr, #4"
2245 // UNDEF: +4/+2 "subs pc, lr, #0"
2246 // UNDEF varies depending on where the exception came from ARM or Thumb
2247 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2250 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2253 else if (IntKind == "SWI" || IntKind == "UNDEF")
2256 report_fatal_error("Unsupported interrupt attribute. If present, value "
2257 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2259 RetOps.insert(RetOps.begin() + 1,
2260 DAG.getConstant(LROffset, DL, MVT::i32, false));
2262 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2266 ARMTargetLowering::LowerReturn(SDValue Chain,
2267 CallingConv::ID CallConv, bool isVarArg,
2268 const SmallVectorImpl<ISD::OutputArg> &Outs,
2269 const SmallVectorImpl<SDValue> &OutVals,
2270 SDLoc dl, SelectionDAG &DAG) const {
2272 // CCValAssign - represent the assignment of the return value to a location.
2273 SmallVector<CCValAssign, 16> RVLocs;
2275 // CCState - Info about the registers and stack slots.
2276 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2277 *DAG.getContext(), Call);
2279 // Analyze outgoing return values.
2280 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2284 SmallVector<SDValue, 4> RetOps;
2285 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2286 bool isLittleEndian = Subtarget->isLittle();
2288 MachineFunction &MF = DAG.getMachineFunction();
2289 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2290 AFI->setReturnRegsCount(RVLocs.size());
2292 // Copy the result values into the output registers.
2293 for (unsigned i = 0, realRVLocIdx = 0;
2295 ++i, ++realRVLocIdx) {
2296 CCValAssign &VA = RVLocs[i];
2297 assert(VA.isRegLoc() && "Can only return in registers!");
2299 SDValue Arg = OutVals[realRVLocIdx];
2301 switch (VA.getLocInfo()) {
2302 default: llvm_unreachable("Unknown loc info!");
2303 case CCValAssign::Full: break;
2304 case CCValAssign::BCvt:
2305 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2309 if (VA.needsCustom()) {
2310 if (VA.getLocVT() == MVT::v2f64) {
2311 // Extract the first half and return it in two registers.
2312 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2313 DAG.getConstant(0, dl, MVT::i32));
2314 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2315 DAG.getVTList(MVT::i32, MVT::i32), Half);
2317 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2318 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2320 Flag = Chain.getValue(1);
2321 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2322 VA = RVLocs[++i]; // skip ahead to next loc
2323 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2324 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2326 Flag = Chain.getValue(1);
2327 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2328 VA = RVLocs[++i]; // skip ahead to next loc
2330 // Extract the 2nd half and fall through to handle it as an f64 value.
2331 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2332 DAG.getConstant(1, dl, MVT::i32));
2334 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2336 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2337 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2338 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2339 fmrrd.getValue(isLittleEndian ? 0 : 1),
2341 Flag = Chain.getValue(1);
2342 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2343 VA = RVLocs[++i]; // skip ahead to next loc
2344 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2345 fmrrd.getValue(isLittleEndian ? 1 : 0),
2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2350 // Guarantee that all emitted copies are
2351 // stuck together, avoiding something bad.
2352 Flag = Chain.getValue(1);
2353 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2356 // Update chain and glue.
2359 RetOps.push_back(Flag);
2361 // CPUs which aren't M-class use a special sequence to return from
2362 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2363 // though we use "subs pc, lr, #N").
2365 // M-class CPUs actually use a normal return sequence with a special
2366 // (hardware-provided) value in LR, so the normal code path works.
2367 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2368 !Subtarget->isMClass()) {
2369 if (Subtarget->isThumb1Only())
2370 report_fatal_error("interrupt attribute is not supported in Thumb1");
2371 return LowerInterruptReturn(RetOps, dl, DAG);
2374 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2377 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2378 if (N->getNumValues() != 1)
2380 if (!N->hasNUsesOfValue(1, 0))
2383 SDValue TCChain = Chain;
2384 SDNode *Copy = *N->use_begin();
2385 if (Copy->getOpcode() == ISD::CopyToReg) {
2386 // If the copy has a glue operand, we conservatively assume it isn't safe to
2387 // perform a tail call.
2388 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2390 TCChain = Copy->getOperand(0);
2391 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2392 SDNode *VMov = Copy;
2393 // f64 returned in a pair of GPRs.
2394 SmallPtrSet<SDNode*, 2> Copies;
2395 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2397 if (UI->getOpcode() != ISD::CopyToReg)
2401 if (Copies.size() > 2)
2404 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2406 SDValue UseChain = UI->getOperand(0);
2407 if (Copies.count(UseChain.getNode()))
2411 // We are at the top of this chain.
2412 // If the copy has a glue operand, we conservatively assume it
2413 // isn't safe to perform a tail call.
2414 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2420 } else if (Copy->getOpcode() == ISD::BITCAST) {
2421 // f32 returned in a single GPR.
2422 if (!Copy->hasOneUse())
2424 Copy = *Copy->use_begin();
2425 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2427 // If the copy has a glue operand, we conservatively assume it isn't safe to
2428 // perform a tail call.
2429 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2431 TCChain = Copy->getOperand(0);
2436 bool HasRet = false;
2437 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2439 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2440 UI->getOpcode() != ARMISD::INTRET_FLAG)
2452 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2453 if (!Subtarget->supportsTailCall())
2457 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2458 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2464 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2465 // and pass the lower and high parts through.
2466 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2468 SDValue WriteValue = Op->getOperand(2);
2470 // This function is only supposed to be called for i64 type argument.
2471 assert(WriteValue.getValueType() == MVT::i64
2472 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2474 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2475 DAG.getConstant(0, DL, MVT::i32));
2476 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2477 DAG.getConstant(1, DL, MVT::i32));
2478 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2479 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2482 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2483 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2484 // one of the above mentioned nodes. It has to be wrapped because otherwise
2485 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2486 // be used to form addressing mode. These wrapped nodes will be selected
2488 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2489 EVT PtrVT = Op.getValueType();
2490 // FIXME there is no actual debug info here
2492 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2494 if (CP->isMachineConstantPoolEntry())
2495 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2496 CP->getAlignment());
2498 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2499 CP->getAlignment());
2500 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2503 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2504 return MachineJumpTableInfo::EK_Inline;
2507 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2508 SelectionDAG &DAG) const {
2509 MachineFunction &MF = DAG.getMachineFunction();
2510 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2511 unsigned ARMPCLabelIndex = 0;
2513 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2514 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2515 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2517 if (RelocM == Reloc::Static) {
2518 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2520 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2521 ARMPCLabelIndex = AFI->createPICLabelUId();
2522 ARMConstantPoolValue *CPV =
2523 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2524 ARMCP::CPBlockAddress, PCAdj);
2525 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2527 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2529 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2530 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2531 false, false, false, 0);
2532 if (RelocM == Reloc::Static)
2534 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2535 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2538 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2540 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2541 SelectionDAG &DAG) const {
2543 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2544 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2545 MachineFunction &MF = DAG.getMachineFunction();
2546 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2547 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2548 ARMConstantPoolValue *CPV =
2549 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2550 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2551 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2552 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2554 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2555 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2556 false, false, false, 0);
2557 SDValue Chain = Argument.getValue(1);
2559 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2560 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2562 // call __tls_get_addr.
2565 Entry.Node = Argument;
2566 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2567 Args.push_back(Entry);
2569 // FIXME: is there useful debug info available here?
2570 TargetLowering::CallLoweringInfo CLI(DAG);
2571 CLI.setDebugLoc(dl).setChain(Chain)
2572 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2573 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2576 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2577 return CallResult.first;
2580 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2581 // "local exec" model.
2583 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2585 TLSModel::Model model) const {
2586 const GlobalValue *GV = GA->getGlobal();
2589 SDValue Chain = DAG.getEntryNode();
2590 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2591 // Get the Thread Pointer
2592 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2594 if (model == TLSModel::InitialExec) {
2595 MachineFunction &MF = DAG.getMachineFunction();
2596 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2597 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2598 // Initial exec model.
2599 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2600 ARMConstantPoolValue *CPV =
2601 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2602 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2604 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2605 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2606 Offset = DAG.getLoad(
2607 PtrVT, dl, Chain, Offset,
2608 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2610 Chain = Offset.getValue(1);
2612 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2613 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2615 Offset = DAG.getLoad(
2616 PtrVT, dl, Chain, Offset,
2617 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2621 assert(model == TLSModel::LocalExec);
2622 ARMConstantPoolValue *CPV =
2623 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2624 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2625 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2626 Offset = DAG.getLoad(
2627 PtrVT, dl, Chain, Offset,
2628 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2632 // The address of the thread local variable is the add of the thread
2633 // pointer with the offset of the variable.
2634 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2638 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2639 // TODO: implement the "local dynamic" model
2640 assert(Subtarget->isTargetELF() &&
2641 "TLS not implemented for non-ELF targets");
2642 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2643 if (DAG.getTarget().Options.EmulatedTLS)
2644 return LowerToTLSEmulatedModel(GA, DAG);
2646 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2649 case TLSModel::GeneralDynamic:
2650 case TLSModel::LocalDynamic:
2651 return LowerToTLSGeneralDynamicModel(GA, DAG);
2652 case TLSModel::InitialExec:
2653 case TLSModel::LocalExec:
2654 return LowerToTLSExecModels(GA, DAG, model);
2656 llvm_unreachable("bogus TLS model");
2659 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2660 SelectionDAG &DAG) const {
2661 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2663 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2664 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2666 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2668 MachineFunction &MF = DAG.getMachineFunction();
2669 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2670 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2671 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2673 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2674 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2675 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2676 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2677 /*AddCurrentAddress=*/UseGOT_PREL);
2678 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2679 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2680 SDValue Result = DAG.getLoad(
2681 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2684 SDValue Chain = Result.getValue(1);
2685 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2686 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2688 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2689 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2690 false, false, false, 0);
2694 // If we have T2 ops, we can materialize the address directly via movt/movw
2695 // pair. This is always cheaper.
2696 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2698 // FIXME: Once remat is capable of dealing with instructions with register
2699 // operands, expand this into two nodes.
2700 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2701 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2703 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2704 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2706 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2707 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2712 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2713 SelectionDAG &DAG) const {
2714 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2716 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2717 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2719 if (Subtarget->useMovt(DAG.getMachineFunction()))
2722 // FIXME: Once remat is capable of dealing with instructions with register
2723 // operands, expand this into multiple nodes
2725 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2727 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2728 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2730 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2731 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2732 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2733 false, false, false, 0);
2737 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2738 SelectionDAG &DAG) const {
2739 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2740 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2741 "Windows on ARM expects to use movw/movt");
2743 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2744 const ARMII::TOF TargetFlags =
2745 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2746 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2752 // FIXME: Once remat is capable of dealing with instructions with register
2753 // operands, expand this into two nodes.
2754 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2755 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2757 if (GV->hasDLLImportStorageClass())
2758 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2759 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2760 false, false, false, 0);
2765 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2767 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2768 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2769 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2770 Op.getOperand(1), Val);
2774 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2776 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2777 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2780 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2781 SelectionDAG &DAG) const {
2783 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2788 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2789 const ARMSubtarget *Subtarget) const {
2790 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2793 default: return SDValue(); // Don't custom lower most intrinsics.
2794 case Intrinsic::arm_rbit: {
2795 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2796 "RBIT intrinsic must have i32 type!");
2797 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2799 case Intrinsic::arm_thread_pointer: {
2800 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2801 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2803 case Intrinsic::eh_sjlj_lsda: {
2804 MachineFunction &MF = DAG.getMachineFunction();
2805 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2806 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2807 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2808 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2810 unsigned PCAdj = (RelocM != Reloc::PIC_)
2811 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2812 ARMConstantPoolValue *CPV =
2813 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2814 ARMCP::CPLSDA, PCAdj);
2815 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2816 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2817 SDValue Result = DAG.getLoad(
2818 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2819 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2822 if (RelocM == Reloc::PIC_) {
2823 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2824 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2828 case Intrinsic::arm_neon_vmulls:
2829 case Intrinsic::arm_neon_vmullu: {
2830 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2831 ? ARMISD::VMULLs : ARMISD::VMULLu;
2832 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2833 Op.getOperand(1), Op.getOperand(2));
2835 case Intrinsic::arm_neon_vminnm:
2836 case Intrinsic::arm_neon_vmaxnm: {
2837 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2838 ? ISD::FMINNUM : ISD::FMAXNUM;
2839 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2840 Op.getOperand(1), Op.getOperand(2));
2842 case Intrinsic::arm_neon_vminu:
2843 case Intrinsic::arm_neon_vmaxu: {
2844 if (Op.getValueType().isFloatingPoint())
2846 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2847 ? ISD::UMIN : ISD::UMAX;
2848 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2849 Op.getOperand(1), Op.getOperand(2));
2851 case Intrinsic::arm_neon_vmins:
2852 case Intrinsic::arm_neon_vmaxs: {
2853 // v{min,max}s is overloaded between signed integers and floats.
2854 if (!Op.getValueType().isFloatingPoint()) {
2855 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2856 ? ISD::SMIN : ISD::SMAX;
2857 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2858 Op.getOperand(1), Op.getOperand(2));
2860 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2861 ? ISD::FMINNAN : ISD::FMAXNAN;
2862 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2863 Op.getOperand(1), Op.getOperand(2));
2868 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2869 const ARMSubtarget *Subtarget) {
2870 // FIXME: handle "fence singlethread" more efficiently.
2872 if (!Subtarget->hasDataBarrier()) {
2873 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2874 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2876 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2877 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2878 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2879 DAG.getConstant(0, dl, MVT::i32));
2882 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2883 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2884 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2885 if (Subtarget->isMClass()) {
2886 // Only a full system barrier exists in the M-class architectures.
2887 Domain = ARM_MB::SY;
2888 } else if (Subtarget->isSwift() && Ord == Release) {
2889 // Swift happens to implement ISHST barriers in a way that's compatible with
2890 // Release semantics but weaker than ISH so we'd be fools not to use
2891 // it. Beware: other processors probably don't!
2892 Domain = ARM_MB::ISHST;
2895 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2896 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2897 DAG.getConstant(Domain, dl, MVT::i32));
2900 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2901 const ARMSubtarget *Subtarget) {
2902 // ARM pre v5TE and Thumb1 does not have preload instructions.
2903 if (!(Subtarget->isThumb2() ||
2904 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2905 // Just preserve the chain.
2906 return Op.getOperand(0);
2909 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2911 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2912 // ARMv7 with MP extension has PLDW.
2913 return Op.getOperand(0);
2915 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2916 if (Subtarget->isThumb()) {
2918 isRead = ~isRead & 1;
2919 isData = ~isData & 1;
2922 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2923 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2924 DAG.getConstant(isData, dl, MVT::i32));
2927 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2928 MachineFunction &MF = DAG.getMachineFunction();
2929 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2931 // vastart just stores the address of the VarArgsFrameIndex slot into the
2932 // memory location argument.
2934 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2935 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2936 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2937 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2938 MachinePointerInfo(SV), false, false, 0);
2942 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2943 SDValue &Root, SelectionDAG &DAG,
2945 MachineFunction &MF = DAG.getMachineFunction();
2946 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2948 const TargetRegisterClass *RC;
2949 if (AFI->isThumb1OnlyFunction())
2950 RC = &ARM::tGPRRegClass;
2952 RC = &ARM::GPRRegClass;
2954 // Transform the arguments stored in physical registers into virtual ones.
2955 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2956 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2959 if (NextVA.isMemLoc()) {
2960 MachineFrameInfo *MFI = MF.getFrameInfo();
2961 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2963 // Create load node to retrieve arguments from the stack.
2964 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2965 ArgValue2 = DAG.getLoad(
2966 MVT::i32, dl, Root, FIN,
2967 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2970 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2971 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2973 if (!Subtarget->isLittle())
2974 std::swap (ArgValue, ArgValue2);
2975 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2978 // The remaining GPRs hold either the beginning of variable-argument
2979 // data, or the beginning of an aggregate passed by value (usually
2980 // byval). Either way, we allocate stack slots adjacent to the data
2981 // provided by our caller, and store the unallocated registers there.
2982 // If this is a variadic function, the va_list pointer will begin with
2983 // these values; otherwise, this reassembles a (byval) structure that
2984 // was split between registers and memory.
2985 // Return: The frame index registers were stored into.
2987 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2988 SDLoc dl, SDValue &Chain,
2989 const Value *OrigArg,
2990 unsigned InRegsParamRecordIdx,
2992 unsigned ArgSize) const {
2993 // Currently, two use-cases possible:
2994 // Case #1. Non-var-args function, and we meet first byval parameter.
2995 // Setup first unallocated register as first byval register;
2996 // eat all remained registers
2997 // (these two actions are performed by HandleByVal method).
2998 // Then, here, we initialize stack frame with
2999 // "store-reg" instructions.
3000 // Case #2. Var-args function, that doesn't contain byval parameters.
3001 // The same: eat all remained unallocated registers,
3002 // initialize stack frame.
3004 MachineFunction &MF = DAG.getMachineFunction();
3005 MachineFrameInfo *MFI = MF.getFrameInfo();
3006 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3007 unsigned RBegin, REnd;
3008 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3009 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3011 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3012 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3017 ArgOffset = -4 * (ARM::R4 - RBegin);
3019 auto PtrVT = getPointerTy(DAG.getDataLayout());
3020 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3021 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3023 SmallVector<SDValue, 4> MemOps;
3024 const TargetRegisterClass *RC =
3025 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3027 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3028 unsigned VReg = MF.addLiveIn(Reg, RC);
3029 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3031 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3032 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3033 MemOps.push_back(Store);
3034 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3037 if (!MemOps.empty())
3038 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3042 // Setup stack frame, the va_list pointer will start from.
3044 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3045 SDLoc dl, SDValue &Chain,
3047 unsigned TotalArgRegsSaveSize,
3048 bool ForceMutable) const {
3049 MachineFunction &MF = DAG.getMachineFunction();
3050 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3052 // Try to store any remaining integer argument regs
3053 // to their spots on the stack so that they may be loaded by deferencing
3054 // the result of va_next.
3055 // If there is no regs to be stored, just point address after last
3056 // argument passed via stack.
3057 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3058 CCInfo.getInRegsParamsCount(),
3059 CCInfo.getNextStackOffset(), 4);
3060 AFI->setVarArgsFrameIndex(FrameIndex);
3064 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3065 CallingConv::ID CallConv, bool isVarArg,
3066 const SmallVectorImpl<ISD::InputArg>
3068 SDLoc dl, SelectionDAG &DAG,
3069 SmallVectorImpl<SDValue> &InVals)
3071 MachineFunction &MF = DAG.getMachineFunction();
3072 MachineFrameInfo *MFI = MF.getFrameInfo();
3074 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3076 // Assign locations to all of the incoming arguments.
3077 SmallVector<CCValAssign, 16> ArgLocs;
3078 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3079 *DAG.getContext(), Prologue);
3080 CCInfo.AnalyzeFormalArguments(Ins,
3081 CCAssignFnForNode(CallConv, /* Return*/ false,
3084 SmallVector<SDValue, 16> ArgValues;
3086 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3087 unsigned CurArgIdx = 0;
3089 // Initially ArgRegsSaveSize is zero.
3090 // Then we increase this value each time we meet byval parameter.
3091 // We also increase this value in case of varargs function.
3092 AFI->setArgRegsSaveSize(0);
3094 // Calculate the amount of stack space that we need to allocate to store
3095 // byval and variadic arguments that are passed in registers.
3096 // We need to know this before we allocate the first byval or variadic
3097 // argument, as they will be allocated a stack slot below the CFA (Canonical
3098 // Frame Address, the stack pointer at entry to the function).
3099 unsigned ArgRegBegin = ARM::R4;
3100 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3101 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3104 CCValAssign &VA = ArgLocs[i];
3105 unsigned Index = VA.getValNo();
3106 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3107 if (!Flags.isByVal())
3110 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3111 unsigned RBegin, REnd;
3112 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3113 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3115 CCInfo.nextInRegsParam();
3117 CCInfo.rewindByValRegsInfo();
3119 int lastInsIndex = -1;
3120 if (isVarArg && MFI->hasVAStart()) {
3121 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3122 if (RegIdx != array_lengthof(GPRArgRegs))
3123 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3126 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3127 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3128 auto PtrVT = getPointerTy(DAG.getDataLayout());
3130 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3131 CCValAssign &VA = ArgLocs[i];
3132 if (Ins[VA.getValNo()].isOrigArg()) {
3133 std::advance(CurOrigArg,
3134 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3135 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3137 // Arguments stored in registers.
3138 if (VA.isRegLoc()) {
3139 EVT RegVT = VA.getLocVT();
3141 if (VA.needsCustom()) {
3142 // f64 and vector types are split up into multiple registers or
3143 // combinations of registers and stack slots.
3144 if (VA.getLocVT() == MVT::v2f64) {
3145 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3147 VA = ArgLocs[++i]; // skip ahead to next loc
3149 if (VA.isMemLoc()) {
3150 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3151 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3152 ArgValue2 = DAG.getLoad(
3153 MVT::f64, dl, Chain, FIN,
3154 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3155 false, false, false, 0);
3157 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3160 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3161 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3162 ArgValue, ArgValue1,
3163 DAG.getIntPtrConstant(0, dl));
3164 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3165 ArgValue, ArgValue2,
3166 DAG.getIntPtrConstant(1, dl));
3168 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3171 const TargetRegisterClass *RC;
3173 if (RegVT == MVT::f32)
3174 RC = &ARM::SPRRegClass;
3175 else if (RegVT == MVT::f64)
3176 RC = &ARM::DPRRegClass;
3177 else if (RegVT == MVT::v2f64)
3178 RC = &ARM::QPRRegClass;
3179 else if (RegVT == MVT::i32)
3180 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3181 : &ARM::GPRRegClass;
3183 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3185 // Transform the arguments in physical registers into virtual ones.
3186 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3187 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3190 // If this is an 8 or 16-bit value, it is really passed promoted
3191 // to 32 bits. Insert an assert[sz]ext to capture this, then
3192 // truncate to the right size.
3193 switch (VA.getLocInfo()) {
3194 default: llvm_unreachable("Unknown loc info!");
3195 case CCValAssign::Full: break;
3196 case CCValAssign::BCvt:
3197 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3199 case CCValAssign::SExt:
3200 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3201 DAG.getValueType(VA.getValVT()));
3202 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3204 case CCValAssign::ZExt:
3205 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3206 DAG.getValueType(VA.getValVT()));
3207 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3211 InVals.push_back(ArgValue);
3213 } else { // VA.isRegLoc()
3216 assert(VA.isMemLoc());
3217 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3219 int index = VA.getValNo();
3221 // Some Ins[] entries become multiple ArgLoc[] entries.
3222 // Process them only once.
3223 if (index != lastInsIndex)
3225 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3226 // FIXME: For now, all byval parameter objects are marked mutable.
3227 // This can be changed with more analysis.
3228 // In case of tail call optimization mark all arguments mutable.
3229 // Since they could be overwritten by lowering of arguments in case of
3231 if (Flags.isByVal()) {
3232 assert(Ins[index].isOrigArg() &&
3233 "Byval arguments cannot be implicit");
3234 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3236 int FrameIndex = StoreByValRegs(
3237 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3238 VA.getLocMemOffset(), Flags.getByValSize());
3239 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3240 CCInfo.nextInRegsParam();
3242 unsigned FIOffset = VA.getLocMemOffset();
3243 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3246 // Create load nodes to retrieve arguments from the stack.
3247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3248 InVals.push_back(DAG.getLoad(
3249 VA.getValVT(), dl, Chain, FIN,
3250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3251 false, false, false, 0));
3253 lastInsIndex = index;
3259 if (isVarArg && MFI->hasVAStart())
3260 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3261 CCInfo.getNextStackOffset(),
3262 TotalArgRegsSaveSize);
3264 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3269 /// isFloatingPointZero - Return true if this is +0.0.
3270 static bool isFloatingPointZero(SDValue Op) {
3271 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3272 return CFP->getValueAPF().isPosZero();
3273 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3274 // Maybe this has already been legalized into the constant pool?
3275 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3276 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3277 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3278 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3279 return CFP->getValueAPF().isPosZero();
3281 } else if (Op->getOpcode() == ISD::BITCAST &&
3282 Op->getValueType(0) == MVT::f64) {
3283 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3284 // created by LowerConstantFP().
3285 SDValue BitcastOp = Op->getOperand(0);
3286 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3287 isNullConstant(BitcastOp->getOperand(0)))
3293 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3294 /// the given operands.
3296 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3297 SDValue &ARMcc, SelectionDAG &DAG,
3299 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3300 unsigned C = RHSC->getZExtValue();
3301 if (!isLegalICmpImmediate(C)) {
3302 // Constant does not fit, try adjusting it by one?
3307 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3308 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3309 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3314 if (C != 0 && isLegalICmpImmediate(C-1)) {
3315 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3316 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3321 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3322 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3323 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3328 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3329 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3330 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3337 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3338 ARMISD::NodeType CompareType;
3341 CompareType = ARMISD::CMP;
3346 CompareType = ARMISD::CMPZ;
3349 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3350 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3353 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3355 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3357 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3359 if (!isFloatingPointZero(RHS))
3360 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3362 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3363 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3366 /// duplicateCmp - Glue values can have only one use, so this function
3367 /// duplicates a comparison node.
3369 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3370 unsigned Opc = Cmp.getOpcode();
3372 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3373 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3375 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3376 Cmp = Cmp.getOperand(0);
3377 Opc = Cmp.getOpcode();
3378 if (Opc == ARMISD::CMPFP)
3379 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3381 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3382 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3384 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3387 std::pair<SDValue, SDValue>
3388 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3389 SDValue &ARMcc) const {
3390 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3392 SDValue Value, OverflowCmp;
3393 SDValue LHS = Op.getOperand(0);
3394 SDValue RHS = Op.getOperand(1);
3397 // FIXME: We are currently always generating CMPs because we don't support
3398 // generating CMN through the backend. This is not as good as the natural
3399 // CMP case because it causes a register dependency and cannot be folded
3402 switch (Op.getOpcode()) {
3404 llvm_unreachable("Unknown overflow instruction!");
3406 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3407 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3408 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3411 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3412 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3413 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3416 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3417 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3418 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3421 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3422 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3423 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3427 return std::make_pair(Value, OverflowCmp);
3432 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3433 // Let legalize expand this if it isn't a legal type yet.
3434 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3437 SDValue Value, OverflowCmp;
3439 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3440 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3442 // We use 0 and 1 as false and true values.
3443 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3444 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3445 EVT VT = Op.getValueType();
3447 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3448 ARMcc, CCR, OverflowCmp);
3450 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3451 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3455 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3456 SDValue Cond = Op.getOperand(0);
3457 SDValue SelectTrue = Op.getOperand(1);
3458 SDValue SelectFalse = Op.getOperand(2);
3460 unsigned Opc = Cond.getOpcode();
3462 if (Cond.getResNo() == 1 &&
3463 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3464 Opc == ISD::USUBO)) {
3465 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3468 SDValue Value, OverflowCmp;
3470 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3471 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3472 EVT VT = Op.getValueType();
3474 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3480 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3481 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3483 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3484 const ConstantSDNode *CMOVTrue =
3485 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3486 const ConstantSDNode *CMOVFalse =
3487 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3489 if (CMOVTrue && CMOVFalse) {
3490 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3491 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3495 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3497 False = SelectFalse;
3498 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3503 if (True.getNode() && False.getNode()) {
3504 EVT VT = Op.getValueType();
3505 SDValue ARMcc = Cond.getOperand(2);
3506 SDValue CCR = Cond.getOperand(3);
3507 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3508 assert(True.getValueType() == VT);
3509 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3514 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3515 // undefined bits before doing a full-word comparison with zero.
3516 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3517 DAG.getConstant(1, dl, Cond.getValueType()));
3519 return DAG.getSelectCC(dl, Cond,
3520 DAG.getConstant(0, dl, Cond.getValueType()),
3521 SelectTrue, SelectFalse, ISD::SETNE);
3524 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3525 bool &swpCmpOps, bool &swpVselOps) {
3526 // Start by selecting the GE condition code for opcodes that return true for
3528 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3530 CondCode = ARMCC::GE;
3532 // and GT for opcodes that return false for 'equality'.
3533 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3535 CondCode = ARMCC::GT;
3537 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3538 // to swap the compare operands.
3539 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3543 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3544 // If we have an unordered opcode, we need to swap the operands to the VSEL
3545 // instruction (effectively negating the condition).
3547 // This also has the effect of swapping which one of 'less' or 'greater'
3548 // returns true, so we also swap the compare operands. It also switches
3549 // whether we return true for 'equality', so we compensate by picking the
3550 // opposite condition code to our original choice.
3551 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3552 CC == ISD::SETUGT) {
3553 swpCmpOps = !swpCmpOps;
3554 swpVselOps = !swpVselOps;
3555 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3558 // 'ordered' is 'anything but unordered', so use the VS condition code and
3559 // swap the VSEL operands.
3560 if (CC == ISD::SETO) {
3561 CondCode = ARMCC::VS;
3565 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3566 // code and swap the VSEL operands.
3567 if (CC == ISD::SETUNE) {
3568 CondCode = ARMCC::EQ;
3573 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3574 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3575 SDValue Cmp, SelectionDAG &DAG) const {
3576 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3577 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3578 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3579 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3580 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3582 SDValue TrueLow = TrueVal.getValue(0);
3583 SDValue TrueHigh = TrueVal.getValue(1);
3584 SDValue FalseLow = FalseVal.getValue(0);
3585 SDValue FalseHigh = FalseVal.getValue(1);
3587 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3589 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3590 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3592 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3594 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3599 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3600 EVT VT = Op.getValueType();
3601 SDValue LHS = Op.getOperand(0);
3602 SDValue RHS = Op.getOperand(1);
3603 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3604 SDValue TrueVal = Op.getOperand(2);
3605 SDValue FalseVal = Op.getOperand(3);
3608 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3609 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3612 // If softenSetCCOperands only returned one value, we should compare it to
3614 if (!RHS.getNode()) {
3615 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3620 if (LHS.getValueType() == MVT::i32) {
3621 // Try to generate VSEL on ARMv8.
3622 // The VSEL instruction can't use all the usual ARM condition
3623 // codes: it only has two bits to select the condition code, so it's
3624 // constrained to use only GE, GT, VS and EQ.
3626 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3627 // swap the operands of the previous compare instruction (effectively
3628 // inverting the compare condition, swapping 'less' and 'greater') and
3629 // sometimes need to swap the operands to the VSEL (which inverts the
3630 // condition in the sense of firing whenever the previous condition didn't)
3631 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3632 TrueVal.getValueType() == MVT::f64)) {
3633 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3634 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3635 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3636 CC = ISD::getSetCCInverse(CC, true);
3637 std::swap(TrueVal, FalseVal);
3642 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3643 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3644 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3647 ARMCC::CondCodes CondCode, CondCode2;
3648 FPCCToARMCC(CC, CondCode, CondCode2);
3650 // Try to generate VMAXNM/VMINNM on ARMv8.
3651 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3652 TrueVal.getValueType() == MVT::f64)) {
3653 bool swpCmpOps = false;
3654 bool swpVselOps = false;
3655 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3657 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3658 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3660 std::swap(LHS, RHS);
3662 std::swap(TrueVal, FalseVal);
3666 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3667 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3668 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3669 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3670 if (CondCode2 != ARMCC::AL) {
3671 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3672 // FIXME: Needs another CMP because flag can have but one use.
3673 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3674 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3679 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3680 /// to morph to an integer compare sequence.
3681 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3682 const ARMSubtarget *Subtarget) {
3683 SDNode *N = Op.getNode();
3684 if (!N->hasOneUse())
3685 // Otherwise it requires moving the value from fp to integer registers.
3687 if (!N->getNumValues())
3689 EVT VT = Op.getValueType();
3690 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3691 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3692 // vmrs are very slow, e.g. cortex-a8.
3695 if (isFloatingPointZero(Op)) {
3699 return ISD::isNormalLoad(N);
3702 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3703 if (isFloatingPointZero(Op))
3704 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3706 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3707 return DAG.getLoad(MVT::i32, SDLoc(Op),
3708 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3709 Ld->isVolatile(), Ld->isNonTemporal(),
3710 Ld->isInvariant(), Ld->getAlignment());
3712 llvm_unreachable("Unknown VFP cmp argument!");
3715 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3716 SDValue &RetVal1, SDValue &RetVal2) {
3719 if (isFloatingPointZero(Op)) {
3720 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3721 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3725 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3726 SDValue Ptr = Ld->getBasePtr();
3727 RetVal1 = DAG.getLoad(MVT::i32, dl,
3728 Ld->getChain(), Ptr,
3729 Ld->getPointerInfo(),
3730 Ld->isVolatile(), Ld->isNonTemporal(),
3731 Ld->isInvariant(), Ld->getAlignment());
3733 EVT PtrType = Ptr.getValueType();
3734 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3735 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3736 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3737 RetVal2 = DAG.getLoad(MVT::i32, dl,
3738 Ld->getChain(), NewPtr,
3739 Ld->getPointerInfo().getWithOffset(4),
3740 Ld->isVolatile(), Ld->isNonTemporal(),
3741 Ld->isInvariant(), NewAlign);
3745 llvm_unreachable("Unknown VFP cmp argument!");
3748 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3749 /// f32 and even f64 comparisons to integer ones.
3751 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3752 SDValue Chain = Op.getOperand(0);
3753 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3754 SDValue LHS = Op.getOperand(2);
3755 SDValue RHS = Op.getOperand(3);
3756 SDValue Dest = Op.getOperand(4);
3759 bool LHSSeenZero = false;
3760 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3761 bool RHSSeenZero = false;
3762 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3763 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3764 // If unsafe fp math optimization is enabled and there are no other uses of
3765 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3766 // to an integer comparison.
3767 if (CC == ISD::SETOEQ)
3769 else if (CC == ISD::SETUNE)
3772 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3774 if (LHS.getValueType() == MVT::f32) {
3775 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3776 bitcastf32Toi32(LHS, DAG), Mask);
3777 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3778 bitcastf32Toi32(RHS, DAG), Mask);
3779 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3780 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3781 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3782 Chain, Dest, ARMcc, CCR, Cmp);
3787 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3788 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3789 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3790 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3791 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3792 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3793 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3794 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3795 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3801 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3802 SDValue Chain = Op.getOperand(0);
3803 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3804 SDValue LHS = Op.getOperand(2);
3805 SDValue RHS = Op.getOperand(3);
3806 SDValue Dest = Op.getOperand(4);
3809 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3810 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3813 // If softenSetCCOperands only returned one value, we should compare it to
3815 if (!RHS.getNode()) {
3816 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3821 if (LHS.getValueType() == MVT::i32) {
3823 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3824 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3825 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3826 Chain, Dest, ARMcc, CCR, Cmp);
3829 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3831 if (getTargetMachine().Options.UnsafeFPMath &&
3832 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3833 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3834 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3835 if (Result.getNode())
3839 ARMCC::CondCodes CondCode, CondCode2;
3840 FPCCToARMCC(CC, CondCode, CondCode2);
3842 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3843 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3844 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3845 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3846 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3847 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3848 if (CondCode2 != ARMCC::AL) {
3849 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3850 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3851 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3856 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3857 SDValue Chain = Op.getOperand(0);
3858 SDValue Table = Op.getOperand(1);
3859 SDValue Index = Op.getOperand(2);
3862 EVT PTy = getPointerTy(DAG.getDataLayout());
3863 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3864 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3865 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3866 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3867 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3868 if (Subtarget->isThumb2()) {
3869 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3870 // which does another jump to the destination. This also makes it easier
3871 // to translate it to TBB / TBH later.
3872 // FIXME: This might not work if the function is extremely large.
3873 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3874 Addr, Op.getOperand(2), JTI);
3876 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3878 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3879 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3880 false, false, false, 0);
3881 Chain = Addr.getValue(1);
3882 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3883 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3886 DAG.getLoad(PTy, dl, Chain, Addr,
3887 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3888 false, false, false, 0);
3889 Chain = Addr.getValue(1);
3890 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3894 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3895 EVT VT = Op.getValueType();
3898 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3899 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3901 return DAG.UnrollVectorOp(Op.getNode());
3904 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3905 "Invalid type for custom lowering!");
3906 if (VT != MVT::v4i16)
3907 return DAG.UnrollVectorOp(Op.getNode());
3909 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3910 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3913 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3914 EVT VT = Op.getValueType();
3916 return LowerVectorFP_TO_INT(Op, DAG);
3917 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3919 if (Op.getOpcode() == ISD::FP_TO_SINT)
3920 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3923 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3925 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3926 /*isSigned*/ false, SDLoc(Op)).first;
3932 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3933 EVT VT = Op.getValueType();
3936 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3937 if (VT.getVectorElementType() == MVT::f32)
3939 return DAG.UnrollVectorOp(Op.getNode());
3942 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3943 "Invalid type for custom lowering!");
3944 if (VT != MVT::v4f32)
3945 return DAG.UnrollVectorOp(Op.getNode());
3949 switch (Op.getOpcode()) {
3950 default: llvm_unreachable("Invalid opcode!");
3951 case ISD::SINT_TO_FP:
3952 CastOpc = ISD::SIGN_EXTEND;
3953 Opc = ISD::SINT_TO_FP;
3955 case ISD::UINT_TO_FP:
3956 CastOpc = ISD::ZERO_EXTEND;
3957 Opc = ISD::UINT_TO_FP;
3961 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3962 return DAG.getNode(Opc, dl, VT, Op);
3965 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3966 EVT VT = Op.getValueType();
3968 return LowerVectorINT_TO_FP(Op, DAG);
3969 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3971 if (Op.getOpcode() == ISD::SINT_TO_FP)
3972 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3975 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3977 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3978 /*isSigned*/ false, SDLoc(Op)).first;
3984 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3985 // Implement fcopysign with a fabs and a conditional fneg.
3986 SDValue Tmp0 = Op.getOperand(0);
3987 SDValue Tmp1 = Op.getOperand(1);
3989 EVT VT = Op.getValueType();
3990 EVT SrcVT = Tmp1.getValueType();
3991 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3992 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3993 bool UseNEON = !InGPR && Subtarget->hasNEON();
3996 // Use VBSL to copy the sign bit.
3997 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3998 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3999 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4000 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4002 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4003 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4004 DAG.getConstant(32, dl, MVT::i32));
4005 else /*if (VT == MVT::f32)*/
4006 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4007 if (SrcVT == MVT::f32) {
4008 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4010 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4011 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4012 DAG.getConstant(32, dl, MVT::i32));
4013 } else if (VT == MVT::f32)
4014 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4015 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4016 DAG.getConstant(32, dl, MVT::i32));
4017 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4018 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4020 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4022 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4023 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4024 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4026 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4027 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4028 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4029 if (VT == MVT::f32) {
4030 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4031 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4032 DAG.getConstant(0, dl, MVT::i32));
4034 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4040 // Bitcast operand 1 to i32.
4041 if (SrcVT == MVT::f64)
4042 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4044 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4046 // Or in the signbit with integer operations.
4047 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4048 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4049 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4050 if (VT == MVT::f32) {
4051 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4052 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4053 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4054 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4057 // f64: Or the high part with signbit and then combine two parts.
4058 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4060 SDValue Lo = Tmp0.getValue(0);
4061 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4062 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4063 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4066 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4067 MachineFunction &MF = DAG.getMachineFunction();
4068 MachineFrameInfo *MFI = MF.getFrameInfo();
4069 MFI->setReturnAddressIsTaken(true);
4071 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4074 EVT VT = Op.getValueType();
4076 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4078 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4079 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4080 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4081 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4082 MachinePointerInfo(), false, false, false, 0);
4085 // Return LR, which contains the return address. Mark it an implicit live-in.
4086 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4087 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4090 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4091 const ARMBaseRegisterInfo &ARI =
4092 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4093 MachineFunction &MF = DAG.getMachineFunction();
4094 MachineFrameInfo *MFI = MF.getFrameInfo();
4095 MFI->setFrameAddressIsTaken(true);
4097 EVT VT = Op.getValueType();
4098 SDLoc dl(Op); // FIXME probably not meaningful
4099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4100 unsigned FrameReg = ARI.getFrameRegister(MF);
4101 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4103 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4104 MachinePointerInfo(),
4105 false, false, false, 0);
4109 // FIXME? Maybe this could be a TableGen attribute on some registers and
4110 // this table could be generated automatically from RegInfo.
4111 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4112 SelectionDAG &DAG) const {
4113 unsigned Reg = StringSwitch<unsigned>(RegName)
4114 .Case("sp", ARM::SP)
4118 report_fatal_error(Twine("Invalid register name \""
4119 + StringRef(RegName) + "\"."));
4122 // Result is 64 bit value so split into two 32 bit values and return as a
4124 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4125 SelectionDAG &DAG) {
4128 // This function is only supposed to be called for i64 type destination.
4129 assert(N->getValueType(0) == MVT::i64
4130 && "ExpandREAD_REGISTER called for non-i64 type result.");
4132 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4133 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4137 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4139 Results.push_back(Read.getOperand(0));
4142 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4143 /// When \p DstVT, the destination type of \p BC, is on the vector
4144 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4145 /// it might be possible to combine them, such that everything stays on the
4146 /// vector register bank.
4147 /// \p return The node that would replace \p BT, if the combine
4149 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4150 SelectionDAG &DAG) {
4151 SDValue Op = BC->getOperand(0);
4152 EVT DstVT = BC->getValueType(0);
4154 // The only vector instruction that can produce a scalar (remember,
4155 // since the bitcast was about to be turned into VMOVDRR, the source
4156 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4157 // Moreover, we can do this combine only if there is one use.
4158 // Finally, if the destination type is not a vector, there is not
4159 // much point on forcing everything on the vector bank.
4160 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4164 // If the index is not constant, we will introduce an additional
4165 // multiply that will stick.
4166 // Give up in that case.
4167 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4170 unsigned DstNumElt = DstVT.getVectorNumElements();
4172 // Compute the new index.
4173 const APInt &APIntIndex = Index->getAPIntValue();
4174 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4175 NewIndex *= APIntIndex;
4176 // Check if the new constant index fits into i32.
4177 if (NewIndex.getBitWidth() > 32)
4180 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4181 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4183 SDValue ExtractSrc = Op.getOperand(0);
4184 EVT VecVT = EVT::getVectorVT(
4185 *DAG.getContext(), DstVT.getScalarType(),
4186 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4187 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4188 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4189 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4192 /// ExpandBITCAST - If the target supports VFP, this function is called to
4193 /// expand a bit convert where either the source or destination type is i64 to
4194 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4195 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4196 /// vectors), since the legalizer won't know what to do with that.
4197 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4200 SDValue Op = N->getOperand(0);
4202 // This function is only supposed to be called for i64 types, either as the
4203 // source or destination of the bit convert.
4204 EVT SrcVT = Op.getValueType();
4205 EVT DstVT = N->getValueType(0);
4206 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4207 "ExpandBITCAST called for non-i64 type");
4209 // Turn i64->f64 into VMOVDRR.
4210 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4211 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4212 // if we can combine the bitcast with its source.
4213 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4216 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4217 DAG.getConstant(0, dl, MVT::i32));
4218 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4219 DAG.getConstant(1, dl, MVT::i32));
4220 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4221 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4224 // Turn f64->i64 into VMOVRRD.
4225 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4227 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4228 SrcVT.getVectorNumElements() > 1)
4229 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4230 DAG.getVTList(MVT::i32, MVT::i32),
4231 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4233 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4234 DAG.getVTList(MVT::i32, MVT::i32), Op);
4235 // Merge the pieces into a single i64 value.
4236 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4242 /// getZeroVector - Returns a vector of specified type with all zero elements.
4243 /// Zero vectors are used to represent vector negation and in those cases
4244 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4245 /// not support i64 elements, so sometimes the zero vectors will need to be
4246 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4248 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4249 assert(VT.isVector() && "Expected a vector type");
4250 // The canonical modified immediate encoding of a zero vector is....0!
4251 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4252 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4253 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4254 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4257 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4258 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4259 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4260 SelectionDAG &DAG) const {
4261 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4262 EVT VT = Op.getValueType();
4263 unsigned VTBits = VT.getSizeInBits();
4265 SDValue ShOpLo = Op.getOperand(0);
4266 SDValue ShOpHi = Op.getOperand(1);
4267 SDValue ShAmt = Op.getOperand(2);
4269 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4271 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4273 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4274 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4275 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4276 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4277 DAG.getConstant(VTBits, dl, MVT::i32));
4278 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4279 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4280 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4282 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4283 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4284 ISD::SETGE, ARMcc, DAG, dl);
4285 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4286 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4289 SDValue Ops[2] = { Lo, Hi };
4290 return DAG.getMergeValues(Ops, dl);
4293 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4294 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4295 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4296 SelectionDAG &DAG) const {
4297 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4298 EVT VT = Op.getValueType();
4299 unsigned VTBits = VT.getSizeInBits();
4301 SDValue ShOpLo = Op.getOperand(0);
4302 SDValue ShOpHi = Op.getOperand(1);
4303 SDValue ShAmt = Op.getOperand(2);
4306 assert(Op.getOpcode() == ISD::SHL_PARTS);
4307 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4308 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4309 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4310 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4311 DAG.getConstant(VTBits, dl, MVT::i32));
4312 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4313 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4315 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4316 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4317 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4318 ISD::SETGE, ARMcc, DAG, dl);
4319 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4320 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4323 SDValue Ops[2] = { Lo, Hi };
4324 return DAG.getMergeValues(Ops, dl);
4327 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4328 SelectionDAG &DAG) const {
4329 // The rounding mode is in bits 23:22 of the FPSCR.
4330 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4331 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4332 // so that the shift + and get folded into a bitfield extract.
4334 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4335 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4337 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4338 DAG.getConstant(1U << 22, dl, MVT::i32));
4339 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4340 DAG.getConstant(22, dl, MVT::i32));
4341 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4342 DAG.getConstant(3, dl, MVT::i32));
4345 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4346 const ARMSubtarget *ST) {
4348 EVT VT = N->getValueType(0);
4349 if (VT.isVector()) {
4350 assert(ST->hasNEON());
4352 // Compute the least significant set bit: LSB = X & -X
4353 SDValue X = N->getOperand(0);
4354 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4355 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4357 EVT ElemTy = VT.getVectorElementType();
4359 if (ElemTy == MVT::i8) {
4360 // Compute with: cttz(x) = ctpop(lsb - 1)
4361 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4362 DAG.getTargetConstant(1, dl, ElemTy));
4363 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4364 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4367 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4368 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4369 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4370 unsigned NumBits = ElemTy.getSizeInBits();
4371 SDValue WidthMinus1 =
4372 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4373 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4374 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4375 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4378 // Compute with: cttz(x) = ctpop(lsb - 1)
4380 // Since we can only compute the number of bits in a byte with vcnt.8, we
4381 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4386 if (ElemTy == MVT::i64) {
4387 // Load constant 0xffff'ffff'ffff'ffff to register.
4388 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4389 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4390 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4392 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4393 DAG.getTargetConstant(1, dl, ElemTy));
4394 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4397 // Count #bits with vcnt.8.
4398 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4399 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4400 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4402 // Gather the #bits with vpaddl (pairwise add.)
4403 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4404 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4405 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4407 if (ElemTy == MVT::i16)
4410 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4411 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4412 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4414 if (ElemTy == MVT::i32)
4417 assert(ElemTy == MVT::i64);
4418 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4419 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4424 if (!ST->hasV6T2Ops())
4427 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4428 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4431 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4432 /// for each 16-bit element from operand, repeated. The basic idea is to
4433 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4435 /// Trace for v4i16:
4436 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4437 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4438 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4439 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4440 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4441 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4442 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4443 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4444 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4445 EVT VT = N->getValueType(0);
4448 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4449 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4450 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4451 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4452 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4453 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4456 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4457 /// bit-count for each 16-bit element from the operand. We need slightly
4458 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4459 /// 64/128-bit registers.
4461 /// Trace for v4i16:
4462 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4463 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4464 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4465 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4466 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4467 EVT VT = N->getValueType(0);
4470 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4471 if (VT.is64BitVector()) {
4472 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4473 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4474 DAG.getIntPtrConstant(0, DL));
4476 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4477 BitCounts, DAG.getIntPtrConstant(0, DL));
4478 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4482 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4483 /// bit-count for each 32-bit element from the operand. The idea here is
4484 /// to split the vector into 16-bit elements, leverage the 16-bit count
4485 /// routine, and then combine the results.
4487 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4488 /// input = [v0 v1 ] (vi: 32-bit elements)
4489 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4490 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4491 /// vrev: N0 = [k1 k0 k3 k2 ]
4493 /// N1 =+[k1 k0 k3 k2 ]
4495 /// N2 =+[k1 k3 k0 k2 ]
4497 /// Extended =+[k1 k3 k0 k2 ]
4499 /// Extracted=+[k1 k3 ]
4501 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4502 EVT VT = N->getValueType(0);
4505 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4507 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4508 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4509 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4510 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4511 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4513 if (VT.is64BitVector()) {
4514 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4515 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4516 DAG.getIntPtrConstant(0, DL));
4518 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4519 DAG.getIntPtrConstant(0, DL));
4520 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4524 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4525 const ARMSubtarget *ST) {
4526 EVT VT = N->getValueType(0);
4528 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4529 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4530 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4531 "Unexpected type for custom ctpop lowering");
4533 if (VT.getVectorElementType() == MVT::i32)
4534 return lowerCTPOP32BitElements(N, DAG);
4536 return lowerCTPOP16BitElements(N, DAG);
4539 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4540 const ARMSubtarget *ST) {
4541 EVT VT = N->getValueType(0);
4547 // Lower vector shifts on NEON to use VSHL.
4548 assert(ST->hasNEON() && "unexpected vector shift");
4550 // Left shifts translate directly to the vshiftu intrinsic.
4551 if (N->getOpcode() == ISD::SHL)
4552 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4553 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4555 N->getOperand(0), N->getOperand(1));
4557 assert((N->getOpcode() == ISD::SRA ||
4558 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4560 // NEON uses the same intrinsics for both left and right shifts. For
4561 // right shifts, the shift amounts are negative, so negate the vector of
4563 EVT ShiftVT = N->getOperand(1).getValueType();
4564 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4565 getZeroVector(ShiftVT, DAG, dl),
4567 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4568 Intrinsic::arm_neon_vshifts :
4569 Intrinsic::arm_neon_vshiftu);
4570 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4571 DAG.getConstant(vshiftInt, dl, MVT::i32),
4572 N->getOperand(0), NegatedCount);
4575 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4576 const ARMSubtarget *ST) {
4577 EVT VT = N->getValueType(0);
4580 // We can get here for a node like i32 = ISD::SHL i32, i64
4584 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4585 "Unknown shift to lower!");
4587 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4588 if (!isOneConstant(N->getOperand(1)))
4591 // If we are in thumb mode, we don't have RRX.
4592 if (ST->isThumb1Only()) return SDValue();
4594 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4595 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4596 DAG.getConstant(0, dl, MVT::i32));
4597 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4598 DAG.getConstant(1, dl, MVT::i32));
4600 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4601 // captures the result into a carry flag.
4602 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4603 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4605 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4606 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4608 // Merge the pieces into a single i64 value.
4609 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4612 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4613 SDValue TmpOp0, TmpOp1;
4614 bool Invert = false;
4618 SDValue Op0 = Op.getOperand(0);
4619 SDValue Op1 = Op.getOperand(1);
4620 SDValue CC = Op.getOperand(2);
4621 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4622 EVT VT = Op.getValueType();
4623 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4626 if (CmpVT.getVectorElementType() == MVT::i64)
4627 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4628 // but it's possible that our operands are 64-bit but our result is 32-bit.
4629 // Bail in this case.
4632 if (Op1.getValueType().isFloatingPoint()) {
4633 switch (SetCCOpcode) {
4634 default: llvm_unreachable("Illegal FP comparison");
4636 case ISD::SETNE: Invert = true; // Fallthrough
4638 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4640 case ISD::SETLT: Swap = true; // Fallthrough
4642 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4644 case ISD::SETLE: Swap = true; // Fallthrough
4646 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4647 case ISD::SETUGE: Swap = true; // Fallthrough
4648 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4649 case ISD::SETUGT: Swap = true; // Fallthrough
4650 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4651 case ISD::SETUEQ: Invert = true; // Fallthrough
4653 // Expand this to (OLT | OGT).
4657 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4658 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4660 case ISD::SETUO: Invert = true; // Fallthrough
4662 // Expand this to (OLT | OGE).
4666 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4667 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4671 // Integer comparisons.
4672 switch (SetCCOpcode) {
4673 default: llvm_unreachable("Illegal integer comparison");
4674 case ISD::SETNE: Invert = true;
4675 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4676 case ISD::SETLT: Swap = true;
4677 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4678 case ISD::SETLE: Swap = true;
4679 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4680 case ISD::SETULT: Swap = true;
4681 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4682 case ISD::SETULE: Swap = true;
4683 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4686 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4687 if (Opc == ARMISD::VCEQ) {
4690 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4692 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4695 // Ignore bitconvert.
4696 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4697 AndOp = AndOp.getOperand(0);
4699 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4701 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4702 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4709 std::swap(Op0, Op1);
4711 // If one of the operands is a constant vector zero, attempt to fold the
4712 // comparison to a specialized compare-against-zero form.
4714 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4716 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4717 if (Opc == ARMISD::VCGE)
4718 Opc = ARMISD::VCLEZ;
4719 else if (Opc == ARMISD::VCGT)
4720 Opc = ARMISD::VCLTZ;
4725 if (SingleOp.getNode()) {
4728 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4730 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4732 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4734 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4736 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4738 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4741 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4744 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4747 Result = DAG.getNOT(dl, Result, VT);
4752 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4753 /// valid vector constant for a NEON instruction with a "modified immediate"
4754 /// operand (e.g., VMOV). If so, return the encoded value.
4755 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4756 unsigned SplatBitSize, SelectionDAG &DAG,
4757 SDLoc dl, EVT &VT, bool is128Bits,
4758 NEONModImmType type) {
4759 unsigned OpCmode, Imm;
4761 // SplatBitSize is set to the smallest size that splats the vector, so a
4762 // zero vector will always have SplatBitSize == 8. However, NEON modified
4763 // immediate instructions others than VMOV do not support the 8-bit encoding
4764 // of a zero vector, and the default encoding of zero is supposed to be the
4769 switch (SplatBitSize) {
4771 if (type != VMOVModImm)
4773 // Any 1-byte value is OK. Op=0, Cmode=1110.
4774 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4777 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4781 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4782 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4783 if ((SplatBits & ~0xff) == 0) {
4784 // Value = 0x00nn: Op=x, Cmode=100x.
4789 if ((SplatBits & ~0xff00) == 0) {
4790 // Value = 0xnn00: Op=x, Cmode=101x.
4792 Imm = SplatBits >> 8;
4798 // NEON's 32-bit VMOV supports splat values where:
4799 // * only one byte is nonzero, or
4800 // * the least significant byte is 0xff and the second byte is nonzero, or
4801 // * the least significant 2 bytes are 0xff and the third is nonzero.
4802 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4803 if ((SplatBits & ~0xff) == 0) {
4804 // Value = 0x000000nn: Op=x, Cmode=000x.
4809 if ((SplatBits & ~0xff00) == 0) {
4810 // Value = 0x0000nn00: Op=x, Cmode=001x.
4812 Imm = SplatBits >> 8;
4815 if ((SplatBits & ~0xff0000) == 0) {
4816 // Value = 0x00nn0000: Op=x, Cmode=010x.
4818 Imm = SplatBits >> 16;
4821 if ((SplatBits & ~0xff000000) == 0) {
4822 // Value = 0xnn000000: Op=x, Cmode=011x.
4824 Imm = SplatBits >> 24;
4828 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4829 if (type == OtherModImm) return SDValue();
4831 if ((SplatBits & ~0xffff) == 0 &&
4832 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4833 // Value = 0x0000nnff: Op=x, Cmode=1100.
4835 Imm = SplatBits >> 8;
4839 if ((SplatBits & ~0xffffff) == 0 &&
4840 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4841 // Value = 0x00nnffff: Op=x, Cmode=1101.
4843 Imm = SplatBits >> 16;
4847 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4848 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4849 // VMOV.I32. A (very) minor optimization would be to replicate the value
4850 // and fall through here to test for a valid 64-bit splat. But, then the
4851 // caller would also need to check and handle the change in size.
4855 if (type != VMOVModImm)
4857 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4858 uint64_t BitMask = 0xff;
4860 unsigned ImmMask = 1;
4862 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4863 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4866 } else if ((SplatBits & BitMask) != 0) {
4873 if (DAG.getDataLayout().isBigEndian())
4874 // swap higher and lower 32 bit word
4875 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4877 // Op=1, Cmode=1110.
4879 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4884 llvm_unreachable("unexpected size for isNEONModifiedImm");
4887 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4888 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4891 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4892 const ARMSubtarget *ST) const {
4896 bool IsDouble = Op.getValueType() == MVT::f64;
4897 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4899 // Use the default (constant pool) lowering for double constants when we have
4901 if (IsDouble && Subtarget->isFPOnlySP())
4904 // Try splatting with a VMOV.f32...
4905 APFloat FPVal = CFP->getValueAPF();
4906 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4909 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4910 // We have code in place to select a valid ConstantFP already, no need to
4915 // It's a float and we are trying to use NEON operations where
4916 // possible. Lower it to a splat followed by an extract.
4918 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4919 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4922 DAG.getConstant(0, DL, MVT::i32));
4925 // The rest of our options are NEON only, make sure that's allowed before
4927 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4931 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4933 // It wouldn't really be worth bothering for doubles except for one very
4934 // important value, which does happen to match: 0.0. So make sure we don't do
4936 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4939 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4940 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4941 VMovVT, false, VMOVModImm);
4942 if (NewVal != SDValue()) {
4944 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4947 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4949 // It's a float: cast and extract a vector element.
4950 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4952 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4953 DAG.getConstant(0, DL, MVT::i32));
4956 // Finally, try a VMVN.i32
4957 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4959 if (NewVal != SDValue()) {
4961 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4964 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4966 // It's a float: cast and extract a vector element.
4967 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4969 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4970 DAG.getConstant(0, DL, MVT::i32));
4976 // check if an VEXT instruction can handle the shuffle mask when the
4977 // vector sources of the shuffle are the same.
4978 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4979 unsigned NumElts = VT.getVectorNumElements();
4981 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4987 // If this is a VEXT shuffle, the immediate value is the index of the first
4988 // element. The other shuffle indices must be the successive elements after
4990 unsigned ExpectedElt = Imm;
4991 for (unsigned i = 1; i < NumElts; ++i) {
4992 // Increment the expected index. If it wraps around, just follow it
4993 // back to index zero and keep going.
4995 if (ExpectedElt == NumElts)
4998 if (M[i] < 0) continue; // ignore UNDEF indices
4999 if (ExpectedElt != static_cast<unsigned>(M[i]))
5007 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5008 bool &ReverseVEXT, unsigned &Imm) {
5009 unsigned NumElts = VT.getVectorNumElements();
5010 ReverseVEXT = false;
5012 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5018 // If this is a VEXT shuffle, the immediate value is the index of the first
5019 // element. The other shuffle indices must be the successive elements after
5021 unsigned ExpectedElt = Imm;
5022 for (unsigned i = 1; i < NumElts; ++i) {
5023 // Increment the expected index. If it wraps around, it may still be
5024 // a VEXT but the source vectors must be swapped.
5026 if (ExpectedElt == NumElts * 2) {
5031 if (M[i] < 0) continue; // ignore UNDEF indices
5032 if (ExpectedElt != static_cast<unsigned>(M[i]))
5036 // Adjust the index value if the source operands will be swapped.
5043 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5044 /// instruction with the specified blocksize. (The order of the elements
5045 /// within each block of the vector is reversed.)
5046 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5047 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5048 "Only possible block sizes for VREV are: 16, 32, 64");
5050 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5054 unsigned NumElts = VT.getVectorNumElements();
5055 unsigned BlockElts = M[0] + 1;
5056 // If the first shuffle index is UNDEF, be optimistic.
5058 BlockElts = BlockSize / EltSz;
5060 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5063 for (unsigned i = 0; i < NumElts; ++i) {
5064 if (M[i] < 0) continue; // ignore UNDEF indices
5065 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5072 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5073 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5074 // range, then 0 is placed into the resulting vector. So pretty much any mask
5075 // of 8 elements can work here.
5076 return VT == MVT::v8i8 && M.size() == 8;
5079 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5080 // checking that pairs of elements in the shuffle mask represent the same index
5081 // in each vector, incrementing the expected index by 2 at each step.
5082 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5083 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5085 // WhichResult gives the offset for each element in the mask based on which
5086 // of the two results it belongs to.
5088 // The transpose can be represented either as:
5089 // result1 = shufflevector v1, v2, result1_shuffle_mask
5090 // result2 = shufflevector v1, v2, result2_shuffle_mask
5091 // where v1/v2 and the shuffle masks have the same number of elements
5092 // (here WhichResult (see below) indicates which result is being checked)
5095 // results = shufflevector v1, v2, shuffle_mask
5096 // where both results are returned in one vector and the shuffle mask has twice
5097 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5098 // want to check the low half and high half of the shuffle mask as if it were
5100 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5101 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5105 unsigned NumElts = VT.getVectorNumElements();
5106 if (M.size() != NumElts && M.size() != NumElts*2)
5109 // If the mask is twice as long as the input vector then we need to check the
5110 // upper and lower parts of the mask with a matching value for WhichResult
5111 // FIXME: A mask with only even values will be rejected in case the first
5112 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5113 // M[0] is used to determine WhichResult
5114 for (unsigned i = 0; i < M.size(); i += NumElts) {
5115 if (M.size() == NumElts * 2)
5116 WhichResult = i / NumElts;
5118 WhichResult = M[i] == 0 ? 0 : 1;
5119 for (unsigned j = 0; j < NumElts; j += 2) {
5120 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5121 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5126 if (M.size() == NumElts*2)
5132 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5133 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5134 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5135 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5136 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5140 unsigned NumElts = VT.getVectorNumElements();
5141 if (M.size() != NumElts && M.size() != NumElts*2)
5144 for (unsigned i = 0; i < M.size(); i += NumElts) {
5145 if (M.size() == NumElts * 2)
5146 WhichResult = i / NumElts;
5148 WhichResult = M[i] == 0 ? 0 : 1;
5149 for (unsigned j = 0; j < NumElts; j += 2) {
5150 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5151 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5156 if (M.size() == NumElts*2)
5162 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5163 // that the mask elements are either all even and in steps of size 2 or all odd
5164 // and in steps of size 2.
5165 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5166 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5168 // Requires similar checks to that of isVTRNMask with
5169 // respect the how results are returned.
5170 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5171 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5175 unsigned NumElts = VT.getVectorNumElements();
5176 if (M.size() != NumElts && M.size() != NumElts*2)
5179 for (unsigned i = 0; i < M.size(); i += NumElts) {
5180 WhichResult = M[i] == 0 ? 0 : 1;
5181 for (unsigned j = 0; j < NumElts; ++j) {
5182 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5187 if (M.size() == NumElts*2)
5190 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5191 if (VT.is64BitVector() && EltSz == 32)
5197 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5198 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5199 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5200 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5201 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5205 unsigned NumElts = VT.getVectorNumElements();
5206 if (M.size() != NumElts && M.size() != NumElts*2)
5209 unsigned Half = NumElts / 2;
5210 for (unsigned i = 0; i < M.size(); i += NumElts) {
5211 WhichResult = M[i] == 0 ? 0 : 1;
5212 for (unsigned j = 0; j < NumElts; j += Half) {
5213 unsigned Idx = WhichResult;
5214 for (unsigned k = 0; k < Half; ++k) {
5215 int MIdx = M[i + j + k];
5216 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5223 if (M.size() == NumElts*2)
5226 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5227 if (VT.is64BitVector() && EltSz == 32)
5233 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5234 // that pairs of elements of the shufflemask represent the same index in each
5235 // vector incrementing sequentially through the vectors.
5236 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5237 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5239 // Requires similar checks to that of isVTRNMask with respect the how results
5241 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5242 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5246 unsigned NumElts = VT.getVectorNumElements();
5247 if (M.size() != NumElts && M.size() != NumElts*2)
5250 for (unsigned i = 0; i < M.size(); i += NumElts) {
5251 WhichResult = M[i] == 0 ? 0 : 1;
5252 unsigned Idx = WhichResult * NumElts / 2;
5253 for (unsigned j = 0; j < NumElts; j += 2) {
5254 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5255 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5261 if (M.size() == NumElts*2)
5264 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5265 if (VT.is64BitVector() && EltSz == 32)
5271 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5272 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5273 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5274 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5275 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5279 unsigned NumElts = VT.getVectorNumElements();
5280 if (M.size() != NumElts && M.size() != NumElts*2)
5283 for (unsigned i = 0; i < M.size(); i += NumElts) {
5284 WhichResult = M[i] == 0 ? 0 : 1;
5285 unsigned Idx = WhichResult * NumElts / 2;
5286 for (unsigned j = 0; j < NumElts; j += 2) {
5287 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5288 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5294 if (M.size() == NumElts*2)
5297 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5298 if (VT.is64BitVector() && EltSz == 32)
5304 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5305 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5306 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5307 unsigned &WhichResult,
5310 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5311 return ARMISD::VTRN;
5312 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5313 return ARMISD::VUZP;
5314 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5315 return ARMISD::VZIP;
5318 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5319 return ARMISD::VTRN;
5320 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5321 return ARMISD::VUZP;
5322 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5323 return ARMISD::VZIP;
5328 /// \return true if this is a reverse operation on an vector.
5329 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5330 unsigned NumElts = VT.getVectorNumElements();
5331 // Make sure the mask has the right size.
5332 if (NumElts != M.size())
5335 // Look for <15, ..., 3, -1, 1, 0>.
5336 for (unsigned i = 0; i != NumElts; ++i)
5337 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5343 // If N is an integer constant that can be moved into a register in one
5344 // instruction, return an SDValue of such a constant (will become a MOV
5345 // instruction). Otherwise return null.
5346 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5347 const ARMSubtarget *ST, SDLoc dl) {
5349 if (!isa<ConstantSDNode>(N))
5351 Val = cast<ConstantSDNode>(N)->getZExtValue();
5353 if (ST->isThumb1Only()) {
5354 if (Val <= 255 || ~Val <= 255)
5355 return DAG.getConstant(Val, dl, MVT::i32);
5357 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5358 return DAG.getConstant(Val, dl, MVT::i32);
5363 // If this is a case we can't handle, return null and let the default
5364 // expansion code take care of it.
5365 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5366 const ARMSubtarget *ST) const {
5367 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5369 EVT VT = Op.getValueType();
5371 APInt SplatBits, SplatUndef;
5372 unsigned SplatBitSize;
5374 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5375 if (SplatBitSize <= 64) {
5376 // Check if an immediate VMOV works.
5378 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5379 SplatUndef.getZExtValue(), SplatBitSize,
5380 DAG, dl, VmovVT, VT.is128BitVector(),
5382 if (Val.getNode()) {
5383 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5384 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5387 // Try an immediate VMVN.
5388 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5389 Val = isNEONModifiedImm(NegatedImm,
5390 SplatUndef.getZExtValue(), SplatBitSize,
5391 DAG, dl, VmovVT, VT.is128BitVector(),
5393 if (Val.getNode()) {
5394 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5395 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5398 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5399 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5400 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5402 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5403 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5409 // Scan through the operands to see if only one value is used.
5411 // As an optimisation, even if more than one value is used it may be more
5412 // profitable to splat with one value then change some lanes.
5414 // Heuristically we decide to do this if the vector has a "dominant" value,
5415 // defined as splatted to more than half of the lanes.
5416 unsigned NumElts = VT.getVectorNumElements();
5417 bool isOnlyLowElement = true;
5418 bool usesOnlyOneValue = true;
5419 bool hasDominantValue = false;
5420 bool isConstant = true;
5422 // Map of the number of times a particular SDValue appears in the
5424 DenseMap<SDValue, unsigned> ValueCounts;
5426 for (unsigned i = 0; i < NumElts; ++i) {
5427 SDValue V = Op.getOperand(i);
5428 if (V.getOpcode() == ISD::UNDEF)
5431 isOnlyLowElement = false;
5432 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5435 ValueCounts.insert(std::make_pair(V, 0));
5436 unsigned &Count = ValueCounts[V];
5438 // Is this value dominant? (takes up more than half of the lanes)
5439 if (++Count > (NumElts / 2)) {
5440 hasDominantValue = true;
5444 if (ValueCounts.size() != 1)
5445 usesOnlyOneValue = false;
5446 if (!Value.getNode() && ValueCounts.size() > 0)
5447 Value = ValueCounts.begin()->first;
5449 if (ValueCounts.size() == 0)
5450 return DAG.getUNDEF(VT);
5452 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5453 // Keep going if we are hitting this case.
5454 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5455 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5457 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5459 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5460 // i32 and try again.
5461 if (hasDominantValue && EltSize <= 32) {
5465 // If we are VDUPing a value that comes directly from a vector, that will
5466 // cause an unnecessary move to and from a GPR, where instead we could
5467 // just use VDUPLANE. We can only do this if the lane being extracted
5468 // is at a constant index, as the VDUP from lane instructions only have
5469 // constant-index forms.
5470 ConstantSDNode *constIndex;
5471 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5472 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5473 // We need to create a new undef vector to use for the VDUPLANE if the
5474 // size of the vector from which we get the value is different than the
5475 // size of the vector that we need to create. We will insert the element
5476 // such that the register coalescer will remove unnecessary copies.
5477 if (VT != Value->getOperand(0).getValueType()) {
5478 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5479 VT.getVectorNumElements();
5480 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5481 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5482 Value, DAG.getConstant(index, dl, MVT::i32)),
5483 DAG.getConstant(index, dl, MVT::i32));
5485 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5486 Value->getOperand(0), Value->getOperand(1));
5488 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5490 if (!usesOnlyOneValue) {
5491 // The dominant value was splatted as 'N', but we now have to insert
5492 // all differing elements.
5493 for (unsigned I = 0; I < NumElts; ++I) {
5494 if (Op.getOperand(I) == Value)
5496 SmallVector<SDValue, 3> Ops;
5498 Ops.push_back(Op.getOperand(I));
5499 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5500 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5505 if (VT.getVectorElementType().isFloatingPoint()) {
5506 SmallVector<SDValue, 8> Ops;
5507 for (unsigned i = 0; i < NumElts; ++i)
5508 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5510 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5511 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5512 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5514 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5516 if (usesOnlyOneValue) {
5517 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5518 if (isConstant && Val.getNode())
5519 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5523 // If all elements are constants and the case above didn't get hit, fall back
5524 // to the default expansion, which will generate a load from the constant
5529 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5531 SDValue shuffle = ReconstructShuffle(Op, DAG);
5532 if (shuffle != SDValue())
5536 // Vectors with 32- or 64-bit elements can be built by directly assigning
5537 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5538 // will be legalized.
5539 if (EltSize >= 32) {
5540 // Do the expansion with floating-point types, since that is what the VFP
5541 // registers are defined to use, and since i64 is not legal.
5542 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5543 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5544 SmallVector<SDValue, 8> Ops;
5545 for (unsigned i = 0; i < NumElts; ++i)
5546 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5547 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5548 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5551 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5552 // know the default expansion would otherwise fall back on something even
5553 // worse. For a vector with one or two non-undef values, that's
5554 // scalar_to_vector for the elements followed by a shuffle (provided the
5555 // shuffle is valid for the target) and materialization element by element
5556 // on the stack followed by a load for everything else.
5557 if (!isConstant && !usesOnlyOneValue) {
5558 SDValue Vec = DAG.getUNDEF(VT);
5559 for (unsigned i = 0 ; i < NumElts; ++i) {
5560 SDValue V = Op.getOperand(i);
5561 if (V.getOpcode() == ISD::UNDEF)
5563 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5564 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5572 // Gather data to see if the operation can be modelled as a
5573 // shuffle in combination with VEXTs.
5574 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5575 SelectionDAG &DAG) const {
5576 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5578 EVT VT = Op.getValueType();
5579 unsigned NumElts = VT.getVectorNumElements();
5581 struct ShuffleSourceInfo {
5586 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5587 // be compatible with the shuffle we intend to construct. As a result
5588 // ShuffleVec will be some sliding window into the original Vec.
5591 // Code should guarantee that element i in Vec starts at element "WindowBase
5592 // + i * WindowScale in ShuffleVec".
5596 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5597 ShuffleSourceInfo(SDValue Vec)
5598 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5602 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5604 SmallVector<ShuffleSourceInfo, 2> Sources;
5605 for (unsigned i = 0; i < NumElts; ++i) {
5606 SDValue V = Op.getOperand(i);
5607 if (V.getOpcode() == ISD::UNDEF)
5609 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5610 // A shuffle can only come from building a vector from various
5611 // elements of other vectors.
5613 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5614 // Furthermore, shuffles require a constant mask, whereas extractelts
5615 // accept variable indices.
5619 // Add this element source to the list if it's not already there.
5620 SDValue SourceVec = V.getOperand(0);
5621 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5622 if (Source == Sources.end())
5623 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5625 // Update the minimum and maximum lane number seen.
5626 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5627 Source->MinElt = std::min(Source->MinElt, EltNo);
5628 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5631 // Currently only do something sane when at most two source vectors
5633 if (Sources.size() > 2)
5636 // Find out the smallest element size among result and two sources, and use
5637 // it as element size to build the shuffle_vector.
5638 EVT SmallestEltTy = VT.getVectorElementType();
5639 for (auto &Source : Sources) {
5640 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5641 if (SrcEltTy.bitsLT(SmallestEltTy))
5642 SmallestEltTy = SrcEltTy;
5644 unsigned ResMultiplier =
5645 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5646 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5647 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5649 // If the source vector is too wide or too narrow, we may nevertheless be able
5650 // to construct a compatible shuffle either by concatenating it with UNDEF or
5651 // extracting a suitable range of elements.
5652 for (auto &Src : Sources) {
5653 EVT SrcVT = Src.ShuffleVec.getValueType();
5655 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5658 // This stage of the search produces a source with the same element type as
5659 // the original, but with a total width matching the BUILD_VECTOR output.
5660 EVT EltVT = SrcVT.getVectorElementType();
5661 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5662 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5664 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5665 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5667 // We can pad out the smaller vector for free, so if it's part of a
5670 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5671 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5675 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5678 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5679 // Span too large for a VEXT to cope
5683 if (Src.MinElt >= NumSrcElts) {
5684 // The extraction can just take the second half
5686 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5687 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5688 Src.WindowBase = -NumSrcElts;
5689 } else if (Src.MaxElt < NumSrcElts) {
5690 // The extraction can just take the first half
5692 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5693 DAG.getConstant(0, dl, MVT::i32));
5695 // An actual VEXT is needed
5697 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5698 DAG.getConstant(0, dl, MVT::i32));
5700 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5701 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5703 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5705 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5706 Src.WindowBase = -Src.MinElt;
5710 // Another possible incompatibility occurs from the vector element types. We
5711 // can fix this by bitcasting the source vectors to the same type we intend
5713 for (auto &Src : Sources) {
5714 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5715 if (SrcEltTy == SmallestEltTy)
5717 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5718 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5719 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5720 Src.WindowBase *= Src.WindowScale;
5723 // Final sanity check before we try to actually produce a shuffle.
5725 for (auto Src : Sources)
5726 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5729 // The stars all align, our next step is to produce the mask for the shuffle.
5730 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5731 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5732 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5733 SDValue Entry = Op.getOperand(i);
5734 if (Entry.getOpcode() == ISD::UNDEF)
5737 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5738 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5740 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5741 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5743 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5744 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5745 VT.getVectorElementType().getSizeInBits());
5746 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5748 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5749 // starting at the appropriate offset.
5750 int *LaneMask = &Mask[i * ResMultiplier];
5752 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5753 ExtractBase += NumElts * (Src - Sources.begin());
5754 for (int j = 0; j < LanesDefined; ++j)
5755 LaneMask[j] = ExtractBase + j;
5758 // Final check before we try to produce nonsense...
5759 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5762 // We can't handle more than two sources. This should have already
5763 // been checked before this point.
5764 assert(Sources.size() <= 2 && "Too many sources!");
5766 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5767 for (unsigned i = 0; i < Sources.size(); ++i)
5768 ShuffleOps[i] = Sources[i].ShuffleVec;
5770 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5771 ShuffleOps[1], &Mask[0]);
5772 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5775 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5776 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5777 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5778 /// are assumed to be legal.
5780 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5782 if (VT.getVectorNumElements() == 4 &&
5783 (VT.is128BitVector() || VT.is64BitVector())) {
5784 unsigned PFIndexes[4];
5785 for (unsigned i = 0; i != 4; ++i) {
5789 PFIndexes[i] = M[i];
5792 // Compute the index in the perfect shuffle table.
5793 unsigned PFTableIndex =
5794 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5795 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5796 unsigned Cost = (PFEntry >> 30);
5802 bool ReverseVEXT, isV_UNDEF;
5803 unsigned Imm, WhichResult;
5805 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5806 return (EltSize >= 32 ||
5807 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5808 isVREVMask(M, VT, 64) ||
5809 isVREVMask(M, VT, 32) ||
5810 isVREVMask(M, VT, 16) ||
5811 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5812 isVTBLMask(M, VT) ||
5813 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5814 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5817 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5818 /// the specified operations to build the shuffle.
5819 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5820 SDValue RHS, SelectionDAG &DAG,
5822 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5823 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5824 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5827 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5836 OP_VUZPL, // VUZP, left result
5837 OP_VUZPR, // VUZP, right result
5838 OP_VZIPL, // VZIP, left result
5839 OP_VZIPR, // VZIP, right result
5840 OP_VTRNL, // VTRN, left result
5841 OP_VTRNR // VTRN, right result
5844 if (OpNum == OP_COPY) {
5845 if (LHSID == (1*9+2)*9+3) return LHS;
5846 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5850 SDValue OpLHS, OpRHS;
5851 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5852 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5853 EVT VT = OpLHS.getValueType();
5856 default: llvm_unreachable("Unknown shuffle opcode!");
5858 // VREV divides the vector in half and swaps within the half.
5859 if (VT.getVectorElementType() == MVT::i32 ||
5860 VT.getVectorElementType() == MVT::f32)
5861 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5862 // vrev <4 x i16> -> VREV32
5863 if (VT.getVectorElementType() == MVT::i16)
5864 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5865 // vrev <4 x i8> -> VREV16
5866 assert(VT.getVectorElementType() == MVT::i8);
5867 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5872 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5873 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5877 return DAG.getNode(ARMISD::VEXT, dl, VT,
5879 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5882 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5883 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5886 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5887 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5890 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5891 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5895 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5896 ArrayRef<int> ShuffleMask,
5897 SelectionDAG &DAG) {
5898 // Check to see if we can use the VTBL instruction.
5899 SDValue V1 = Op.getOperand(0);
5900 SDValue V2 = Op.getOperand(1);
5903 SmallVector<SDValue, 8> VTBLMask;
5904 for (ArrayRef<int>::iterator
5905 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5906 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5908 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5909 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5910 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5912 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5913 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5916 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5917 SelectionDAG &DAG) {
5919 SDValue OpLHS = Op.getOperand(0);
5920 EVT VT = OpLHS.getValueType();
5922 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5923 "Expect an v8i16/v16i8 type");
5924 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5925 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5926 // extract the first 8 bytes into the top double word and the last 8 bytes
5927 // into the bottom double word. The v8i16 case is similar.
5928 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5929 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5930 DAG.getConstant(ExtractNum, DL, MVT::i32));
5933 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5934 SDValue V1 = Op.getOperand(0);
5935 SDValue V2 = Op.getOperand(1);
5937 EVT VT = Op.getValueType();
5938 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5940 // Convert shuffles that are directly supported on NEON to target-specific
5941 // DAG nodes, instead of keeping them as shuffles and matching them again
5942 // during code selection. This is more efficient and avoids the possibility
5943 // of inconsistencies between legalization and selection.
5944 // FIXME: floating-point vectors should be canonicalized to integer vectors
5945 // of the same time so that they get CSEd properly.
5946 ArrayRef<int> ShuffleMask = SVN->getMask();
5948 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5949 if (EltSize <= 32) {
5950 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5951 int Lane = SVN->getSplatIndex();
5952 // If this is undef splat, generate it via "just" vdup, if possible.
5953 if (Lane == -1) Lane = 0;
5955 // Test if V1 is a SCALAR_TO_VECTOR.
5956 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5957 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5959 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5960 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5962 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5963 !isa<ConstantSDNode>(V1.getOperand(0))) {
5964 bool IsScalarToVector = true;
5965 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5966 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5967 IsScalarToVector = false;
5970 if (IsScalarToVector)
5971 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5973 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5974 DAG.getConstant(Lane, dl, MVT::i32));
5979 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5982 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5983 DAG.getConstant(Imm, dl, MVT::i32));
5986 if (isVREVMask(ShuffleMask, VT, 64))
5987 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5988 if (isVREVMask(ShuffleMask, VT, 32))
5989 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5990 if (isVREVMask(ShuffleMask, VT, 16))
5991 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5993 if (V2->getOpcode() == ISD::UNDEF &&
5994 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5995 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5996 DAG.getConstant(Imm, dl, MVT::i32));
5999 // Check for Neon shuffles that modify both input vectors in place.
6000 // If both results are used, i.e., if there are two shuffles with the same
6001 // source operands and with masks corresponding to both results of one of
6002 // these operations, DAG memoization will ensure that a single node is
6003 // used for both shuffles.
6004 unsigned WhichResult;
6006 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6007 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6010 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6011 .getValue(WhichResult);
6014 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6015 // shuffles that produce a result larger than their operands with:
6016 // shuffle(concat(v1, undef), concat(v2, undef))
6018 // shuffle(concat(v1, v2), undef)
6019 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6021 // This is useful in the general case, but there are special cases where
6022 // native shuffles produce larger results: the two-result ops.
6024 // Look through the concat when lowering them:
6025 // shuffle(concat(v1, v2), undef)
6027 // concat(VZIP(v1, v2):0, :1)
6029 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6030 V2->getOpcode() == ISD::UNDEF) {
6031 SDValue SubV1 = V1->getOperand(0);
6032 SDValue SubV2 = V1->getOperand(1);
6033 EVT SubVT = SubV1.getValueType();
6035 // We expect these to have been canonicalized to -1.
6036 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6037 return i < (int)VT.getVectorNumElements();
6038 }) && "Unexpected shuffle index into UNDEF operand!");
6040 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6041 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6044 assert((WhichResult == 0) &&
6045 "In-place shuffle of concat can only have one result!");
6046 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6048 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6054 // If the shuffle is not directly supported and it has 4 elements, use
6055 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6056 unsigned NumElts = VT.getVectorNumElements();
6058 unsigned PFIndexes[4];
6059 for (unsigned i = 0; i != 4; ++i) {
6060 if (ShuffleMask[i] < 0)
6063 PFIndexes[i] = ShuffleMask[i];
6066 // Compute the index in the perfect shuffle table.
6067 unsigned PFTableIndex =
6068 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6069 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6070 unsigned Cost = (PFEntry >> 30);
6073 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6076 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6077 if (EltSize >= 32) {
6078 // Do the expansion with floating-point types, since that is what the VFP
6079 // registers are defined to use, and since i64 is not legal.
6080 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6081 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6082 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6083 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6084 SmallVector<SDValue, 8> Ops;
6085 for (unsigned i = 0; i < NumElts; ++i) {
6086 if (ShuffleMask[i] < 0)
6087 Ops.push_back(DAG.getUNDEF(EltVT));
6089 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6090 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6091 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6094 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6095 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6098 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6099 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6101 if (VT == MVT::v8i8) {
6102 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6103 if (NewOp.getNode())
6110 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6111 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6112 SDValue Lane = Op.getOperand(2);
6113 if (!isa<ConstantSDNode>(Lane))
6119 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6120 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6121 SDValue Lane = Op.getOperand(1);
6122 if (!isa<ConstantSDNode>(Lane))
6125 SDValue Vec = Op.getOperand(0);
6126 if (Op.getValueType() == MVT::i32 &&
6127 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6129 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6135 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6136 // The only time a CONCAT_VECTORS operation can have legal types is when
6137 // two 64-bit vectors are concatenated to a 128-bit vector.
6138 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6139 "unexpected CONCAT_VECTORS");
6141 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6142 SDValue Op0 = Op.getOperand(0);
6143 SDValue Op1 = Op.getOperand(1);
6144 if (Op0.getOpcode() != ISD::UNDEF)
6145 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6146 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6147 DAG.getIntPtrConstant(0, dl));
6148 if (Op1.getOpcode() != ISD::UNDEF)
6149 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6150 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6151 DAG.getIntPtrConstant(1, dl));
6152 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6155 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6156 /// element has been zero/sign-extended, depending on the isSigned parameter,
6157 /// from an integer type half its size.
6158 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6160 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6161 EVT VT = N->getValueType(0);
6162 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6163 SDNode *BVN = N->getOperand(0).getNode();
6164 if (BVN->getValueType(0) != MVT::v4i32 ||
6165 BVN->getOpcode() != ISD::BUILD_VECTOR)
6167 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6168 unsigned HiElt = 1 - LoElt;
6169 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6170 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6171 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6172 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6173 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6176 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6177 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6180 if (Hi0->isNullValue() && Hi1->isNullValue())
6186 if (N->getOpcode() != ISD::BUILD_VECTOR)
6189 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6190 SDNode *Elt = N->getOperand(i).getNode();
6191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6192 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6193 unsigned HalfSize = EltSize / 2;
6195 if (!isIntN(HalfSize, C->getSExtValue()))
6198 if (!isUIntN(HalfSize, C->getZExtValue()))
6209 /// isSignExtended - Check if a node is a vector value that is sign-extended
6210 /// or a constant BUILD_VECTOR with sign-extended elements.
6211 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6212 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6214 if (isExtendedBUILD_VECTOR(N, DAG, true))
6219 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6220 /// or a constant BUILD_VECTOR with zero-extended elements.
6221 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6222 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6224 if (isExtendedBUILD_VECTOR(N, DAG, false))
6229 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6230 if (OrigVT.getSizeInBits() >= 64)
6233 assert(OrigVT.isSimple() && "Expecting a simple value type");
6235 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6236 switch (OrigSimpleTy) {
6237 default: llvm_unreachable("Unexpected Vector Type");
6246 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6247 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6248 /// We insert the required extension here to get the vector to fill a D register.
6249 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6252 unsigned ExtOpcode) {
6253 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6254 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6255 // 64-bits we need to insert a new extension so that it will be 64-bits.
6256 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6257 if (OrigTy.getSizeInBits() >= 64)
6260 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6261 EVT NewVT = getExtensionTo64Bits(OrigTy);
6263 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6266 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6267 /// does not do any sign/zero extension. If the original vector is less
6268 /// than 64 bits, an appropriate extension will be added after the load to
6269 /// reach a total size of 64 bits. We have to add the extension separately
6270 /// because ARM does not have a sign/zero extending load for vectors.
6271 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6272 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6274 // The load already has the right type.
6275 if (ExtendedTy == LD->getMemoryVT())
6276 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6277 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6278 LD->isNonTemporal(), LD->isInvariant(),
6279 LD->getAlignment());
6281 // We need to create a zextload/sextload. We cannot just create a load
6282 // followed by a zext/zext node because LowerMUL is also run during normal
6283 // operation legalization where we can't create illegal types.
6284 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6285 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6286 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6287 LD->isNonTemporal(), LD->getAlignment());
6290 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6291 /// extending load, or BUILD_VECTOR with extended elements, return the
6292 /// unextended value. The unextended vector should be 64 bits so that it can
6293 /// be used as an operand to a VMULL instruction. If the original vector size
6294 /// before extension is less than 64 bits we add a an extension to resize
6295 /// the vector to 64 bits.
6296 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6297 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6298 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6299 N->getOperand(0)->getValueType(0),
6303 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6304 return SkipLoadExtensionForVMULL(LD, DAG);
6306 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6307 // have been legalized as a BITCAST from v4i32.
6308 if (N->getOpcode() == ISD::BITCAST) {
6309 SDNode *BVN = N->getOperand(0).getNode();
6310 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6311 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6312 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6313 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6314 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6316 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6317 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6318 EVT VT = N->getValueType(0);
6319 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6320 unsigned NumElts = VT.getVectorNumElements();
6321 MVT TruncVT = MVT::getIntegerVT(EltSize);
6322 SmallVector<SDValue, 8> Ops;
6324 for (unsigned i = 0; i != NumElts; ++i) {
6325 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6326 const APInt &CInt = C->getAPIntValue();
6327 // Element types smaller than 32 bits are not legal, so use i32 elements.
6328 // The values are implicitly truncated so sext vs. zext doesn't matter.
6329 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6331 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6332 MVT::getVectorVT(TruncVT, NumElts), Ops);
6335 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6336 unsigned Opcode = N->getOpcode();
6337 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6338 SDNode *N0 = N->getOperand(0).getNode();
6339 SDNode *N1 = N->getOperand(1).getNode();
6340 return N0->hasOneUse() && N1->hasOneUse() &&
6341 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6346 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6347 unsigned Opcode = N->getOpcode();
6348 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6349 SDNode *N0 = N->getOperand(0).getNode();
6350 SDNode *N1 = N->getOperand(1).getNode();
6351 return N0->hasOneUse() && N1->hasOneUse() &&
6352 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6357 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6358 // Multiplications are only custom-lowered for 128-bit vectors so that
6359 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6360 EVT VT = Op.getValueType();
6361 assert(VT.is128BitVector() && VT.isInteger() &&
6362 "unexpected type for custom-lowering ISD::MUL");
6363 SDNode *N0 = Op.getOperand(0).getNode();
6364 SDNode *N1 = Op.getOperand(1).getNode();
6365 unsigned NewOpc = 0;
6367 bool isN0SExt = isSignExtended(N0, DAG);
6368 bool isN1SExt = isSignExtended(N1, DAG);
6369 if (isN0SExt && isN1SExt)
6370 NewOpc = ARMISD::VMULLs;
6372 bool isN0ZExt = isZeroExtended(N0, DAG);
6373 bool isN1ZExt = isZeroExtended(N1, DAG);
6374 if (isN0ZExt && isN1ZExt)
6375 NewOpc = ARMISD::VMULLu;
6376 else if (isN1SExt || isN1ZExt) {
6377 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6378 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6379 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6380 NewOpc = ARMISD::VMULLs;
6382 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6383 NewOpc = ARMISD::VMULLu;
6385 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6387 NewOpc = ARMISD::VMULLu;
6393 if (VT == MVT::v2i64)
6394 // Fall through to expand this. It is not legal.
6397 // Other vector multiplications are legal.
6402 // Legalize to a VMULL instruction.
6405 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6407 Op0 = SkipExtensionForVMULL(N0, DAG);
6408 assert(Op0.getValueType().is64BitVector() &&
6409 Op1.getValueType().is64BitVector() &&
6410 "unexpected types for extended operands to VMULL");
6411 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6414 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6415 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6422 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6423 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6424 EVT Op1VT = Op1.getValueType();
6425 return DAG.getNode(N0->getOpcode(), DL, VT,
6426 DAG.getNode(NewOpc, DL, VT,
6427 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6428 DAG.getNode(NewOpc, DL, VT,
6429 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6433 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6434 // TODO: Should this propagate fast-math-flags?
6437 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6438 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6439 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6440 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6441 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6442 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6443 // Get reciprocal estimate.
6444 // float4 recip = vrecpeq_f32(yf);
6445 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6446 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6448 // Because char has a smaller range than uchar, we can actually get away
6449 // without any newton steps. This requires that we use a weird bias
6450 // of 0xb000, however (again, this has been exhaustively tested).
6451 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6452 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6453 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6454 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6455 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6456 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6457 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6458 // Convert back to short.
6459 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6460 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6465 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6466 // TODO: Should this propagate fast-math-flags?
6469 // Convert to float.
6470 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6471 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6472 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6473 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6474 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6475 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6477 // Use reciprocal estimate and one refinement step.
6478 // float4 recip = vrecpeq_f32(yf);
6479 // recip *= vrecpsq_f32(yf, recip);
6480 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6481 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6483 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6484 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6486 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6487 // Because short has a smaller range than ushort, we can actually get away
6488 // with only a single newton step. This requires that we use a weird bias
6489 // of 89, however (again, this has been exhaustively tested).
6490 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6491 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6492 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6493 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6494 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6495 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6496 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6497 // Convert back to integer and return.
6498 // return vmovn_s32(vcvt_s32_f32(result));
6499 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6500 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6504 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6505 EVT VT = Op.getValueType();
6506 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6507 "unexpected type for custom-lowering ISD::SDIV");
6510 SDValue N0 = Op.getOperand(0);
6511 SDValue N1 = Op.getOperand(1);
6514 if (VT == MVT::v8i8) {
6515 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6516 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6518 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6519 DAG.getIntPtrConstant(4, dl));
6520 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6521 DAG.getIntPtrConstant(4, dl));
6522 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6523 DAG.getIntPtrConstant(0, dl));
6524 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6525 DAG.getIntPtrConstant(0, dl));
6527 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6528 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6530 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6531 N0 = LowerCONCAT_VECTORS(N0, DAG);
6533 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6536 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6539 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6540 // TODO: Should this propagate fast-math-flags?
6541 EVT VT = Op.getValueType();
6542 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6543 "unexpected type for custom-lowering ISD::UDIV");
6546 SDValue N0 = Op.getOperand(0);
6547 SDValue N1 = Op.getOperand(1);
6550 if (VT == MVT::v8i8) {
6551 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6552 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6554 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6555 DAG.getIntPtrConstant(4, dl));
6556 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6557 DAG.getIntPtrConstant(4, dl));
6558 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6559 DAG.getIntPtrConstant(0, dl));
6560 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6561 DAG.getIntPtrConstant(0, dl));
6563 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6564 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6566 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6567 N0 = LowerCONCAT_VECTORS(N0, DAG);
6569 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6570 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6576 // v4i16 sdiv ... Convert to float.
6577 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6578 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6579 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6580 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6581 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6582 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6584 // Use reciprocal estimate and two refinement steps.
6585 // float4 recip = vrecpeq_f32(yf);
6586 // recip *= vrecpsq_f32(yf, recip);
6587 // recip *= vrecpsq_f32(yf, recip);
6588 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6589 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6591 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6592 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6594 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6595 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6596 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6598 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6599 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6600 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6601 // and that it will never cause us to return an answer too large).
6602 // float4 result = as_float4(as_int4(xf*recip) + 2);
6603 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6604 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6605 N1 = DAG.getConstant(2, dl, MVT::i32);
6606 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6607 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6608 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6609 // Convert back to integer and return.
6610 // return vmovn_u32(vcvt_s32_f32(result));
6611 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6612 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6616 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6617 EVT VT = Op.getNode()->getValueType(0);
6618 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6621 bool ExtraOp = false;
6622 switch (Op.getOpcode()) {
6623 default: llvm_unreachable("Invalid code");
6624 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6625 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6626 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6627 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6631 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6633 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6634 Op.getOperand(1), Op.getOperand(2));
6637 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6638 assert(Subtarget->isTargetDarwin());
6640 // For iOS, we want to call an alternative entry point: __sincos_stret,
6641 // return values are passed via sret.
6643 SDValue Arg = Op.getOperand(0);
6644 EVT ArgVT = Arg.getValueType();
6645 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6646 auto PtrVT = getPointerTy(DAG.getDataLayout());
6648 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6649 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6651 // Pair of floats / doubles used to pass the result.
6652 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6653 auto &DL = DAG.getDataLayout();
6656 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6658 if (ShouldUseSRet) {
6659 // Create stack object for sret.
6660 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6661 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6662 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6663 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6667 Entry.Ty = RetTy->getPointerTo();
6668 Entry.isSExt = false;
6669 Entry.isZExt = false;
6670 Entry.isSRet = true;
6671 Args.push_back(Entry);
6672 RetTy = Type::getVoidTy(*DAG.getContext());
6678 Entry.isSExt = false;
6679 Entry.isZExt = false;
6680 Args.push_back(Entry);
6682 const char *LibcallName =
6683 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6685 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6686 CallingConv::ID CC = getLibcallCallingConv(LC);
6687 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6689 TargetLowering::CallLoweringInfo CLI(DAG);
6691 .setChain(DAG.getEntryNode())
6692 .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6693 .setDiscardResult(ShouldUseSRet);
6694 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6697 return CallResult.first;
6699 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6700 MachinePointerInfo(), false, false, false, 0);
6702 // Address of cos field.
6703 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6704 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6705 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6706 MachinePointerInfo(), false, false, false, 0);
6708 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6709 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6710 LoadSin.getValue(0), LoadCos.getValue(0));
6713 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6715 SDValue &Chain) const {
6716 EVT VT = Op.getValueType();
6717 assert((VT == MVT::i32 || VT == MVT::i64) &&
6718 "unexpected type for custom lowering DIV");
6721 const auto &DL = DAG.getDataLayout();
6722 const auto &TLI = DAG.getTargetLoweringInfo();
6724 const char *Name = nullptr;
6726 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6728 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6730 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6732 ARMTargetLowering::ArgListTy Args;
6734 for (auto AI : {1, 0}) {
6736 Arg.Node = Op.getOperand(AI);
6737 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6738 Args.push_back(Arg);
6741 CallLoweringInfo CLI(DAG);
6744 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6745 ES, std::move(Args), 0);
6747 return LowerCallTo(CLI).first;
6750 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6751 bool Signed) const {
6752 assert(Op.getValueType() == MVT::i32 &&
6753 "unexpected type for custom lowering DIV");
6756 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6757 DAG.getEntryNode(), Op.getOperand(1));
6759 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6762 void ARMTargetLowering::ExpandDIV_Windows(
6763 SDValue Op, SelectionDAG &DAG, bool Signed,
6764 SmallVectorImpl<SDValue> &Results) const {
6765 const auto &DL = DAG.getDataLayout();
6766 const auto &TLI = DAG.getTargetLoweringInfo();
6768 assert(Op.getValueType() == MVT::i64 &&
6769 "unexpected type for custom lowering DIV");
6772 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6773 DAG.getConstant(0, dl, MVT::i32));
6774 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6775 DAG.getConstant(1, dl, MVT::i32));
6776 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6779 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6781 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6783 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6784 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6785 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6786 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6788 Results.push_back(Lower);
6789 Results.push_back(Upper);
6792 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6793 // Monotonic load/store is legal for all targets
6794 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6797 // Acquire/Release load/store is not legal for targets without a
6798 // dmb or equivalent available.
6802 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6803 SmallVectorImpl<SDValue> &Results,
6805 const ARMSubtarget *Subtarget) {
6807 // Under Power Management extensions, the cycle-count is:
6808 // mrc p15, #0, <Rt>, c9, c13, #0
6809 SDValue Ops[] = { N->getOperand(0), // Chain
6810 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6811 DAG.getConstant(15, DL, MVT::i32),
6812 DAG.getConstant(0, DL, MVT::i32),
6813 DAG.getConstant(9, DL, MVT::i32),
6814 DAG.getConstant(13, DL, MVT::i32),
6815 DAG.getConstant(0, DL, MVT::i32)
6818 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6819 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6820 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6821 DAG.getConstant(0, DL, MVT::i32)));
6822 Results.push_back(Cycles32.getValue(1));
6825 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6826 switch (Op.getOpcode()) {
6827 default: llvm_unreachable("Don't know how to custom lower this!");
6828 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6829 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6830 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6831 case ISD::GlobalAddress:
6832 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6833 default: llvm_unreachable("unknown object format");
6835 return LowerGlobalAddressWindows(Op, DAG);
6837 return LowerGlobalAddressELF(Op, DAG);
6839 return LowerGlobalAddressDarwin(Op, DAG);
6841 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6842 case ISD::SELECT: return LowerSELECT(Op, DAG);
6843 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6844 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6845 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6846 case ISD::VASTART: return LowerVASTART(Op, DAG);
6847 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6848 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6849 case ISD::SINT_TO_FP:
6850 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6851 case ISD::FP_TO_SINT:
6852 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6853 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6854 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6855 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6856 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6857 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6858 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6859 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6861 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6864 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6865 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6866 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6867 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6868 case ISD::SRL_PARTS:
6869 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6871 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6872 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6873 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6874 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6875 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6876 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6877 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6878 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6879 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6880 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6881 case ISD::MUL: return LowerMUL(Op, DAG);
6882 case ISD::SDIV: return LowerSDIV(Op, DAG);
6883 case ISD::UDIV: return LowerUDIV(Op, DAG);
6887 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6892 return LowerXALUO(Op, DAG);
6893 case ISD::ATOMIC_LOAD:
6894 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6895 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6897 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6898 case ISD::DYNAMIC_STACKALLOC:
6899 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6900 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6901 llvm_unreachable("Don't know how to custom lower this!");
6902 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6903 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6904 case ARMISD::WIN__DBZCHK: return SDValue();
6908 /// ReplaceNodeResults - Replace the results of node with an illegal result
6909 /// type with new values built out of custom code.
6910 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6911 SmallVectorImpl<SDValue> &Results,
6912 SelectionDAG &DAG) const {
6914 switch (N->getOpcode()) {
6916 llvm_unreachable("Don't know how to custom expand this!");
6917 case ISD::READ_REGISTER:
6918 ExpandREAD_REGISTER(N, Results, DAG);
6921 Res = ExpandBITCAST(N, DAG);
6925 Res = Expand64BitShift(N, DAG, Subtarget);
6929 Res = LowerREM(N, DAG);
6931 case ISD::READCYCLECOUNTER:
6932 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6936 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6937 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6941 Results.push_back(Res);
6944 //===----------------------------------------------------------------------===//
6945 // ARM Scheduler Hooks
6946 //===----------------------------------------------------------------------===//
6948 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6949 /// registers the function context.
6950 void ARMTargetLowering::
6951 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6952 MachineBasicBlock *DispatchBB, int FI) const {
6953 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6954 DebugLoc dl = MI->getDebugLoc();
6955 MachineFunction *MF = MBB->getParent();
6956 MachineRegisterInfo *MRI = &MF->getRegInfo();
6957 MachineConstantPool *MCP = MF->getConstantPool();
6958 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6959 const Function *F = MF->getFunction();
6961 bool isThumb = Subtarget->isThumb();
6962 bool isThumb2 = Subtarget->isThumb2();
6964 unsigned PCLabelId = AFI->createPICLabelUId();
6965 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6966 ARMConstantPoolValue *CPV =
6967 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6968 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6970 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6971 : &ARM::GPRRegClass;
6973 // Grab constant pool and fixed stack memory operands.
6974 MachineMemOperand *CPMMO =
6975 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6976 MachineMemOperand::MOLoad, 4, 4);
6978 MachineMemOperand *FIMMOSt =
6979 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6980 MachineMemOperand::MOStore, 4, 4);
6982 // Load the address of the dispatch MBB into the jump buffer.
6984 // Incoming value: jbuf
6985 // ldr.n r5, LCPI1_1
6988 // str r5, [$jbuf, #+4] ; &jbuf[1]
6989 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6990 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6991 .addConstantPoolIndex(CPI)
6992 .addMemOperand(CPMMO));
6993 // Set the low bit because of thumb mode.
6994 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6996 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6997 .addReg(NewVReg1, RegState::Kill)
6999 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7000 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7001 .addReg(NewVReg2, RegState::Kill)
7003 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7004 .addReg(NewVReg3, RegState::Kill)
7006 .addImm(36) // &jbuf[1] :: pc
7007 .addMemOperand(FIMMOSt));
7008 } else if (isThumb) {
7009 // Incoming value: jbuf
7010 // ldr.n r1, LCPI1_4
7014 // add r2, $jbuf, #+4 ; &jbuf[1]
7016 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7017 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7018 .addConstantPoolIndex(CPI)
7019 .addMemOperand(CPMMO));
7020 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7021 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7022 .addReg(NewVReg1, RegState::Kill)
7024 // Set the low bit because of thumb mode.
7025 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7026 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7027 .addReg(ARM::CPSR, RegState::Define)
7029 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7030 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7031 .addReg(ARM::CPSR, RegState::Define)
7032 .addReg(NewVReg2, RegState::Kill)
7033 .addReg(NewVReg3, RegState::Kill));
7034 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7035 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7037 .addImm(36); // &jbuf[1] :: pc
7038 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7039 .addReg(NewVReg4, RegState::Kill)
7040 .addReg(NewVReg5, RegState::Kill)
7042 .addMemOperand(FIMMOSt));
7044 // Incoming value: jbuf
7047 // str r1, [$jbuf, #+4] ; &jbuf[1]
7048 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7049 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7050 .addConstantPoolIndex(CPI)
7052 .addMemOperand(CPMMO));
7053 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7054 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7055 .addReg(NewVReg1, RegState::Kill)
7056 .addImm(PCLabelId));
7057 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7058 .addReg(NewVReg2, RegState::Kill)
7060 .addImm(36) // &jbuf[1] :: pc
7061 .addMemOperand(FIMMOSt));
7065 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7066 MachineBasicBlock *MBB) const {
7067 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7068 DebugLoc dl = MI->getDebugLoc();
7069 MachineFunction *MF = MBB->getParent();
7070 MachineRegisterInfo *MRI = &MF->getRegInfo();
7071 MachineFrameInfo *MFI = MF->getFrameInfo();
7072 int FI = MFI->getFunctionContextIndex();
7074 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7075 : &ARM::GPRnopcRegClass;
7077 // Get a mapping of the call site numbers to all of the landing pads they're
7079 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7080 unsigned MaxCSNum = 0;
7081 MachineModuleInfo &MMI = MF->getMMI();
7082 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7084 if (!BB->isEHPad()) continue;
7086 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7088 for (MachineBasicBlock::iterator
7089 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7090 if (!II->isEHLabel()) continue;
7092 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7093 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7095 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7096 for (SmallVectorImpl<unsigned>::iterator
7097 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7098 CSI != CSE; ++CSI) {
7099 CallSiteNumToLPad[*CSI].push_back(&*BB);
7100 MaxCSNum = std::max(MaxCSNum, *CSI);
7106 // Get an ordered list of the machine basic blocks for the jump table.
7107 std::vector<MachineBasicBlock*> LPadList;
7108 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7109 LPadList.reserve(CallSiteNumToLPad.size());
7110 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7111 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7112 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7113 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7114 LPadList.push_back(*II);
7115 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7119 assert(!LPadList.empty() &&
7120 "No landing pad destinations for the dispatch jump table!");
7122 // Create the jump table and associated information.
7123 MachineJumpTableInfo *JTI =
7124 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7125 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7126 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7128 // Create the MBBs for the dispatch code.
7130 // Shove the dispatch's address into the return slot in the function context.
7131 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7132 DispatchBB->setIsEHPad();
7134 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7135 unsigned trap_opcode;
7136 if (Subtarget->isThumb())
7137 trap_opcode = ARM::tTRAP;
7139 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7141 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7142 DispatchBB->addSuccessor(TrapBB);
7144 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7145 DispatchBB->addSuccessor(DispContBB);
7148 MF->insert(MF->end(), DispatchBB);
7149 MF->insert(MF->end(), DispContBB);
7150 MF->insert(MF->end(), TrapBB);
7152 // Insert code into the entry block that creates and registers the function
7154 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7156 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7157 MachinePointerInfo::getFixedStack(*MF, FI),
7158 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7160 MachineInstrBuilder MIB;
7161 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7163 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7164 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7166 // Add a register mask with no preserved registers. This results in all
7167 // registers being marked as clobbered.
7168 MIB.addRegMask(RI.getNoPreservedMask());
7170 unsigned NumLPads = LPadList.size();
7171 if (Subtarget->isThumb2()) {
7172 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7173 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7176 .addMemOperand(FIMMOLd));
7178 if (NumLPads < 256) {
7179 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7181 .addImm(LPadList.size()));
7183 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7184 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7185 .addImm(NumLPads & 0xFFFF));
7187 unsigned VReg2 = VReg1;
7188 if ((NumLPads & 0xFFFF0000) != 0) {
7189 VReg2 = MRI->createVirtualRegister(TRC);
7190 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7192 .addImm(NumLPads >> 16));
7195 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7200 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7205 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7206 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7207 .addJumpTableIndex(MJTI));
7209 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7212 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7213 .addReg(NewVReg3, RegState::Kill)
7215 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7217 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7218 .addReg(NewVReg4, RegState::Kill)
7220 .addJumpTableIndex(MJTI);
7221 } else if (Subtarget->isThumb()) {
7222 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7223 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7226 .addMemOperand(FIMMOLd));
7228 if (NumLPads < 256) {
7229 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7233 MachineConstantPool *ConstantPool = MF->getConstantPool();
7234 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7235 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7237 // MachineConstantPool wants an explicit alignment.
7238 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7240 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7241 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7243 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7244 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7245 .addReg(VReg1, RegState::Define)
7246 .addConstantPoolIndex(Idx));
7247 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7252 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7257 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7258 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7259 .addReg(ARM::CPSR, RegState::Define)
7263 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7264 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7265 .addJumpTableIndex(MJTI));
7267 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7268 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7269 .addReg(ARM::CPSR, RegState::Define)
7270 .addReg(NewVReg2, RegState::Kill)
7273 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7274 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7276 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7277 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7278 .addReg(NewVReg4, RegState::Kill)
7280 .addMemOperand(JTMMOLd));
7282 unsigned NewVReg6 = NewVReg5;
7283 if (RelocM == Reloc::PIC_) {
7284 NewVReg6 = MRI->createVirtualRegister(TRC);
7285 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7286 .addReg(ARM::CPSR, RegState::Define)
7287 .addReg(NewVReg5, RegState::Kill)
7291 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7292 .addReg(NewVReg6, RegState::Kill)
7293 .addJumpTableIndex(MJTI);
7295 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7296 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7299 .addMemOperand(FIMMOLd));
7301 if (NumLPads < 256) {
7302 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7305 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7306 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7307 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7308 .addImm(NumLPads & 0xFFFF));
7310 unsigned VReg2 = VReg1;
7311 if ((NumLPads & 0xFFFF0000) != 0) {
7312 VReg2 = MRI->createVirtualRegister(TRC);
7313 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7315 .addImm(NumLPads >> 16));
7318 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7322 MachineConstantPool *ConstantPool = MF->getConstantPool();
7323 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7324 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7326 // MachineConstantPool wants an explicit alignment.
7327 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7329 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7330 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7332 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7333 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7334 .addReg(VReg1, RegState::Define)
7335 .addConstantPoolIndex(Idx)
7337 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7339 .addReg(VReg1, RegState::Kill));
7342 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7347 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7349 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7351 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7352 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7353 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7354 .addJumpTableIndex(MJTI));
7356 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7357 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7358 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7360 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7361 .addReg(NewVReg3, RegState::Kill)
7364 .addMemOperand(JTMMOLd));
7366 if (RelocM == Reloc::PIC_) {
7367 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7368 .addReg(NewVReg5, RegState::Kill)
7370 .addJumpTableIndex(MJTI);
7372 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7373 .addReg(NewVReg5, RegState::Kill)
7374 .addJumpTableIndex(MJTI);
7378 // Add the jump table entries as successors to the MBB.
7379 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7380 for (std::vector<MachineBasicBlock*>::iterator
7381 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7382 MachineBasicBlock *CurMBB = *I;
7383 if (SeenMBBs.insert(CurMBB).second)
7384 DispContBB->addSuccessor(CurMBB);
7387 // N.B. the order the invoke BBs are processed in doesn't matter here.
7388 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7389 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7390 for (MachineBasicBlock *BB : InvokeBBs) {
7392 // Remove the landing pad successor from the invoke block and replace it
7393 // with the new dispatch block.
7394 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7396 while (!Successors.empty()) {
7397 MachineBasicBlock *SMBB = Successors.pop_back_val();
7398 if (SMBB->isEHPad()) {
7399 BB->removeSuccessor(SMBB);
7400 MBBLPads.push_back(SMBB);
7404 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7406 // Find the invoke call and mark all of the callee-saved registers as
7407 // 'implicit defined' so that they're spilled. This prevents code from
7408 // moving instructions to before the EH block, where they will never be
7410 for (MachineBasicBlock::reverse_iterator
7411 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7412 if (!II->isCall()) continue;
7414 DenseMap<unsigned, bool> DefRegs;
7415 for (MachineInstr::mop_iterator
7416 OI = II->operands_begin(), OE = II->operands_end();
7418 if (!OI->isReg()) continue;
7419 DefRegs[OI->getReg()] = true;
7422 MachineInstrBuilder MIB(*MF, &*II);
7424 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7425 unsigned Reg = SavedRegs[i];
7426 if (Subtarget->isThumb2() &&
7427 !ARM::tGPRRegClass.contains(Reg) &&
7428 !ARM::hGPRRegClass.contains(Reg))
7430 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7432 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7435 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7442 // Mark all former landing pads as non-landing pads. The dispatch is the only
7444 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7445 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7446 (*I)->setIsEHPad(false);
7448 // The instruction is gone now.
7449 MI->eraseFromParent();
7453 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7454 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7455 E = MBB->succ_end(); I != E; ++I)
7458 llvm_unreachable("Expecting a BB with two successors!");
7461 /// Return the load opcode for a given load size. If load size >= 8,
7462 /// neon opcode will be returned.
7463 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7465 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7466 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7468 return LdSize == 4 ? ARM::tLDRi
7469 : LdSize == 2 ? ARM::tLDRHi
7470 : LdSize == 1 ? ARM::tLDRBi : 0;
7472 return LdSize == 4 ? ARM::t2LDR_POST
7473 : LdSize == 2 ? ARM::t2LDRH_POST
7474 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7475 return LdSize == 4 ? ARM::LDR_POST_IMM
7476 : LdSize == 2 ? ARM::LDRH_POST
7477 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7480 /// Return the store opcode for a given store size. If store size >= 8,
7481 /// neon opcode will be returned.
7482 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7484 return StSize == 16 ? ARM::VST1q32wb_fixed
7485 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7487 return StSize == 4 ? ARM::tSTRi
7488 : StSize == 2 ? ARM::tSTRHi
7489 : StSize == 1 ? ARM::tSTRBi : 0;
7491 return StSize == 4 ? ARM::t2STR_POST
7492 : StSize == 2 ? ARM::t2STRH_POST
7493 : StSize == 1 ? ARM::t2STRB_POST : 0;
7494 return StSize == 4 ? ARM::STR_POST_IMM
7495 : StSize == 2 ? ARM::STRH_POST
7496 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7499 /// Emit a post-increment load operation with given size. The instructions
7500 /// will be added to BB at Pos.
7501 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7502 const TargetInstrInfo *TII, DebugLoc dl,
7503 unsigned LdSize, unsigned Data, unsigned AddrIn,
7504 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7505 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7506 assert(LdOpc != 0 && "Should have a load opcode");
7508 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7509 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7511 } else if (IsThumb1) {
7512 // load + update AddrIn
7513 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7514 .addReg(AddrIn).addImm(0));
7515 MachineInstrBuilder MIB =
7516 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7517 MIB = AddDefaultT1CC(MIB);
7518 MIB.addReg(AddrIn).addImm(LdSize);
7519 AddDefaultPred(MIB);
7520 } else if (IsThumb2) {
7521 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7522 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7525 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7526 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7527 .addReg(0).addImm(LdSize));
7531 /// Emit a post-increment store operation with given size. The instructions
7532 /// will be added to BB at Pos.
7533 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7534 const TargetInstrInfo *TII, DebugLoc dl,
7535 unsigned StSize, unsigned Data, unsigned AddrIn,
7536 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7537 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7538 assert(StOpc != 0 && "Should have a store opcode");
7540 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7541 .addReg(AddrIn).addImm(0).addReg(Data));
7542 } else if (IsThumb1) {
7543 // store + update AddrIn
7544 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7545 .addReg(AddrIn).addImm(0));
7546 MachineInstrBuilder MIB =
7547 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7548 MIB = AddDefaultT1CC(MIB);
7549 MIB.addReg(AddrIn).addImm(StSize);
7550 AddDefaultPred(MIB);
7551 } else if (IsThumb2) {
7552 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7553 .addReg(Data).addReg(AddrIn).addImm(StSize));
7555 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7556 .addReg(Data).addReg(AddrIn).addReg(0)
7562 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7563 MachineBasicBlock *BB) const {
7564 // This pseudo instruction has 3 operands: dst, src, size
7565 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7566 // Otherwise, we will generate unrolled scalar copies.
7567 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7568 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7569 MachineFunction::iterator It = ++BB->getIterator();
7571 unsigned dest = MI->getOperand(0).getReg();
7572 unsigned src = MI->getOperand(1).getReg();
7573 unsigned SizeVal = MI->getOperand(2).getImm();
7574 unsigned Align = MI->getOperand(3).getImm();
7575 DebugLoc dl = MI->getDebugLoc();
7577 MachineFunction *MF = BB->getParent();
7578 MachineRegisterInfo &MRI = MF->getRegInfo();
7579 unsigned UnitSize = 0;
7580 const TargetRegisterClass *TRC = nullptr;
7581 const TargetRegisterClass *VecTRC = nullptr;
7583 bool IsThumb1 = Subtarget->isThumb1Only();
7584 bool IsThumb2 = Subtarget->isThumb2();
7588 } else if (Align & 2) {
7591 // Check whether we can use NEON instructions.
7592 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7593 Subtarget->hasNEON()) {
7594 if ((Align % 16 == 0) && SizeVal >= 16)
7596 else if ((Align % 8 == 0) && SizeVal >= 8)
7599 // Can't use NEON instructions.
7604 // Select the correct opcode and register class for unit size load/store
7605 bool IsNeon = UnitSize >= 8;
7606 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7608 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7609 : UnitSize == 8 ? &ARM::DPRRegClass
7612 unsigned BytesLeft = SizeVal % UnitSize;
7613 unsigned LoopSize = SizeVal - BytesLeft;
7615 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7616 // Use LDR and STR to copy.
7617 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7618 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7619 unsigned srcIn = src;
7620 unsigned destIn = dest;
7621 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7622 unsigned srcOut = MRI.createVirtualRegister(TRC);
7623 unsigned destOut = MRI.createVirtualRegister(TRC);
7624 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7625 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7626 IsThumb1, IsThumb2);
7627 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7628 IsThumb1, IsThumb2);
7633 // Handle the leftover bytes with LDRB and STRB.
7634 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7635 // [destOut] = STRB_POST(scratch, destIn, 1)
7636 for (unsigned i = 0; i < BytesLeft; i++) {
7637 unsigned srcOut = MRI.createVirtualRegister(TRC);
7638 unsigned destOut = MRI.createVirtualRegister(TRC);
7639 unsigned scratch = MRI.createVirtualRegister(TRC);
7640 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7641 IsThumb1, IsThumb2);
7642 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7643 IsThumb1, IsThumb2);
7647 MI->eraseFromParent(); // The instruction is gone now.
7651 // Expand the pseudo op to a loop.
7654 // movw varEnd, # --> with thumb2
7656 // ldrcp varEnd, idx --> without thumb2
7657 // fallthrough --> loopMBB
7659 // PHI varPhi, varEnd, varLoop
7660 // PHI srcPhi, src, srcLoop
7661 // PHI destPhi, dst, destLoop
7662 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7663 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7664 // subs varLoop, varPhi, #UnitSize
7666 // fallthrough --> exitMBB
7668 // epilogue to handle left-over bytes
7669 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7670 // [destOut] = STRB_POST(scratch, destLoop, 1)
7671 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7672 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7673 MF->insert(It, loopMBB);
7674 MF->insert(It, exitMBB);
7676 // Transfer the remainder of BB and its successor edges to exitMBB.
7677 exitMBB->splice(exitMBB->begin(), BB,
7678 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7679 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7681 // Load an immediate to varEnd.
7682 unsigned varEnd = MRI.createVirtualRegister(TRC);
7683 if (Subtarget->useMovt(*MF)) {
7684 unsigned Vtmp = varEnd;
7685 if ((LoopSize & 0xFFFF0000) != 0)
7686 Vtmp = MRI.createVirtualRegister(TRC);
7687 AddDefaultPred(BuildMI(BB, dl,
7688 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7689 Vtmp).addImm(LoopSize & 0xFFFF));
7691 if ((LoopSize & 0xFFFF0000) != 0)
7692 AddDefaultPred(BuildMI(BB, dl,
7693 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7696 .addImm(LoopSize >> 16));
7698 MachineConstantPool *ConstantPool = MF->getConstantPool();
7699 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7700 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7702 // MachineConstantPool wants an explicit alignment.
7703 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7705 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7706 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7709 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7710 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7712 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7713 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7715 BB->addSuccessor(loopMBB);
7717 // Generate the loop body:
7718 // varPhi = PHI(varLoop, varEnd)
7719 // srcPhi = PHI(srcLoop, src)
7720 // destPhi = PHI(destLoop, dst)
7721 MachineBasicBlock *entryBB = BB;
7723 unsigned varLoop = MRI.createVirtualRegister(TRC);
7724 unsigned varPhi = MRI.createVirtualRegister(TRC);
7725 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7726 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7727 unsigned destLoop = MRI.createVirtualRegister(TRC);
7728 unsigned destPhi = MRI.createVirtualRegister(TRC);
7730 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7731 .addReg(varLoop).addMBB(loopMBB)
7732 .addReg(varEnd).addMBB(entryBB);
7733 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7734 .addReg(srcLoop).addMBB(loopMBB)
7735 .addReg(src).addMBB(entryBB);
7736 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7737 .addReg(destLoop).addMBB(loopMBB)
7738 .addReg(dest).addMBB(entryBB);
7740 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7741 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7742 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7743 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7744 IsThumb1, IsThumb2);
7745 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7746 IsThumb1, IsThumb2);
7748 // Decrement loop variable by UnitSize.
7750 MachineInstrBuilder MIB =
7751 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7752 MIB = AddDefaultT1CC(MIB);
7753 MIB.addReg(varPhi).addImm(UnitSize);
7754 AddDefaultPred(MIB);
7756 MachineInstrBuilder MIB =
7757 BuildMI(*BB, BB->end(), dl,
7758 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7759 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7760 MIB->getOperand(5).setReg(ARM::CPSR);
7761 MIB->getOperand(5).setIsDef(true);
7763 BuildMI(*BB, BB->end(), dl,
7764 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7765 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7767 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7768 BB->addSuccessor(loopMBB);
7769 BB->addSuccessor(exitMBB);
7771 // Add epilogue to handle BytesLeft.
7773 MachineInstr *StartOfExit = exitMBB->begin();
7775 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7776 // [destOut] = STRB_POST(scratch, destLoop, 1)
7777 unsigned srcIn = srcLoop;
7778 unsigned destIn = destLoop;
7779 for (unsigned i = 0; i < BytesLeft; i++) {
7780 unsigned srcOut = MRI.createVirtualRegister(TRC);
7781 unsigned destOut = MRI.createVirtualRegister(TRC);
7782 unsigned scratch = MRI.createVirtualRegister(TRC);
7783 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7784 IsThumb1, IsThumb2);
7785 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7786 IsThumb1, IsThumb2);
7791 MI->eraseFromParent(); // The instruction is gone now.
7796 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7797 MachineBasicBlock *MBB) const {
7798 const TargetMachine &TM = getTargetMachine();
7799 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7800 DebugLoc DL = MI->getDebugLoc();
7802 assert(Subtarget->isTargetWindows() &&
7803 "__chkstk is only supported on Windows");
7804 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7806 // __chkstk takes the number of words to allocate on the stack in R4, and
7807 // returns the stack adjustment in number of bytes in R4. This will not
7808 // clober any other registers (other than the obvious lr).
7810 // Although, technically, IP should be considered a register which may be
7811 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7812 // thumb-2 environment, so there is no interworking required. As a result, we
7813 // do not expect a veneer to be emitted by the linker, clobbering IP.
7815 // Each module receives its own copy of __chkstk, so no import thunk is
7816 // required, again, ensuring that IP is not clobbered.
7818 // Finally, although some linkers may theoretically provide a trampoline for
7819 // out of range calls (which is quite common due to a 32M range limitation of
7820 // branches for Thumb), we can generate the long-call version via
7821 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7824 switch (TM.getCodeModel()) {
7825 case CodeModel::Small:
7826 case CodeModel::Medium:
7827 case CodeModel::Default:
7828 case CodeModel::Kernel:
7829 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7830 .addImm((unsigned)ARMCC::AL).addReg(0)
7831 .addExternalSymbol("__chkstk")
7832 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7833 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7834 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7836 case CodeModel::Large:
7837 case CodeModel::JITDefault: {
7838 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7839 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7841 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7842 .addExternalSymbol("__chkstk");
7843 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7844 .addImm((unsigned)ARMCC::AL).addReg(0)
7845 .addReg(Reg, RegState::Kill)
7846 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7847 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7848 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7853 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7855 .addReg(ARM::SP).addReg(ARM::R4)));
7857 MI->eraseFromParent();
7862 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7863 MachineBasicBlock *MBB) const {
7864 DebugLoc DL = MI->getDebugLoc();
7865 MachineFunction *MF = MBB->getParent();
7866 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7868 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7869 MF->push_back(ContBB);
7870 ContBB->splice(ContBB->begin(), MBB,
7871 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7872 MBB->addSuccessor(ContBB);
7874 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7875 MF->push_back(TrapBB);
7876 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7877 MBB->addSuccessor(TrapBB);
7879 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7880 .addReg(MI->getOperand(0).getReg())
7883 MI->eraseFromParent();
7888 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7889 MachineBasicBlock *BB) const {
7890 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7891 DebugLoc dl = MI->getDebugLoc();
7892 bool isThumb2 = Subtarget->isThumb2();
7893 switch (MI->getOpcode()) {
7896 llvm_unreachable("Unexpected instr type to insert");
7898 // The Thumb2 pre-indexed stores have the same MI operands, they just
7899 // define them differently in the .td files from the isel patterns, so
7900 // they need pseudos.
7901 case ARM::t2STR_preidx:
7902 MI->setDesc(TII->get(ARM::t2STR_PRE));
7904 case ARM::t2STRB_preidx:
7905 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7907 case ARM::t2STRH_preidx:
7908 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7911 case ARM::STRi_preidx:
7912 case ARM::STRBi_preidx: {
7913 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7914 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7915 // Decode the offset.
7916 unsigned Offset = MI->getOperand(4).getImm();
7917 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7918 Offset = ARM_AM::getAM2Offset(Offset);
7922 MachineMemOperand *MMO = *MI->memoperands_begin();
7923 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7924 .addOperand(MI->getOperand(0)) // Rn_wb
7925 .addOperand(MI->getOperand(1)) // Rt
7926 .addOperand(MI->getOperand(2)) // Rn
7927 .addImm(Offset) // offset (skip GPR==zero_reg)
7928 .addOperand(MI->getOperand(5)) // pred
7929 .addOperand(MI->getOperand(6))
7930 .addMemOperand(MMO);
7931 MI->eraseFromParent();
7934 case ARM::STRr_preidx:
7935 case ARM::STRBr_preidx:
7936 case ARM::STRH_preidx: {
7938 switch (MI->getOpcode()) {
7939 default: llvm_unreachable("unexpected opcode!");
7940 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7941 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7942 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7944 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7945 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7946 MIB.addOperand(MI->getOperand(i));
7947 MI->eraseFromParent();
7951 case ARM::tMOVCCr_pseudo: {
7952 // To "insert" a SELECT_CC instruction, we actually have to insert the
7953 // diamond control-flow pattern. The incoming instruction knows the
7954 // destination vreg to set, the condition code register to branch on, the
7955 // true/false values to select between, and a branch opcode to use.
7956 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7957 MachineFunction::iterator It = ++BB->getIterator();
7962 // cmpTY ccX, r1, r2
7964 // fallthrough --> copy0MBB
7965 MachineBasicBlock *thisMBB = BB;
7966 MachineFunction *F = BB->getParent();
7967 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7968 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7969 F->insert(It, copy0MBB);
7970 F->insert(It, sinkMBB);
7972 // Transfer the remainder of BB and its successor edges to sinkMBB.
7973 sinkMBB->splice(sinkMBB->begin(), BB,
7974 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7975 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7977 BB->addSuccessor(copy0MBB);
7978 BB->addSuccessor(sinkMBB);
7980 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7981 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7984 // %FalseValue = ...
7985 // # fallthrough to sinkMBB
7988 // Update machine-CFG edges
7989 BB->addSuccessor(sinkMBB);
7992 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7995 BuildMI(*BB, BB->begin(), dl,
7996 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7997 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7998 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8000 MI->eraseFromParent(); // The pseudo instruction is gone now.
8005 case ARM::BCCZi64: {
8006 // If there is an unconditional branch to the other successor, remove it.
8007 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8009 // Compare both parts that make up the double comparison separately for
8011 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8013 unsigned LHS1 = MI->getOperand(1).getReg();
8014 unsigned LHS2 = MI->getOperand(2).getReg();
8016 AddDefaultPred(BuildMI(BB, dl,
8017 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8018 .addReg(LHS1).addImm(0));
8019 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8020 .addReg(LHS2).addImm(0)
8021 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8023 unsigned RHS1 = MI->getOperand(3).getReg();
8024 unsigned RHS2 = MI->getOperand(4).getReg();
8025 AddDefaultPred(BuildMI(BB, dl,
8026 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8027 .addReg(LHS1).addReg(RHS1));
8028 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8029 .addReg(LHS2).addReg(RHS2)
8030 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8033 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8034 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8035 if (MI->getOperand(0).getImm() == ARMCC::NE)
8036 std::swap(destMBB, exitMBB);
8038 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8039 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8041 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8043 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8045 MI->eraseFromParent(); // The pseudo instruction is gone now.
8049 case ARM::Int_eh_sjlj_setjmp:
8050 case ARM::Int_eh_sjlj_setjmp_nofp:
8051 case ARM::tInt_eh_sjlj_setjmp:
8052 case ARM::t2Int_eh_sjlj_setjmp:
8053 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8056 case ARM::Int_eh_sjlj_setup_dispatch:
8057 EmitSjLjDispatchBlock(MI, BB);
8062 // To insert an ABS instruction, we have to insert the
8063 // diamond control-flow pattern. The incoming instruction knows the
8064 // source vreg to test against 0, the destination vreg to set,
8065 // the condition code register to branch on, the
8066 // true/false values to select between, and a branch opcode to use.
8071 // BCC (branch to SinkBB if V0 >= 0)
8072 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8073 // SinkBB: V1 = PHI(V2, V3)
8074 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8075 MachineFunction::iterator BBI = ++BB->getIterator();
8076 MachineFunction *Fn = BB->getParent();
8077 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8078 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8079 Fn->insert(BBI, RSBBB);
8080 Fn->insert(BBI, SinkBB);
8082 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8083 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8084 bool ABSSrcKIll = MI->getOperand(1).isKill();
8085 bool isThumb2 = Subtarget->isThumb2();
8086 MachineRegisterInfo &MRI = Fn->getRegInfo();
8087 // In Thumb mode S must not be specified if source register is the SP or
8088 // PC and if destination register is the SP, so restrict register class
8089 unsigned NewRsbDstReg =
8090 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8092 // Transfer the remainder of BB and its successor edges to sinkMBB.
8093 SinkBB->splice(SinkBB->begin(), BB,
8094 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8095 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8097 BB->addSuccessor(RSBBB);
8098 BB->addSuccessor(SinkBB);
8100 // fall through to SinkMBB
8101 RSBBB->addSuccessor(SinkBB);
8103 // insert a cmp at the end of BB
8104 AddDefaultPred(BuildMI(BB, dl,
8105 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8106 .addReg(ABSSrcReg).addImm(0));
8108 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8110 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8111 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8113 // insert rsbri in RSBBB
8114 // Note: BCC and rsbri will be converted into predicated rsbmi
8115 // by if-conversion pass
8116 BuildMI(*RSBBB, RSBBB->begin(), dl,
8117 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8118 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8119 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8121 // insert PHI in SinkBB,
8122 // reuse ABSDstReg to not change uses of ABS instruction
8123 BuildMI(*SinkBB, SinkBB->begin(), dl,
8124 TII->get(ARM::PHI), ABSDstReg)
8125 .addReg(NewRsbDstReg).addMBB(RSBBB)
8126 .addReg(ABSSrcReg).addMBB(BB);
8128 // remove ABS instruction
8129 MI->eraseFromParent();
8131 // return last added BB
8134 case ARM::COPY_STRUCT_BYVAL_I32:
8136 return EmitStructByval(MI, BB);
8137 case ARM::WIN__CHKSTK:
8138 return EmitLowered__chkstk(MI, BB);
8139 case ARM::WIN__DBZCHK:
8140 return EmitLowered__dbzchk(MI, BB);
8144 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8145 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8146 /// instead of as a custom inserter because we need the use list from the SDNode.
8147 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8148 MachineInstr *MI, const SDNode *Node) {
8149 bool isThumb1 = Subtarget->isThumb1Only();
8151 DebugLoc DL = MI->getDebugLoc();
8152 MachineFunction *MF = MI->getParent()->getParent();
8153 MachineRegisterInfo &MRI = MF->getRegInfo();
8154 MachineInstrBuilder MIB(*MF, MI);
8156 // If the new dst/src is unused mark it as dead.
8157 if (!Node->hasAnyUseOfValue(0)) {
8158 MI->getOperand(0).setIsDead(true);
8160 if (!Node->hasAnyUseOfValue(1)) {
8161 MI->getOperand(1).setIsDead(true);
8164 // The MEMCPY both defines and kills the scratch registers.
8165 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8166 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8167 : &ARM::GPRRegClass);
8168 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8172 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8173 SDNode *Node) const {
8174 if (MI->getOpcode() == ARM::MEMCPY) {
8175 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8179 const MCInstrDesc *MCID = &MI->getDesc();
8180 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8181 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8182 // operand is still set to noreg. If needed, set the optional operand's
8183 // register to CPSR, and remove the redundant implicit def.
8185 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8187 // Rename pseudo opcodes.
8188 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8190 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8191 MCID = &TII->get(NewOpc);
8193 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8194 "converted opcode should be the same except for cc_out");
8198 // Add the optional cc_out operand
8199 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8201 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8203 // Any ARM instruction that sets the 's' bit should specify an optional
8204 // "cc_out" operand in the last operand position.
8205 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8206 assert(!NewOpc && "Optional cc_out operand required");
8209 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8210 // since we already have an optional CPSR def.
8211 bool definesCPSR = false;
8212 bool deadCPSR = false;
8213 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8215 const MachineOperand &MO = MI->getOperand(i);
8216 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8220 MI->RemoveOperand(i);
8225 assert(!NewOpc && "Optional cc_out operand required");
8228 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8230 assert(!MI->getOperand(ccOutIdx).getReg() &&
8231 "expect uninitialized optional cc_out operand");
8235 // If this instruction was defined with an optional CPSR def and its dag node
8236 // had a live implicit CPSR def, then activate the optional CPSR def.
8237 MachineOperand &MO = MI->getOperand(ccOutIdx);
8238 MO.setReg(ARM::CPSR);
8242 //===----------------------------------------------------------------------===//
8243 // ARM Optimization Hooks
8244 //===----------------------------------------------------------------------===//
8246 // Helper function that checks if N is a null or all ones constant.
8247 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8248 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8251 // Return true if N is conditionally 0 or all ones.
8252 // Detects these expressions where cc is an i1 value:
8254 // (select cc 0, y) [AllOnes=0]
8255 // (select cc y, 0) [AllOnes=0]
8256 // (zext cc) [AllOnes=0]
8257 // (sext cc) [AllOnes=0/1]
8258 // (select cc -1, y) [AllOnes=1]
8259 // (select cc y, -1) [AllOnes=1]
8261 // Invert is set when N is the null/all ones constant when CC is false.
8262 // OtherOp is set to the alternative value of N.
8263 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8264 SDValue &CC, bool &Invert,
8266 SelectionDAG &DAG) {
8267 switch (N->getOpcode()) {
8268 default: return false;
8270 CC = N->getOperand(0);
8271 SDValue N1 = N->getOperand(1);
8272 SDValue N2 = N->getOperand(2);
8273 if (isZeroOrAllOnes(N1, AllOnes)) {
8278 if (isZeroOrAllOnes(N2, AllOnes)) {
8285 case ISD::ZERO_EXTEND:
8286 // (zext cc) can never be the all ones value.
8290 case ISD::SIGN_EXTEND: {
8292 EVT VT = N->getValueType(0);
8293 CC = N->getOperand(0);
8294 if (CC.getValueType() != MVT::i1)
8298 // When looking for an AllOnes constant, N is an sext, and the 'other'
8300 OtherOp = DAG.getConstant(0, dl, VT);
8301 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8302 // When looking for a 0 constant, N can be zext or sext.
8303 OtherOp = DAG.getConstant(1, dl, VT);
8305 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8312 // Combine a constant select operand into its use:
8314 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8315 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8316 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8317 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8318 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8320 // The transform is rejected if the select doesn't have a constant operand that
8321 // is null, or all ones when AllOnes is set.
8323 // Also recognize sext/zext from i1:
8325 // (add (zext cc), x) -> (select cc (add x, 1), x)
8326 // (add (sext cc), x) -> (select cc (add x, -1), x)
8328 // These transformations eventually create predicated instructions.
8330 // @param N The node to transform.
8331 // @param Slct The N operand that is a select.
8332 // @param OtherOp The other N operand (x above).
8333 // @param DCI Context.
8334 // @param AllOnes Require the select constant to be all ones instead of null.
8335 // @returns The new node, or SDValue() on failure.
8337 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8338 TargetLowering::DAGCombinerInfo &DCI,
8339 bool AllOnes = false) {
8340 SelectionDAG &DAG = DCI.DAG;
8341 EVT VT = N->getValueType(0);
8342 SDValue NonConstantVal;
8345 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8346 NonConstantVal, DAG))
8349 // Slct is now know to be the desired identity constant when CC is true.
8350 SDValue TrueVal = OtherOp;
8351 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8352 OtherOp, NonConstantVal);
8353 // Unless SwapSelectOps says CC should be false.
8355 std::swap(TrueVal, FalseVal);
8357 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8358 CCOp, TrueVal, FalseVal);
8361 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8363 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8364 TargetLowering::DAGCombinerInfo &DCI) {
8365 SDValue N0 = N->getOperand(0);
8366 SDValue N1 = N->getOperand(1);
8367 if (N0.getNode()->hasOneUse()) {
8368 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8369 if (Result.getNode())
8372 if (N1.getNode()->hasOneUse()) {
8373 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8374 if (Result.getNode())
8380 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8381 // (only after legalization).
8382 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8383 TargetLowering::DAGCombinerInfo &DCI,
8384 const ARMSubtarget *Subtarget) {
8386 // Only perform optimization if after legalize, and if NEON is available. We
8387 // also expected both operands to be BUILD_VECTORs.
8388 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8389 || N0.getOpcode() != ISD::BUILD_VECTOR
8390 || N1.getOpcode() != ISD::BUILD_VECTOR)
8393 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8394 EVT VT = N->getValueType(0);
8395 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8398 // Check that the vector operands are of the right form.
8399 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8400 // operands, where N is the size of the formed vector.
8401 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8402 // index such that we have a pair wise add pattern.
8404 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8405 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8407 SDValue Vec = N0->getOperand(0)->getOperand(0);
8408 SDNode *V = Vec.getNode();
8409 unsigned nextIndex = 0;
8411 // For each operands to the ADD which are BUILD_VECTORs,
8412 // check to see if each of their operands are an EXTRACT_VECTOR with
8413 // the same vector and appropriate index.
8414 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8415 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8416 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8418 SDValue ExtVec0 = N0->getOperand(i);
8419 SDValue ExtVec1 = N1->getOperand(i);
8421 // First operand is the vector, verify its the same.
8422 if (V != ExtVec0->getOperand(0).getNode() ||
8423 V != ExtVec1->getOperand(0).getNode())
8426 // Second is the constant, verify its correct.
8427 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8428 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8430 // For the constant, we want to see all the even or all the odd.
8431 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8432 || C1->getZExtValue() != nextIndex+1)
8441 // Create VPADDL node.
8442 SelectionDAG &DAG = DCI.DAG;
8443 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8447 // Build operand list.
8448 SmallVector<SDValue, 8> Ops;
8449 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8450 TLI.getPointerTy(DAG.getDataLayout())));
8452 // Input is the vector.
8455 // Get widened type and narrowed type.
8457 unsigned numElem = VT.getVectorNumElements();
8459 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8460 switch (inputLaneType.getSimpleVT().SimpleTy) {
8461 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8462 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8463 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8465 llvm_unreachable("Invalid vector element type for padd optimization.");
8468 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8469 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8470 return DAG.getNode(ExtOp, dl, VT, tmp);
8473 static SDValue findMUL_LOHI(SDValue V) {
8474 if (V->getOpcode() == ISD::UMUL_LOHI ||
8475 V->getOpcode() == ISD::SMUL_LOHI)
8480 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8481 TargetLowering::DAGCombinerInfo &DCI,
8482 const ARMSubtarget *Subtarget) {
8484 if (Subtarget->isThumb1Only()) return SDValue();
8486 // Only perform the checks after legalize when the pattern is available.
8487 if (DCI.isBeforeLegalize()) return SDValue();
8489 // Look for multiply add opportunities.
8490 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8491 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8492 // a glue link from the first add to the second add.
8493 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8494 // a S/UMLAL instruction.
8497 // / \ [no multiline comment]
8503 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8504 SDValue AddcOp0 = AddcNode->getOperand(0);
8505 SDValue AddcOp1 = AddcNode->getOperand(1);
8507 // Check if the two operands are from the same mul_lohi node.
8508 if (AddcOp0.getNode() == AddcOp1.getNode())
8511 assert(AddcNode->getNumValues() == 2 &&
8512 AddcNode->getValueType(0) == MVT::i32 &&
8513 "Expect ADDC with two result values. First: i32");
8515 // Check that we have a glued ADDC node.
8516 if (AddcNode->getValueType(1) != MVT::Glue)
8519 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8520 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8521 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8522 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8523 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8526 // Look for the glued ADDE.
8527 SDNode* AddeNode = AddcNode->getGluedUser();
8531 // Make sure it is really an ADDE.
8532 if (AddeNode->getOpcode() != ISD::ADDE)
8535 assert(AddeNode->getNumOperands() == 3 &&
8536 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8537 "ADDE node has the wrong inputs");
8539 // Check for the triangle shape.
8540 SDValue AddeOp0 = AddeNode->getOperand(0);
8541 SDValue AddeOp1 = AddeNode->getOperand(1);
8543 // Make sure that the ADDE operands are not coming from the same node.
8544 if (AddeOp0.getNode() == AddeOp1.getNode())
8547 // Find the MUL_LOHI node walking up ADDE's operands.
8548 bool IsLeftOperandMUL = false;
8549 SDValue MULOp = findMUL_LOHI(AddeOp0);
8550 if (MULOp == SDValue())
8551 MULOp = findMUL_LOHI(AddeOp1);
8553 IsLeftOperandMUL = true;
8554 if (MULOp == SDValue())
8557 // Figure out the right opcode.
8558 unsigned Opc = MULOp->getOpcode();
8559 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8561 // Figure out the high and low input values to the MLAL node.
8562 SDValue* HiAdd = nullptr;
8563 SDValue* LoMul = nullptr;
8564 SDValue* LowAdd = nullptr;
8566 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8567 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8570 if (IsLeftOperandMUL)
8576 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8577 // whose low result is fed to the ADDC we are checking.
8579 if (AddcOp0 == MULOp.getValue(0)) {
8583 if (AddcOp1 == MULOp.getValue(0)) {
8591 // Create the merged node.
8592 SelectionDAG &DAG = DCI.DAG;
8594 // Build operand list.
8595 SmallVector<SDValue, 8> Ops;
8596 Ops.push_back(LoMul->getOperand(0));
8597 Ops.push_back(LoMul->getOperand(1));
8598 Ops.push_back(*LowAdd);
8599 Ops.push_back(*HiAdd);
8601 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8602 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8604 // Replace the ADDs' nodes uses by the MLA node's values.
8605 SDValue HiMLALResult(MLALNode.getNode(), 1);
8606 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8608 SDValue LoMLALResult(MLALNode.getNode(), 0);
8609 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8611 // Return original node to notify the driver to stop replacing.
8612 SDValue resNode(AddcNode, 0);
8616 /// PerformADDCCombine - Target-specific dag combine transform from
8617 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8618 static SDValue PerformADDCCombine(SDNode *N,
8619 TargetLowering::DAGCombinerInfo &DCI,
8620 const ARMSubtarget *Subtarget) {
8622 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8626 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8627 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8628 /// called with the default operands, and if that fails, with commuted
8630 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8631 TargetLowering::DAGCombinerInfo &DCI,
8632 const ARMSubtarget *Subtarget){
8634 // Attempt to create vpaddl for this add.
8635 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8636 if (Result.getNode())
8639 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8640 if (N0.getNode()->hasOneUse()) {
8641 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8642 if (Result.getNode()) return Result;
8647 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8649 static SDValue PerformADDCombine(SDNode *N,
8650 TargetLowering::DAGCombinerInfo &DCI,
8651 const ARMSubtarget *Subtarget) {
8652 SDValue N0 = N->getOperand(0);
8653 SDValue N1 = N->getOperand(1);
8655 // First try with the default operand order.
8656 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8657 if (Result.getNode())
8660 // If that didn't work, try again with the operands commuted.
8661 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8664 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8666 static SDValue PerformSUBCombine(SDNode *N,
8667 TargetLowering::DAGCombinerInfo &DCI) {
8668 SDValue N0 = N->getOperand(0);
8669 SDValue N1 = N->getOperand(1);
8671 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8672 if (N1.getNode()->hasOneUse()) {
8673 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8674 if (Result.getNode()) return Result;
8680 /// PerformVMULCombine
8681 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8682 /// special multiplier accumulator forwarding.
8688 // However, for (A + B) * (A + B),
8695 static SDValue PerformVMULCombine(SDNode *N,
8696 TargetLowering::DAGCombinerInfo &DCI,
8697 const ARMSubtarget *Subtarget) {
8698 if (!Subtarget->hasVMLxForwarding())
8701 SelectionDAG &DAG = DCI.DAG;
8702 SDValue N0 = N->getOperand(0);
8703 SDValue N1 = N->getOperand(1);
8704 unsigned Opcode = N0.getOpcode();
8705 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8706 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8707 Opcode = N1.getOpcode();
8708 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8709 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8717 EVT VT = N->getValueType(0);
8719 SDValue N00 = N0->getOperand(0);
8720 SDValue N01 = N0->getOperand(1);
8721 return DAG.getNode(Opcode, DL, VT,
8722 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8723 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8726 static SDValue PerformMULCombine(SDNode *N,
8727 TargetLowering::DAGCombinerInfo &DCI,
8728 const ARMSubtarget *Subtarget) {
8729 SelectionDAG &DAG = DCI.DAG;
8731 if (Subtarget->isThumb1Only())
8734 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8737 EVT VT = N->getValueType(0);
8738 if (VT.is64BitVector() || VT.is128BitVector())
8739 return PerformVMULCombine(N, DCI, Subtarget);
8743 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8747 int64_t MulAmt = C->getSExtValue();
8748 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8750 ShiftAmt = ShiftAmt & (32 - 1);
8751 SDValue V = N->getOperand(0);
8755 MulAmt >>= ShiftAmt;
8758 if (isPowerOf2_32(MulAmt - 1)) {
8759 // (mul x, 2^N + 1) => (add (shl x, N), x)
8760 Res = DAG.getNode(ISD::ADD, DL, VT,
8762 DAG.getNode(ISD::SHL, DL, VT,
8764 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8766 } else if (isPowerOf2_32(MulAmt + 1)) {
8767 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8768 Res = DAG.getNode(ISD::SUB, DL, VT,
8769 DAG.getNode(ISD::SHL, DL, VT,
8771 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8777 uint64_t MulAmtAbs = -MulAmt;
8778 if (isPowerOf2_32(MulAmtAbs + 1)) {
8779 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8780 Res = DAG.getNode(ISD::SUB, DL, VT,
8782 DAG.getNode(ISD::SHL, DL, VT,
8784 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8786 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8787 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8788 Res = DAG.getNode(ISD::ADD, DL, VT,
8790 DAG.getNode(ISD::SHL, DL, VT,
8792 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8794 Res = DAG.getNode(ISD::SUB, DL, VT,
8795 DAG.getConstant(0, DL, MVT::i32), Res);
8802 Res = DAG.getNode(ISD::SHL, DL, VT,
8803 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8805 // Do not add new nodes to DAG combiner worklist.
8806 DCI.CombineTo(N, Res, false);
8810 static SDValue PerformANDCombine(SDNode *N,
8811 TargetLowering::DAGCombinerInfo &DCI,
8812 const ARMSubtarget *Subtarget) {
8814 // Attempt to use immediate-form VBIC
8815 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8817 EVT VT = N->getValueType(0);
8818 SelectionDAG &DAG = DCI.DAG;
8820 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8823 APInt SplatBits, SplatUndef;
8824 unsigned SplatBitSize;
8827 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8828 if (SplatBitSize <= 64) {
8830 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8831 SplatUndef.getZExtValue(), SplatBitSize,
8832 DAG, dl, VbicVT, VT.is128BitVector(),
8834 if (Val.getNode()) {
8836 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8837 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8838 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8843 if (!Subtarget->isThumb1Only()) {
8844 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8845 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8846 if (Result.getNode())
8853 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8854 static SDValue PerformORCombine(SDNode *N,
8855 TargetLowering::DAGCombinerInfo &DCI,
8856 const ARMSubtarget *Subtarget) {
8857 // Attempt to use immediate-form VORR
8858 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8860 EVT VT = N->getValueType(0);
8861 SelectionDAG &DAG = DCI.DAG;
8863 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8866 APInt SplatBits, SplatUndef;
8867 unsigned SplatBitSize;
8869 if (BVN && Subtarget->hasNEON() &&
8870 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8871 if (SplatBitSize <= 64) {
8873 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8874 SplatUndef.getZExtValue(), SplatBitSize,
8875 DAG, dl, VorrVT, VT.is128BitVector(),
8877 if (Val.getNode()) {
8879 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8880 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8881 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8886 if (!Subtarget->isThumb1Only()) {
8887 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8888 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8889 if (Result.getNode())
8893 // The code below optimizes (or (and X, Y), Z).
8894 // The AND operand needs to have a single user to make these optimizations
8896 SDValue N0 = N->getOperand(0);
8897 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8899 SDValue N1 = N->getOperand(1);
8901 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8902 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8903 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8905 unsigned SplatBitSize;
8908 APInt SplatBits0, SplatBits1;
8909 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8910 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8911 // Ensure that the second operand of both ands are constants
8912 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8913 HasAnyUndefs) && !HasAnyUndefs) {
8914 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8915 HasAnyUndefs) && !HasAnyUndefs) {
8916 // Ensure that the bit width of the constants are the same and that
8917 // the splat arguments are logical inverses as per the pattern we
8918 // are trying to simplify.
8919 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8920 SplatBits0 == ~SplatBits1) {
8921 // Canonicalize the vector type to make instruction selection
8923 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8924 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8928 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8934 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8937 // BFI is only available on V6T2+
8938 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8942 // 1) or (and A, mask), val => ARMbfi A, val, mask
8943 // iff (val & mask) == val
8945 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8946 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8947 // && mask == ~mask2
8948 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8949 // && ~mask == mask2
8950 // (i.e., copy a bitfield value into another bitfield of the same width)
8955 SDValue N00 = N0.getOperand(0);
8957 // The value and the mask need to be constants so we can verify this is
8958 // actually a bitfield set. If the mask is 0xffff, we can do better
8959 // via a movt instruction, so don't use BFI in that case.
8960 SDValue MaskOp = N0.getOperand(1);
8961 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8964 unsigned Mask = MaskC->getZExtValue();
8968 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8969 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8971 unsigned Val = N1C->getZExtValue();
8972 if ((Val & ~Mask) != Val)
8975 if (ARM::isBitFieldInvertedMask(Mask)) {
8976 Val >>= countTrailingZeros(~Mask);
8978 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8979 DAG.getConstant(Val, DL, MVT::i32),
8980 DAG.getConstant(Mask, DL, MVT::i32));
8982 // Do not add new nodes to DAG combiner worklist.
8983 DCI.CombineTo(N, Res, false);
8986 } else if (N1.getOpcode() == ISD::AND) {
8987 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8988 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8991 unsigned Mask2 = N11C->getZExtValue();
8993 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8995 if (ARM::isBitFieldInvertedMask(Mask) &&
8997 // The pack halfword instruction works better for masks that fit it,
8998 // so use that when it's available.
8999 if (Subtarget->hasT2ExtractPack() &&
9000 (Mask == 0xffff || Mask == 0xffff0000))
9003 unsigned amt = countTrailingZeros(Mask2);
9004 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9005 DAG.getConstant(amt, DL, MVT::i32));
9006 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9007 DAG.getConstant(Mask, DL, MVT::i32));
9008 // Do not add new nodes to DAG combiner worklist.
9009 DCI.CombineTo(N, Res, false);
9011 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9013 // The pack halfword instruction works better for masks that fit it,
9014 // so use that when it's available.
9015 if (Subtarget->hasT2ExtractPack() &&
9016 (Mask2 == 0xffff || Mask2 == 0xffff0000))
9019 unsigned lsb = countTrailingZeros(Mask);
9020 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9021 DAG.getConstant(lsb, DL, MVT::i32));
9022 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9023 DAG.getConstant(Mask2, DL, MVT::i32));
9024 // Do not add new nodes to DAG combiner worklist.
9025 DCI.CombineTo(N, Res, false);
9030 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9031 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9032 ARM::isBitFieldInvertedMask(~Mask)) {
9033 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9034 // where lsb(mask) == #shamt and masked bits of B are known zero.
9035 SDValue ShAmt = N00.getOperand(1);
9036 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9037 unsigned LSB = countTrailingZeros(Mask);
9041 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9042 DAG.getConstant(~Mask, DL, MVT::i32));
9044 // Do not add new nodes to DAG combiner worklist.
9045 DCI.CombineTo(N, Res, false);
9051 static SDValue PerformXORCombine(SDNode *N,
9052 TargetLowering::DAGCombinerInfo &DCI,
9053 const ARMSubtarget *Subtarget) {
9054 EVT VT = N->getValueType(0);
9055 SelectionDAG &DAG = DCI.DAG;
9057 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9060 if (!Subtarget->isThumb1Only()) {
9061 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9062 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9063 if (Result.getNode())
9070 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9071 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9072 // their position in "to" (Rd).
9073 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9074 assert(N->getOpcode() == ARMISD::BFI);
9076 SDValue From = N->getOperand(1);
9077 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9078 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9080 // If the Base came from a SHR #C, we can deduce that it is really testing bit
9081 // #C in the base of the SHR.
9082 if (From->getOpcode() == ISD::SRL &&
9083 isa<ConstantSDNode>(From->getOperand(1))) {
9084 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9085 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9086 FromMask <<= Shift.getLimitedValue(31);
9087 From = From->getOperand(0);
9093 // If A and B contain one contiguous set of bits, does A | B == A . B?
9095 // Neither A nor B must be zero.
9096 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9097 unsigned LastActiveBitInA = A.countTrailingZeros();
9098 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9099 return LastActiveBitInA - 1 == FirstActiveBitInB;
9102 static SDValue FindBFIToCombineWith(SDNode *N) {
9103 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9105 APInt ToMask, FromMask;
9106 SDValue From = ParseBFI(N, ToMask, FromMask);
9107 SDValue To = N->getOperand(0);
9109 // Now check for a compatible BFI to merge with. We can pass through BFIs that
9110 // aren't compatible, but not if they set the same bit in their destination as
9111 // we do (or that of any BFI we're going to combine with).
9113 APInt CombinedToMask = ToMask;
9114 while (V.getOpcode() == ARMISD::BFI) {
9115 APInt NewToMask, NewFromMask;
9116 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9117 if (NewFrom != From) {
9118 // This BFI has a different base. Keep going.
9119 CombinedToMask |= NewToMask;
9120 V = V.getOperand(0);
9124 // Do the written bits conflict with any we've seen so far?
9125 if ((NewToMask & CombinedToMask).getBoolValue())
9126 // Conflicting bits - bail out because going further is unsafe.
9129 // Are the new bits contiguous when combined with the old bits?
9130 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9131 BitsProperlyConcatenate(FromMask, NewFromMask))
9133 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9134 BitsProperlyConcatenate(NewFromMask, FromMask))
9137 // We've seen a write to some bits, so track it.
9138 CombinedToMask |= NewToMask;
9140 V = V.getOperand(0);
9146 static SDValue PerformBFICombine(SDNode *N,
9147 TargetLowering::DAGCombinerInfo &DCI) {
9148 SDValue N1 = N->getOperand(1);
9149 if (N1.getOpcode() == ISD::AND) {
9150 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9151 // the bits being cleared by the AND are not demanded by the BFI.
9152 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9155 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9156 unsigned LSB = countTrailingZeros(~InvMask);
9157 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9159 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9160 "undefined behavior");
9161 unsigned Mask = (1u << Width) - 1;
9162 unsigned Mask2 = N11C->getZExtValue();
9163 if ((Mask & (~Mask2)) == 0)
9164 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9165 N->getOperand(0), N1.getOperand(0),
9167 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9168 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9169 // Keep track of any consecutive bits set that all come from the same base
9170 // value. We can combine these together into a single BFI.
9171 SDValue CombineBFI = FindBFIToCombineWith(N);
9172 if (CombineBFI == SDValue())
9175 // We've found a BFI.
9176 APInt ToMask1, FromMask1;
9177 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9179 APInt ToMask2, FromMask2;
9180 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9181 assert(From1 == From2);
9184 // First, unlink CombineBFI.
9185 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9186 // Then create a new BFI, combining the two together.
9187 APInt NewFromMask = FromMask1 | FromMask2;
9188 APInt NewToMask = ToMask1 | ToMask2;
9190 EVT VT = N->getValueType(0);
9193 if (NewFromMask[0] == 0)
9194 From1 = DCI.DAG.getNode(
9195 ISD::SRL, dl, VT, From1,
9196 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9197 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9198 DCI.DAG.getConstant(~NewToMask, dl, VT));
9203 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9204 /// ARMISD::VMOVRRD.
9205 static SDValue PerformVMOVRRDCombine(SDNode *N,
9206 TargetLowering::DAGCombinerInfo &DCI,
9207 const ARMSubtarget *Subtarget) {
9208 // vmovrrd(vmovdrr x, y) -> x,y
9209 SDValue InDouble = N->getOperand(0);
9210 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9211 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9213 // vmovrrd(load f64) -> (load i32), (load i32)
9214 SDNode *InNode = InDouble.getNode();
9215 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9216 InNode->getValueType(0) == MVT::f64 &&
9217 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9218 !cast<LoadSDNode>(InNode)->isVolatile()) {
9219 // TODO: Should this be done for non-FrameIndex operands?
9220 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9222 SelectionDAG &DAG = DCI.DAG;
9224 SDValue BasePtr = LD->getBasePtr();
9225 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9226 LD->getPointerInfo(), LD->isVolatile(),
9227 LD->isNonTemporal(), LD->isInvariant(),
9228 LD->getAlignment());
9230 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9231 DAG.getConstant(4, DL, MVT::i32));
9232 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9233 LD->getPointerInfo(), LD->isVolatile(),
9234 LD->isNonTemporal(), LD->isInvariant(),
9235 std::min(4U, LD->getAlignment() / 2));
9237 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9238 if (DCI.DAG.getDataLayout().isBigEndian())
9239 std::swap (NewLD1, NewLD2);
9240 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9247 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9248 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9249 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9250 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9251 SDValue Op0 = N->getOperand(0);
9252 SDValue Op1 = N->getOperand(1);
9253 if (Op0.getOpcode() == ISD::BITCAST)
9254 Op0 = Op0.getOperand(0);
9255 if (Op1.getOpcode() == ISD::BITCAST)
9256 Op1 = Op1.getOperand(0);
9257 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9258 Op0.getNode() == Op1.getNode() &&
9259 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9260 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9261 N->getValueType(0), Op0.getOperand(0));
9265 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9266 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9267 /// i64 vector to have f64 elements, since the value can then be loaded
9268 /// directly into a VFP register.
9269 static bool hasNormalLoadOperand(SDNode *N) {
9270 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9271 for (unsigned i = 0; i < NumElts; ++i) {
9272 SDNode *Elt = N->getOperand(i).getNode();
9273 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9279 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9280 /// ISD::BUILD_VECTOR.
9281 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9282 TargetLowering::DAGCombinerInfo &DCI,
9283 const ARMSubtarget *Subtarget) {
9284 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9285 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9286 // into a pair of GPRs, which is fine when the value is used as a scalar,
9287 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9288 SelectionDAG &DAG = DCI.DAG;
9289 if (N->getNumOperands() == 2) {
9290 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9295 // Load i64 elements as f64 values so that type legalization does not split
9296 // them up into i32 values.
9297 EVT VT = N->getValueType(0);
9298 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9301 SmallVector<SDValue, 8> Ops;
9302 unsigned NumElts = VT.getVectorNumElements();
9303 for (unsigned i = 0; i < NumElts; ++i) {
9304 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9306 // Make the DAGCombiner fold the bitcast.
9307 DCI.AddToWorklist(V.getNode());
9309 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9310 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9311 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9314 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9316 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9317 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9318 // At that time, we may have inserted bitcasts from integer to float.
9319 // If these bitcasts have survived DAGCombine, change the lowering of this
9320 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9321 // force to use floating point types.
9323 // Make sure we can change the type of the vector.
9324 // This is possible iff:
9325 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9326 // 1.1. Vector is used only once.
9327 // 1.2. Use is a bit convert to an integer type.
9328 // 2. The size of its operands are 32-bits (64-bits are not legal).
9329 EVT VT = N->getValueType(0);
9330 EVT EltVT = VT.getVectorElementType();
9332 // Check 1.1. and 2.
9333 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9336 // By construction, the input type must be float.
9337 assert(EltVT == MVT::f32 && "Unexpected type!");
9340 SDNode *Use = *N->use_begin();
9341 if (Use->getOpcode() != ISD::BITCAST ||
9342 Use->getValueType(0).isFloatingPoint())
9345 // Check profitability.
9346 // Model is, if more than half of the relevant operands are bitcast from
9347 // i32, turn the build_vector into a sequence of insert_vector_elt.
9348 // Relevant operands are everything that is not statically
9349 // (i.e., at compile time) bitcasted.
9350 unsigned NumOfBitCastedElts = 0;
9351 unsigned NumElts = VT.getVectorNumElements();
9352 unsigned NumOfRelevantElts = NumElts;
9353 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9354 SDValue Elt = N->getOperand(Idx);
9355 if (Elt->getOpcode() == ISD::BITCAST) {
9356 // Assume only bit cast to i32 will go away.
9357 if (Elt->getOperand(0).getValueType() == MVT::i32)
9358 ++NumOfBitCastedElts;
9359 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9360 // Constants are statically casted, thus do not count them as
9361 // relevant operands.
9362 --NumOfRelevantElts;
9365 // Check if more than half of the elements require a non-free bitcast.
9366 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9369 SelectionDAG &DAG = DCI.DAG;
9370 // Create the new vector type.
9371 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9372 // Check if the type is legal.
9373 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9374 if (!TLI.isTypeLegal(VecVT))
9378 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9379 // => BITCAST INSERT_VECTOR_ELT
9380 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9382 SDValue Vec = DAG.getUNDEF(VecVT);
9384 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9385 SDValue V = N->getOperand(Idx);
9386 if (V.getOpcode() == ISD::UNDEF)
9388 if (V.getOpcode() == ISD::BITCAST &&
9389 V->getOperand(0).getValueType() == MVT::i32)
9390 // Fold obvious case.
9391 V = V.getOperand(0);
9393 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9394 // Make the DAGCombiner fold the bitcasts.
9395 DCI.AddToWorklist(V.getNode());
9397 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9398 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9400 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9401 // Make the DAGCombiner fold the bitcasts.
9402 DCI.AddToWorklist(Vec.getNode());
9406 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9407 /// ISD::INSERT_VECTOR_ELT.
9408 static SDValue PerformInsertEltCombine(SDNode *N,
9409 TargetLowering::DAGCombinerInfo &DCI) {
9410 // Bitcast an i64 load inserted into a vector to f64.
9411 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9412 EVT VT = N->getValueType(0);
9413 SDNode *Elt = N->getOperand(1).getNode();
9414 if (VT.getVectorElementType() != MVT::i64 ||
9415 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9418 SelectionDAG &DAG = DCI.DAG;
9420 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9421 VT.getVectorNumElements());
9422 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9423 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9424 // Make the DAGCombiner fold the bitcasts.
9425 DCI.AddToWorklist(Vec.getNode());
9426 DCI.AddToWorklist(V.getNode());
9427 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9428 Vec, V, N->getOperand(2));
9429 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9432 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9433 /// ISD::VECTOR_SHUFFLE.
9434 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9435 // The LLVM shufflevector instruction does not require the shuffle mask
9436 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9437 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9438 // operands do not match the mask length, they are extended by concatenating
9439 // them with undef vectors. That is probably the right thing for other
9440 // targets, but for NEON it is better to concatenate two double-register
9441 // size vector operands into a single quad-register size vector. Do that
9442 // transformation here:
9443 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9444 // shuffle(concat(v1, v2), undef)
9445 SDValue Op0 = N->getOperand(0);
9446 SDValue Op1 = N->getOperand(1);
9447 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9448 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9449 Op0.getNumOperands() != 2 ||
9450 Op1.getNumOperands() != 2)
9452 SDValue Concat0Op1 = Op0.getOperand(1);
9453 SDValue Concat1Op1 = Op1.getOperand(1);
9454 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9455 Concat1Op1.getOpcode() != ISD::UNDEF)
9457 // Skip the transformation if any of the types are illegal.
9458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9459 EVT VT = N->getValueType(0);
9460 if (!TLI.isTypeLegal(VT) ||
9461 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9462 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9465 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9466 Op0.getOperand(0), Op1.getOperand(0));
9467 // Translate the shuffle mask.
9468 SmallVector<int, 16> NewMask;
9469 unsigned NumElts = VT.getVectorNumElements();
9470 unsigned HalfElts = NumElts/2;
9471 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9472 for (unsigned n = 0; n < NumElts; ++n) {
9473 int MaskElt = SVN->getMaskElt(n);
9475 if (MaskElt < (int)HalfElts)
9477 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9478 NewElt = HalfElts + MaskElt - NumElts;
9479 NewMask.push_back(NewElt);
9481 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9482 DAG.getUNDEF(VT), NewMask.data());
9485 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9486 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9487 /// base address updates.
9488 /// For generic load/stores, the memory type is assumed to be a vector.
9489 /// The caller is assumed to have checked legality.
9490 static SDValue CombineBaseUpdate(SDNode *N,
9491 TargetLowering::DAGCombinerInfo &DCI) {
9492 SelectionDAG &DAG = DCI.DAG;
9493 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9494 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9495 const bool isStore = N->getOpcode() == ISD::STORE;
9496 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9497 SDValue Addr = N->getOperand(AddrOpIdx);
9498 MemSDNode *MemN = cast<MemSDNode>(N);
9501 // Search for a use of the address operand that is an increment.
9502 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9503 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9505 if (User->getOpcode() != ISD::ADD ||
9506 UI.getUse().getResNo() != Addr.getResNo())
9509 // Check that the add is independent of the load/store. Otherwise, folding
9510 // it would create a cycle.
9511 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9514 // Find the new opcode for the updating load/store.
9515 bool isLoadOp = true;
9516 bool isLaneOp = false;
9517 unsigned NewOpc = 0;
9518 unsigned NumVecs = 0;
9520 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9522 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9523 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9525 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9527 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9529 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9531 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9532 NumVecs = 2; isLaneOp = true; break;
9533 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9534 NumVecs = 3; isLaneOp = true; break;
9535 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9536 NumVecs = 4; isLaneOp = true; break;
9537 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9538 NumVecs = 1; isLoadOp = false; break;
9539 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9540 NumVecs = 2; isLoadOp = false; break;
9541 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9542 NumVecs = 3; isLoadOp = false; break;
9543 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9544 NumVecs = 4; isLoadOp = false; break;
9545 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9546 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9547 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9548 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9549 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9550 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9554 switch (N->getOpcode()) {
9555 default: llvm_unreachable("unexpected opcode for Neon base update");
9556 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9557 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9558 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9559 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9560 NumVecs = 1; isLaneOp = false; break;
9561 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9562 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9566 // Find the size of memory referenced by the load/store.
9569 VecTy = N->getValueType(0);
9570 } else if (isIntrinsic) {
9571 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9573 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9574 VecTy = N->getOperand(1).getValueType();
9577 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9579 NumBytes /= VecTy.getVectorNumElements();
9581 // If the increment is a constant, it must match the memory ref size.
9582 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9583 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9584 uint64_t IncVal = CInc->getZExtValue();
9585 if (IncVal != NumBytes)
9587 } else if (NumBytes >= 3 * 16) {
9588 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9589 // separate instructions that make it harder to use a non-constant update.
9593 // OK, we found an ADD we can fold into the base update.
9594 // Now, create a _UPD node, taking care of not breaking alignment.
9596 EVT AlignedVecTy = VecTy;
9597 unsigned Alignment = MemN->getAlignment();
9599 // If this is a less-than-standard-aligned load/store, change the type to
9600 // match the standard alignment.
9601 // The alignment is overlooked when selecting _UPD variants; and it's
9602 // easier to introduce bitcasts here than fix that.
9603 // There are 3 ways to get to this base-update combine:
9604 // - intrinsics: they are assumed to be properly aligned (to the standard
9605 // alignment of the memory type), so we don't need to do anything.
9606 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9607 // intrinsics, so, likewise, there's nothing to do.
9608 // - generic load/store instructions: the alignment is specified as an
9609 // explicit operand, rather than implicitly as the standard alignment
9610 // of the memory type (like the intrisics). We need to change the
9611 // memory type to match the explicit alignment. That way, we don't
9612 // generate non-standard-aligned ARMISD::VLDx nodes.
9613 if (isa<LSBaseSDNode>(N)) {
9616 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9617 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9618 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9619 assert(!isLaneOp && "Unexpected generic load/store lane.");
9620 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9621 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9623 // Don't set an explicit alignment on regular load/stores that we want
9624 // to transform to VLD/VST 1_UPD nodes.
9625 // This matches the behavior of regular load/stores, which only get an
9626 // explicit alignment if the MMO alignment is larger than the standard
9627 // alignment of the memory type.
9628 // Intrinsics, however, always get an explicit alignment, set to the
9629 // alignment of the MMO.
9633 // Create the new updating load/store node.
9634 // First, create an SDVTList for the new updating node's results.
9636 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9638 for (n = 0; n < NumResultVecs; ++n)
9639 Tys[n] = AlignedVecTy;
9640 Tys[n++] = MVT::i32;
9641 Tys[n] = MVT::Other;
9642 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9644 // Then, gather the new node's operands.
9645 SmallVector<SDValue, 8> Ops;
9646 Ops.push_back(N->getOperand(0)); // incoming chain
9647 Ops.push_back(N->getOperand(AddrOpIdx));
9650 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9651 // Try to match the intrinsic's signature
9652 Ops.push_back(StN->getValue());
9654 // Loads (and of course intrinsics) match the intrinsics' signature,
9655 // so just add all but the alignment operand.
9656 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9657 Ops.push_back(N->getOperand(i));
9660 // For all node types, the alignment operand is always the last one.
9661 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9663 // If this is a non-standard-aligned STORE, the penultimate operand is the
9664 // stored value. Bitcast it to the aligned type.
9665 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9666 SDValue &StVal = Ops[Ops.size()-2];
9667 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9670 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9672 MemN->getMemOperand());
9675 SmallVector<SDValue, 5> NewResults;
9676 for (unsigned i = 0; i < NumResultVecs; ++i)
9677 NewResults.push_back(SDValue(UpdN.getNode(), i));
9679 // If this is an non-standard-aligned LOAD, the first result is the loaded
9680 // value. Bitcast it to the expected result type.
9681 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9682 SDValue &LdVal = NewResults[0];
9683 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9686 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9687 DCI.CombineTo(N, NewResults);
9688 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9695 static SDValue PerformVLDCombine(SDNode *N,
9696 TargetLowering::DAGCombinerInfo &DCI) {
9697 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9700 return CombineBaseUpdate(N, DCI);
9703 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9704 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9705 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9707 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9708 SelectionDAG &DAG = DCI.DAG;
9709 EVT VT = N->getValueType(0);
9710 // vldN-dup instructions only support 64-bit vectors for N > 1.
9711 if (!VT.is64BitVector())
9714 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9715 SDNode *VLD = N->getOperand(0).getNode();
9716 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9718 unsigned NumVecs = 0;
9719 unsigned NewOpc = 0;
9720 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9721 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9723 NewOpc = ARMISD::VLD2DUP;
9724 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9726 NewOpc = ARMISD::VLD3DUP;
9727 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9729 NewOpc = ARMISD::VLD4DUP;
9734 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9735 // numbers match the load.
9736 unsigned VLDLaneNo =
9737 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9738 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9740 // Ignore uses of the chain result.
9741 if (UI.getUse().getResNo() == NumVecs)
9744 if (User->getOpcode() != ARMISD::VDUPLANE ||
9745 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9749 // Create the vldN-dup node.
9752 for (n = 0; n < NumVecs; ++n)
9754 Tys[n] = MVT::Other;
9755 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9756 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9757 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9758 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9759 Ops, VLDMemInt->getMemoryVT(),
9760 VLDMemInt->getMemOperand());
9763 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9765 unsigned ResNo = UI.getUse().getResNo();
9766 // Ignore uses of the chain result.
9767 if (ResNo == NumVecs)
9770 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9773 // Now the vldN-lane intrinsic is dead except for its chain result.
9774 // Update uses of the chain.
9775 std::vector<SDValue> VLDDupResults;
9776 for (unsigned n = 0; n < NumVecs; ++n)
9777 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9778 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9779 DCI.CombineTo(VLD, VLDDupResults);
9784 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9785 /// ARMISD::VDUPLANE.
9786 static SDValue PerformVDUPLANECombine(SDNode *N,
9787 TargetLowering::DAGCombinerInfo &DCI) {
9788 SDValue Op = N->getOperand(0);
9790 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9791 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9792 if (CombineVLDDUP(N, DCI))
9793 return SDValue(N, 0);
9795 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9796 // redundant. Ignore bit_converts for now; element sizes are checked below.
9797 while (Op.getOpcode() == ISD::BITCAST)
9798 Op = Op.getOperand(0);
9799 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9802 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9803 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9804 // The canonical VMOV for a zero vector uses a 32-bit element size.
9805 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9807 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9809 EVT VT = N->getValueType(0);
9810 if (EltSize > VT.getVectorElementType().getSizeInBits())
9813 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9816 static SDValue PerformLOADCombine(SDNode *N,
9817 TargetLowering::DAGCombinerInfo &DCI) {
9818 EVT VT = N->getValueType(0);
9820 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9821 if (ISD::isNormalLoad(N) && VT.isVector() &&
9822 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9823 return CombineBaseUpdate(N, DCI);
9828 /// PerformSTORECombine - Target-specific dag combine xforms for
9830 static SDValue PerformSTORECombine(SDNode *N,
9831 TargetLowering::DAGCombinerInfo &DCI) {
9832 StoreSDNode *St = cast<StoreSDNode>(N);
9833 if (St->isVolatile())
9836 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9837 // pack all of the elements in one place. Next, store to memory in fewer
9839 SDValue StVal = St->getValue();
9840 EVT VT = StVal.getValueType();
9841 if (St->isTruncatingStore() && VT.isVector()) {
9842 SelectionDAG &DAG = DCI.DAG;
9843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9844 EVT StVT = St->getMemoryVT();
9845 unsigned NumElems = VT.getVectorNumElements();
9846 assert(StVT != VT && "Cannot truncate to the same type");
9847 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9848 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9850 // From, To sizes and ElemCount must be pow of two
9851 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9853 // We are going to use the original vector elt for storing.
9854 // Accumulated smaller vector elements must be a multiple of the store size.
9855 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9857 unsigned SizeRatio = FromEltSz / ToEltSz;
9858 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9860 // Create a type on which we perform the shuffle.
9861 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9862 NumElems*SizeRatio);
9863 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9866 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9867 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9868 for (unsigned i = 0; i < NumElems; ++i)
9869 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9870 ? (i + 1) * SizeRatio - 1
9873 // Can't shuffle using an illegal type.
9874 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9876 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9877 DAG.getUNDEF(WideVec.getValueType()),
9879 // At this point all of the data is stored at the bottom of the
9880 // register. We now need to save it to mem.
9882 // Find the largest store unit
9883 MVT StoreType = MVT::i8;
9884 for (MVT Tp : MVT::integer_valuetypes()) {
9885 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9888 // Didn't find a legal store type.
9889 if (!TLI.isTypeLegal(StoreType))
9892 // Bitcast the original vector into a vector of store-size units
9893 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9894 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9895 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9896 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9897 SmallVector<SDValue, 8> Chains;
9898 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9899 TLI.getPointerTy(DAG.getDataLayout()));
9900 SDValue BasePtr = St->getBasePtr();
9902 // Perform one or more big stores into memory.
9903 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9904 for (unsigned I = 0; I < E; I++) {
9905 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9906 StoreType, ShuffWide,
9907 DAG.getIntPtrConstant(I, DL));
9908 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9909 St->getPointerInfo(), St->isVolatile(),
9910 St->isNonTemporal(), St->getAlignment());
9911 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9913 Chains.push_back(Ch);
9915 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9918 if (!ISD::isNormalStore(St))
9921 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9922 // ARM stores of arguments in the same cache line.
9923 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9924 StVal.getNode()->hasOneUse()) {
9925 SelectionDAG &DAG = DCI.DAG;
9926 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9928 SDValue BasePtr = St->getBasePtr();
9929 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9930 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9931 BasePtr, St->getPointerInfo(), St->isVolatile(),
9932 St->isNonTemporal(), St->getAlignment());
9934 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9935 DAG.getConstant(4, DL, MVT::i32));
9936 return DAG.getStore(NewST1.getValue(0), DL,
9937 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9938 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9939 St->isNonTemporal(),
9940 std::min(4U, St->getAlignment() / 2));
9943 if (StVal.getValueType() == MVT::i64 &&
9944 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9946 // Bitcast an i64 store extracted from a vector to f64.
9947 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9948 SelectionDAG &DAG = DCI.DAG;
9950 SDValue IntVec = StVal.getOperand(0);
9951 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9952 IntVec.getValueType().getVectorNumElements());
9953 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9954 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9955 Vec, StVal.getOperand(1));
9957 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9958 // Make the DAGCombiner fold the bitcasts.
9959 DCI.AddToWorklist(Vec.getNode());
9960 DCI.AddToWorklist(ExtElt.getNode());
9961 DCI.AddToWorklist(V.getNode());
9962 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9963 St->getPointerInfo(), St->isVolatile(),
9964 St->isNonTemporal(), St->getAlignment(),
9968 // If this is a legal vector store, try to combine it into a VST1_UPD.
9969 if (ISD::isNormalStore(N) && VT.isVector() &&
9970 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9971 return CombineBaseUpdate(N, DCI);
9976 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9977 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9978 /// when the VMUL has a constant operand that is a power of 2.
9980 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9981 /// vmul.f32 d16, d17, d16
9982 /// vcvt.s32.f32 d16, d16
9984 /// vcvt.s32.f32 d16, d16, #3
9985 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9986 const ARMSubtarget *Subtarget) {
9987 if (!Subtarget->hasNEON())
9990 SDValue Op = N->getOperand(0);
9991 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9994 SDValue ConstVec = Op->getOperand(1);
9995 if (!isa<BuildVectorSDNode>(ConstVec))
9998 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9999 uint32_t FloatBits = FloatTy.getSizeInBits();
10000 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10001 uint32_t IntBits = IntTy.getSizeInBits();
10002 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10003 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10004 // These instructions only exist converting from f32 to i32. We can handle
10005 // smaller integers by generating an extra truncate, but larger ones would
10006 // be lossy. We also can't handle more then 4 lanes, since these intructions
10007 // only support v2i32/v4i32 types.
10011 BitVector UndefElements;
10012 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10013 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10014 if (C == -1 || C == 0 || C > 32)
10018 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10019 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10020 Intrinsic::arm_neon_vcvtfp2fxu;
10021 SDValue FixConv = DAG.getNode(
10022 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10023 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10024 DAG.getConstant(C, dl, MVT::i32));
10026 if (IntBits < FloatBits)
10027 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10032 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10033 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10034 /// when the VDIV has a constant operand that is a power of 2.
10036 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10037 /// vcvt.f32.s32 d16, d16
10038 /// vdiv.f32 d16, d17, d16
10040 /// vcvt.f32.s32 d16, d16, #3
10041 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10042 const ARMSubtarget *Subtarget) {
10043 if (!Subtarget->hasNEON())
10046 SDValue Op = N->getOperand(0);
10047 unsigned OpOpcode = Op.getNode()->getOpcode();
10048 if (!N->getValueType(0).isVector() ||
10049 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10052 SDValue ConstVec = N->getOperand(1);
10053 if (!isa<BuildVectorSDNode>(ConstVec))
10056 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10057 uint32_t FloatBits = FloatTy.getSizeInBits();
10058 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10059 uint32_t IntBits = IntTy.getSizeInBits();
10060 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10061 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10062 // These instructions only exist converting from i32 to f32. We can handle
10063 // smaller integers by generating an extra extend, but larger ones would
10064 // be lossy. We also can't handle more then 4 lanes, since these intructions
10065 // only support v2i32/v4i32 types.
10069 BitVector UndefElements;
10070 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10071 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10072 if (C == -1 || C == 0 || C > 32)
10076 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10077 SDValue ConvInput = Op.getOperand(0);
10078 if (IntBits < FloatBits)
10079 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10080 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10083 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10084 Intrinsic::arm_neon_vcvtfxu2fp;
10085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10087 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10088 ConvInput, DAG.getConstant(C, dl, MVT::i32));
10091 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10092 /// operand of a vector shift operation, where all the elements of the
10093 /// build_vector must have the same constant integer value.
10094 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10095 // Ignore bit_converts.
10096 while (Op.getOpcode() == ISD::BITCAST)
10097 Op = Op.getOperand(0);
10098 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10099 APInt SplatBits, SplatUndef;
10100 unsigned SplatBitSize;
10102 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10103 HasAnyUndefs, ElementBits) ||
10104 SplatBitSize > ElementBits)
10106 Cnt = SplatBits.getSExtValue();
10110 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10111 /// operand of a vector shift left operation. That value must be in the range:
10112 /// 0 <= Value < ElementBits for a left shift; or
10113 /// 0 <= Value <= ElementBits for a long left shift.
10114 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10115 assert(VT.isVector() && "vector shift count is not a vector type");
10116 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10117 if (! getVShiftImm(Op, ElementBits, Cnt))
10119 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10122 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10123 /// operand of a vector shift right operation. For a shift opcode, the value
10124 /// is positive, but for an intrinsic the value count must be negative. The
10125 /// absolute value must be in the range:
10126 /// 1 <= |Value| <= ElementBits for a right shift; or
10127 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
10128 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10130 assert(VT.isVector() && "vector shift count is not a vector type");
10131 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10132 if (! getVShiftImm(Op, ElementBits, Cnt))
10135 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10136 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10143 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10144 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10145 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10148 // Don't do anything for most intrinsics.
10151 case Intrinsic::arm_neon_vabds:
10152 if (!N->getValueType(0).isInteger())
10154 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
10155 N->getOperand(1), N->getOperand(2));
10156 case Intrinsic::arm_neon_vabdu:
10157 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10158 N->getOperand(1), N->getOperand(2));
10160 // Vector shifts: check for immediate versions and lower them.
10161 // Note: This is done during DAG combining instead of DAG legalizing because
10162 // the build_vectors for 64-bit vector element shift counts are generally
10163 // not legal, and it is hard to see their values after they get legalized to
10164 // loads from a constant pool.
10165 case Intrinsic::arm_neon_vshifts:
10166 case Intrinsic::arm_neon_vshiftu:
10167 case Intrinsic::arm_neon_vrshifts:
10168 case Intrinsic::arm_neon_vrshiftu:
10169 case Intrinsic::arm_neon_vrshiftn:
10170 case Intrinsic::arm_neon_vqshifts:
10171 case Intrinsic::arm_neon_vqshiftu:
10172 case Intrinsic::arm_neon_vqshiftsu:
10173 case Intrinsic::arm_neon_vqshiftns:
10174 case Intrinsic::arm_neon_vqshiftnu:
10175 case Intrinsic::arm_neon_vqshiftnsu:
10176 case Intrinsic::arm_neon_vqrshiftns:
10177 case Intrinsic::arm_neon_vqrshiftnu:
10178 case Intrinsic::arm_neon_vqrshiftnsu: {
10179 EVT VT = N->getOperand(1).getValueType();
10181 unsigned VShiftOpc = 0;
10184 case Intrinsic::arm_neon_vshifts:
10185 case Intrinsic::arm_neon_vshiftu:
10186 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10187 VShiftOpc = ARMISD::VSHL;
10190 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10191 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10192 ARMISD::VSHRs : ARMISD::VSHRu);
10197 case Intrinsic::arm_neon_vrshifts:
10198 case Intrinsic::arm_neon_vrshiftu:
10199 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10203 case Intrinsic::arm_neon_vqshifts:
10204 case Intrinsic::arm_neon_vqshiftu:
10205 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10209 case Intrinsic::arm_neon_vqshiftsu:
10210 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10212 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10214 case Intrinsic::arm_neon_vrshiftn:
10215 case Intrinsic::arm_neon_vqshiftns:
10216 case Intrinsic::arm_neon_vqshiftnu:
10217 case Intrinsic::arm_neon_vqshiftnsu:
10218 case Intrinsic::arm_neon_vqrshiftns:
10219 case Intrinsic::arm_neon_vqrshiftnu:
10220 case Intrinsic::arm_neon_vqrshiftnsu:
10221 // Narrowing shifts require an immediate right shift.
10222 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10224 llvm_unreachable("invalid shift count for narrowing vector shift "
10228 llvm_unreachable("unhandled vector shift");
10232 case Intrinsic::arm_neon_vshifts:
10233 case Intrinsic::arm_neon_vshiftu:
10234 // Opcode already set above.
10236 case Intrinsic::arm_neon_vrshifts:
10237 VShiftOpc = ARMISD::VRSHRs; break;
10238 case Intrinsic::arm_neon_vrshiftu:
10239 VShiftOpc = ARMISD::VRSHRu; break;
10240 case Intrinsic::arm_neon_vrshiftn:
10241 VShiftOpc = ARMISD::VRSHRN; break;
10242 case Intrinsic::arm_neon_vqshifts:
10243 VShiftOpc = ARMISD::VQSHLs; break;
10244 case Intrinsic::arm_neon_vqshiftu:
10245 VShiftOpc = ARMISD::VQSHLu; break;
10246 case Intrinsic::arm_neon_vqshiftsu:
10247 VShiftOpc = ARMISD::VQSHLsu; break;
10248 case Intrinsic::arm_neon_vqshiftns:
10249 VShiftOpc = ARMISD::VQSHRNs; break;
10250 case Intrinsic::arm_neon_vqshiftnu:
10251 VShiftOpc = ARMISD::VQSHRNu; break;
10252 case Intrinsic::arm_neon_vqshiftnsu:
10253 VShiftOpc = ARMISD::VQSHRNsu; break;
10254 case Intrinsic::arm_neon_vqrshiftns:
10255 VShiftOpc = ARMISD::VQRSHRNs; break;
10256 case Intrinsic::arm_neon_vqrshiftnu:
10257 VShiftOpc = ARMISD::VQRSHRNu; break;
10258 case Intrinsic::arm_neon_vqrshiftnsu:
10259 VShiftOpc = ARMISD::VQRSHRNsu; break;
10263 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10264 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10267 case Intrinsic::arm_neon_vshiftins: {
10268 EVT VT = N->getOperand(1).getValueType();
10270 unsigned VShiftOpc = 0;
10272 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10273 VShiftOpc = ARMISD::VSLI;
10274 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10275 VShiftOpc = ARMISD::VSRI;
10277 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10281 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10282 N->getOperand(1), N->getOperand(2),
10283 DAG.getConstant(Cnt, dl, MVT::i32));
10286 case Intrinsic::arm_neon_vqrshifts:
10287 case Intrinsic::arm_neon_vqrshiftu:
10288 // No immediate versions of these to check for.
10295 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10296 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10297 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10298 /// vector element shift counts are generally not legal, and it is hard to see
10299 /// their values after they get legalized to loads from a constant pool.
10300 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10301 const ARMSubtarget *ST) {
10302 EVT VT = N->getValueType(0);
10303 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10304 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10305 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10306 SDValue N1 = N->getOperand(1);
10307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10308 SDValue N0 = N->getOperand(0);
10309 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10310 DAG.MaskedValueIsZero(N0.getOperand(0),
10311 APInt::getHighBitsSet(32, 16)))
10312 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10316 // Nothing to be done for scalar shifts.
10317 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10318 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10321 assert(ST->hasNEON() && "unexpected vector shift");
10324 switch (N->getOpcode()) {
10325 default: llvm_unreachable("unexpected shift opcode");
10328 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10330 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10331 DAG.getConstant(Cnt, dl, MVT::i32));
10337 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10338 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10339 ARMISD::VSHRs : ARMISD::VSHRu);
10341 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10342 DAG.getConstant(Cnt, dl, MVT::i32));
10348 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10349 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10350 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10351 const ARMSubtarget *ST) {
10352 SDValue N0 = N->getOperand(0);
10354 // Check for sign- and zero-extensions of vector extract operations of 8-
10355 // and 16-bit vector elements. NEON supports these directly. They are
10356 // handled during DAG combining because type legalization will promote them
10357 // to 32-bit types and it is messy to recognize the operations after that.
10358 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10359 SDValue Vec = N0.getOperand(0);
10360 SDValue Lane = N0.getOperand(1);
10361 EVT VT = N->getValueType(0);
10362 EVT EltVT = N0.getValueType();
10363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10365 if (VT == MVT::i32 &&
10366 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10367 TLI.isTypeLegal(Vec.getValueType()) &&
10368 isa<ConstantSDNode>(Lane)) {
10371 switch (N->getOpcode()) {
10372 default: llvm_unreachable("unexpected opcode");
10373 case ISD::SIGN_EXTEND:
10374 Opc = ARMISD::VGETLANEs;
10376 case ISD::ZERO_EXTEND:
10377 case ISD::ANY_EXTEND:
10378 Opc = ARMISD::VGETLANEu;
10381 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10388 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10390 if (Op.getOpcode() == ARMISD::BFI) {
10391 // Conservatively, we can recurse down the first operand
10392 // and just mask out all affected bits.
10393 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10395 // The operand to BFI is already a mask suitable for removing the bits it
10397 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10398 APInt Mask = CI->getAPIntValue();
10403 if (Op.getOpcode() == ARMISD::CMOV) {
10404 APInt KZ2(KnownZero.getBitWidth(), 0);
10405 APInt KO2(KnownOne.getBitWidth(), 0);
10406 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10407 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10413 return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10416 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10417 // If we have a CMOV, OR and AND combination such as:
10422 // * CN is a single bit;
10423 // * All bits covered by CM are known zero in y
10425 // Then we can convert this into a sequence of BFI instructions. This will
10426 // always be a win if CM is a single bit, will always be no worse than the
10427 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10428 // three bits (due to the extra IT instruction).
10430 SDValue Op0 = CMOV->getOperand(0);
10431 SDValue Op1 = CMOV->getOperand(1);
10432 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10433 auto CC = CCNode->getAPIntValue().getLimitedValue();
10434 SDValue CmpZ = CMOV->getOperand(4);
10436 // The compare must be against zero.
10437 if (!isNullConstant(CmpZ->getOperand(1)))
10440 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10441 SDValue And = CmpZ->getOperand(0);
10442 if (And->getOpcode() != ISD::AND)
10444 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10445 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10447 SDValue X = And->getOperand(0);
10449 if (CC == ARMCC::EQ) {
10450 // We're performing an "equal to zero" compare. Swap the operands so we
10451 // canonicalize on a "not equal to zero" compare.
10452 std::swap(Op0, Op1);
10454 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10457 if (Op1->getOpcode() != ISD::OR)
10460 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10463 SDValue Y = Op1->getOperand(0);
10468 // Now, is it profitable to continue?
10469 APInt OrCI = OrC->getAPIntValue();
10470 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10471 if (OrCI.countPopulation() > Heuristic)
10474 // Lastly, can we determine that the bits defined by OrCI
10476 APInt KnownZero, KnownOne;
10477 computeKnownBits(DAG, Y, KnownZero, KnownOne);
10478 if ((OrCI & KnownZero) != OrCI)
10481 // OK, we can do the combine.
10484 EVT VT = X.getValueType();
10485 unsigned BitInX = AndC->getAPIntValue().logBase2();
10488 // We must shift X first.
10489 X = DAG.getNode(ISD::SRL, dl, VT, X,
10490 DAG.getConstant(BitInX, dl, VT));
10493 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10494 BitInY < NumActiveBits; ++BitInY) {
10495 if (OrCI[BitInY] == 0)
10497 APInt Mask(VT.getSizeInBits(), 0);
10498 Mask.setBit(BitInY);
10499 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10500 // Confusingly, the operand is an *inverted* mask.
10501 DAG.getConstant(~Mask, dl, VT));
10507 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10509 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10510 SDValue Cmp = N->getOperand(4);
10511 if (Cmp.getOpcode() != ARMISD::CMPZ)
10512 // Only looking at EQ and NE cases.
10515 EVT VT = N->getValueType(0);
10517 SDValue LHS = Cmp.getOperand(0);
10518 SDValue RHS = Cmp.getOperand(1);
10519 SDValue FalseVal = N->getOperand(0);
10520 SDValue TrueVal = N->getOperand(1);
10521 SDValue ARMcc = N->getOperand(2);
10522 ARMCC::CondCodes CC =
10523 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10525 // BFI is only available on V6T2+.
10526 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10527 SDValue R = PerformCMOVToBFICombine(N, DAG);
10548 /// FIXME: Turn this into a target neutral optimization?
10550 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10551 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10552 N->getOperand(3), Cmp);
10553 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10555 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10556 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10557 N->getOperand(3), NewCmp);
10560 if (Res.getNode()) {
10561 APInt KnownZero, KnownOne;
10562 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10563 // Capture demanded bits information that would be otherwise lost.
10564 if (KnownZero == 0xfffffffe)
10565 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10566 DAG.getValueType(MVT::i1));
10567 else if (KnownZero == 0xffffff00)
10568 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10569 DAG.getValueType(MVT::i8));
10570 else if (KnownZero == 0xffff0000)
10571 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10572 DAG.getValueType(MVT::i16));
10578 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10579 DAGCombinerInfo &DCI) const {
10580 switch (N->getOpcode()) {
10582 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10583 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10584 case ISD::SUB: return PerformSUBCombine(N, DCI);
10585 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10586 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10587 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10588 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10589 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10590 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10591 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10592 case ISD::STORE: return PerformSTORECombine(N, DCI);
10593 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10594 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10595 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10596 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10597 case ISD::FP_TO_SINT:
10598 case ISD::FP_TO_UINT:
10599 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10601 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10602 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10605 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10606 case ISD::SIGN_EXTEND:
10607 case ISD::ZERO_EXTEND:
10608 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10609 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10610 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10611 case ARMISD::VLD2DUP:
10612 case ARMISD::VLD3DUP:
10613 case ARMISD::VLD4DUP:
10614 return PerformVLDCombine(N, DCI);
10615 case ARMISD::BUILD_VECTOR:
10616 return PerformARMBUILD_VECTORCombine(N, DCI);
10617 case ISD::INTRINSIC_VOID:
10618 case ISD::INTRINSIC_W_CHAIN:
10619 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10620 case Intrinsic::arm_neon_vld1:
10621 case Intrinsic::arm_neon_vld2:
10622 case Intrinsic::arm_neon_vld3:
10623 case Intrinsic::arm_neon_vld4:
10624 case Intrinsic::arm_neon_vld2lane:
10625 case Intrinsic::arm_neon_vld3lane:
10626 case Intrinsic::arm_neon_vld4lane:
10627 case Intrinsic::arm_neon_vst1:
10628 case Intrinsic::arm_neon_vst2:
10629 case Intrinsic::arm_neon_vst3:
10630 case Intrinsic::arm_neon_vst4:
10631 case Intrinsic::arm_neon_vst2lane:
10632 case Intrinsic::arm_neon_vst3lane:
10633 case Intrinsic::arm_neon_vst4lane:
10634 return PerformVLDCombine(N, DCI);
10642 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10644 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10647 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10650 bool *Fast) const {
10651 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10652 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10654 switch (VT.getSimpleVT().SimpleTy) {
10660 // Unaligned access can use (for example) LRDB, LRDH, LDR
10661 if (AllowsUnaligned) {
10663 *Fast = Subtarget->hasV7Ops();
10670 // For any little-endian targets with neon, we can support unaligned ld/st
10671 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10672 // A big-endian target may also explicitly support unaligned accesses
10673 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10683 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10684 unsigned AlignCheck) {
10685 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10686 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10689 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10690 unsigned DstAlign, unsigned SrcAlign,
10691 bool IsMemset, bool ZeroMemset,
10693 MachineFunction &MF) const {
10694 const Function *F = MF.getFunction();
10696 // See if we can use NEON instructions for this...
10697 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10698 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10701 (memOpAlign(SrcAlign, DstAlign, 16) ||
10702 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10704 } else if (Size >= 8 &&
10705 (memOpAlign(SrcAlign, DstAlign, 8) ||
10706 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10712 // Lowering to i32/i16 if the size permits.
10715 else if (Size >= 2)
10718 // Let the target-independent logic figure it out.
10722 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10723 if (Val.getOpcode() != ISD::LOAD)
10726 EVT VT1 = Val.getValueType();
10727 if (!VT1.isSimple() || !VT1.isInteger() ||
10728 !VT2.isSimple() || !VT2.isInteger())
10731 switch (VT1.getSimpleVT().SimpleTy) {
10736 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10743 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10744 EVT VT = ExtVal.getValueType();
10746 if (!isTypeLegal(VT))
10749 // Don't create a loadext if we can fold the extension into a wide/long
10751 // If there's more than one user instruction, the loadext is desirable no
10752 // matter what. There can be two uses by the same instruction.
10753 if (ExtVal->use_empty() ||
10754 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10757 SDNode *U = *ExtVal->use_begin();
10758 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10759 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10765 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10766 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10769 if (!isTypeLegal(EVT::getEVT(Ty1)))
10772 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10774 // Assuming the caller doesn't have a zeroext or signext return parameter,
10775 // truncation all the way down to i1 is valid.
10780 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10784 unsigned Scale = 1;
10785 switch (VT.getSimpleVT().SimpleTy) {
10786 default: return false;
10801 if ((V & (Scale - 1)) != 0)
10804 return V == (V & ((1LL << 5) - 1));
10807 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10808 const ARMSubtarget *Subtarget) {
10809 bool isNeg = false;
10815 switch (VT.getSimpleVT().SimpleTy) {
10816 default: return false;
10821 // + imm12 or - imm8
10823 return V == (V & ((1LL << 8) - 1));
10824 return V == (V & ((1LL << 12) - 1));
10827 // Same as ARM mode. FIXME: NEON?
10828 if (!Subtarget->hasVFP2())
10833 return V == (V & ((1LL << 8) - 1));
10837 /// isLegalAddressImmediate - Return true if the integer value can be used
10838 /// as the offset of the target addressing mode for load / store of the
10840 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10841 const ARMSubtarget *Subtarget) {
10845 if (!VT.isSimple())
10848 if (Subtarget->isThumb1Only())
10849 return isLegalT1AddressImmediate(V, VT);
10850 else if (Subtarget->isThumb2())
10851 return isLegalT2AddressImmediate(V, VT, Subtarget);
10856 switch (VT.getSimpleVT().SimpleTy) {
10857 default: return false;
10862 return V == (V & ((1LL << 12) - 1));
10865 return V == (V & ((1LL << 8) - 1));
10868 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10873 return V == (V & ((1LL << 8) - 1));
10877 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10879 int Scale = AM.Scale;
10883 switch (VT.getSimpleVT().SimpleTy) {
10884 default: return false;
10892 Scale = Scale & ~1;
10893 return Scale == 2 || Scale == 4 || Scale == 8;
10896 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10900 // Note, we allow "void" uses (basically, uses that aren't loads or
10901 // stores), because arm allows folding a scale into many arithmetic
10902 // operations. This should be made more precise and revisited later.
10904 // Allow r << imm, but the imm has to be a multiple of two.
10905 if (Scale & 1) return false;
10906 return isPowerOf2_32(Scale);
10910 /// isLegalAddressingMode - Return true if the addressing mode represented
10911 /// by AM is legal for this target, for a load/store of the specified type.
10912 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10913 const AddrMode &AM, Type *Ty,
10914 unsigned AS) const {
10915 EVT VT = getValueType(DL, Ty, true);
10916 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10919 // Can never fold addr of global into load/store.
10923 switch (AM.Scale) {
10924 case 0: // no scale reg, must be "r+i" or "r", or "i".
10927 if (Subtarget->isThumb1Only())
10931 // ARM doesn't support any R+R*scale+imm addr modes.
10935 if (!VT.isSimple())
10938 if (Subtarget->isThumb2())
10939 return isLegalT2ScaledAddressingMode(AM, VT);
10941 int Scale = AM.Scale;
10942 switch (VT.getSimpleVT().SimpleTy) {
10943 default: return false;
10947 if (Scale < 0) Scale = -Scale;
10951 return isPowerOf2_32(Scale & ~1);
10955 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10960 // Note, we allow "void" uses (basically, uses that aren't loads or
10961 // stores), because arm allows folding a scale into many arithmetic
10962 // operations. This should be made more precise and revisited later.
10964 // Allow r << imm, but the imm has to be a multiple of two.
10965 if (Scale & 1) return false;
10966 return isPowerOf2_32(Scale);
10972 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10973 /// icmp immediate, that is the target has icmp instructions which can compare
10974 /// a register against the immediate without having to materialize the
10975 /// immediate into a register.
10976 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10977 // Thumb2 and ARM modes can use cmn for negative immediates.
10978 if (!Subtarget->isThumb())
10979 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10980 if (Subtarget->isThumb2())
10981 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10982 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10983 return Imm >= 0 && Imm <= 255;
10986 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10987 /// *or sub* immediate, that is the target has add or sub instructions which can
10988 /// add a register with the immediate without having to materialize the
10989 /// immediate into a register.
10990 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10991 // Same encoding for add/sub, just flip the sign.
10992 int64_t AbsImm = std::abs(Imm);
10993 if (!Subtarget->isThumb())
10994 return ARM_AM::getSOImmVal(AbsImm) != -1;
10995 if (Subtarget->isThumb2())
10996 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10997 // Thumb1 only has 8-bit unsigned immediate.
10998 return AbsImm >= 0 && AbsImm <= 255;
11001 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11002 bool isSEXTLoad, SDValue &Base,
11003 SDValue &Offset, bool &isInc,
11004 SelectionDAG &DAG) {
11005 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11008 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11009 // AddressingMode 3
11010 Base = Ptr->getOperand(0);
11011 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11012 int RHSC = (int)RHS->getZExtValue();
11013 if (RHSC < 0 && RHSC > -256) {
11014 assert(Ptr->getOpcode() == ISD::ADD);
11016 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11020 isInc = (Ptr->getOpcode() == ISD::ADD);
11021 Offset = Ptr->getOperand(1);
11023 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11024 // AddressingMode 2
11025 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11026 int RHSC = (int)RHS->getZExtValue();
11027 if (RHSC < 0 && RHSC > -0x1000) {
11028 assert(Ptr->getOpcode() == ISD::ADD);
11030 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11031 Base = Ptr->getOperand(0);
11036 if (Ptr->getOpcode() == ISD::ADD) {
11038 ARM_AM::ShiftOpc ShOpcVal=
11039 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11040 if (ShOpcVal != ARM_AM::no_shift) {
11041 Base = Ptr->getOperand(1);
11042 Offset = Ptr->getOperand(0);
11044 Base = Ptr->getOperand(0);
11045 Offset = Ptr->getOperand(1);
11050 isInc = (Ptr->getOpcode() == ISD::ADD);
11051 Base = Ptr->getOperand(0);
11052 Offset = Ptr->getOperand(1);
11056 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11060 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11061 bool isSEXTLoad, SDValue &Base,
11062 SDValue &Offset, bool &isInc,
11063 SelectionDAG &DAG) {
11064 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11067 Base = Ptr->getOperand(0);
11068 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11069 int RHSC = (int)RHS->getZExtValue();
11070 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11071 assert(Ptr->getOpcode() == ISD::ADD);
11073 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11075 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11076 isInc = Ptr->getOpcode() == ISD::ADD;
11077 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11085 /// getPreIndexedAddressParts - returns true by value, base pointer and
11086 /// offset pointer and addressing mode by reference if the node's address
11087 /// can be legally represented as pre-indexed load / store address.
11089 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11091 ISD::MemIndexedMode &AM,
11092 SelectionDAG &DAG) const {
11093 if (Subtarget->isThumb1Only())
11098 bool isSEXTLoad = false;
11099 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11100 Ptr = LD->getBasePtr();
11101 VT = LD->getMemoryVT();
11102 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11103 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11104 Ptr = ST->getBasePtr();
11105 VT = ST->getMemoryVT();
11110 bool isLegal = false;
11111 if (Subtarget->isThumb2())
11112 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11113 Offset, isInc, DAG);
11115 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11116 Offset, isInc, DAG);
11120 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11124 /// getPostIndexedAddressParts - returns true by value, base pointer and
11125 /// offset pointer and addressing mode by reference if this node can be
11126 /// combined with a load / store to form a post-indexed load / store.
11127 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11130 ISD::MemIndexedMode &AM,
11131 SelectionDAG &DAG) const {
11132 if (Subtarget->isThumb1Only())
11137 bool isSEXTLoad = false;
11138 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11139 VT = LD->getMemoryVT();
11140 Ptr = LD->getBasePtr();
11141 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11142 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11143 VT = ST->getMemoryVT();
11144 Ptr = ST->getBasePtr();
11149 bool isLegal = false;
11150 if (Subtarget->isThumb2())
11151 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11154 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11160 // Swap base ptr and offset to catch more post-index load / store when
11161 // it's legal. In Thumb2 mode, offset must be an immediate.
11162 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11163 !Subtarget->isThumb2())
11164 std::swap(Base, Offset);
11166 // Post-indexed load / store update the base pointer.
11171 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11175 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11178 const SelectionDAG &DAG,
11179 unsigned Depth) const {
11180 unsigned BitWidth = KnownOne.getBitWidth();
11181 KnownZero = KnownOne = APInt(BitWidth, 0);
11182 switch (Op.getOpcode()) {
11188 // These nodes' second result is a boolean
11189 if (Op.getResNo() == 0)
11191 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11193 case ARMISD::CMOV: {
11194 // Bits are known zero/one if known on the LHS and RHS.
11195 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11196 if (KnownZero == 0 && KnownOne == 0) return;
11198 APInt KnownZeroRHS, KnownOneRHS;
11199 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11200 KnownZero &= KnownZeroRHS;
11201 KnownOne &= KnownOneRHS;
11204 case ISD::INTRINSIC_W_CHAIN: {
11205 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11206 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11209 case Intrinsic::arm_ldaex:
11210 case Intrinsic::arm_ldrex: {
11211 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11212 unsigned MemBits = VT.getScalarType().getSizeInBits();
11213 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11221 //===----------------------------------------------------------------------===//
11222 // ARM Inline Assembly Support
11223 //===----------------------------------------------------------------------===//
11225 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11226 // Looking for "rev" which is V6+.
11227 if (!Subtarget->hasV6Ops())
11230 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11231 std::string AsmStr = IA->getAsmString();
11232 SmallVector<StringRef, 4> AsmPieces;
11233 SplitString(AsmStr, AsmPieces, ";\n");
11235 switch (AsmPieces.size()) {
11236 default: return false;
11238 AsmStr = AsmPieces[0];
11240 SplitString(AsmStr, AsmPieces, " \t,");
11243 if (AsmPieces.size() == 3 &&
11244 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11245 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11246 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11247 if (Ty && Ty->getBitWidth() == 32)
11248 return IntrinsicLowering::LowerToByteSwap(CI);
11256 /// getConstraintType - Given a constraint letter, return the type of
11257 /// constraint it is for this target.
11258 ARMTargetLowering::ConstraintType
11259 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11260 if (Constraint.size() == 1) {
11261 switch (Constraint[0]) {
11263 case 'l': return C_RegisterClass;
11264 case 'w': return C_RegisterClass;
11265 case 'h': return C_RegisterClass;
11266 case 'x': return C_RegisterClass;
11267 case 't': return C_RegisterClass;
11268 case 'j': return C_Other; // Constant for movw.
11269 // An address with a single base register. Due to the way we
11270 // currently handle addresses it is the same as an 'r' memory constraint.
11271 case 'Q': return C_Memory;
11273 } else if (Constraint.size() == 2) {
11274 switch (Constraint[0]) {
11276 // All 'U+' constraints are addresses.
11277 case 'U': return C_Memory;
11280 return TargetLowering::getConstraintType(Constraint);
11283 /// Examine constraint type and operand type and determine a weight value.
11284 /// This object must already have been set up with the operand type
11285 /// and the current alternative constraint selected.
11286 TargetLowering::ConstraintWeight
11287 ARMTargetLowering::getSingleConstraintMatchWeight(
11288 AsmOperandInfo &info, const char *constraint) const {
11289 ConstraintWeight weight = CW_Invalid;
11290 Value *CallOperandVal = info.CallOperandVal;
11291 // If we don't have a value, we can't do a match,
11292 // but allow it at the lowest weight.
11293 if (!CallOperandVal)
11295 Type *type = CallOperandVal->getType();
11296 // Look at the constraint type.
11297 switch (*constraint) {
11299 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11302 if (type->isIntegerTy()) {
11303 if (Subtarget->isThumb())
11304 weight = CW_SpecificReg;
11306 weight = CW_Register;
11310 if (type->isFloatingPointTy())
11311 weight = CW_Register;
11317 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11318 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11319 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11320 if (Constraint.size() == 1) {
11321 // GCC ARM Constraint Letters
11322 switch (Constraint[0]) {
11323 case 'l': // Low regs or general regs.
11324 if (Subtarget->isThumb())
11325 return RCPair(0U, &ARM::tGPRRegClass);
11326 return RCPair(0U, &ARM::GPRRegClass);
11327 case 'h': // High regs or no regs.
11328 if (Subtarget->isThumb())
11329 return RCPair(0U, &ARM::hGPRRegClass);
11332 if (Subtarget->isThumb1Only())
11333 return RCPair(0U, &ARM::tGPRRegClass);
11334 return RCPair(0U, &ARM::GPRRegClass);
11336 if (VT == MVT::Other)
11338 if (VT == MVT::f32)
11339 return RCPair(0U, &ARM::SPRRegClass);
11340 if (VT.getSizeInBits() == 64)
11341 return RCPair(0U, &ARM::DPRRegClass);
11342 if (VT.getSizeInBits() == 128)
11343 return RCPair(0U, &ARM::QPRRegClass);
11346 if (VT == MVT::Other)
11348 if (VT == MVT::f32)
11349 return RCPair(0U, &ARM::SPR_8RegClass);
11350 if (VT.getSizeInBits() == 64)
11351 return RCPair(0U, &ARM::DPR_8RegClass);
11352 if (VT.getSizeInBits() == 128)
11353 return RCPair(0U, &ARM::QPR_8RegClass);
11356 if (VT == MVT::f32)
11357 return RCPair(0U, &ARM::SPRRegClass);
11361 if (StringRef("{cc}").equals_lower(Constraint))
11362 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11364 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11367 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11368 /// vector. If it is invalid, don't add anything to Ops.
11369 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11370 std::string &Constraint,
11371 std::vector<SDValue>&Ops,
11372 SelectionDAG &DAG) const {
11375 // Currently only support length 1 constraints.
11376 if (Constraint.length() != 1) return;
11378 char ConstraintLetter = Constraint[0];
11379 switch (ConstraintLetter) {
11382 case 'I': case 'J': case 'K': case 'L':
11383 case 'M': case 'N': case 'O':
11384 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11388 int64_t CVal64 = C->getSExtValue();
11389 int CVal = (int) CVal64;
11390 // None of these constraints allow values larger than 32 bits. Check
11391 // that the value fits in an int.
11392 if (CVal != CVal64)
11395 switch (ConstraintLetter) {
11397 // Constant suitable for movw, must be between 0 and
11399 if (Subtarget->hasV6T2Ops())
11400 if (CVal >= 0 && CVal <= 65535)
11404 if (Subtarget->isThumb1Only()) {
11405 // This must be a constant between 0 and 255, for ADD
11407 if (CVal >= 0 && CVal <= 255)
11409 } else if (Subtarget->isThumb2()) {
11410 // A constant that can be used as an immediate value in a
11411 // data-processing instruction.
11412 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11415 // A constant that can be used as an immediate value in a
11416 // data-processing instruction.
11417 if (ARM_AM::getSOImmVal(CVal) != -1)
11423 if (Subtarget->isThumb()) { // FIXME thumb2
11424 // This must be a constant between -255 and -1, for negated ADD
11425 // immediates. This can be used in GCC with an "n" modifier that
11426 // prints the negated value, for use with SUB instructions. It is
11427 // not useful otherwise but is implemented for compatibility.
11428 if (CVal >= -255 && CVal <= -1)
11431 // This must be a constant between -4095 and 4095. It is not clear
11432 // what this constraint is intended for. Implemented for
11433 // compatibility with GCC.
11434 if (CVal >= -4095 && CVal <= 4095)
11440 if (Subtarget->isThumb1Only()) {
11441 // A 32-bit value where only one byte has a nonzero value. Exclude
11442 // zero to match GCC. This constraint is used by GCC internally for
11443 // constants that can be loaded with a move/shift combination.
11444 // It is not useful otherwise but is implemented for compatibility.
11445 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11447 } else if (Subtarget->isThumb2()) {
11448 // A constant whose bitwise inverse can be used as an immediate
11449 // value in a data-processing instruction. This can be used in GCC
11450 // with a "B" modifier that prints the inverted value, for use with
11451 // BIC and MVN instructions. It is not useful otherwise but is
11452 // implemented for compatibility.
11453 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11456 // A constant whose bitwise inverse can be used as an immediate
11457 // value in a data-processing instruction. This can be used in GCC
11458 // with a "B" modifier that prints the inverted value, for use with
11459 // BIC and MVN instructions. It is not useful otherwise but is
11460 // implemented for compatibility.
11461 if (ARM_AM::getSOImmVal(~CVal) != -1)
11467 if (Subtarget->isThumb1Only()) {
11468 // This must be a constant between -7 and 7,
11469 // for 3-operand ADD/SUB immediate instructions.
11470 if (CVal >= -7 && CVal < 7)
11472 } else if (Subtarget->isThumb2()) {
11473 // A constant whose negation can be used as an immediate value in a
11474 // data-processing instruction. This can be used in GCC with an "n"
11475 // modifier that prints the negated value, for use with SUB
11476 // instructions. It is not useful otherwise but is implemented for
11478 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11481 // A constant whose negation can be used as an immediate value in a
11482 // data-processing instruction. This can be used in GCC with an "n"
11483 // modifier that prints the negated value, for use with SUB
11484 // instructions. It is not useful otherwise but is implemented for
11486 if (ARM_AM::getSOImmVal(-CVal) != -1)
11492 if (Subtarget->isThumb()) { // FIXME thumb2
11493 // This must be a multiple of 4 between 0 and 1020, for
11494 // ADD sp + immediate.
11495 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11498 // A power of two or a constant between 0 and 32. This is used in
11499 // GCC for the shift amount on shifted register operands, but it is
11500 // useful in general for any shift amounts.
11501 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11507 if (Subtarget->isThumb()) { // FIXME thumb2
11508 // This must be a constant between 0 and 31, for shift amounts.
11509 if (CVal >= 0 && CVal <= 31)
11515 if (Subtarget->isThumb()) { // FIXME thumb2
11516 // This must be a multiple of 4 between -508 and 508, for
11517 // ADD/SUB sp = sp + immediate.
11518 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11523 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11527 if (Result.getNode()) {
11528 Ops.push_back(Result);
11531 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11534 static RTLIB::Libcall getDivRemLibcall(
11535 const SDNode *N, MVT::SimpleValueType SVT) {
11536 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11537 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11538 "Unhandled Opcode in getDivRemLibcall");
11539 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11540 N->getOpcode() == ISD::SREM;
11543 default: llvm_unreachable("Unexpected request for libcall!");
11544 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11545 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11546 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11547 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11552 static TargetLowering::ArgListTy getDivRemArgList(
11553 const SDNode *N, LLVMContext *Context) {
11554 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11555 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11556 "Unhandled Opcode in getDivRemArgList");
11557 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11558 N->getOpcode() == ISD::SREM;
11559 TargetLowering::ArgListTy Args;
11560 TargetLowering::ArgListEntry Entry;
11561 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11562 EVT ArgVT = N->getOperand(i).getValueType();
11563 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11564 Entry.Node = N->getOperand(i);
11566 Entry.isSExt = isSigned;
11567 Entry.isZExt = !isSigned;
11568 Args.push_back(Entry);
11573 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11574 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11575 "Register-based DivRem lowering only");
11576 unsigned Opcode = Op->getOpcode();
11577 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11578 "Invalid opcode for Div/Rem lowering");
11579 bool isSigned = (Opcode == ISD::SDIVREM);
11580 EVT VT = Op->getValueType(0);
11581 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11583 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11584 VT.getSimpleVT().SimpleTy);
11585 SDValue InChain = DAG.getEntryNode();
11587 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11590 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11591 getPointerTy(DAG.getDataLayout()));
11593 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11596 TargetLowering::CallLoweringInfo CLI(DAG);
11597 CLI.setDebugLoc(dl).setChain(InChain)
11598 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11599 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11601 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11602 return CallInfo.first;
11605 // Lowers REM using divmod helpers
11606 // see RTABI section 4.2/4.3
11607 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11608 // Build return types (div and rem)
11609 std::vector<Type*> RetTyParams;
11610 Type *RetTyElement;
11612 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11613 default: llvm_unreachable("Unexpected request for libcall!");
11614 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11615 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11616 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11617 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11620 RetTyParams.push_back(RetTyElement);
11621 RetTyParams.push_back(RetTyElement);
11622 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11623 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11625 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11627 SDValue InChain = DAG.getEntryNode();
11628 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11629 bool isSigned = N->getOpcode() == ISD::SREM;
11630 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11631 getPointerTy(DAG.getDataLayout()));
11634 CallLoweringInfo CLI(DAG);
11635 CLI.setChain(InChain)
11636 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11637 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11638 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11640 // Return second (rem) result operand (first contains div)
11641 SDNode *ResNode = CallResult.first.getNode();
11642 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11643 return ResNode->getOperand(1);
11647 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11648 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11652 SDValue Chain = Op.getOperand(0);
11653 SDValue Size = Op.getOperand(1);
11655 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11656 DAG.getConstant(2, DL, MVT::i32));
11659 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11660 Flag = Chain.getValue(1);
11662 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11663 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11665 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11666 Chain = NewSP.getValue(1);
11668 SDValue Ops[2] = { NewSP, Chain };
11669 return DAG.getMergeValues(Ops, DL);
11672 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11673 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11674 "Unexpected type for custom-lowering FP_EXTEND");
11677 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11679 SDValue SrcVal = Op.getOperand(0);
11680 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11684 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11685 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11686 Subtarget->isFPOnlySP() &&
11687 "Unexpected type for custom-lowering FP_ROUND");
11690 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11692 SDValue SrcVal = Op.getOperand(0);
11693 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11698 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11699 // The ARM target isn't yet aware of offsets.
11703 bool ARM::isBitFieldInvertedMask(unsigned v) {
11704 if (v == 0xffffffff)
11707 // there can be 1's on either or both "outsides", all the "inside"
11708 // bits must be 0's
11709 return isShiftedMask_32(~v);
11712 /// isFPImmLegal - Returns true if the target can instruction select the
11713 /// specified FP immediate natively. If false, the legalizer will
11714 /// materialize the FP immediate as a load from a constant pool.
11715 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11716 if (!Subtarget->hasVFP3())
11718 if (VT == MVT::f32)
11719 return ARM_AM::getFP32Imm(Imm) != -1;
11720 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11721 return ARM_AM::getFP64Imm(Imm) != -1;
11725 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11726 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11727 /// specified in the intrinsic calls.
11728 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11730 unsigned Intrinsic) const {
11731 switch (Intrinsic) {
11732 case Intrinsic::arm_neon_vld1:
11733 case Intrinsic::arm_neon_vld2:
11734 case Intrinsic::arm_neon_vld3:
11735 case Intrinsic::arm_neon_vld4:
11736 case Intrinsic::arm_neon_vld2lane:
11737 case Intrinsic::arm_neon_vld3lane:
11738 case Intrinsic::arm_neon_vld4lane: {
11739 Info.opc = ISD::INTRINSIC_W_CHAIN;
11740 // Conservatively set memVT to the entire set of vectors loaded.
11741 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11742 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11743 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11744 Info.ptrVal = I.getArgOperand(0);
11746 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11747 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11748 Info.vol = false; // volatile loads with NEON intrinsics not supported
11749 Info.readMem = true;
11750 Info.writeMem = false;
11753 case Intrinsic::arm_neon_vst1:
11754 case Intrinsic::arm_neon_vst2:
11755 case Intrinsic::arm_neon_vst3:
11756 case Intrinsic::arm_neon_vst4:
11757 case Intrinsic::arm_neon_vst2lane:
11758 case Intrinsic::arm_neon_vst3lane:
11759 case Intrinsic::arm_neon_vst4lane: {
11760 Info.opc = ISD::INTRINSIC_VOID;
11761 // Conservatively set memVT to the entire set of vectors stored.
11762 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11763 unsigned NumElts = 0;
11764 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11765 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11766 if (!ArgTy->isVectorTy())
11768 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11770 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11771 Info.ptrVal = I.getArgOperand(0);
11773 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11774 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11775 Info.vol = false; // volatile stores with NEON intrinsics not supported
11776 Info.readMem = false;
11777 Info.writeMem = true;
11780 case Intrinsic::arm_ldaex:
11781 case Intrinsic::arm_ldrex: {
11782 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11783 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11784 Info.opc = ISD::INTRINSIC_W_CHAIN;
11785 Info.memVT = MVT::getVT(PtrTy->getElementType());
11786 Info.ptrVal = I.getArgOperand(0);
11788 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11790 Info.readMem = true;
11791 Info.writeMem = false;
11794 case Intrinsic::arm_stlex:
11795 case Intrinsic::arm_strex: {
11796 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11797 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11798 Info.opc = ISD::INTRINSIC_W_CHAIN;
11799 Info.memVT = MVT::getVT(PtrTy->getElementType());
11800 Info.ptrVal = I.getArgOperand(1);
11802 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11804 Info.readMem = false;
11805 Info.writeMem = true;
11808 case Intrinsic::arm_stlexd:
11809 case Intrinsic::arm_strexd: {
11810 Info.opc = ISD::INTRINSIC_W_CHAIN;
11811 Info.memVT = MVT::i64;
11812 Info.ptrVal = I.getArgOperand(2);
11816 Info.readMem = false;
11817 Info.writeMem = true;
11820 case Intrinsic::arm_ldaexd:
11821 case Intrinsic::arm_ldrexd: {
11822 Info.opc = ISD::INTRINSIC_W_CHAIN;
11823 Info.memVT = MVT::i64;
11824 Info.ptrVal = I.getArgOperand(0);
11828 Info.readMem = true;
11829 Info.writeMem = false;
11839 /// \brief Returns true if it is beneficial to convert a load of a constant
11840 /// to just the constant itself.
11841 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11843 assert(Ty->isIntegerTy());
11845 unsigned Bits = Ty->getPrimitiveSizeInBits();
11846 if (Bits == 0 || Bits > 32)
11851 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11852 ARM_MB::MemBOpt Domain) const {
11853 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11855 // First, if the target has no DMB, see what fallback we can use.
11856 if (!Subtarget->hasDataBarrier()) {
11857 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11858 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11860 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11861 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11862 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11863 Builder.getInt32(0), Builder.getInt32(7),
11864 Builder.getInt32(10), Builder.getInt32(5)};
11865 return Builder.CreateCall(MCR, args);
11867 // Instead of using barriers, atomic accesses on these subtargets use
11869 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11872 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11873 // Only a full system barrier exists in the M-class architectures.
11874 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11875 Constant *CDomain = Builder.getInt32(Domain);
11876 return Builder.CreateCall(DMB, CDomain);
11880 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11881 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11882 AtomicOrdering Ord, bool IsStore,
11883 bool IsLoad) const {
11884 if (!getInsertFencesForAtomic())
11890 llvm_unreachable("Invalid fence: unordered/non-atomic");
11893 return nullptr; // Nothing to do
11894 case SequentiallyConsistent:
11896 return nullptr; // Nothing to do
11899 case AcquireRelease:
11900 if (Subtarget->isSwift())
11901 return makeDMB(Builder, ARM_MB::ISHST);
11902 // FIXME: add a comment with a link to documentation justifying this.
11904 return makeDMB(Builder, ARM_MB::ISH);
11906 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11909 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11910 AtomicOrdering Ord, bool IsStore,
11911 bool IsLoad) const {
11912 if (!getInsertFencesForAtomic())
11918 llvm_unreachable("Invalid fence: unordered/not-atomic");
11921 return nullptr; // Nothing to do
11923 case AcquireRelease:
11924 case SequentiallyConsistent:
11925 return makeDMB(Builder, ARM_MB::ISH);
11927 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11930 // Loads and stores less than 64-bits are already atomic; ones above that
11931 // are doomed anyway, so defer to the default libcall and blame the OS when
11932 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11933 // anything for those.
11934 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11935 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11936 return (Size == 64) && !Subtarget->isMClass();
11939 // Loads and stores less than 64-bits are already atomic; ones above that
11940 // are doomed anyway, so defer to the default libcall and blame the OS when
11941 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11942 // anything for those.
11943 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11944 // guarantee, see DDI0406C ARM architecture reference manual,
11945 // sections A8.8.72-74 LDRD)
11946 TargetLowering::AtomicExpansionKind
11947 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11948 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11949 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
11950 : AtomicExpansionKind::None;
11953 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11954 // and up to 64 bits on the non-M profiles
11955 TargetLowering::AtomicExpansionKind
11956 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11957 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11958 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11959 ? AtomicExpansionKind::LLSC
11960 : AtomicExpansionKind::None;
11963 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11964 AtomicCmpXchgInst *AI) const {
11968 // This has so far only been implemented for MachO.
11969 bool ARMTargetLowering::useLoadStackGuardNode() const {
11970 return Subtarget->isTargetMachO();
11973 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11974 unsigned &Cost) const {
11975 // If we do not have NEON, vector types are not natively supported.
11976 if (!Subtarget->hasNEON())
11979 // Floating point values and vector values map to the same register file.
11980 // Therefore, although we could do a store extract of a vector type, this is
11981 // better to leave at float as we have more freedom in the addressing mode for
11983 if (VectorTy->isFPOrFPVectorTy())
11986 // If the index is unknown at compile time, this is very expensive to lower
11987 // and it is not possible to combine the store with the extract.
11988 if (!isa<ConstantInt>(Idx))
11991 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11992 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11993 // We can do a store + vector extract on any vector that fits perfectly in a D
11995 if (BitWidth == 64 || BitWidth == 128) {
12002 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12003 return Subtarget->hasV6T2Ops();
12006 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12007 return Subtarget->hasV6T2Ops();
12010 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12011 AtomicOrdering Ord) const {
12012 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12013 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12014 bool IsAcquire = isAtLeastAcquire(Ord);
12016 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12017 // intrinsic must return {i32, i32} and we have to recombine them into a
12018 // single i64 here.
12019 if (ValTy->getPrimitiveSizeInBits() == 64) {
12020 Intrinsic::ID Int =
12021 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12022 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12024 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12025 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12027 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12028 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12029 if (!Subtarget->isLittle())
12030 std::swap (Lo, Hi);
12031 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12032 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12033 return Builder.CreateOr(
12034 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12037 Type *Tys[] = { Addr->getType() };
12038 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12039 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12041 return Builder.CreateTruncOrBitCast(
12042 Builder.CreateCall(Ldrex, Addr),
12043 cast<PointerType>(Addr->getType())->getElementType());
12046 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12047 IRBuilder<> &Builder) const {
12048 if (!Subtarget->hasV7Ops())
12050 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12051 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12054 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12056 AtomicOrdering Ord) const {
12057 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12058 bool IsRelease = isAtLeastRelease(Ord);
12060 // Since the intrinsics must have legal type, the i64 intrinsics take two
12061 // parameters: "i32, i32". We must marshal Val into the appropriate form
12062 // before the call.
12063 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12064 Intrinsic::ID Int =
12065 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12066 Function *Strex = Intrinsic::getDeclaration(M, Int);
12067 Type *Int32Ty = Type::getInt32Ty(M->getContext());
12069 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12070 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12071 if (!Subtarget->isLittle())
12072 std::swap (Lo, Hi);
12073 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12074 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12077 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12078 Type *Tys[] = { Addr->getType() };
12079 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12081 return Builder.CreateCall(
12082 Strex, {Builder.CreateZExtOrBitCast(
12083 Val, Strex->getFunctionType()->getParamType(0)),
12087 /// \brief Lower an interleaved load into a vldN intrinsic.
12089 /// E.g. Lower an interleaved load (Factor = 2):
12090 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12091 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
12092 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
12095 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12096 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12097 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12098 bool ARMTargetLowering::lowerInterleavedLoad(
12099 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12100 ArrayRef<unsigned> Indices, unsigned Factor) const {
12101 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12102 "Invalid interleave factor");
12103 assert(!Shuffles.empty() && "Empty shufflevector input");
12104 assert(Shuffles.size() == Indices.size() &&
12105 "Unmatched number of shufflevectors and indices");
12107 VectorType *VecTy = Shuffles[0]->getType();
12108 Type *EltTy = VecTy->getVectorElementType();
12110 const DataLayout &DL = LI->getModule()->getDataLayout();
12111 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12112 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12114 // Skip if we do not have NEON and skip illegal vector types and vector types
12115 // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12116 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12119 // A pointer vector can not be the return type of the ldN intrinsics. Need to
12120 // load integer vectors first and then convert to pointer vectors.
12121 if (EltTy->isPointerTy())
12123 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12125 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12126 Intrinsic::arm_neon_vld3,
12127 Intrinsic::arm_neon_vld4};
12129 IRBuilder<> Builder(LI);
12130 SmallVector<Value *, 2> Ops;
12132 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12133 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12134 Ops.push_back(Builder.getInt32(LI->getAlignment()));
12136 Type *Tys[] = { VecTy, Int8Ptr };
12137 Function *VldnFunc =
12138 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12139 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12141 // Replace uses of each shufflevector with the corresponding vector loaded
12143 for (unsigned i = 0; i < Shuffles.size(); i++) {
12144 ShuffleVectorInst *SV = Shuffles[i];
12145 unsigned Index = Indices[i];
12147 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12149 // Convert the integer vector to pointer vector if the element is pointer.
12150 if (EltTy->isPointerTy())
12151 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12153 SV->replaceAllUsesWith(SubVec);
12159 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12161 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12162 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12163 unsigned NumElts) {
12164 SmallVector<Constant *, 16> Mask;
12165 for (unsigned i = 0; i < NumElts; i++)
12166 Mask.push_back(Builder.getInt32(Start + i));
12168 return ConstantVector::get(Mask);
12171 /// \brief Lower an interleaved store into a vstN intrinsic.
12173 /// E.g. Lower an interleaved store (Factor = 3):
12174 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12175 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12176 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12179 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12180 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12181 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12182 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12184 /// Note that the new shufflevectors will be removed and we'll only generate one
12185 /// vst3 instruction in CodeGen.
12186 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12187 ShuffleVectorInst *SVI,
12188 unsigned Factor) const {
12189 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12190 "Invalid interleave factor");
12192 VectorType *VecTy = SVI->getType();
12193 assert(VecTy->getVectorNumElements() % Factor == 0 &&
12194 "Invalid interleaved store");
12196 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12197 Type *EltTy = VecTy->getVectorElementType();
12198 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12200 const DataLayout &DL = SI->getModule()->getDataLayout();
12201 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12202 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12204 // Skip if we do not have NEON and skip illegal vector types and vector types
12205 // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12206 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12210 Value *Op0 = SVI->getOperand(0);
12211 Value *Op1 = SVI->getOperand(1);
12212 IRBuilder<> Builder(SI);
12214 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12215 // vectors to integer vectors.
12216 if (EltTy->isPointerTy()) {
12217 Type *IntTy = DL.getIntPtrType(EltTy);
12219 // Convert to the corresponding integer vector.
12221 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12222 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12223 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12225 SubVecTy = VectorType::get(IntTy, NumSubElts);
12228 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12229 Intrinsic::arm_neon_vst3,
12230 Intrinsic::arm_neon_vst4};
12231 SmallVector<Value *, 6> Ops;
12233 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12234 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12236 Type *Tys[] = { Int8Ptr, SubVecTy };
12237 Function *VstNFunc = Intrinsic::getDeclaration(
12238 SI->getModule(), StoreInts[Factor - 2], Tys);
12240 // Split the shufflevector operands into sub vectors for the new vstN call.
12241 for (unsigned i = 0; i < Factor; i++)
12242 Ops.push_back(Builder.CreateShuffleVector(
12243 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12245 Ops.push_back(Builder.getInt32(SI->getAlignment()));
12246 Builder.CreateCall(VstNFunc, Ops);
12258 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12259 uint64_t &Members) {
12260 if (auto *ST = dyn_cast<StructType>(Ty)) {
12261 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12262 uint64_t SubMembers = 0;
12263 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12265 Members += SubMembers;
12267 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12268 uint64_t SubMembers = 0;
12269 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12271 Members += SubMembers * AT->getNumElements();
12272 } else if (Ty->isFloatTy()) {
12273 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12277 } else if (Ty->isDoubleTy()) {
12278 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12282 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12289 return VT->getBitWidth() == 64;
12291 return VT->getBitWidth() == 128;
12293 switch (VT->getBitWidth()) {
12306 return (Members > 0 && Members <= 4);
12309 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12310 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12311 /// passing according to AAPCS rules.
12312 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12313 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12314 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12315 CallingConv::ARM_AAPCS_VFP)
12318 HABaseType Base = HA_UNKNOWN;
12319 uint64_t Members = 0;
12320 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12321 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12323 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12324 return IsHA || IsIntArray;
12327 unsigned ARMTargetLowering::getExceptionPointerRegister(
12328 const Constant *PersonalityFn) const {
12329 // Platforms which do not use SjLj EH may return values in these registers
12330 // via the personality function.
12331 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12334 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12335 const Constant *PersonalityFn) const {
12336 // Platforms which do not use SjLj EH may return values in these registers
12337 // via the personality function.
12338 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;