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)"),
68 // Disabled for causing self-hosting failures once returned-attribute inference
71 EnableThisRetForwarding("arm-this-return-forwarding", cl::Hidden,
72 cl::desc("Directly forward this return"),
76 class ARMCCState : public CCState {
78 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
79 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
81 : CCState(CC, isVarArg, MF, locs, C) {
82 assert(((PC == Call) || (PC == Prologue)) &&
83 "ARMCCState users must specify whether their context is call"
84 "or prologue generation.");
90 // The APCS parameter registers.
91 static const MCPhysReg GPRArgRegs[] = {
92 ARM::R0, ARM::R1, ARM::R2, ARM::R3
95 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
96 MVT PromotedBitwiseVT) {
97 if (VT != PromotedLdStVT) {
98 setOperationAction(ISD::LOAD, VT, Promote);
99 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
101 setOperationAction(ISD::STORE, VT, Promote);
102 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
105 MVT ElemTy = VT.getVectorElementType();
106 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
107 setOperationAction(ISD::SETCC, VT, Custom);
108 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
109 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
110 if (ElemTy == MVT::i32) {
111 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
112 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
113 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
114 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
116 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
117 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
118 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
119 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
121 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
122 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
123 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
124 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
125 setOperationAction(ISD::SELECT, VT, Expand);
126 setOperationAction(ISD::SELECT_CC, VT, Expand);
127 setOperationAction(ISD::VSELECT, VT, Expand);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
129 if (VT.isInteger()) {
130 setOperationAction(ISD::SHL, VT, Custom);
131 setOperationAction(ISD::SRA, VT, Custom);
132 setOperationAction(ISD::SRL, VT, Custom);
135 // Promote all bit-wise operations.
136 if (VT.isInteger() && VT != PromotedBitwiseVT) {
137 setOperationAction(ISD::AND, VT, Promote);
138 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
139 setOperationAction(ISD::OR, VT, Promote);
140 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
141 setOperationAction(ISD::XOR, VT, Promote);
142 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
145 // Neon does not support vector divide/remainder operations.
146 setOperationAction(ISD::SDIV, VT, Expand);
147 setOperationAction(ISD::UDIV, VT, Expand);
148 setOperationAction(ISD::FDIV, VT, Expand);
149 setOperationAction(ISD::SREM, VT, Expand);
150 setOperationAction(ISD::UREM, VT, Expand);
151 setOperationAction(ISD::FREM, VT, Expand);
153 if (!VT.isFloatingPoint() &&
154 VT != MVT::v2i64 && VT != MVT::v1i64)
155 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
156 setOperationAction(Opcode, VT, Legal);
159 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
160 addRegisterClass(VT, &ARM::DPRRegClass);
161 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
164 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
165 addRegisterClass(VT, &ARM::DPairRegClass);
166 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
169 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
170 const ARMSubtarget &STI)
171 : TargetLowering(TM), Subtarget(&STI) {
172 RegInfo = Subtarget->getRegisterInfo();
173 Itins = Subtarget->getInstrItineraryData();
175 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177 if (Subtarget->isTargetMachO()) {
178 // Uses VFP for Thumb libfuncs if available.
179 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
180 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
181 static const struct {
182 const RTLIB::Libcall Op;
183 const char * const Name;
184 const ISD::CondCode Cond;
186 // Single-precision floating-point arithmetic.
187 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
189 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
190 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
192 // Double-precision floating-point arithmetic.
193 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
194 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
195 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
196 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
198 // Single-precision comparisons.
199 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
200 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
201 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
202 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
203 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
204 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
205 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
206 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
208 // Double-precision comparisons.
209 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
210 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
211 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
212 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
213 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
214 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
215 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
216 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
218 // Floating-point to integer conversions.
219 // i64 conversions are done via library routines even when generating VFP
220 // instructions, so use the same ones.
221 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
222 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
223 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
224 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
226 // Conversions between floating types.
227 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
228 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
230 // Integer to floating-point conversions.
231 // i64 conversions are done via library routines even when generating VFP
232 // instructions, so use the same ones.
233 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
234 // e.g., __floatunsidf vs. __floatunssidfvfp.
235 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
236 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
237 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
238 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
241 for (const auto &LC : LibraryCalls) {
242 setLibcallName(LC.Op, LC.Name);
243 if (LC.Cond != ISD::SETCC_INVALID)
244 setCmpLibcallCC(LC.Op, LC.Cond);
248 // Set the correct calling convention for ARMv7k WatchOS. It's just
249 // AAPCS_VFP for functions as simple as libcalls.
250 if (Subtarget->isTargetWatchABI()) {
251 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
252 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
256 // These libcalls are not available in 32-bit.
257 setLibcallName(RTLIB::SHL_I128, nullptr);
258 setLibcallName(RTLIB::SRL_I128, nullptr);
259 setLibcallName(RTLIB::SRA_I128, nullptr);
262 if (Subtarget->isAAPCS_ABI() &&
263 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
264 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
265 static const struct {
266 const RTLIB::Libcall Op;
267 const char * const Name;
268 const CallingConv::ID CC;
269 const ISD::CondCode Cond;
271 // Double-precision floating-point arithmetic helper functions
272 // RTABI chapter 4.1.2, Table 2
273 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
274 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
275 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278 // Double-precision floating-point comparison helper functions
279 // RTABI chapter 4.1.2, Table 3
280 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
282 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
284 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
286 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
287 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
289 // Single-precision floating-point arithmetic helper functions
290 // RTABI chapter 4.1.2, Table 4
291 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
293 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296 // Single-precision floating-point comparison helper functions
297 // RTABI chapter 4.1.2, Table 5
298 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
300 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
301 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
302 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
303 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
304 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
305 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
307 // Floating-point to integer conversions.
308 // RTABI chapter 4.1.2, Table 6
309 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 // Conversions between floating types.
319 // RTABI chapter 4.1.2, Table 7
320 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 // Integer to floating-point conversions.
325 // RTABI chapter 4.1.2, Table 8
326 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 // Long long helper functions
336 // RTABI chapter 4.2, Table 9
337 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 // Integer division functions
343 // RTABI chapter 4.3.1
344 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354 for (const auto &LC : LibraryCalls) {
355 setLibcallName(LC.Op, LC.Name);
356 setLibcallCallingConv(LC.Op, LC.CC);
357 if (LC.Cond != ISD::SETCC_INVALID)
358 setCmpLibcallCC(LC.Op, LC.Cond);
361 // EABI dependent RTLIB
362 if (TM.Options.EABIVersion == EABI::EABI4 ||
363 TM.Options.EABIVersion == EABI::EABI5) {
364 static const struct {
365 const RTLIB::Libcall Op;
366 const char *const Name;
367 const CallingConv::ID CC;
368 const ISD::CondCode Cond;
369 } MemOpsLibraryCalls[] = {
371 // RTABI chapter 4.3.4
372 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377 for (const auto &LC : MemOpsLibraryCalls) {
378 setLibcallName(LC.Op, LC.Name);
379 setLibcallCallingConv(LC.Op, LC.CC);
380 if (LC.Cond != ISD::SETCC_INVALID)
381 setCmpLibcallCC(LC.Op, LC.Cond);
386 if (Subtarget->isTargetWindows()) {
387 static const struct {
388 const RTLIB::Libcall Op;
389 const char * const Name;
390 const CallingConv::ID CC;
392 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
393 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
394 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
395 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
396 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
397 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
398 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
399 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
402 for (const auto &LC : LibraryCalls) {
403 setLibcallName(LC.Op, LC.Name);
404 setLibcallCallingConv(LC.Op, LC.CC);
408 // Use divmod compiler-rt calls for iOS 5.0 and later.
409 if (Subtarget->isTargetWatchOS() ||
410 (Subtarget->isTargetIOS() &&
411 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
412 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
413 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
416 // The half <-> float conversion functions are always soft-float on
417 // non-watchos platforms, but are needed for some targets which use a
418 // hard-float calling convention by default.
419 if (!Subtarget->isTargetWatchABI()) {
420 if (Subtarget->isAAPCS_ABI()) {
421 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
425 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
426 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
427 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);
589 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand);
590 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand);
592 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
593 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
595 // NEON does not have single instruction CTTZ for vectors.
596 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
597 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
598 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
599 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
601 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
602 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
603 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
604 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
608 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
609 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
611 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
612 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
613 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
614 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
616 // NEON only has FMA instructions as of VFP4.
617 if (!Subtarget->hasVFP4()) {
618 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
619 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
622 setTargetDAGCombine(ISD::INTRINSIC_VOID);
623 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
624 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
625 setTargetDAGCombine(ISD::SHL);
626 setTargetDAGCombine(ISD::SRL);
627 setTargetDAGCombine(ISD::SRA);
628 setTargetDAGCombine(ISD::SIGN_EXTEND);
629 setTargetDAGCombine(ISD::ZERO_EXTEND);
630 setTargetDAGCombine(ISD::ANY_EXTEND);
631 setTargetDAGCombine(ISD::BUILD_VECTOR);
632 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
633 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
634 setTargetDAGCombine(ISD::STORE);
635 setTargetDAGCombine(ISD::FP_TO_SINT);
636 setTargetDAGCombine(ISD::FP_TO_UINT);
637 setTargetDAGCombine(ISD::FDIV);
638 setTargetDAGCombine(ISD::LOAD);
640 // It is legal to extload from v4i8 to v4i16 or v4i32.
641 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
643 for (MVT VT : MVT::integer_vector_valuetypes()) {
644 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
645 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
646 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
651 // ARM and Thumb2 support UMLAL/SMLAL.
652 if (!Subtarget->isThumb1Only())
653 setTargetDAGCombine(ISD::ADDC);
655 if (Subtarget->isFPOnlySP()) {
656 // When targeting a floating-point unit with only single-precision
657 // operations, f64 is legal for the few double-precision instructions which
658 // are present However, no double-precision operations other than moves,
659 // loads and stores are provided by the hardware.
660 setOperationAction(ISD::FADD, MVT::f64, Expand);
661 setOperationAction(ISD::FSUB, MVT::f64, Expand);
662 setOperationAction(ISD::FMUL, MVT::f64, Expand);
663 setOperationAction(ISD::FMA, MVT::f64, Expand);
664 setOperationAction(ISD::FDIV, MVT::f64, Expand);
665 setOperationAction(ISD::FREM, MVT::f64, Expand);
666 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
667 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
668 setOperationAction(ISD::FNEG, MVT::f64, Expand);
669 setOperationAction(ISD::FABS, MVT::f64, Expand);
670 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
671 setOperationAction(ISD::FSIN, MVT::f64, Expand);
672 setOperationAction(ISD::FCOS, MVT::f64, Expand);
673 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
674 setOperationAction(ISD::FPOW, MVT::f64, Expand);
675 setOperationAction(ISD::FLOG, MVT::f64, Expand);
676 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
677 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
678 setOperationAction(ISD::FEXP, MVT::f64, Expand);
679 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
680 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
681 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
682 setOperationAction(ISD::FRINT, MVT::f64, Expand);
683 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
684 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
685 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
686 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
687 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
688 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
689 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
690 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
691 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
692 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
695 computeRegisterProperties(Subtarget->getRegisterInfo());
697 // ARM does not have floating-point extending loads.
698 for (MVT VT : MVT::fp_valuetypes()) {
699 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
700 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
703 // ... or truncating stores
704 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
705 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
706 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
708 // ARM does not have i1 sign extending load.
709 for (MVT VT : MVT::integer_valuetypes())
710 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
712 // ARM supports all 4 flavors of integer indexed load / store.
713 if (!Subtarget->isThumb1Only()) {
714 for (unsigned im = (unsigned)ISD::PRE_INC;
715 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
716 setIndexedLoadAction(im, MVT::i1, Legal);
717 setIndexedLoadAction(im, MVT::i8, Legal);
718 setIndexedLoadAction(im, MVT::i16, Legal);
719 setIndexedLoadAction(im, MVT::i32, Legal);
720 setIndexedStoreAction(im, MVT::i1, Legal);
721 setIndexedStoreAction(im, MVT::i8, Legal);
722 setIndexedStoreAction(im, MVT::i16, Legal);
723 setIndexedStoreAction(im, MVT::i32, Legal);
726 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
727 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
728 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
731 setOperationAction(ISD::SADDO, MVT::i32, Custom);
732 setOperationAction(ISD::UADDO, MVT::i32, Custom);
733 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
734 setOperationAction(ISD::USUBO, MVT::i32, Custom);
736 // i64 operation support.
737 setOperationAction(ISD::MUL, MVT::i64, Expand);
738 setOperationAction(ISD::MULHU, MVT::i32, Expand);
739 if (Subtarget->isThumb1Only()) {
740 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
741 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
743 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
744 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
745 setOperationAction(ISD::MULHS, MVT::i32, Expand);
747 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
748 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
749 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
750 setOperationAction(ISD::SRL, MVT::i64, Custom);
751 setOperationAction(ISD::SRA, MVT::i64, Custom);
753 if (!Subtarget->isThumb1Only()) {
754 // FIXME: We should do this for Thumb1 as well.
755 setOperationAction(ISD::ADDC, MVT::i32, Custom);
756 setOperationAction(ISD::ADDE, MVT::i32, Custom);
757 setOperationAction(ISD::SUBC, MVT::i32, Custom);
758 setOperationAction(ISD::SUBE, MVT::i32, Custom);
761 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
762 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
764 // ARM does not have ROTL.
765 setOperationAction(ISD::ROTL, MVT::i32, Expand);
766 for (MVT VT : MVT::vector_valuetypes()) {
767 setOperationAction(ISD::ROTL, VT, Expand);
768 setOperationAction(ISD::ROTR, VT, Expand);
770 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
771 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
772 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
773 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
775 // @llvm.readcyclecounter requires the Performance Monitors extension.
776 // Default to the 0 expansion on unsupported platforms.
777 // FIXME: Technically there are older ARM CPUs that have
778 // implementation-specific ways of obtaining this information.
779 if (Subtarget->hasPerfMon())
780 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
782 // Only ARMv6 has BSWAP.
783 if (!Subtarget->hasV6Ops())
784 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
786 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
787 : Subtarget->hasDivideInARMMode();
789 // These are expanded into libcalls if the cpu doesn't have HW divider.
790 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
791 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
794 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
795 setOperationAction(ISD::SDIV, MVT::i32, Custom);
796 setOperationAction(ISD::UDIV, MVT::i32, Custom);
798 setOperationAction(ISD::SDIV, MVT::i64, Custom);
799 setOperationAction(ISD::UDIV, MVT::i64, Custom);
802 setOperationAction(ISD::SREM, MVT::i32, Expand);
803 setOperationAction(ISD::UREM, MVT::i32, Expand);
804 // Register based DivRem for AEABI (RTABI 4.2)
805 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
806 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) {
807 setOperationAction(ISD::SREM, MVT::i64, Custom);
808 setOperationAction(ISD::UREM, MVT::i64, Custom);
809 HasStandaloneRem = false;
811 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
812 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
813 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
814 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
815 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
816 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
817 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
818 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
820 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
821 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
822 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
823 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
824 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
825 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
826 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
827 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
829 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
830 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
831 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
832 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
834 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
835 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
838 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
839 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
840 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
841 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
843 setOperationAction(ISD::TRAP, MVT::Other, Legal);
845 // Use the default implementation.
846 setOperationAction(ISD::VASTART, MVT::Other, Custom);
847 setOperationAction(ISD::VAARG, MVT::Other, Expand);
848 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
849 setOperationAction(ISD::VAEND, MVT::Other, Expand);
850 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
851 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
853 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
854 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
856 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
858 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
859 // the default expansion.
860 InsertFencesForAtomic = false;
861 if (Subtarget->hasAnyDataBarrier() &&
862 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
863 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
864 // to ldrex/strex loops already.
865 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
866 if (!Subtarget->isThumb() || !Subtarget->isMClass())
867 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
869 // On v8, we have particularly efficient implementations of atomic fences
870 // if they can be combined with nearby atomic loads and stores.
871 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
872 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
873 InsertFencesForAtomic = true;
876 // If there's anything we can use as a barrier, go through custom lowering
878 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
879 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
881 // Set them all for expansion, which will force libcalls.
882 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
883 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
884 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
885 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
886 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
887 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
888 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
889 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
890 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
891 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
892 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
893 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
894 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
895 // Unordered/Monotonic case.
896 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
897 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
900 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
902 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
903 if (!Subtarget->hasV6Ops()) {
904 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
905 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
907 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
909 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
910 !Subtarget->isThumb1Only()) {
911 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
912 // iff target supports vfp2.
913 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
914 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
917 // We want to custom lower some of our intrinsics.
918 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
919 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
920 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
921 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
922 if (Subtarget->useSjLjEH())
923 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
925 setOperationAction(ISD::SETCC, MVT::i32, Expand);
926 setOperationAction(ISD::SETCC, MVT::f32, Expand);
927 setOperationAction(ISD::SETCC, MVT::f64, Expand);
928 setOperationAction(ISD::SELECT, MVT::i32, Custom);
929 setOperationAction(ISD::SELECT, MVT::f32, Custom);
930 setOperationAction(ISD::SELECT, MVT::f64, Custom);
931 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
932 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
933 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
935 // Thumb-1 cannot currently select ARMISD::SUBE.
936 if (!Subtarget->isThumb1Only())
937 setOperationAction(ISD::SETCCE, MVT::i32, Custom);
939 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
940 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
941 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
942 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
943 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
945 // We don't support sin/cos/fmod/copysign/pow
946 setOperationAction(ISD::FSIN, MVT::f64, Expand);
947 setOperationAction(ISD::FSIN, MVT::f32, Expand);
948 setOperationAction(ISD::FCOS, MVT::f32, Expand);
949 setOperationAction(ISD::FCOS, MVT::f64, Expand);
950 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
951 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
952 setOperationAction(ISD::FREM, MVT::f64, Expand);
953 setOperationAction(ISD::FREM, MVT::f32, Expand);
954 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
955 !Subtarget->isThumb1Only()) {
956 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
957 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
959 setOperationAction(ISD::FPOW, MVT::f64, Expand);
960 setOperationAction(ISD::FPOW, MVT::f32, Expand);
962 if (!Subtarget->hasVFP4()) {
963 setOperationAction(ISD::FMA, MVT::f64, Expand);
964 setOperationAction(ISD::FMA, MVT::f32, Expand);
967 // Various VFP goodness
968 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
969 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
970 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
971 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
972 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
975 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
976 if (!Subtarget->hasFP16()) {
977 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
978 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
982 // Combine sin / cos into one node or libcall if possible.
983 if (Subtarget->hasSinCos()) {
984 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
985 setLibcallName(RTLIB::SINCOS_F64, "sincos");
986 if (Subtarget->isTargetWatchABI()) {
987 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
988 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
990 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
991 // For iOS, we don't want to the normal expansion of a libcall to
992 // sincos. We want to issue a libcall to __sincos_stret.
993 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
994 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
998 // FP-ARMv8 implements a lot of rounding-like FP operations.
999 if (Subtarget->hasFPARMv8()) {
1000 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1001 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1002 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1003 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1004 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1005 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1006 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1007 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1008 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1009 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1010 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1011 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1013 if (!Subtarget->isFPOnlySP()) {
1014 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1015 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1016 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1017 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1018 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1019 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1020 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1021 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1025 if (Subtarget->hasNEON()) {
1026 // vmin and vmax aren't available in a scalar form, so we use
1027 // a NEON instruction with an undef lane instead.
1028 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1029 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1030 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1031 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1032 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1033 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1036 // We have target-specific dag combine patterns for the following nodes:
1037 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1038 setTargetDAGCombine(ISD::ADD);
1039 setTargetDAGCombine(ISD::SUB);
1040 setTargetDAGCombine(ISD::MUL);
1041 setTargetDAGCombine(ISD::AND);
1042 setTargetDAGCombine(ISD::OR);
1043 setTargetDAGCombine(ISD::XOR);
1045 if (Subtarget->hasV6Ops())
1046 setTargetDAGCombine(ISD::SRL);
1048 setStackPointerRegisterToSaveRestore(ARM::SP);
1050 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1051 !Subtarget->hasVFP2())
1052 setSchedulingPreference(Sched::RegPressure);
1054 setSchedulingPreference(Sched::Hybrid);
1056 //// temporary - rewrite interface to use type
1057 MaxStoresPerMemset = 8;
1058 MaxStoresPerMemsetOptSize = 4;
1059 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1060 MaxStoresPerMemcpyOptSize = 2;
1061 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1062 MaxStoresPerMemmoveOptSize = 2;
1064 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1065 // are at least 4 bytes aligned.
1066 setMinStackArgumentAlignment(4);
1068 // Prefer likely predicted branches to selects on out-of-order cores.
1069 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1071 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1074 bool ARMTargetLowering::useSoftFloat() const {
1075 return Subtarget->useSoftFloat();
1078 // FIXME: It might make sense to define the representative register class as the
1079 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1080 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1081 // SPR's representative would be DPR_VFP2. This should work well if register
1082 // pressure tracking were modified such that a register use would increment the
1083 // pressure of the register class's representative and all of it's super
1084 // classes' representatives transitively. We have not implemented this because
1085 // of the difficulty prior to coalescing of modeling operand register classes
1086 // due to the common occurrence of cross class copies and subregister insertions
1088 std::pair<const TargetRegisterClass *, uint8_t>
1089 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1091 const TargetRegisterClass *RRC = nullptr;
1093 switch (VT.SimpleTy) {
1095 return TargetLowering::findRepresentativeClass(TRI, VT);
1096 // Use DPR as representative register class for all floating point
1097 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1098 // the cost is 1 for both f32 and f64.
1099 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1100 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1101 RRC = &ARM::DPRRegClass;
1102 // When NEON is used for SP, only half of the register file is available
1103 // because operations that define both SP and DP results will be constrained
1104 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1105 // coalescing by double-counting the SP regs. See the FIXME above.
1106 if (Subtarget->useNEONForSinglePrecisionFP())
1109 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1110 case MVT::v4f32: case MVT::v2f64:
1111 RRC = &ARM::DPRRegClass;
1115 RRC = &ARM::DPRRegClass;
1119 RRC = &ARM::DPRRegClass;
1123 return std::make_pair(RRC, Cost);
1126 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1127 switch ((ARMISD::NodeType)Opcode) {
1128 case ARMISD::FIRST_NUMBER: break;
1129 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1130 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1131 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1132 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1133 case ARMISD::CALL: return "ARMISD::CALL";
1134 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1135 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1136 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1137 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1138 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1139 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1140 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1141 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1142 case ARMISD::CMP: return "ARMISD::CMP";
1143 case ARMISD::CMN: return "ARMISD::CMN";
1144 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1145 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1146 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1147 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1148 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1150 case ARMISD::CMOV: return "ARMISD::CMOV";
1152 case ARMISD::SSAT: return "ARMISD::SSAT";
1154 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1155 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1156 case ARMISD::RRX: return "ARMISD::RRX";
1158 case ARMISD::ADDC: return "ARMISD::ADDC";
1159 case ARMISD::ADDE: return "ARMISD::ADDE";
1160 case ARMISD::SUBC: return "ARMISD::SUBC";
1161 case ARMISD::SUBE: return "ARMISD::SUBE";
1163 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1164 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1166 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1167 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1168 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1170 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1172 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1174 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1176 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1178 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1180 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1181 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1183 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1184 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1185 case ARMISD::VCGE: return "ARMISD::VCGE";
1186 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1187 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1188 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1189 case ARMISD::VCGT: return "ARMISD::VCGT";
1190 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1191 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1192 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1193 case ARMISD::VTST: return "ARMISD::VTST";
1195 case ARMISD::VSHL: return "ARMISD::VSHL";
1196 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1197 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1198 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1199 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1200 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1201 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1202 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1203 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1204 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1205 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1206 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1207 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1208 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1209 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1210 case ARMISD::VSLI: return "ARMISD::VSLI";
1211 case ARMISD::VSRI: return "ARMISD::VSRI";
1212 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1213 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1214 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1215 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1216 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1217 case ARMISD::VDUP: return "ARMISD::VDUP";
1218 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1219 case ARMISD::VEXT: return "ARMISD::VEXT";
1220 case ARMISD::VREV64: return "ARMISD::VREV64";
1221 case ARMISD::VREV32: return "ARMISD::VREV32";
1222 case ARMISD::VREV16: return "ARMISD::VREV16";
1223 case ARMISD::VZIP: return "ARMISD::VZIP";
1224 case ARMISD::VUZP: return "ARMISD::VUZP";
1225 case ARMISD::VTRN: return "ARMISD::VTRN";
1226 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1227 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1228 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1229 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1230 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1231 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1232 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1233 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1234 case ARMISD::BFI: return "ARMISD::BFI";
1235 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1236 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1237 case ARMISD::VBSL: return "ARMISD::VBSL";
1238 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1239 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1240 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1241 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1242 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1243 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1244 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1245 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1246 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1247 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1248 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1249 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1250 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1251 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1252 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1253 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1254 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1255 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1256 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1257 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1258 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1263 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1266 return getPointerTy(DL);
1267 return VT.changeVectorElementTypeToInteger();
1270 /// getRegClassFor - Return the register class that should be used for the
1271 /// specified value type.
1272 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1273 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1274 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1275 // load / store 4 to 8 consecutive D registers.
1276 if (Subtarget->hasNEON()) {
1277 if (VT == MVT::v4i64)
1278 return &ARM::QQPRRegClass;
1279 if (VT == MVT::v8i64)
1280 return &ARM::QQQQPRRegClass;
1282 return TargetLowering::getRegClassFor(VT);
1285 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1286 // source/dest is aligned and the copy size is large enough. We therefore want
1287 // to align such objects passed to memory intrinsics.
1288 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1289 unsigned &PrefAlign) const {
1290 if (!isa<MemIntrinsic>(CI))
1293 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1294 // cycle faster than 4-byte aligned LDM.
1295 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1299 // Create a fast isel object.
1301 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1302 const TargetLibraryInfo *libInfo) const {
1303 return ARM::createFastISel(funcInfo, libInfo);
1306 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1307 unsigned NumVals = N->getNumValues();
1309 return Sched::RegPressure;
1311 for (unsigned i = 0; i != NumVals; ++i) {
1312 EVT VT = N->getValueType(i);
1313 if (VT == MVT::Glue || VT == MVT::Other)
1315 if (VT.isFloatingPoint() || VT.isVector())
1319 if (!N->isMachineOpcode())
1320 return Sched::RegPressure;
1322 // Load are scheduled for latency even if there instruction itinerary
1323 // is not available.
1324 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1325 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1327 if (MCID.getNumDefs() == 0)
1328 return Sched::RegPressure;
1329 if (!Itins->isEmpty() &&
1330 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1333 return Sched::RegPressure;
1336 //===----------------------------------------------------------------------===//
1338 //===----------------------------------------------------------------------===//
1340 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1341 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1343 default: llvm_unreachable("Unknown condition code!");
1344 case ISD::SETNE: return ARMCC::NE;
1345 case ISD::SETEQ: return ARMCC::EQ;
1346 case ISD::SETGT: return ARMCC::GT;
1347 case ISD::SETGE: return ARMCC::GE;
1348 case ISD::SETLT: return ARMCC::LT;
1349 case ISD::SETLE: return ARMCC::LE;
1350 case ISD::SETUGT: return ARMCC::HI;
1351 case ISD::SETUGE: return ARMCC::HS;
1352 case ISD::SETULT: return ARMCC::LO;
1353 case ISD::SETULE: return ARMCC::LS;
1357 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1358 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1359 ARMCC::CondCodes &CondCode2) {
1360 CondCode2 = ARMCC::AL;
1362 default: llvm_unreachable("Unknown FP condition!");
1364 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1366 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1368 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1369 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1370 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1371 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1372 case ISD::SETO: CondCode = ARMCC::VC; break;
1373 case ISD::SETUO: CondCode = ARMCC::VS; break;
1374 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1375 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1376 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1378 case ISD::SETULT: CondCode = ARMCC::LT; break;
1380 case ISD::SETULE: CondCode = ARMCC::LE; break;
1382 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1386 //===----------------------------------------------------------------------===//
1387 // Calling Convention Implementation
1388 //===----------------------------------------------------------------------===//
1390 #include "ARMGenCallingConv.inc"
1392 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1393 /// account presence of floating point hardware and calling convention
1394 /// limitations, such as support for variadic functions.
1396 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1397 bool isVarArg) const {
1400 llvm_unreachable("Unsupported calling convention");
1401 case CallingConv::ARM_AAPCS:
1402 case CallingConv::ARM_APCS:
1403 case CallingConv::GHC:
1405 case CallingConv::PreserveMost:
1406 return CallingConv::PreserveMost;
1407 case CallingConv::ARM_AAPCS_VFP:
1408 case CallingConv::Swift:
1409 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1410 case CallingConv::C:
1411 if (!Subtarget->isAAPCS_ABI())
1412 return CallingConv::ARM_APCS;
1413 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1414 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1416 return CallingConv::ARM_AAPCS_VFP;
1418 return CallingConv::ARM_AAPCS;
1419 case CallingConv::Fast:
1420 case CallingConv::CXX_FAST_TLS:
1421 if (!Subtarget->isAAPCS_ABI()) {
1422 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1423 return CallingConv::Fast;
1424 return CallingConv::ARM_APCS;
1425 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1426 return CallingConv::ARM_AAPCS_VFP;
1428 return CallingConv::ARM_AAPCS;
1432 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1433 /// CallingConvention.
1434 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1436 bool isVarArg) const {
1437 switch (getEffectiveCallingConv(CC, isVarArg)) {
1439 llvm_unreachable("Unsupported calling convention");
1440 case CallingConv::ARM_APCS:
1441 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1442 case CallingConv::ARM_AAPCS:
1443 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1444 case CallingConv::ARM_AAPCS_VFP:
1445 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1446 case CallingConv::Fast:
1447 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1448 case CallingConv::GHC:
1449 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1450 case CallingConv::PreserveMost:
1451 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1455 /// LowerCallResult - Lower the result values of a call into the
1456 /// appropriate copies out of appropriate physical registers.
1457 SDValue ARMTargetLowering::LowerCallResult(
1458 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1459 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1460 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1461 SDValue ThisVal) const {
1463 // Assign locations to each value returned by this call.
1464 SmallVector<CCValAssign, 16> RVLocs;
1465 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1466 *DAG.getContext(), Call);
1467 CCInfo.AnalyzeCallResult(Ins,
1468 CCAssignFnForNode(CallConv, /* Return*/ true,
1471 // Copy all of the result registers out of their specified physreg.
1472 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1473 CCValAssign VA = RVLocs[i];
1475 // Pass 'this' value directly from the argument to return value, to avoid
1476 // reg unit interference
1477 if (i == 0 && isThisReturn && EnableThisRetForwarding) {
1478 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1479 "unexpected return calling convention register assignment");
1480 InVals.push_back(ThisVal);
1485 if (VA.needsCustom()) {
1486 // Handle f64 or half of a v2f64.
1487 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1489 Chain = Lo.getValue(1);
1490 InFlag = Lo.getValue(2);
1491 VA = RVLocs[++i]; // skip ahead to next loc
1492 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1494 Chain = Hi.getValue(1);
1495 InFlag = Hi.getValue(2);
1496 if (!Subtarget->isLittle())
1498 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1500 if (VA.getLocVT() == MVT::v2f64) {
1501 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1502 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1503 DAG.getConstant(0, dl, MVT::i32));
1505 VA = RVLocs[++i]; // skip ahead to next loc
1506 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1507 Chain = Lo.getValue(1);
1508 InFlag = Lo.getValue(2);
1509 VA = RVLocs[++i]; // skip ahead to next loc
1510 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1511 Chain = Hi.getValue(1);
1512 InFlag = Hi.getValue(2);
1513 if (!Subtarget->isLittle())
1515 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1516 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1517 DAG.getConstant(1, dl, MVT::i32));
1520 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1522 Chain = Val.getValue(1);
1523 InFlag = Val.getValue(2);
1526 switch (VA.getLocInfo()) {
1527 default: llvm_unreachable("Unknown loc info!");
1528 case CCValAssign::Full: break;
1529 case CCValAssign::BCvt:
1530 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1534 InVals.push_back(Val);
1540 /// LowerMemOpCallTo - Store the argument to the stack.
1541 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1542 SDValue Arg, const SDLoc &dl,
1544 const CCValAssign &VA,
1545 ISD::ArgFlagsTy Flags) const {
1546 unsigned LocMemOffset = VA.getLocMemOffset();
1547 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1548 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1550 return DAG.getStore(
1551 Chain, dl, Arg, PtrOff,
1552 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1555 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1556 SDValue Chain, SDValue &Arg,
1557 RegsToPassVector &RegsToPass,
1558 CCValAssign &VA, CCValAssign &NextVA,
1560 SmallVectorImpl<SDValue> &MemOpChains,
1561 ISD::ArgFlagsTy Flags) const {
1563 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1564 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1565 unsigned id = Subtarget->isLittle() ? 0 : 1;
1566 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1568 if (NextVA.isRegLoc())
1569 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1571 assert(NextVA.isMemLoc());
1572 if (!StackPtr.getNode())
1573 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1574 getPointerTy(DAG.getDataLayout()));
1576 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1582 /// LowerCall - Lowering a call into a callseq_start <-
1583 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1586 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1587 SmallVectorImpl<SDValue> &InVals) const {
1588 SelectionDAG &DAG = CLI.DAG;
1590 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1591 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1592 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1593 SDValue Chain = CLI.Chain;
1594 SDValue Callee = CLI.Callee;
1595 bool &isTailCall = CLI.IsTailCall;
1596 CallingConv::ID CallConv = CLI.CallConv;
1597 bool doesNotRet = CLI.DoesNotReturn;
1598 bool isVarArg = CLI.IsVarArg;
1600 MachineFunction &MF = DAG.getMachineFunction();
1601 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1602 bool isThisReturn = false;
1603 bool isSibCall = false;
1604 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1606 // Disable tail calls if they're not supported.
1607 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1611 // Check if it's really possible to do a tail call.
1612 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1613 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1614 Outs, OutVals, Ins, DAG);
1615 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1616 report_fatal_error("failed to perform tail call elimination on a call "
1617 "site marked musttail");
1618 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1619 // detected sibcalls.
1626 // Analyze operands of the call, assigning locations to each operand.
1627 SmallVector<CCValAssign, 16> ArgLocs;
1628 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1629 *DAG.getContext(), Call);
1630 CCInfo.AnalyzeCallOperands(Outs,
1631 CCAssignFnForNode(CallConv, /* Return*/ false,
1634 // Get a count of how many bytes are to be pushed on the stack.
1635 unsigned NumBytes = CCInfo.getNextStackOffset();
1637 // For tail calls, memory operands are available in our caller's stack.
1641 // Adjust the stack pointer for the new arguments...
1642 // These operations are automatically eliminated by the prolog/epilog pass
1644 Chain = DAG.getCALLSEQ_START(Chain,
1645 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1648 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1650 RegsToPassVector RegsToPass;
1651 SmallVector<SDValue, 8> MemOpChains;
1653 // Walk the register/memloc assignments, inserting copies/loads. In the case
1654 // of tail call optimization, arguments are handled later.
1655 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1657 ++i, ++realArgIdx) {
1658 CCValAssign &VA = ArgLocs[i];
1659 SDValue Arg = OutVals[realArgIdx];
1660 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1661 bool isByVal = Flags.isByVal();
1663 // Promote the value if needed.
1664 switch (VA.getLocInfo()) {
1665 default: llvm_unreachable("Unknown loc info!");
1666 case CCValAssign::Full: break;
1667 case CCValAssign::SExt:
1668 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1670 case CCValAssign::ZExt:
1671 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1673 case CCValAssign::AExt:
1674 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1676 case CCValAssign::BCvt:
1677 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1681 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1682 if (VA.needsCustom()) {
1683 if (VA.getLocVT() == MVT::v2f64) {
1684 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1685 DAG.getConstant(0, dl, MVT::i32));
1686 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1687 DAG.getConstant(1, dl, MVT::i32));
1689 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1690 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1692 VA = ArgLocs[++i]; // skip ahead to next loc
1693 if (VA.isRegLoc()) {
1694 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1695 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1697 assert(VA.isMemLoc());
1699 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1700 dl, DAG, VA, Flags));
1703 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1704 StackPtr, MemOpChains, Flags);
1706 } else if (VA.isRegLoc()) {
1707 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1708 assert(VA.getLocVT() == MVT::i32 &&
1709 "unexpected calling convention register assignment");
1710 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1711 "unexpected use of 'returned'");
1712 isThisReturn = true;
1714 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1715 } else if (isByVal) {
1716 assert(VA.isMemLoc());
1717 unsigned offset = 0;
1719 // True if this byval aggregate will be split between registers
1721 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1722 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1724 if (CurByValIdx < ByValArgsCount) {
1726 unsigned RegBegin, RegEnd;
1727 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1730 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1732 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1733 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1734 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1735 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1736 MachinePointerInfo(),
1737 DAG.InferPtrAlignment(AddArg));
1738 MemOpChains.push_back(Load.getValue(1));
1739 RegsToPass.push_back(std::make_pair(j, Load));
1742 // If parameter size outsides register area, "offset" value
1743 // helps us to calculate stack slot for remained part properly.
1744 offset = RegEnd - RegBegin;
1746 CCInfo.nextInRegsParam();
1749 if (Flags.getByValSize() > 4*offset) {
1750 auto PtrVT = getPointerTy(DAG.getDataLayout());
1751 unsigned LocMemOffset = VA.getLocMemOffset();
1752 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1753 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1754 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1755 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1756 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1758 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1761 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1762 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1763 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1766 } else if (!isSibCall) {
1767 assert(VA.isMemLoc());
1769 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1770 dl, DAG, VA, Flags));
1774 if (!MemOpChains.empty())
1775 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1777 // Build a sequence of copy-to-reg nodes chained together with token chain
1778 // and flag operands which copy the outgoing args into the appropriate regs.
1780 // Tail call byval lowering might overwrite argument registers so in case of
1781 // tail call optimization the copies to registers are lowered later.
1783 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1784 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1785 RegsToPass[i].second, InFlag);
1786 InFlag = Chain.getValue(1);
1789 // For tail calls lower the arguments to the 'real' stack slot.
1791 // Force all the incoming stack arguments to be loaded from the stack
1792 // before any new outgoing arguments are stored to the stack, because the
1793 // outgoing stack slots may alias the incoming argument stack slots, and
1794 // the alias isn't otherwise explicit. This is slightly more conservative
1795 // than necessary, because it means that each store effectively depends
1796 // on every argument instead of just those arguments it would clobber.
1798 // Do not flag preceding copytoreg stuff together with the following stuff.
1800 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1801 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1802 RegsToPass[i].second, InFlag);
1803 InFlag = Chain.getValue(1);
1808 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1809 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1810 // node so that legalize doesn't hack it.
1811 bool isDirect = false;
1813 const TargetMachine &TM = getTargetMachine();
1814 const Module *Mod = MF.getFunction()->getParent();
1815 const GlobalValue *GV = nullptr;
1816 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1817 GV = G->getGlobal();
1819 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1821 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1822 bool isLocalARMFunc = false;
1823 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1824 auto PtrVt = getPointerTy(DAG.getDataLayout());
1826 if (Subtarget->genLongCalls()) {
1827 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1828 "long-calls codegen is not position independent!");
1829 // Handle a global address or an external symbol. If it's not one of
1830 // those, the target's already in a register, so we don't need to do
1832 if (isa<GlobalAddressSDNode>(Callee)) {
1833 // Create a constant pool entry for the callee address
1834 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1835 ARMConstantPoolValue *CPV =
1836 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1838 // Get the address of the callee into a register
1839 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1840 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1841 Callee = DAG.getLoad(
1842 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1843 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1844 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1845 const char *Sym = S->getSymbol();
1847 // Create a constant pool entry for the callee address
1848 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1849 ARMConstantPoolValue *CPV =
1850 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1851 ARMPCLabelIndex, 0);
1852 // Get the address of the callee into a register
1853 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1854 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1855 Callee = DAG.getLoad(
1856 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1857 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1859 } else if (isa<GlobalAddressSDNode>(Callee)) {
1860 // If we're optimizing for minimum size and the function is called three or
1861 // more times in this block, we can improve codesize by calling indirectly
1862 // as BLXr has a 16-bit encoding.
1863 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1864 auto *BB = CLI.CS->getParent();
1865 bool PreferIndirect =
1866 Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
1867 std::count_if(GV->user_begin(), GV->user_end(), [&BB](const User *U) {
1868 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
1871 if (!PreferIndirect) {
1873 bool isDef = GV->isStrongDefinitionForLinker();
1875 // ARM call to a local ARM function is predicable.
1876 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1877 // tBX takes a register source operand.
1878 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1879 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1880 Callee = DAG.getNode(
1881 ARMISD::WrapperPIC, dl, PtrVt,
1882 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1884 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1885 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1886 /* Alignment = */ 0, MachineMemOperand::MOInvariant);
1887 } else if (Subtarget->isTargetCOFF()) {
1888 assert(Subtarget->isTargetWindows() &&
1889 "Windows is the only supported COFF target");
1890 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1891 ? ARMII::MO_DLLIMPORT
1892 : ARMII::MO_NO_FLAG;
1893 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
1895 if (GV->hasDLLImportStorageClass())
1897 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1898 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1899 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1901 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
1904 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1906 // tBX takes a register source operand.
1907 const char *Sym = S->getSymbol();
1908 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1909 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1910 ARMConstantPoolValue *CPV =
1911 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1912 ARMPCLabelIndex, 4);
1913 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1914 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1915 Callee = DAG.getLoad(
1916 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1917 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1918 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1919 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1921 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
1925 // FIXME: handle tail calls differently.
1927 if (Subtarget->isThumb()) {
1928 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1929 CallOpc = ARMISD::CALL_NOLINK;
1931 CallOpc = ARMISD::CALL;
1933 if (!isDirect && !Subtarget->hasV5TOps())
1934 CallOpc = ARMISD::CALL_NOLINK;
1935 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
1936 // Emit regular call when code size is the priority
1937 !MF.getFunction()->optForMinSize())
1938 // "mov lr, pc; b _foo" to avoid confusing the RSP
1939 CallOpc = ARMISD::CALL_NOLINK;
1941 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1944 std::vector<SDValue> Ops;
1945 Ops.push_back(Chain);
1946 Ops.push_back(Callee);
1948 // Add argument registers to the end of the list so that they are known live
1950 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1951 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1952 RegsToPass[i].second.getValueType()));
1954 // Add a register mask operand representing the call-preserved registers.
1956 const uint32_t *Mask;
1957 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1959 // For 'this' returns, use the R0-preserving mask if applicable
1960 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1962 // Set isThisReturn to false if the calling convention is not one that
1963 // allows 'returned' to be modeled in this way, so LowerCallResult does
1964 // not try to pass 'this' straight through
1965 isThisReturn = false;
1966 Mask = ARI->getCallPreservedMask(MF, CallConv);
1969 Mask = ARI->getCallPreservedMask(MF, CallConv);
1971 assert(Mask && "Missing call preserved mask for calling convention");
1972 Ops.push_back(DAG.getRegisterMask(Mask));
1975 if (InFlag.getNode())
1976 Ops.push_back(InFlag);
1978 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1980 MF.getFrameInfo()->setHasTailCall();
1981 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1984 // Returns a chain and a flag for retval copy to use.
1985 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1986 InFlag = Chain.getValue(1);
1988 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1989 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1991 InFlag = Chain.getValue(1);
1993 // Handle result values, copying them out of physregs into vregs that we
1995 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1996 InVals, isThisReturn,
1997 isThisReturn ? OutVals[0] : SDValue());
2000 /// HandleByVal - Every parameter *after* a byval parameter is passed
2001 /// on the stack. Remember the next parameter register to allocate,
2002 /// and then confiscate the rest of the parameter registers to insure
2004 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2005 unsigned Align) const {
2006 assert((State->getCallOrPrologue() == Prologue ||
2007 State->getCallOrPrologue() == Call) &&
2008 "unhandled ParmContext");
2010 // Byval (as with any stack) slots are always at least 4 byte aligned.
2011 Align = std::max(Align, 4U);
2013 unsigned Reg = State->AllocateReg(GPRArgRegs);
2017 unsigned AlignInRegs = Align / 4;
2018 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2019 for (unsigned i = 0; i < Waste; ++i)
2020 Reg = State->AllocateReg(GPRArgRegs);
2025 unsigned Excess = 4 * (ARM::R4 - Reg);
2027 // Special case when NSAA != SP and parameter size greater than size of
2028 // all remained GPR regs. In that case we can't split parameter, we must
2029 // send it to stack. We also must set NCRN to R4, so waste all
2030 // remained registers.
2031 const unsigned NSAAOffset = State->getNextStackOffset();
2032 if (NSAAOffset != 0 && Size > Excess) {
2033 while (State->AllocateReg(GPRArgRegs))
2038 // First register for byval parameter is the first register that wasn't
2039 // allocated before this method call, so it would be "reg".
2040 // If parameter is small enough to be saved in range [reg, r4), then
2041 // the end (first after last) register would be reg + param-size-in-regs,
2042 // else parameter would be splitted between registers and stack,
2043 // end register would be r4 in this case.
2044 unsigned ByValRegBegin = Reg;
2045 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2046 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2047 // Note, first register is allocated in the beginning of function already,
2048 // allocate remained amount of registers we need.
2049 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2050 State->AllocateReg(GPRArgRegs);
2051 // A byval parameter that is split between registers and memory needs its
2052 // size truncated here.
2053 // In the case where the entire structure fits in registers, we set the
2054 // size in memory to zero.
2055 Size = std::max<int>(Size - Excess, 0);
2058 /// MatchingStackOffset - Return true if the given stack call argument is
2059 /// already available in the same position (relatively) of the caller's
2060 /// incoming argument stack.
2062 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2063 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2064 const TargetInstrInfo *TII) {
2065 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2067 if (Arg.getOpcode() == ISD::CopyFromReg) {
2068 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2069 if (!TargetRegisterInfo::isVirtualRegister(VR))
2071 MachineInstr *Def = MRI->getVRegDef(VR);
2074 if (!Flags.isByVal()) {
2075 if (!TII->isLoadFromStackSlot(*Def, FI))
2080 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2081 if (Flags.isByVal())
2082 // ByVal argument is passed in as a pointer but it's now being
2083 // dereferenced. e.g.
2084 // define @foo(%struct.X* %A) {
2085 // tail call @bar(%struct.X* byval %A)
2088 SDValue Ptr = Ld->getBasePtr();
2089 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2092 FI = FINode->getIndex();
2096 assert(FI != INT_MAX);
2097 if (!MFI->isFixedObjectIndex(FI))
2099 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2102 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2103 /// for tail call optimization. Targets which want to do tail call
2104 /// optimization should implement this function.
2106 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2107 CallingConv::ID CalleeCC,
2109 bool isCalleeStructRet,
2110 bool isCallerStructRet,
2111 const SmallVectorImpl<ISD::OutputArg> &Outs,
2112 const SmallVectorImpl<SDValue> &OutVals,
2113 const SmallVectorImpl<ISD::InputArg> &Ins,
2114 SelectionDAG& DAG) const {
2115 MachineFunction &MF = DAG.getMachineFunction();
2116 const Function *CallerF = MF.getFunction();
2117 CallingConv::ID CallerCC = CallerF->getCallingConv();
2119 assert(Subtarget->supportsTailCall());
2121 // Look for obvious safe cases to perform tail call optimization that do not
2122 // require ABI changes. This is what gcc calls sibcall.
2124 // Do not sibcall optimize vararg calls unless the call site is not passing
2126 if (isVarArg && !Outs.empty())
2129 // Exception-handling functions need a special set of instructions to indicate
2130 // a return to the hardware. Tail-calling another function would probably
2132 if (CallerF->hasFnAttribute("interrupt"))
2135 // Also avoid sibcall optimization if either caller or callee uses struct
2136 // return semantics.
2137 if (isCalleeStructRet || isCallerStructRet)
2140 // Externally-defined functions with weak linkage should not be
2141 // tail-called on ARM when the OS does not support dynamic
2142 // pre-emption of symbols, as the AAELF spec requires normal calls
2143 // to undefined weak functions to be replaced with a NOP or jump to the
2144 // next instruction. The behaviour of branch instructions in this
2145 // situation (as used for tail calls) is implementation-defined, so we
2146 // cannot rely on the linker replacing the tail call with a return.
2147 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2148 const GlobalValue *GV = G->getGlobal();
2149 const Triple &TT = getTargetMachine().getTargetTriple();
2150 if (GV->hasExternalWeakLinkage() &&
2151 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2155 // Check that the call results are passed in the same way.
2156 LLVMContext &C = *DAG.getContext();
2157 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2158 CCAssignFnForNode(CalleeCC, true, isVarArg),
2159 CCAssignFnForNode(CallerCC, true, isVarArg)))
2161 // The callee has to preserve all registers the caller needs to preserve.
2162 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2163 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2164 if (CalleeCC != CallerCC) {
2165 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2166 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2170 // If Caller's vararg or byval argument has been split between registers and
2171 // stack, do not perform tail call, since part of the argument is in caller's
2173 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2174 if (AFI_Caller->getArgRegsSaveSize())
2177 // If the callee takes no arguments then go on to check the results of the
2179 if (!Outs.empty()) {
2180 // Check if stack adjustment is needed. For now, do not do this if any
2181 // argument is passed on the stack.
2182 SmallVector<CCValAssign, 16> ArgLocs;
2183 ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call);
2184 CCInfo.AnalyzeCallOperands(Outs,
2185 CCAssignFnForNode(CalleeCC, false, isVarArg));
2186 if (CCInfo.getNextStackOffset()) {
2187 // Check if the arguments are already laid out in the right way as
2188 // the caller's fixed stack objects.
2189 MachineFrameInfo *MFI = MF.getFrameInfo();
2190 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2191 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2192 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2194 ++i, ++realArgIdx) {
2195 CCValAssign &VA = ArgLocs[i];
2196 EVT RegVT = VA.getLocVT();
2197 SDValue Arg = OutVals[realArgIdx];
2198 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2199 if (VA.getLocInfo() == CCValAssign::Indirect)
2201 if (VA.needsCustom()) {
2202 // f64 and vector types are split into multiple registers or
2203 // register/stack-slot combinations. The types will not match
2204 // the registers; give up on memory f64 refs until we figure
2205 // out what to do about this.
2208 if (!ArgLocs[++i].isRegLoc())
2210 if (RegVT == MVT::v2f64) {
2211 if (!ArgLocs[++i].isRegLoc())
2213 if (!ArgLocs[++i].isRegLoc())
2216 } else if (!VA.isRegLoc()) {
2217 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2224 const MachineRegisterInfo &MRI = MF.getRegInfo();
2225 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2233 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2234 MachineFunction &MF, bool isVarArg,
2235 const SmallVectorImpl<ISD::OutputArg> &Outs,
2236 LLVMContext &Context) const {
2237 SmallVector<CCValAssign, 16> RVLocs;
2238 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2239 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2243 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2244 const SDLoc &DL, SelectionDAG &DAG) {
2245 const MachineFunction &MF = DAG.getMachineFunction();
2246 const Function *F = MF.getFunction();
2248 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2250 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2251 // version of the "preferred return address". These offsets affect the return
2252 // instruction if this is a return from PL1 without hypervisor extensions.
2253 // IRQ/FIQ: +4 "subs pc, lr, #4"
2254 // SWI: 0 "subs pc, lr, #0"
2255 // ABORT: +4 "subs pc, lr, #4"
2256 // UNDEF: +4/+2 "subs pc, lr, #0"
2257 // UNDEF varies depending on where the exception came from ARM or Thumb
2258 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2261 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2264 else if (IntKind == "SWI" || IntKind == "UNDEF")
2267 report_fatal_error("Unsupported interrupt attribute. If present, value "
2268 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2270 RetOps.insert(RetOps.begin() + 1,
2271 DAG.getConstant(LROffset, DL, MVT::i32, false));
2273 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2277 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2279 const SmallVectorImpl<ISD::OutputArg> &Outs,
2280 const SmallVectorImpl<SDValue> &OutVals,
2281 const SDLoc &dl, SelectionDAG &DAG) const {
2283 // CCValAssign - represent the assignment of the return value to a location.
2284 SmallVector<CCValAssign, 16> RVLocs;
2286 // CCState - Info about the registers and stack slots.
2287 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2288 *DAG.getContext(), Call);
2290 // Analyze outgoing return values.
2291 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2295 SmallVector<SDValue, 4> RetOps;
2296 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2297 bool isLittleEndian = Subtarget->isLittle();
2299 MachineFunction &MF = DAG.getMachineFunction();
2300 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2301 AFI->setReturnRegsCount(RVLocs.size());
2303 // Copy the result values into the output registers.
2304 for (unsigned i = 0, realRVLocIdx = 0;
2306 ++i, ++realRVLocIdx) {
2307 CCValAssign &VA = RVLocs[i];
2308 assert(VA.isRegLoc() && "Can only return in registers!");
2310 SDValue Arg = OutVals[realRVLocIdx];
2312 switch (VA.getLocInfo()) {
2313 default: llvm_unreachable("Unknown loc info!");
2314 case CCValAssign::Full: break;
2315 case CCValAssign::BCvt:
2316 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2320 if (VA.needsCustom()) {
2321 if (VA.getLocVT() == MVT::v2f64) {
2322 // Extract the first half and return it in two registers.
2323 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2324 DAG.getConstant(0, dl, MVT::i32));
2325 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2326 DAG.getVTList(MVT::i32, MVT::i32), Half);
2328 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2329 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2331 Flag = Chain.getValue(1);
2332 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2333 VA = RVLocs[++i]; // skip ahead to next loc
2334 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2335 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2337 Flag = Chain.getValue(1);
2338 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2339 VA = RVLocs[++i]; // skip ahead to next loc
2341 // Extract the 2nd half and fall through to handle it as an f64 value.
2342 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2343 DAG.getConstant(1, dl, MVT::i32));
2345 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2347 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2348 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2349 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2350 fmrrd.getValue(isLittleEndian ? 0 : 1),
2352 Flag = Chain.getValue(1);
2353 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2354 VA = RVLocs[++i]; // skip ahead to next loc
2355 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2356 fmrrd.getValue(isLittleEndian ? 1 : 0),
2359 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2361 // Guarantee that all emitted copies are
2362 // stuck together, avoiding something bad.
2363 Flag = Chain.getValue(1);
2364 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2366 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2367 const MCPhysReg *I =
2368 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2371 if (ARM::GPRRegClass.contains(*I))
2372 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2373 else if (ARM::DPRRegClass.contains(*I))
2374 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2376 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2380 // Update chain and glue.
2383 RetOps.push_back(Flag);
2385 // CPUs which aren't M-class use a special sequence to return from
2386 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2387 // though we use "subs pc, lr, #N").
2389 // M-class CPUs actually use a normal return sequence with a special
2390 // (hardware-provided) value in LR, so the normal code path works.
2391 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2392 !Subtarget->isMClass()) {
2393 if (Subtarget->isThumb1Only())
2394 report_fatal_error("interrupt attribute is not supported in Thumb1");
2395 return LowerInterruptReturn(RetOps, dl, DAG);
2398 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2401 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2402 if (N->getNumValues() != 1)
2404 if (!N->hasNUsesOfValue(1, 0))
2407 SDValue TCChain = Chain;
2408 SDNode *Copy = *N->use_begin();
2409 if (Copy->getOpcode() == ISD::CopyToReg) {
2410 // If the copy has a glue operand, we conservatively assume it isn't safe to
2411 // perform a tail call.
2412 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2414 TCChain = Copy->getOperand(0);
2415 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2416 SDNode *VMov = Copy;
2417 // f64 returned in a pair of GPRs.
2418 SmallPtrSet<SDNode*, 2> Copies;
2419 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2421 if (UI->getOpcode() != ISD::CopyToReg)
2425 if (Copies.size() > 2)
2428 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2430 SDValue UseChain = UI->getOperand(0);
2431 if (Copies.count(UseChain.getNode()))
2435 // We are at the top of this chain.
2436 // If the copy has a glue operand, we conservatively assume it
2437 // isn't safe to perform a tail call.
2438 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2444 } else if (Copy->getOpcode() == ISD::BITCAST) {
2445 // f32 returned in a single GPR.
2446 if (!Copy->hasOneUse())
2448 Copy = *Copy->use_begin();
2449 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2451 // If the copy has a glue operand, we conservatively assume it isn't safe to
2452 // perform a tail call.
2453 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2455 TCChain = Copy->getOperand(0);
2460 bool HasRet = false;
2461 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2463 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2464 UI->getOpcode() != ARMISD::INTRET_FLAG)
2476 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2477 if (!Subtarget->supportsTailCall())
2481 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2482 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2488 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2489 // and pass the lower and high parts through.
2490 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2492 SDValue WriteValue = Op->getOperand(2);
2494 // This function is only supposed to be called for i64 type argument.
2495 assert(WriteValue.getValueType() == MVT::i64
2496 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2498 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2499 DAG.getConstant(0, DL, MVT::i32));
2500 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2501 DAG.getConstant(1, DL, MVT::i32));
2502 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2503 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2506 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2507 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2508 // one of the above mentioned nodes. It has to be wrapped because otherwise
2509 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2510 // be used to form addressing mode. These wrapped nodes will be selected
2512 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2513 EVT PtrVT = Op.getValueType();
2514 // FIXME there is no actual debug info here
2516 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2518 if (CP->isMachineConstantPoolEntry())
2519 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2520 CP->getAlignment());
2522 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2523 CP->getAlignment());
2524 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2527 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2528 return MachineJumpTableInfo::EK_Inline;
2531 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2532 SelectionDAG &DAG) const {
2533 MachineFunction &MF = DAG.getMachineFunction();
2534 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2535 unsigned ARMPCLabelIndex = 0;
2537 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2538 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2540 bool IsPositionIndependent = isPositionIndependent();
2541 if (!IsPositionIndependent) {
2542 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2544 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2545 ARMPCLabelIndex = AFI->createPICLabelUId();
2546 ARMConstantPoolValue *CPV =
2547 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2548 ARMCP::CPBlockAddress, PCAdj);
2549 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2552 SDValue Result = DAG.getLoad(
2553 PtrVT, DL, DAG.getEntryNode(), CPAddr,
2554 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2555 if (!IsPositionIndependent)
2557 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2558 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2561 /// \brief Convert a TLS address reference into the correct sequence of loads
2562 /// and calls to compute the variable's address for Darwin, and return an
2563 /// SDValue containing the final node.
2565 /// Darwin only has one TLS scheme which must be capable of dealing with the
2566 /// fully general situation, in the worst case. This means:
2567 /// + "extern __thread" declaration.
2568 /// + Defined in a possibly unknown dynamic library.
2570 /// The general system is that each __thread variable has a [3 x i32] descriptor
2571 /// which contains information used by the runtime to calculate the address. The
2572 /// only part of this the compiler needs to know about is the first word, which
2573 /// contains a function pointer that must be called with the address of the
2574 /// entire descriptor in "r0".
2576 /// Since this descriptor may be in a different unit, in general access must
2577 /// proceed along the usual ARM rules. A common sequence to produce is:
2579 /// movw rT1, :lower16:_var$non_lazy_ptr
2580 /// movt rT1, :upper16:_var$non_lazy_ptr
2584 /// [...address now in r0...]
2586 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2587 SelectionDAG &DAG) const {
2588 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2591 // First step is to get the address of the actua global symbol. This is where
2592 // the TLS descriptor lives.
2593 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2595 // The first entry in the descriptor is a function pointer that we must call
2596 // to obtain the address of the variable.
2597 SDValue Chain = DAG.getEntryNode();
2598 SDValue FuncTLVGet =
2599 DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2600 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2601 /* Alignment = */ 4, MachineMemOperand::MONonTemporal |
2602 MachineMemOperand::MOInvariant);
2603 Chain = FuncTLVGet.getValue(1);
2605 MachineFunction &F = DAG.getMachineFunction();
2606 MachineFrameInfo *MFI = F.getFrameInfo();
2607 MFI->setAdjustsStack(true);
2609 // TLS calls preserve all registers except those that absolutely must be
2610 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2613 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2614 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2615 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2617 // Finally, we can make the call. This is just a degenerate version of a
2618 // normal AArch64 call node: r0 takes the address of the descriptor, and
2619 // returns the address of the variable in this thread.
2620 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2622 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2623 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2624 DAG.getRegisterMask(Mask), Chain.getValue(1));
2625 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2629 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2630 SelectionDAG &DAG) const {
2631 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2633 SDValue Chain = DAG.getEntryNode();
2634 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2637 // Load the current TEB (thread environment block)
2638 SDValue Ops[] = {Chain,
2639 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2640 DAG.getConstant(15, DL, MVT::i32),
2641 DAG.getConstant(0, DL, MVT::i32),
2642 DAG.getConstant(13, DL, MVT::i32),
2643 DAG.getConstant(0, DL, MVT::i32),
2644 DAG.getConstant(2, DL, MVT::i32)};
2645 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2646 DAG.getVTList(MVT::i32, MVT::Other), Ops);
2648 SDValue TEB = CurrentTEB.getValue(0);
2649 Chain = CurrentTEB.getValue(1);
2651 // Load the ThreadLocalStoragePointer from the TEB
2652 // A pointer to the TLS array is located at offset 0x2c from the TEB.
2654 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2655 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2657 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2658 // offset into the TLSArray.
2660 // Load the TLS index from the C runtime
2662 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2663 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2664 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2666 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2667 DAG.getConstant(2, DL, MVT::i32));
2668 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2669 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2670 MachinePointerInfo());
2672 // Get the offset of the start of the .tls section (section base)
2673 const auto *GA = cast<GlobalAddressSDNode>(Op);
2674 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2675 SDValue Offset = DAG.getLoad(
2676 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2677 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2678 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2680 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2683 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2685 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2686 SelectionDAG &DAG) const {
2688 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2689 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2690 MachineFunction &MF = DAG.getMachineFunction();
2691 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2692 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2693 ARMConstantPoolValue *CPV =
2694 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2695 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2696 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2697 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2698 Argument = DAG.getLoad(
2699 PtrVT, dl, DAG.getEntryNode(), Argument,
2700 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2701 SDValue Chain = Argument.getValue(1);
2703 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2704 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2706 // call __tls_get_addr.
2709 Entry.Node = Argument;
2710 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2711 Args.push_back(Entry);
2713 // FIXME: is there useful debug info available here?
2714 TargetLowering::CallLoweringInfo CLI(DAG);
2715 CLI.setDebugLoc(dl).setChain(Chain)
2716 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2717 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2719 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2720 return CallResult.first;
2723 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2724 // "local exec" model.
2726 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2728 TLSModel::Model model) const {
2729 const GlobalValue *GV = GA->getGlobal();
2732 SDValue Chain = DAG.getEntryNode();
2733 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2734 // Get the Thread Pointer
2735 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2737 if (model == TLSModel::InitialExec) {
2738 MachineFunction &MF = DAG.getMachineFunction();
2739 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2740 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2741 // Initial exec model.
2742 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2743 ARMConstantPoolValue *CPV =
2744 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2745 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2747 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2748 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2749 Offset = DAG.getLoad(
2750 PtrVT, dl, Chain, Offset,
2751 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2752 Chain = Offset.getValue(1);
2754 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2755 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2757 Offset = DAG.getLoad(
2758 PtrVT, dl, Chain, Offset,
2759 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2762 assert(model == TLSModel::LocalExec);
2763 ARMConstantPoolValue *CPV =
2764 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2765 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2766 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2767 Offset = DAG.getLoad(
2768 PtrVT, dl, Chain, Offset,
2769 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2772 // The address of the thread local variable is the add of the thread
2773 // pointer with the offset of the variable.
2774 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2778 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2779 if (Subtarget->isTargetDarwin())
2780 return LowerGlobalTLSAddressDarwin(Op, DAG);
2782 if (Subtarget->isTargetWindows())
2783 return LowerGlobalTLSAddressWindows(Op, DAG);
2785 // TODO: implement the "local dynamic" model
2786 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2787 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2788 if (DAG.getTarget().Options.EmulatedTLS)
2789 return LowerToTLSEmulatedModel(GA, DAG);
2791 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2794 case TLSModel::GeneralDynamic:
2795 case TLSModel::LocalDynamic:
2796 return LowerToTLSGeneralDynamicModel(GA, DAG);
2797 case TLSModel::InitialExec:
2798 case TLSModel::LocalExec:
2799 return LowerToTLSExecModels(GA, DAG, model);
2801 llvm_unreachable("bogus TLS model");
2804 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2805 SelectionDAG &DAG) const {
2806 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2808 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2809 const TargetMachine &TM = getTargetMachine();
2810 if (isPositionIndependent()) {
2811 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
2813 MachineFunction &MF = DAG.getMachineFunction();
2814 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2815 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2816 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2818 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2819 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2820 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2821 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2822 /*AddCurrentAddress=*/UseGOT_PREL);
2823 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2824 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2825 SDValue Result = DAG.getLoad(
2826 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2827 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2828 SDValue Chain = Result.getValue(1);
2829 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2830 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2833 DAG.getLoad(PtrVT, dl, Chain, Result,
2834 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2838 // If we have T2 ops, we can materialize the address directly via movt/movw
2839 // pair. This is always cheaper.
2840 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2842 // FIXME: Once remat is capable of dealing with instructions with register
2843 // operands, expand this into two nodes.
2844 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2845 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2847 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2848 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2850 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2851 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2855 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2856 SelectionDAG &DAG) const {
2857 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2859 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2861 if (Subtarget->useMovt(DAG.getMachineFunction()))
2864 // FIXME: Once remat is capable of dealing with instructions with register
2865 // operands, expand this into multiple nodes
2867 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2869 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2870 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2872 if (Subtarget->isGVIndirectSymbol(GV))
2873 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2874 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2878 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2879 SelectionDAG &DAG) const {
2880 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2881 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2882 "Windows on ARM expects to use movw/movt");
2884 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2885 const ARMII::TOF TargetFlags =
2886 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2887 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2893 // FIXME: Once remat is capable of dealing with instructions with register
2894 // operands, expand this into two nodes.
2895 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2896 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2898 if (GV->hasDLLImportStorageClass())
2899 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2900 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2905 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2907 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2908 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2909 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2910 Op.getOperand(1), Val);
2914 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2916 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2917 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2920 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2921 SelectionDAG &DAG) const {
2923 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2928 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2929 const ARMSubtarget *Subtarget) const {
2930 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2933 default: return SDValue(); // Don't custom lower most intrinsics.
2934 case Intrinsic::arm_rbit: {
2935 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2936 "RBIT intrinsic must have i32 type!");
2937 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2939 case Intrinsic::thread_pointer: {
2940 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2941 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2943 case Intrinsic::eh_sjlj_lsda: {
2944 MachineFunction &MF = DAG.getMachineFunction();
2945 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2946 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2947 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2949 bool IsPositionIndependent = isPositionIndependent();
2950 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
2951 ARMConstantPoolValue *CPV =
2952 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2953 ARMCP::CPLSDA, PCAdj);
2954 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2955 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2956 SDValue Result = DAG.getLoad(
2957 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2958 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2960 if (IsPositionIndependent) {
2961 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2962 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2966 case Intrinsic::arm_neon_vmulls:
2967 case Intrinsic::arm_neon_vmullu: {
2968 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2969 ? ARMISD::VMULLs : ARMISD::VMULLu;
2970 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2971 Op.getOperand(1), Op.getOperand(2));
2973 case Intrinsic::arm_neon_vminnm:
2974 case Intrinsic::arm_neon_vmaxnm: {
2975 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2976 ? ISD::FMINNUM : ISD::FMAXNUM;
2977 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2978 Op.getOperand(1), Op.getOperand(2));
2980 case Intrinsic::arm_neon_vminu:
2981 case Intrinsic::arm_neon_vmaxu: {
2982 if (Op.getValueType().isFloatingPoint())
2984 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2985 ? ISD::UMIN : ISD::UMAX;
2986 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2987 Op.getOperand(1), Op.getOperand(2));
2989 case Intrinsic::arm_neon_vmins:
2990 case Intrinsic::arm_neon_vmaxs: {
2991 // v{min,max}s is overloaded between signed integers and floats.
2992 if (!Op.getValueType().isFloatingPoint()) {
2993 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2994 ? ISD::SMIN : ISD::SMAX;
2995 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2996 Op.getOperand(1), Op.getOperand(2));
2998 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2999 ? ISD::FMINNAN : ISD::FMAXNAN;
3000 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3001 Op.getOperand(1), Op.getOperand(2));
3006 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3007 const ARMSubtarget *Subtarget) {
3008 // FIXME: handle "fence singlethread" more efficiently.
3010 if (!Subtarget->hasDataBarrier()) {
3011 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3012 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3014 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3015 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3016 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3017 DAG.getConstant(0, dl, MVT::i32));
3020 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3021 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3022 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3023 if (Subtarget->isMClass()) {
3024 // Only a full system barrier exists in the M-class architectures.
3025 Domain = ARM_MB::SY;
3026 } else if (Subtarget->preferISHSTBarriers() &&
3027 Ord == AtomicOrdering::Release) {
3028 // Swift happens to implement ISHST barriers in a way that's compatible with
3029 // Release semantics but weaker than ISH so we'd be fools not to use
3030 // it. Beware: other processors probably don't!
3031 Domain = ARM_MB::ISHST;
3034 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3035 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3036 DAG.getConstant(Domain, dl, MVT::i32));
3039 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3040 const ARMSubtarget *Subtarget) {
3041 // ARM pre v5TE and Thumb1 does not have preload instructions.
3042 if (!(Subtarget->isThumb2() ||
3043 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3044 // Just preserve the chain.
3045 return Op.getOperand(0);
3048 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3050 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3051 // ARMv7 with MP extension has PLDW.
3052 return Op.getOperand(0);
3054 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3055 if (Subtarget->isThumb()) {
3057 isRead = ~isRead & 1;
3058 isData = ~isData & 1;
3061 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3062 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3063 DAG.getConstant(isData, dl, MVT::i32));
3066 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3067 MachineFunction &MF = DAG.getMachineFunction();
3068 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3070 // vastart just stores the address of the VarArgsFrameIndex slot into the
3071 // memory location argument.
3073 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3074 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3075 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3076 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3077 MachinePointerInfo(SV));
3080 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3081 CCValAssign &NextVA,
3084 const SDLoc &dl) const {
3085 MachineFunction &MF = DAG.getMachineFunction();
3086 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3088 const TargetRegisterClass *RC;
3089 if (AFI->isThumb1OnlyFunction())
3090 RC = &ARM::tGPRRegClass;
3092 RC = &ARM::GPRRegClass;
3094 // Transform the arguments stored in physical registers into virtual ones.
3095 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3096 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3099 if (NextVA.isMemLoc()) {
3100 MachineFrameInfo *MFI = MF.getFrameInfo();
3101 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3103 // Create load node to retrieve arguments from the stack.
3104 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3105 ArgValue2 = DAG.getLoad(
3106 MVT::i32, dl, Root, FIN,
3107 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3109 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3110 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3112 if (!Subtarget->isLittle())
3113 std::swap (ArgValue, ArgValue2);
3114 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3117 // The remaining GPRs hold either the beginning of variable-argument
3118 // data, or the beginning of an aggregate passed by value (usually
3119 // byval). Either way, we allocate stack slots adjacent to the data
3120 // provided by our caller, and store the unallocated registers there.
3121 // If this is a variadic function, the va_list pointer will begin with
3122 // these values; otherwise, this reassembles a (byval) structure that
3123 // was split between registers and memory.
3124 // Return: The frame index registers were stored into.
3125 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3126 const SDLoc &dl, SDValue &Chain,
3127 const Value *OrigArg,
3128 unsigned InRegsParamRecordIdx,
3129 int ArgOffset, unsigned ArgSize) const {
3130 // Currently, two use-cases possible:
3131 // Case #1. Non-var-args function, and we meet first byval parameter.
3132 // Setup first unallocated register as first byval register;
3133 // eat all remained registers
3134 // (these two actions are performed by HandleByVal method).
3135 // Then, here, we initialize stack frame with
3136 // "store-reg" instructions.
3137 // Case #2. Var-args function, that doesn't contain byval parameters.
3138 // The same: eat all remained unallocated registers,
3139 // initialize stack frame.
3141 MachineFunction &MF = DAG.getMachineFunction();
3142 MachineFrameInfo *MFI = MF.getFrameInfo();
3143 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3144 unsigned RBegin, REnd;
3145 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3146 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3148 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3149 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3154 ArgOffset = -4 * (ARM::R4 - RBegin);
3156 auto PtrVT = getPointerTy(DAG.getDataLayout());
3157 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3158 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3160 SmallVector<SDValue, 4> MemOps;
3161 const TargetRegisterClass *RC =
3162 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3164 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3165 unsigned VReg = MF.addLiveIn(Reg, RC);
3166 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3167 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3168 MachinePointerInfo(OrigArg, 4 * i));
3169 MemOps.push_back(Store);
3170 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3173 if (!MemOps.empty())
3174 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3178 // Setup stack frame, the va_list pointer will start from.
3179 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3180 const SDLoc &dl, SDValue &Chain,
3182 unsigned TotalArgRegsSaveSize,
3183 bool ForceMutable) const {
3184 MachineFunction &MF = DAG.getMachineFunction();
3185 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3187 // Try to store any remaining integer argument regs
3188 // to their spots on the stack so that they may be loaded by dereferencing
3189 // the result of va_next.
3190 // If there is no regs to be stored, just point address after last
3191 // argument passed via stack.
3192 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3193 CCInfo.getInRegsParamsCount(),
3194 CCInfo.getNextStackOffset(), 4);
3195 AFI->setVarArgsFrameIndex(FrameIndex);
3198 SDValue ARMTargetLowering::LowerFormalArguments(
3199 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3200 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3201 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3202 MachineFunction &MF = DAG.getMachineFunction();
3203 MachineFrameInfo *MFI = MF.getFrameInfo();
3205 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3207 // Assign locations to all of the incoming arguments.
3208 SmallVector<CCValAssign, 16> ArgLocs;
3209 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3210 *DAG.getContext(), Prologue);
3211 CCInfo.AnalyzeFormalArguments(Ins,
3212 CCAssignFnForNode(CallConv, /* Return*/ false,
3215 SmallVector<SDValue, 16> ArgValues;
3217 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3218 unsigned CurArgIdx = 0;
3220 // Initially ArgRegsSaveSize is zero.
3221 // Then we increase this value each time we meet byval parameter.
3222 // We also increase this value in case of varargs function.
3223 AFI->setArgRegsSaveSize(0);
3225 // Calculate the amount of stack space that we need to allocate to store
3226 // byval and variadic arguments that are passed in registers.
3227 // We need to know this before we allocate the first byval or variadic
3228 // argument, as they will be allocated a stack slot below the CFA (Canonical
3229 // Frame Address, the stack pointer at entry to the function).
3230 unsigned ArgRegBegin = ARM::R4;
3231 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3232 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3235 CCValAssign &VA = ArgLocs[i];
3236 unsigned Index = VA.getValNo();
3237 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3238 if (!Flags.isByVal())
3241 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3242 unsigned RBegin, REnd;
3243 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3244 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3246 CCInfo.nextInRegsParam();
3248 CCInfo.rewindByValRegsInfo();
3250 int lastInsIndex = -1;
3251 if (isVarArg && MFI->hasVAStart()) {
3252 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3253 if (RegIdx != array_lengthof(GPRArgRegs))
3254 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3257 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3258 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3259 auto PtrVT = getPointerTy(DAG.getDataLayout());
3261 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3262 CCValAssign &VA = ArgLocs[i];
3263 if (Ins[VA.getValNo()].isOrigArg()) {
3264 std::advance(CurOrigArg,
3265 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3266 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3268 // Arguments stored in registers.
3269 if (VA.isRegLoc()) {
3270 EVT RegVT = VA.getLocVT();
3272 if (VA.needsCustom()) {
3273 // f64 and vector types are split up into multiple registers or
3274 // combinations of registers and stack slots.
3275 if (VA.getLocVT() == MVT::v2f64) {
3276 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3278 VA = ArgLocs[++i]; // skip ahead to next loc
3280 if (VA.isMemLoc()) {
3281 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3282 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3283 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3284 MachinePointerInfo::getFixedStack(
3285 DAG.getMachineFunction(), FI));
3287 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3290 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3291 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3292 ArgValue, ArgValue1,
3293 DAG.getIntPtrConstant(0, dl));
3294 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3295 ArgValue, ArgValue2,
3296 DAG.getIntPtrConstant(1, dl));
3298 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3301 const TargetRegisterClass *RC;
3303 if (RegVT == MVT::f32)
3304 RC = &ARM::SPRRegClass;
3305 else if (RegVT == MVT::f64)
3306 RC = &ARM::DPRRegClass;
3307 else if (RegVT == MVT::v2f64)
3308 RC = &ARM::QPRRegClass;
3309 else if (RegVT == MVT::i32)
3310 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3311 : &ARM::GPRRegClass;
3313 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3315 // Transform the arguments in physical registers into virtual ones.
3316 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3317 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3320 // If this is an 8 or 16-bit value, it is really passed promoted
3321 // to 32 bits. Insert an assert[sz]ext to capture this, then
3322 // truncate to the right size.
3323 switch (VA.getLocInfo()) {
3324 default: llvm_unreachable("Unknown loc info!");
3325 case CCValAssign::Full: break;
3326 case CCValAssign::BCvt:
3327 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3329 case CCValAssign::SExt:
3330 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3331 DAG.getValueType(VA.getValVT()));
3332 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3334 case CCValAssign::ZExt:
3335 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3336 DAG.getValueType(VA.getValVT()));
3337 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3341 InVals.push_back(ArgValue);
3343 } else { // VA.isRegLoc()
3346 assert(VA.isMemLoc());
3347 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3349 int index = VA.getValNo();
3351 // Some Ins[] entries become multiple ArgLoc[] entries.
3352 // Process them only once.
3353 if (index != lastInsIndex)
3355 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3356 // FIXME: For now, all byval parameter objects are marked mutable.
3357 // This can be changed with more analysis.
3358 // In case of tail call optimization mark all arguments mutable.
3359 // Since they could be overwritten by lowering of arguments in case of
3361 if (Flags.isByVal()) {
3362 assert(Ins[index].isOrigArg() &&
3363 "Byval arguments cannot be implicit");
3364 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3366 int FrameIndex = StoreByValRegs(
3367 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3368 VA.getLocMemOffset(), Flags.getByValSize());
3369 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3370 CCInfo.nextInRegsParam();
3372 unsigned FIOffset = VA.getLocMemOffset();
3373 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3376 // Create load nodes to retrieve arguments from the stack.
3377 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3378 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3379 MachinePointerInfo::getFixedStack(
3380 DAG.getMachineFunction(), FI)));
3382 lastInsIndex = index;
3388 if (isVarArg && MFI->hasVAStart())
3389 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3390 CCInfo.getNextStackOffset(),
3391 TotalArgRegsSaveSize);
3393 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3398 /// isFloatingPointZero - Return true if this is +0.0.
3399 static bool isFloatingPointZero(SDValue Op) {
3400 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3401 return CFP->getValueAPF().isPosZero();
3402 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3403 // Maybe this has already been legalized into the constant pool?
3404 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3405 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3406 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3407 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3408 return CFP->getValueAPF().isPosZero();
3410 } else if (Op->getOpcode() == ISD::BITCAST &&
3411 Op->getValueType(0) == MVT::f64) {
3412 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3413 // created by LowerConstantFP().
3414 SDValue BitcastOp = Op->getOperand(0);
3415 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3416 isNullConstant(BitcastOp->getOperand(0)))
3422 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3423 /// the given operands.
3424 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3425 SDValue &ARMcc, SelectionDAG &DAG,
3426 const SDLoc &dl) const {
3427 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3428 unsigned C = RHSC->getZExtValue();
3429 if (!isLegalICmpImmediate(C)) {
3430 // Constant does not fit, try adjusting it by one?
3435 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3436 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3437 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3442 if (C != 0 && isLegalICmpImmediate(C-1)) {
3443 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3444 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3449 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3450 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3451 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3456 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3457 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3458 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3465 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3466 ARMISD::NodeType CompareType;
3469 CompareType = ARMISD::CMP;
3474 CompareType = ARMISD::CMPZ;
3477 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3478 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3481 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3482 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3483 SelectionDAG &DAG, const SDLoc &dl) const {
3484 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3486 if (!isFloatingPointZero(RHS))
3487 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3489 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3490 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3493 /// duplicateCmp - Glue values can have only one use, so this function
3494 /// duplicates a comparison node.
3496 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3497 unsigned Opc = Cmp.getOpcode();
3499 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3500 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3502 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3503 Cmp = Cmp.getOperand(0);
3504 Opc = Cmp.getOpcode();
3505 if (Opc == ARMISD::CMPFP)
3506 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3508 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3509 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3511 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3514 std::pair<SDValue, SDValue>
3515 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3516 SDValue &ARMcc) const {
3517 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3519 SDValue Value, OverflowCmp;
3520 SDValue LHS = Op.getOperand(0);
3521 SDValue RHS = Op.getOperand(1);
3524 // FIXME: We are currently always generating CMPs because we don't support
3525 // generating CMN through the backend. This is not as good as the natural
3526 // CMP case because it causes a register dependency and cannot be folded
3529 switch (Op.getOpcode()) {
3531 llvm_unreachable("Unknown overflow instruction!");
3533 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3534 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3535 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3538 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3539 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3540 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3543 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3544 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3545 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3548 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3549 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3550 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3554 return std::make_pair(Value, OverflowCmp);
3559 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3560 // Let legalize expand this if it isn't a legal type yet.
3561 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3564 SDValue Value, OverflowCmp;
3566 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3567 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3569 // We use 0 and 1 as false and true values.
3570 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3571 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3572 EVT VT = Op.getValueType();
3574 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3575 ARMcc, CCR, OverflowCmp);
3577 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3578 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3582 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3583 SDValue Cond = Op.getOperand(0);
3584 SDValue SelectTrue = Op.getOperand(1);
3585 SDValue SelectFalse = Op.getOperand(2);
3587 unsigned Opc = Cond.getOpcode();
3589 if (Cond.getResNo() == 1 &&
3590 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3591 Opc == ISD::USUBO)) {
3592 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3595 SDValue Value, OverflowCmp;
3597 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3598 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3599 EVT VT = Op.getValueType();
3601 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3607 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3608 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3610 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3611 const ConstantSDNode *CMOVTrue =
3612 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3613 const ConstantSDNode *CMOVFalse =
3614 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3616 if (CMOVTrue && CMOVFalse) {
3617 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3618 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3622 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3624 False = SelectFalse;
3625 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3630 if (True.getNode() && False.getNode()) {
3631 EVT VT = Op.getValueType();
3632 SDValue ARMcc = Cond.getOperand(2);
3633 SDValue CCR = Cond.getOperand(3);
3634 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3635 assert(True.getValueType() == VT);
3636 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3641 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3642 // undefined bits before doing a full-word comparison with zero.
3643 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3644 DAG.getConstant(1, dl, Cond.getValueType()));
3646 return DAG.getSelectCC(dl, Cond,
3647 DAG.getConstant(0, dl, Cond.getValueType()),
3648 SelectTrue, SelectFalse, ISD::SETNE);
3651 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3652 bool &swpCmpOps, bool &swpVselOps) {
3653 // Start by selecting the GE condition code for opcodes that return true for
3655 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3657 CondCode = ARMCC::GE;
3659 // and GT for opcodes that return false for 'equality'.
3660 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3662 CondCode = ARMCC::GT;
3664 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3665 // to swap the compare operands.
3666 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3670 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3671 // If we have an unordered opcode, we need to swap the operands to the VSEL
3672 // instruction (effectively negating the condition).
3674 // This also has the effect of swapping which one of 'less' or 'greater'
3675 // returns true, so we also swap the compare operands. It also switches
3676 // whether we return true for 'equality', so we compensate by picking the
3677 // opposite condition code to our original choice.
3678 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3679 CC == ISD::SETUGT) {
3680 swpCmpOps = !swpCmpOps;
3681 swpVselOps = !swpVselOps;
3682 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3685 // 'ordered' is 'anything but unordered', so use the VS condition code and
3686 // swap the VSEL operands.
3687 if (CC == ISD::SETO) {
3688 CondCode = ARMCC::VS;
3692 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3693 // code and swap the VSEL operands.
3694 if (CC == ISD::SETUNE) {
3695 CondCode = ARMCC::EQ;
3700 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
3701 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3702 SDValue Cmp, SelectionDAG &DAG) const {
3703 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3704 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3705 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3706 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3707 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3709 SDValue TrueLow = TrueVal.getValue(0);
3710 SDValue TrueHigh = TrueVal.getValue(1);
3711 SDValue FalseLow = FalseVal.getValue(0);
3712 SDValue FalseHigh = FalseVal.getValue(1);
3714 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3716 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3717 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3719 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3721 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3726 static bool isGTorGE(ISD::CondCode CC) {
3727 return CC == ISD::SETGT || CC == ISD::SETGE;
3730 static bool isLTorLE(ISD::CondCode CC) {
3731 return CC == ISD::SETLT || CC == ISD::SETLE;
3734 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
3735 // All of these conditions (and their <= and >= counterparts) will do:
3740 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
3741 const SDValue TrueVal, const SDValue FalseVal,
3742 const ISD::CondCode CC, const SDValue K) {
3743 return (isGTorGE(CC) &&
3744 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
3746 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
3749 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
3750 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
3751 const SDValue TrueVal, const SDValue FalseVal,
3752 const ISD::CondCode CC, const SDValue K) {
3753 return (isGTorGE(CC) &&
3754 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
3756 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
3759 // Check if two chained conditionals could be converted into SSAT.
3761 // SSAT can replace a set of two conditional selectors that bound a number to an
3762 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
3764 // x < -k ? -k : (x > k ? k : x)
3765 // x < -k ? -k : (x < k ? x : k)
3766 // x > -k ? (x > k ? k : x) : -k
3767 // x < k ? (x < -k ? -k : x) : k
3770 // It returns true if the conversion can be done, false otherwise.
3771 // Additionally, the variable is returned in parameter V and the constant in K.
3772 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
3775 SDValue LHS1 = Op.getOperand(0);
3776 SDValue RHS1 = Op.getOperand(1);
3777 SDValue TrueVal1 = Op.getOperand(2);
3778 SDValue FalseVal1 = Op.getOperand(3);
3779 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3781 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
3782 if (Op2.getOpcode() != ISD::SELECT_CC)
3785 SDValue LHS2 = Op2.getOperand(0);
3786 SDValue RHS2 = Op2.getOperand(1);
3787 SDValue TrueVal2 = Op2.getOperand(2);
3788 SDValue FalseVal2 = Op2.getOperand(3);
3789 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
3791 // Find out which are the constants and which are the variables
3792 // in each conditional
3793 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
3796 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
3799 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
3800 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
3801 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
3802 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
3804 // We must detect cases where the original operations worked with 16- or
3805 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
3806 // must work with sign-extended values but the select operations return
3807 // the original non-extended value.
3808 SDValue V2TmpReg = V2Tmp;
3809 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
3810 V2TmpReg = V2Tmp->getOperand(0);
3812 // Check that the registers and the constants have the correct values
3813 // in both conditionals
3814 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
3818 // Figure out which conditional is saturating the lower/upper bound.
3819 const SDValue *LowerCheckOp =
3820 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
3822 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
3824 const SDValue *UpperCheckOp =
3825 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
3827 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
3830 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
3833 // Check that the constant in the lower-bound check is
3834 // the opposite of the constant in the upper-bound check
3835 // in 1's complement.
3836 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
3837 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
3838 int64_t PosVal = std::max(Val1, Val2);
3840 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
3841 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
3842 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
3845 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
3852 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3854 EVT VT = Op.getValueType();
3857 // Try to convert two saturating conditional selects into a single SSAT
3859 uint64_t SatConstant;
3860 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
3861 isSaturatingConditional(Op, SatValue, SatConstant))
3862 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
3863 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
3865 SDValue LHS = Op.getOperand(0);
3866 SDValue RHS = Op.getOperand(1);
3867 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3868 SDValue TrueVal = Op.getOperand(2);
3869 SDValue FalseVal = Op.getOperand(3);
3871 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3872 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3875 // If softenSetCCOperands only returned one value, we should compare it to
3877 if (!RHS.getNode()) {
3878 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3883 if (LHS.getValueType() == MVT::i32) {
3884 // Try to generate VSEL on ARMv8.
3885 // The VSEL instruction can't use all the usual ARM condition
3886 // codes: it only has two bits to select the condition code, so it's
3887 // constrained to use only GE, GT, VS and EQ.
3889 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3890 // swap the operands of the previous compare instruction (effectively
3891 // inverting the compare condition, swapping 'less' and 'greater') and
3892 // sometimes need to swap the operands to the VSEL (which inverts the
3893 // condition in the sense of firing whenever the previous condition didn't)
3894 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3895 TrueVal.getValueType() == MVT::f64)) {
3896 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3897 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3898 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3899 CC = ISD::getSetCCInverse(CC, true);
3900 std::swap(TrueVal, FalseVal);
3905 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3906 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3907 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3910 ARMCC::CondCodes CondCode, CondCode2;
3911 FPCCToARMCC(CC, CondCode, CondCode2);
3913 // Try to generate VMAXNM/VMINNM on ARMv8.
3914 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3915 TrueVal.getValueType() == MVT::f64)) {
3916 bool swpCmpOps = false;
3917 bool swpVselOps = false;
3918 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3920 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3921 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3923 std::swap(LHS, RHS);
3925 std::swap(TrueVal, FalseVal);
3929 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3930 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3931 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3932 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3933 if (CondCode2 != ARMCC::AL) {
3934 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3935 // FIXME: Needs another CMP because flag can have but one use.
3936 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3937 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3942 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3943 /// to morph to an integer compare sequence.
3944 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3945 const ARMSubtarget *Subtarget) {
3946 SDNode *N = Op.getNode();
3947 if (!N->hasOneUse())
3948 // Otherwise it requires moving the value from fp to integer registers.
3950 if (!N->getNumValues())
3952 EVT VT = Op.getValueType();
3953 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3954 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3955 // vmrs are very slow, e.g. cortex-a8.
3958 if (isFloatingPointZero(Op)) {
3962 return ISD::isNormalLoad(N);
3965 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3966 if (isFloatingPointZero(Op))
3967 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3969 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3970 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
3971 Ld->getPointerInfo(), Ld->getAlignment(),
3972 Ld->getMemOperand()->getFlags());
3974 llvm_unreachable("Unknown VFP cmp argument!");
3977 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3978 SDValue &RetVal1, SDValue &RetVal2) {
3981 if (isFloatingPointZero(Op)) {
3982 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3983 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3987 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3988 SDValue Ptr = Ld->getBasePtr();
3990 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
3991 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
3993 EVT PtrType = Ptr.getValueType();
3994 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3995 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3996 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3997 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
3998 Ld->getPointerInfo().getWithOffset(4), NewAlign,
3999 Ld->getMemOperand()->getFlags());
4003 llvm_unreachable("Unknown VFP cmp argument!");
4006 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4007 /// f32 and even f64 comparisons to integer ones.
4009 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4010 SDValue Chain = Op.getOperand(0);
4011 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4012 SDValue LHS = Op.getOperand(2);
4013 SDValue RHS = Op.getOperand(3);
4014 SDValue Dest = Op.getOperand(4);
4017 bool LHSSeenZero = false;
4018 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4019 bool RHSSeenZero = false;
4020 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4021 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4022 // If unsafe fp math optimization is enabled and there are no other uses of
4023 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4024 // to an integer comparison.
4025 if (CC == ISD::SETOEQ)
4027 else if (CC == ISD::SETUNE)
4030 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4032 if (LHS.getValueType() == MVT::f32) {
4033 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4034 bitcastf32Toi32(LHS, DAG), Mask);
4035 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4036 bitcastf32Toi32(RHS, DAG), Mask);
4037 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4038 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4039 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4040 Chain, Dest, ARMcc, CCR, Cmp);
4045 expandf64Toi32(LHS, DAG, LHS1, LHS2);
4046 expandf64Toi32(RHS, DAG, RHS1, RHS2);
4047 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4048 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4049 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4050 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4051 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4052 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4053 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4059 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4060 SDValue Chain = Op.getOperand(0);
4061 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4062 SDValue LHS = Op.getOperand(2);
4063 SDValue RHS = Op.getOperand(3);
4064 SDValue Dest = Op.getOperand(4);
4067 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4068 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4071 // If softenSetCCOperands only returned one value, we should compare it to
4073 if (!RHS.getNode()) {
4074 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4079 if (LHS.getValueType() == MVT::i32) {
4081 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4082 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4083 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4084 Chain, Dest, ARMcc, CCR, Cmp);
4087 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4089 if (getTargetMachine().Options.UnsafeFPMath &&
4090 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4091 CC == ISD::SETNE || CC == ISD::SETUNE)) {
4092 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4096 ARMCC::CondCodes CondCode, CondCode2;
4097 FPCCToARMCC(CC, CondCode, CondCode2);
4099 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4100 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4101 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4102 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4103 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4104 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4105 if (CondCode2 != ARMCC::AL) {
4106 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4107 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4108 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4113 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4114 SDValue Chain = Op.getOperand(0);
4115 SDValue Table = Op.getOperand(1);
4116 SDValue Index = Op.getOperand(2);
4119 EVT PTy = getPointerTy(DAG.getDataLayout());
4120 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4121 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4122 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4123 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4124 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4125 if (Subtarget->isThumb2()) {
4126 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4127 // which does another jump to the destination. This also makes it easier
4128 // to translate it to TBB / TBH later.
4129 // FIXME: This might not work if the function is extremely large.
4130 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4131 Addr, Op.getOperand(2), JTI);
4133 if (isPositionIndependent()) {
4135 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4136 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4137 Chain = Addr.getValue(1);
4138 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4139 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4142 DAG.getLoad(PTy, dl, Chain, Addr,
4143 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4144 Chain = Addr.getValue(1);
4145 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4149 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4150 EVT VT = Op.getValueType();
4153 if (Op.getValueType().getVectorElementType() == MVT::i32) {
4154 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4156 return DAG.UnrollVectorOp(Op.getNode());
4159 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4160 "Invalid type for custom lowering!");
4161 if (VT != MVT::v4i16)
4162 return DAG.UnrollVectorOp(Op.getNode());
4164 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4165 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4168 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4169 EVT VT = Op.getValueType();
4171 return LowerVectorFP_TO_INT(Op, DAG);
4172 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4174 if (Op.getOpcode() == ISD::FP_TO_SINT)
4175 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4178 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4180 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4181 /*isSigned*/ false, SDLoc(Op)).first;
4187 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4188 EVT VT = Op.getValueType();
4191 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4192 if (VT.getVectorElementType() == MVT::f32)
4194 return DAG.UnrollVectorOp(Op.getNode());
4197 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4198 "Invalid type for custom lowering!");
4199 if (VT != MVT::v4f32)
4200 return DAG.UnrollVectorOp(Op.getNode());
4204 switch (Op.getOpcode()) {
4205 default: llvm_unreachable("Invalid opcode!");
4206 case ISD::SINT_TO_FP:
4207 CastOpc = ISD::SIGN_EXTEND;
4208 Opc = ISD::SINT_TO_FP;
4210 case ISD::UINT_TO_FP:
4211 CastOpc = ISD::ZERO_EXTEND;
4212 Opc = ISD::UINT_TO_FP;
4216 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4217 return DAG.getNode(Opc, dl, VT, Op);
4220 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4221 EVT VT = Op.getValueType();
4223 return LowerVectorINT_TO_FP(Op, DAG);
4224 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4226 if (Op.getOpcode() == ISD::SINT_TO_FP)
4227 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4230 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4232 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4233 /*isSigned*/ false, SDLoc(Op)).first;
4239 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4240 // Implement fcopysign with a fabs and a conditional fneg.
4241 SDValue Tmp0 = Op.getOperand(0);
4242 SDValue Tmp1 = Op.getOperand(1);
4244 EVT VT = Op.getValueType();
4245 EVT SrcVT = Tmp1.getValueType();
4246 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4247 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4248 bool UseNEON = !InGPR && Subtarget->hasNEON();
4251 // Use VBSL to copy the sign bit.
4252 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4253 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4254 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4255 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4257 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4258 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4259 DAG.getConstant(32, dl, MVT::i32));
4260 else /*if (VT == MVT::f32)*/
4261 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4262 if (SrcVT == MVT::f32) {
4263 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4265 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4266 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4267 DAG.getConstant(32, dl, MVT::i32));
4268 } else if (VT == MVT::f32)
4269 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4270 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4271 DAG.getConstant(32, dl, MVT::i32));
4272 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4273 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4275 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4277 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4278 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4279 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4281 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4282 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4283 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4284 if (VT == MVT::f32) {
4285 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4286 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4287 DAG.getConstant(0, dl, MVT::i32));
4289 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4295 // Bitcast operand 1 to i32.
4296 if (SrcVT == MVT::f64)
4297 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4299 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4301 // Or in the signbit with integer operations.
4302 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4303 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4304 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4305 if (VT == MVT::f32) {
4306 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4307 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4308 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4309 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4312 // f64: Or the high part with signbit and then combine two parts.
4313 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4315 SDValue Lo = Tmp0.getValue(0);
4316 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4317 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4318 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4321 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4322 MachineFunction &MF = DAG.getMachineFunction();
4323 MachineFrameInfo *MFI = MF.getFrameInfo();
4324 MFI->setReturnAddressIsTaken(true);
4326 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4329 EVT VT = Op.getValueType();
4331 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4333 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4334 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4335 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4336 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4337 MachinePointerInfo());
4340 // Return LR, which contains the return address. Mark it an implicit live-in.
4341 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4342 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4345 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4346 const ARMBaseRegisterInfo &ARI =
4347 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4348 MachineFunction &MF = DAG.getMachineFunction();
4349 MachineFrameInfo *MFI = MF.getFrameInfo();
4350 MFI->setFrameAddressIsTaken(true);
4352 EVT VT = Op.getValueType();
4353 SDLoc dl(Op); // FIXME probably not meaningful
4354 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4355 unsigned FrameReg = ARI.getFrameRegister(MF);
4356 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4358 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4359 MachinePointerInfo());
4363 // FIXME? Maybe this could be a TableGen attribute on some registers and
4364 // this table could be generated automatically from RegInfo.
4365 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4366 SelectionDAG &DAG) const {
4367 unsigned Reg = StringSwitch<unsigned>(RegName)
4368 .Case("sp", ARM::SP)
4372 report_fatal_error(Twine("Invalid register name \""
4373 + StringRef(RegName) + "\"."));
4376 // Result is 64 bit value so split into two 32 bit values and return as a
4378 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4379 SelectionDAG &DAG) {
4382 // This function is only supposed to be called for i64 type destination.
4383 assert(N->getValueType(0) == MVT::i64
4384 && "ExpandREAD_REGISTER called for non-i64 type result.");
4386 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4387 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4391 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4393 Results.push_back(Read.getOperand(0));
4396 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4397 /// When \p DstVT, the destination type of \p BC, is on the vector
4398 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4399 /// it might be possible to combine them, such that everything stays on the
4400 /// vector register bank.
4401 /// \p return The node that would replace \p BT, if the combine
4403 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4404 SelectionDAG &DAG) {
4405 SDValue Op = BC->getOperand(0);
4406 EVT DstVT = BC->getValueType(0);
4408 // The only vector instruction that can produce a scalar (remember,
4409 // since the bitcast was about to be turned into VMOVDRR, the source
4410 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4411 // Moreover, we can do this combine only if there is one use.
4412 // Finally, if the destination type is not a vector, there is not
4413 // much point on forcing everything on the vector bank.
4414 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4418 // If the index is not constant, we will introduce an additional
4419 // multiply that will stick.
4420 // Give up in that case.
4421 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4424 unsigned DstNumElt = DstVT.getVectorNumElements();
4426 // Compute the new index.
4427 const APInt &APIntIndex = Index->getAPIntValue();
4428 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4429 NewIndex *= APIntIndex;
4430 // Check if the new constant index fits into i32.
4431 if (NewIndex.getBitWidth() > 32)
4434 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4435 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4437 SDValue ExtractSrc = Op.getOperand(0);
4438 EVT VecVT = EVT::getVectorVT(
4439 *DAG.getContext(), DstVT.getScalarType(),
4440 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4441 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4442 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4443 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4446 /// ExpandBITCAST - If the target supports VFP, this function is called to
4447 /// expand a bit convert where either the source or destination type is i64 to
4448 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4449 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4450 /// vectors), since the legalizer won't know what to do with that.
4451 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4452 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4454 SDValue Op = N->getOperand(0);
4456 // This function is only supposed to be called for i64 types, either as the
4457 // source or destination of the bit convert.
4458 EVT SrcVT = Op.getValueType();
4459 EVT DstVT = N->getValueType(0);
4460 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4461 "ExpandBITCAST called for non-i64 type");
4463 // Turn i64->f64 into VMOVDRR.
4464 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4465 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4466 // if we can combine the bitcast with its source.
4467 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4470 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4471 DAG.getConstant(0, dl, MVT::i32));
4472 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4473 DAG.getConstant(1, dl, MVT::i32));
4474 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4475 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4478 // Turn f64->i64 into VMOVRRD.
4479 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4481 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4482 SrcVT.getVectorNumElements() > 1)
4483 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4484 DAG.getVTList(MVT::i32, MVT::i32),
4485 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4487 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4488 DAG.getVTList(MVT::i32, MVT::i32), Op);
4489 // Merge the pieces into a single i64 value.
4490 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4496 /// getZeroVector - Returns a vector of specified type with all zero elements.
4497 /// Zero vectors are used to represent vector negation and in those cases
4498 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4499 /// not support i64 elements, so sometimes the zero vectors will need to be
4500 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4502 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4503 assert(VT.isVector() && "Expected a vector type");
4504 // The canonical modified immediate encoding of a zero vector is....0!
4505 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4506 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4507 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4508 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4511 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4512 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4513 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4514 SelectionDAG &DAG) const {
4515 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4516 EVT VT = Op.getValueType();
4517 unsigned VTBits = VT.getSizeInBits();
4519 SDValue ShOpLo = Op.getOperand(0);
4520 SDValue ShOpHi = Op.getOperand(1);
4521 SDValue ShAmt = Op.getOperand(2);
4523 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4525 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4527 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4528 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4529 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4530 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4531 DAG.getConstant(VTBits, dl, MVT::i32));
4532 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4533 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4534 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4536 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4537 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4538 ISD::SETGE, ARMcc, DAG, dl);
4539 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4540 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4543 SDValue Ops[2] = { Lo, Hi };
4544 return DAG.getMergeValues(Ops, dl);
4547 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4548 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4549 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4550 SelectionDAG &DAG) const {
4551 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4552 EVT VT = Op.getValueType();
4553 unsigned VTBits = VT.getSizeInBits();
4555 SDValue ShOpLo = Op.getOperand(0);
4556 SDValue ShOpHi = Op.getOperand(1);
4557 SDValue ShAmt = Op.getOperand(2);
4560 assert(Op.getOpcode() == ISD::SHL_PARTS);
4561 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4562 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4563 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4564 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4565 DAG.getConstant(VTBits, dl, MVT::i32));
4566 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4567 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4569 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4570 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4571 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4572 ISD::SETGE, ARMcc, DAG, dl);
4573 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4574 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4577 SDValue Ops[2] = { Lo, Hi };
4578 return DAG.getMergeValues(Ops, dl);
4581 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4582 SelectionDAG &DAG) const {
4583 // The rounding mode is in bits 23:22 of the FPSCR.
4584 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4585 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4586 // so that the shift + and get folded into a bitfield extract.
4588 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4589 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4591 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4592 DAG.getConstant(1U << 22, dl, MVT::i32));
4593 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4594 DAG.getConstant(22, dl, MVT::i32));
4595 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4596 DAG.getConstant(3, dl, MVT::i32));
4599 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4600 const ARMSubtarget *ST) {
4602 EVT VT = N->getValueType(0);
4603 if (VT.isVector()) {
4604 assert(ST->hasNEON());
4606 // Compute the least significant set bit: LSB = X & -X
4607 SDValue X = N->getOperand(0);
4608 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4609 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4611 EVT ElemTy = VT.getVectorElementType();
4613 if (ElemTy == MVT::i8) {
4614 // Compute with: cttz(x) = ctpop(lsb - 1)
4615 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4616 DAG.getTargetConstant(1, dl, ElemTy));
4617 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4618 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4621 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4622 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4623 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4624 unsigned NumBits = ElemTy.getSizeInBits();
4625 SDValue WidthMinus1 =
4626 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4627 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4628 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4629 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4632 // Compute with: cttz(x) = ctpop(lsb - 1)
4634 // Since we can only compute the number of bits in a byte with vcnt.8, we
4635 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4640 if (ElemTy == MVT::i64) {
4641 // Load constant 0xffff'ffff'ffff'ffff to register.
4642 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4643 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4644 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4646 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4647 DAG.getTargetConstant(1, dl, ElemTy));
4648 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4651 // Count #bits with vcnt.8.
4652 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4653 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4654 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4656 // Gather the #bits with vpaddl (pairwise add.)
4657 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4658 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4659 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4661 if (ElemTy == MVT::i16)
4664 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4665 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4666 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4668 if (ElemTy == MVT::i32)
4671 assert(ElemTy == MVT::i64);
4672 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4673 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4678 if (!ST->hasV6T2Ops())
4681 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4682 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4685 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4686 /// for each 16-bit element from operand, repeated. The basic idea is to
4687 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4689 /// Trace for v4i16:
4690 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4691 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4692 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4693 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4694 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4695 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4696 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4697 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4698 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4699 EVT VT = N->getValueType(0);
4702 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4703 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4704 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4705 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4706 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4707 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4710 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4711 /// bit-count for each 16-bit element from the operand. We need slightly
4712 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4713 /// 64/128-bit registers.
4715 /// Trace for v4i16:
4716 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4717 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4718 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4719 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4720 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4721 EVT VT = N->getValueType(0);
4724 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4725 if (VT.is64BitVector()) {
4726 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4727 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4728 DAG.getIntPtrConstant(0, DL));
4730 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4731 BitCounts, DAG.getIntPtrConstant(0, DL));
4732 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4736 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4737 /// bit-count for each 32-bit element from the operand. The idea here is
4738 /// to split the vector into 16-bit elements, leverage the 16-bit count
4739 /// routine, and then combine the results.
4741 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4742 /// input = [v0 v1 ] (vi: 32-bit elements)
4743 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4744 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4745 /// vrev: N0 = [k1 k0 k3 k2 ]
4747 /// N1 =+[k1 k0 k3 k2 ]
4749 /// N2 =+[k1 k3 k0 k2 ]
4751 /// Extended =+[k1 k3 k0 k2 ]
4753 /// Extracted=+[k1 k3 ]
4755 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4756 EVT VT = N->getValueType(0);
4759 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4761 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4762 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4763 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4764 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4765 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4767 if (VT.is64BitVector()) {
4768 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4769 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4770 DAG.getIntPtrConstant(0, DL));
4772 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4773 DAG.getIntPtrConstant(0, DL));
4774 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4778 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4779 const ARMSubtarget *ST) {
4780 EVT VT = N->getValueType(0);
4782 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4783 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4784 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4785 "Unexpected type for custom ctpop lowering");
4787 if (VT.getVectorElementType() == MVT::i32)
4788 return lowerCTPOP32BitElements(N, DAG);
4790 return lowerCTPOP16BitElements(N, DAG);
4793 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4794 const ARMSubtarget *ST) {
4795 EVT VT = N->getValueType(0);
4801 // Lower vector shifts on NEON to use VSHL.
4802 assert(ST->hasNEON() && "unexpected vector shift");
4804 // Left shifts translate directly to the vshiftu intrinsic.
4805 if (N->getOpcode() == ISD::SHL)
4806 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4807 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4809 N->getOperand(0), N->getOperand(1));
4811 assert((N->getOpcode() == ISD::SRA ||
4812 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4814 // NEON uses the same intrinsics for both left and right shifts. For
4815 // right shifts, the shift amounts are negative, so negate the vector of
4817 EVT ShiftVT = N->getOperand(1).getValueType();
4818 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4819 getZeroVector(ShiftVT, DAG, dl),
4821 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4822 Intrinsic::arm_neon_vshifts :
4823 Intrinsic::arm_neon_vshiftu);
4824 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4825 DAG.getConstant(vshiftInt, dl, MVT::i32),
4826 N->getOperand(0), NegatedCount);
4829 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4830 const ARMSubtarget *ST) {
4831 EVT VT = N->getValueType(0);
4834 // We can get here for a node like i32 = ISD::SHL i32, i64
4838 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4839 "Unknown shift to lower!");
4841 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4842 if (!isOneConstant(N->getOperand(1)))
4845 // If we are in thumb mode, we don't have RRX.
4846 if (ST->isThumb1Only()) return SDValue();
4848 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4849 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4850 DAG.getConstant(0, dl, MVT::i32));
4851 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4852 DAG.getConstant(1, dl, MVT::i32));
4854 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4855 // captures the result into a carry flag.
4856 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4857 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4859 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4860 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4862 // Merge the pieces into a single i64 value.
4863 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4866 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4867 SDValue TmpOp0, TmpOp1;
4868 bool Invert = false;
4872 SDValue Op0 = Op.getOperand(0);
4873 SDValue Op1 = Op.getOperand(1);
4874 SDValue CC = Op.getOperand(2);
4875 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4876 EVT VT = Op.getValueType();
4877 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4880 if (CmpVT.getVectorElementType() == MVT::i64)
4881 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4882 // but it's possible that our operands are 64-bit but our result is 32-bit.
4883 // Bail in this case.
4886 if (Op1.getValueType().isFloatingPoint()) {
4887 switch (SetCCOpcode) {
4888 default: llvm_unreachable("Illegal FP comparison");
4890 case ISD::SETNE: Invert = true; // Fallthrough
4892 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4894 case ISD::SETLT: Swap = true; // Fallthrough
4896 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4898 case ISD::SETLE: Swap = true; // Fallthrough
4900 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4901 case ISD::SETUGE: Swap = true; // Fallthrough
4902 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4903 case ISD::SETUGT: Swap = true; // Fallthrough
4904 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4905 case ISD::SETUEQ: Invert = true; // Fallthrough
4907 // Expand this to (OLT | OGT).
4911 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4912 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4914 case ISD::SETUO: Invert = true; // Fallthrough
4916 // Expand this to (OLT | OGE).
4920 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4921 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4925 // Integer comparisons.
4926 switch (SetCCOpcode) {
4927 default: llvm_unreachable("Illegal integer comparison");
4928 case ISD::SETNE: Invert = true;
4929 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4930 case ISD::SETLT: Swap = true;
4931 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4932 case ISD::SETLE: Swap = true;
4933 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4934 case ISD::SETULT: Swap = true;
4935 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4936 case ISD::SETULE: Swap = true;
4937 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4940 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4941 if (Opc == ARMISD::VCEQ) {
4944 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4946 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4949 // Ignore bitconvert.
4950 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4951 AndOp = AndOp.getOperand(0);
4953 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4955 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4956 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4963 std::swap(Op0, Op1);
4965 // If one of the operands is a constant vector zero, attempt to fold the
4966 // comparison to a specialized compare-against-zero form.
4968 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4970 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4971 if (Opc == ARMISD::VCGE)
4972 Opc = ARMISD::VCLEZ;
4973 else if (Opc == ARMISD::VCGT)
4974 Opc = ARMISD::VCLTZ;
4979 if (SingleOp.getNode()) {
4982 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4984 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4986 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4988 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4990 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4992 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4995 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4998 Result = DAG.getSExtOrTrunc(Result, dl, VT);
5001 Result = DAG.getNOT(dl, Result, VT);
5006 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5007 SDValue LHS = Op.getOperand(0);
5008 SDValue RHS = Op.getOperand(1);
5009 SDValue Carry = Op.getOperand(2);
5010 SDValue Cond = Op.getOperand(3);
5013 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5015 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5016 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5017 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5019 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5020 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5021 SDValue ARMcc = DAG.getConstant(
5022 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5023 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5024 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5025 Cmp.getValue(1), SDValue());
5026 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5027 CCR, Chain.getValue(1));
5030 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5031 /// valid vector constant for a NEON instruction with a "modified immediate"
5032 /// operand (e.g., VMOV). If so, return the encoded value.
5033 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5034 unsigned SplatBitSize, SelectionDAG &DAG,
5035 const SDLoc &dl, EVT &VT, bool is128Bits,
5036 NEONModImmType type) {
5037 unsigned OpCmode, Imm;
5039 // SplatBitSize is set to the smallest size that splats the vector, so a
5040 // zero vector will always have SplatBitSize == 8. However, NEON modified
5041 // immediate instructions others than VMOV do not support the 8-bit encoding
5042 // of a zero vector, and the default encoding of zero is supposed to be the
5047 switch (SplatBitSize) {
5049 if (type != VMOVModImm)
5051 // Any 1-byte value is OK. Op=0, Cmode=1110.
5052 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5055 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5059 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5060 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5061 if ((SplatBits & ~0xff) == 0) {
5062 // Value = 0x00nn: Op=x, Cmode=100x.
5067 if ((SplatBits & ~0xff00) == 0) {
5068 // Value = 0xnn00: Op=x, Cmode=101x.
5070 Imm = SplatBits >> 8;
5076 // NEON's 32-bit VMOV supports splat values where:
5077 // * only one byte is nonzero, or
5078 // * the least significant byte is 0xff and the second byte is nonzero, or
5079 // * the least significant 2 bytes are 0xff and the third is nonzero.
5080 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5081 if ((SplatBits & ~0xff) == 0) {
5082 // Value = 0x000000nn: Op=x, Cmode=000x.
5087 if ((SplatBits & ~0xff00) == 0) {
5088 // Value = 0x0000nn00: Op=x, Cmode=001x.
5090 Imm = SplatBits >> 8;
5093 if ((SplatBits & ~0xff0000) == 0) {
5094 // Value = 0x00nn0000: Op=x, Cmode=010x.
5096 Imm = SplatBits >> 16;
5099 if ((SplatBits & ~0xff000000) == 0) {
5100 // Value = 0xnn000000: Op=x, Cmode=011x.
5102 Imm = SplatBits >> 24;
5106 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5107 if (type == OtherModImm) return SDValue();
5109 if ((SplatBits & ~0xffff) == 0 &&
5110 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5111 // Value = 0x0000nnff: Op=x, Cmode=1100.
5113 Imm = SplatBits >> 8;
5117 if ((SplatBits & ~0xffffff) == 0 &&
5118 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5119 // Value = 0x00nnffff: Op=x, Cmode=1101.
5121 Imm = SplatBits >> 16;
5125 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5126 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5127 // VMOV.I32. A (very) minor optimization would be to replicate the value
5128 // and fall through here to test for a valid 64-bit splat. But, then the
5129 // caller would also need to check and handle the change in size.
5133 if (type != VMOVModImm)
5135 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5136 uint64_t BitMask = 0xff;
5138 unsigned ImmMask = 1;
5140 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5141 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5144 } else if ((SplatBits & BitMask) != 0) {
5151 if (DAG.getDataLayout().isBigEndian())
5152 // swap higher and lower 32 bit word
5153 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5155 // Op=1, Cmode=1110.
5157 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5162 llvm_unreachable("unexpected size for isNEONModifiedImm");
5165 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5166 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5169 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5170 const ARMSubtarget *ST) const {
5174 bool IsDouble = Op.getValueType() == MVT::f64;
5175 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5177 // Use the default (constant pool) lowering for double constants when we have
5179 if (IsDouble && Subtarget->isFPOnlySP())
5182 // Try splatting with a VMOV.f32...
5183 const APFloat &FPVal = CFP->getValueAPF();
5184 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5187 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5188 // We have code in place to select a valid ConstantFP already, no need to
5193 // It's a float and we are trying to use NEON operations where
5194 // possible. Lower it to a splat followed by an extract.
5196 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5197 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5199 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5200 DAG.getConstant(0, DL, MVT::i32));
5203 // The rest of our options are NEON only, make sure that's allowed before
5205 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5209 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5211 // It wouldn't really be worth bothering for doubles except for one very
5212 // important value, which does happen to match: 0.0. So make sure we don't do
5214 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5217 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5218 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5219 VMovVT, false, VMOVModImm);
5220 if (NewVal != SDValue()) {
5222 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5225 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5227 // It's a float: cast and extract a vector element.
5228 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5230 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5231 DAG.getConstant(0, DL, MVT::i32));
5234 // Finally, try a VMVN.i32
5235 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5237 if (NewVal != SDValue()) {
5239 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5242 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5244 // It's a float: cast and extract a vector element.
5245 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5247 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5248 DAG.getConstant(0, DL, MVT::i32));
5254 // check if an VEXT instruction can handle the shuffle mask when the
5255 // vector sources of the shuffle are the same.
5256 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5257 unsigned NumElts = VT.getVectorNumElements();
5259 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5265 // If this is a VEXT shuffle, the immediate value is the index of the first
5266 // element. The other shuffle indices must be the successive elements after
5268 unsigned ExpectedElt = Imm;
5269 for (unsigned i = 1; i < NumElts; ++i) {
5270 // Increment the expected index. If it wraps around, just follow it
5271 // back to index zero and keep going.
5273 if (ExpectedElt == NumElts)
5276 if (M[i] < 0) continue; // ignore UNDEF indices
5277 if (ExpectedElt != static_cast<unsigned>(M[i]))
5285 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5286 bool &ReverseVEXT, unsigned &Imm) {
5287 unsigned NumElts = VT.getVectorNumElements();
5288 ReverseVEXT = false;
5290 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5296 // If this is a VEXT shuffle, the immediate value is the index of the first
5297 // element. The other shuffle indices must be the successive elements after
5299 unsigned ExpectedElt = Imm;
5300 for (unsigned i = 1; i < NumElts; ++i) {
5301 // Increment the expected index. If it wraps around, it may still be
5302 // a VEXT but the source vectors must be swapped.
5304 if (ExpectedElt == NumElts * 2) {
5309 if (M[i] < 0) continue; // ignore UNDEF indices
5310 if (ExpectedElt != static_cast<unsigned>(M[i]))
5314 // Adjust the index value if the source operands will be swapped.
5321 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5322 /// instruction with the specified blocksize. (The order of the elements
5323 /// within each block of the vector is reversed.)
5324 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5325 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5326 "Only possible block sizes for VREV are: 16, 32, 64");
5328 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5332 unsigned NumElts = VT.getVectorNumElements();
5333 unsigned BlockElts = M[0] + 1;
5334 // If the first shuffle index is UNDEF, be optimistic.
5336 BlockElts = BlockSize / EltSz;
5338 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5341 for (unsigned i = 0; i < NumElts; ++i) {
5342 if (M[i] < 0) continue; // ignore UNDEF indices
5343 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5350 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5351 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5352 // range, then 0 is placed into the resulting vector. So pretty much any mask
5353 // of 8 elements can work here.
5354 return VT == MVT::v8i8 && M.size() == 8;
5357 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5358 // checking that pairs of elements in the shuffle mask represent the same index
5359 // in each vector, incrementing the expected index by 2 at each step.
5360 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5361 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5363 // WhichResult gives the offset for each element in the mask based on which
5364 // of the two results it belongs to.
5366 // The transpose can be represented either as:
5367 // result1 = shufflevector v1, v2, result1_shuffle_mask
5368 // result2 = shufflevector v1, v2, result2_shuffle_mask
5369 // where v1/v2 and the shuffle masks have the same number of elements
5370 // (here WhichResult (see below) indicates which result is being checked)
5373 // results = shufflevector v1, v2, shuffle_mask
5374 // where both results are returned in one vector and the shuffle mask has twice
5375 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5376 // want to check the low half and high half of the shuffle mask as if it were
5378 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5379 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5383 unsigned NumElts = VT.getVectorNumElements();
5384 if (M.size() != NumElts && M.size() != NumElts*2)
5387 // If the mask is twice as long as the input vector then we need to check the
5388 // upper and lower parts of the mask with a matching value for WhichResult
5389 // FIXME: A mask with only even values will be rejected in case the first
5390 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5391 // M[0] is used to determine WhichResult
5392 for (unsigned i = 0; i < M.size(); i += NumElts) {
5393 if (M.size() == NumElts * 2)
5394 WhichResult = i / NumElts;
5396 WhichResult = M[i] == 0 ? 0 : 1;
5397 for (unsigned j = 0; j < NumElts; j += 2) {
5398 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5399 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5404 if (M.size() == NumElts*2)
5410 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5411 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5412 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5413 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5414 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5418 unsigned NumElts = VT.getVectorNumElements();
5419 if (M.size() != NumElts && M.size() != NumElts*2)
5422 for (unsigned i = 0; i < M.size(); i += NumElts) {
5423 if (M.size() == NumElts * 2)
5424 WhichResult = i / NumElts;
5426 WhichResult = M[i] == 0 ? 0 : 1;
5427 for (unsigned j = 0; j < NumElts; j += 2) {
5428 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5429 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5434 if (M.size() == NumElts*2)
5440 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5441 // that the mask elements are either all even and in steps of size 2 or all odd
5442 // and in steps of size 2.
5443 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5444 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5446 // Requires similar checks to that of isVTRNMask with
5447 // respect the how results are returned.
5448 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5449 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5453 unsigned NumElts = VT.getVectorNumElements();
5454 if (M.size() != NumElts && M.size() != NumElts*2)
5457 for (unsigned i = 0; i < M.size(); i += NumElts) {
5458 WhichResult = M[i] == 0 ? 0 : 1;
5459 for (unsigned j = 0; j < NumElts; ++j) {
5460 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5465 if (M.size() == NumElts*2)
5468 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5469 if (VT.is64BitVector() && EltSz == 32)
5475 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5476 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5477 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5478 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5479 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5483 unsigned NumElts = VT.getVectorNumElements();
5484 if (M.size() != NumElts && M.size() != NumElts*2)
5487 unsigned Half = NumElts / 2;
5488 for (unsigned i = 0; i < M.size(); i += NumElts) {
5489 WhichResult = M[i] == 0 ? 0 : 1;
5490 for (unsigned j = 0; j < NumElts; j += Half) {
5491 unsigned Idx = WhichResult;
5492 for (unsigned k = 0; k < Half; ++k) {
5493 int MIdx = M[i + j + k];
5494 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5501 if (M.size() == NumElts*2)
5504 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5505 if (VT.is64BitVector() && EltSz == 32)
5511 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5512 // that pairs of elements of the shufflemask represent the same index in each
5513 // vector incrementing sequentially through the vectors.
5514 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5515 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5517 // Requires similar checks to that of isVTRNMask with respect the how results
5519 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5520 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5524 unsigned NumElts = VT.getVectorNumElements();
5525 if (M.size() != NumElts && M.size() != NumElts*2)
5528 for (unsigned i = 0; i < M.size(); i += NumElts) {
5529 WhichResult = M[i] == 0 ? 0 : 1;
5530 unsigned Idx = WhichResult * NumElts / 2;
5531 for (unsigned j = 0; j < NumElts; j += 2) {
5532 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5533 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5539 if (M.size() == NumElts*2)
5542 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5543 if (VT.is64BitVector() && EltSz == 32)
5549 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5550 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5551 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5552 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5553 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5557 unsigned NumElts = VT.getVectorNumElements();
5558 if (M.size() != NumElts && M.size() != NumElts*2)
5561 for (unsigned i = 0; i < M.size(); i += NumElts) {
5562 WhichResult = M[i] == 0 ? 0 : 1;
5563 unsigned Idx = WhichResult * NumElts / 2;
5564 for (unsigned j = 0; j < NumElts; j += 2) {
5565 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5566 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5572 if (M.size() == NumElts*2)
5575 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5576 if (VT.is64BitVector() && EltSz == 32)
5582 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5583 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5584 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5585 unsigned &WhichResult,
5588 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5589 return ARMISD::VTRN;
5590 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5591 return ARMISD::VUZP;
5592 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5593 return ARMISD::VZIP;
5596 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5597 return ARMISD::VTRN;
5598 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5599 return ARMISD::VUZP;
5600 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5601 return ARMISD::VZIP;
5606 /// \return true if this is a reverse operation on an vector.
5607 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5608 unsigned NumElts = VT.getVectorNumElements();
5609 // Make sure the mask has the right size.
5610 if (NumElts != M.size())
5613 // Look for <15, ..., 3, -1, 1, 0>.
5614 for (unsigned i = 0; i != NumElts; ++i)
5615 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5621 // If N is an integer constant that can be moved into a register in one
5622 // instruction, return an SDValue of such a constant (will become a MOV
5623 // instruction). Otherwise return null.
5624 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5625 const ARMSubtarget *ST, const SDLoc &dl) {
5627 if (!isa<ConstantSDNode>(N))
5629 Val = cast<ConstantSDNode>(N)->getZExtValue();
5631 if (ST->isThumb1Only()) {
5632 if (Val <= 255 || ~Val <= 255)
5633 return DAG.getConstant(Val, dl, MVT::i32);
5635 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5636 return DAG.getConstant(Val, dl, MVT::i32);
5641 // If this is a case we can't handle, return null and let the default
5642 // expansion code take care of it.
5643 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5644 const ARMSubtarget *ST) const {
5645 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5647 EVT VT = Op.getValueType();
5649 APInt SplatBits, SplatUndef;
5650 unsigned SplatBitSize;
5652 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5653 if (SplatBitSize <= 64) {
5654 // Check if an immediate VMOV works.
5656 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5657 SplatUndef.getZExtValue(), SplatBitSize,
5658 DAG, dl, VmovVT, VT.is128BitVector(),
5660 if (Val.getNode()) {
5661 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5662 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5665 // Try an immediate VMVN.
5666 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5667 Val = isNEONModifiedImm(NegatedImm,
5668 SplatUndef.getZExtValue(), SplatBitSize,
5669 DAG, dl, VmovVT, VT.is128BitVector(),
5671 if (Val.getNode()) {
5672 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5673 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5676 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5677 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5678 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5680 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5681 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5687 // Scan through the operands to see if only one value is used.
5689 // As an optimisation, even if more than one value is used it may be more
5690 // profitable to splat with one value then change some lanes.
5692 // Heuristically we decide to do this if the vector has a "dominant" value,
5693 // defined as splatted to more than half of the lanes.
5694 unsigned NumElts = VT.getVectorNumElements();
5695 bool isOnlyLowElement = true;
5696 bool usesOnlyOneValue = true;
5697 bool hasDominantValue = false;
5698 bool isConstant = true;
5700 // Map of the number of times a particular SDValue appears in the
5702 DenseMap<SDValue, unsigned> ValueCounts;
5704 for (unsigned i = 0; i < NumElts; ++i) {
5705 SDValue V = Op.getOperand(i);
5709 isOnlyLowElement = false;
5710 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5713 ValueCounts.insert(std::make_pair(V, 0));
5714 unsigned &Count = ValueCounts[V];
5716 // Is this value dominant? (takes up more than half of the lanes)
5717 if (++Count > (NumElts / 2)) {
5718 hasDominantValue = true;
5722 if (ValueCounts.size() != 1)
5723 usesOnlyOneValue = false;
5724 if (!Value.getNode() && ValueCounts.size() > 0)
5725 Value = ValueCounts.begin()->first;
5727 if (ValueCounts.size() == 0)
5728 return DAG.getUNDEF(VT);
5730 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5731 // Keep going if we are hitting this case.
5732 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5733 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5735 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5737 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5738 // i32 and try again.
5739 if (hasDominantValue && EltSize <= 32) {
5743 // If we are VDUPing a value that comes directly from a vector, that will
5744 // cause an unnecessary move to and from a GPR, where instead we could
5745 // just use VDUPLANE. We can only do this if the lane being extracted
5746 // is at a constant index, as the VDUP from lane instructions only have
5747 // constant-index forms.
5748 ConstantSDNode *constIndex;
5749 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5750 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5751 // We need to create a new undef vector to use for the VDUPLANE if the
5752 // size of the vector from which we get the value is different than the
5753 // size of the vector that we need to create. We will insert the element
5754 // such that the register coalescer will remove unnecessary copies.
5755 if (VT != Value->getOperand(0).getValueType()) {
5756 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5757 VT.getVectorNumElements();
5758 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5759 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5760 Value, DAG.getConstant(index, dl, MVT::i32)),
5761 DAG.getConstant(index, dl, MVT::i32));
5763 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5764 Value->getOperand(0), Value->getOperand(1));
5766 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5768 if (!usesOnlyOneValue) {
5769 // The dominant value was splatted as 'N', but we now have to insert
5770 // all differing elements.
5771 for (unsigned I = 0; I < NumElts; ++I) {
5772 if (Op.getOperand(I) == Value)
5774 SmallVector<SDValue, 3> Ops;
5776 Ops.push_back(Op.getOperand(I));
5777 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5778 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5783 if (VT.getVectorElementType().isFloatingPoint()) {
5784 SmallVector<SDValue, 8> Ops;
5785 for (unsigned i = 0; i < NumElts; ++i)
5786 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5788 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5789 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
5790 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5792 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5794 if (usesOnlyOneValue) {
5795 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5796 if (isConstant && Val.getNode())
5797 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5801 // If all elements are constants and the case above didn't get hit, fall back
5802 // to the default expansion, which will generate a load from the constant
5807 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5809 SDValue shuffle = ReconstructShuffle(Op, DAG);
5810 if (shuffle != SDValue())
5814 // Vectors with 32- or 64-bit elements can be built by directly assigning
5815 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5816 // will be legalized.
5817 if (EltSize >= 32) {
5818 // Do the expansion with floating-point types, since that is what the VFP
5819 // registers are defined to use, and since i64 is not legal.
5820 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5821 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5822 SmallVector<SDValue, 8> Ops;
5823 for (unsigned i = 0; i < NumElts; ++i)
5824 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5825 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5826 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5829 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5830 // know the default expansion would otherwise fall back on something even
5831 // worse. For a vector with one or two non-undef values, that's
5832 // scalar_to_vector for the elements followed by a shuffle (provided the
5833 // shuffle is valid for the target) and materialization element by element
5834 // on the stack followed by a load for everything else.
5835 if (!isConstant && !usesOnlyOneValue) {
5836 SDValue Vec = DAG.getUNDEF(VT);
5837 for (unsigned i = 0 ; i < NumElts; ++i) {
5838 SDValue V = Op.getOperand(i);
5841 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5842 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5850 // Gather data to see if the operation can be modelled as a
5851 // shuffle in combination with VEXTs.
5852 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5853 SelectionDAG &DAG) const {
5854 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5856 EVT VT = Op.getValueType();
5857 unsigned NumElts = VT.getVectorNumElements();
5859 struct ShuffleSourceInfo {
5864 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5865 // be compatible with the shuffle we intend to construct. As a result
5866 // ShuffleVec will be some sliding window into the original Vec.
5869 // Code should guarantee that element i in Vec starts at element "WindowBase
5870 // + i * WindowScale in ShuffleVec".
5874 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5875 ShuffleSourceInfo(SDValue Vec)
5876 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5880 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5882 SmallVector<ShuffleSourceInfo, 2> Sources;
5883 for (unsigned i = 0; i < NumElts; ++i) {
5884 SDValue V = Op.getOperand(i);
5887 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5888 // A shuffle can only come from building a vector from various
5889 // elements of other vectors.
5891 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5892 // Furthermore, shuffles require a constant mask, whereas extractelts
5893 // accept variable indices.
5897 // Add this element source to the list if it's not already there.
5898 SDValue SourceVec = V.getOperand(0);
5899 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5900 if (Source == Sources.end())
5901 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5903 // Update the minimum and maximum lane number seen.
5904 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5905 Source->MinElt = std::min(Source->MinElt, EltNo);
5906 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5909 // Currently only do something sane when at most two source vectors
5911 if (Sources.size() > 2)
5914 // Find out the smallest element size among result and two sources, and use
5915 // it as element size to build the shuffle_vector.
5916 EVT SmallestEltTy = VT.getVectorElementType();
5917 for (auto &Source : Sources) {
5918 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5919 if (SrcEltTy.bitsLT(SmallestEltTy))
5920 SmallestEltTy = SrcEltTy;
5922 unsigned ResMultiplier =
5923 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5924 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5925 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5927 // If the source vector is too wide or too narrow, we may nevertheless be able
5928 // to construct a compatible shuffle either by concatenating it with UNDEF or
5929 // extracting a suitable range of elements.
5930 for (auto &Src : Sources) {
5931 EVT SrcVT = Src.ShuffleVec.getValueType();
5933 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5936 // This stage of the search produces a source with the same element type as
5937 // the original, but with a total width matching the BUILD_VECTOR output.
5938 EVT EltVT = SrcVT.getVectorElementType();
5939 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5940 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5942 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5943 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5945 // We can pad out the smaller vector for free, so if it's part of a
5948 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5949 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5953 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5956 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5957 // Span too large for a VEXT to cope
5961 if (Src.MinElt >= NumSrcElts) {
5962 // The extraction can just take the second half
5964 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5965 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5966 Src.WindowBase = -NumSrcElts;
5967 } else if (Src.MaxElt < NumSrcElts) {
5968 // The extraction can just take the first half
5970 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5971 DAG.getConstant(0, dl, MVT::i32));
5973 // An actual VEXT is needed
5975 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5976 DAG.getConstant(0, dl, MVT::i32));
5978 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5979 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5981 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5983 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5984 Src.WindowBase = -Src.MinElt;
5988 // Another possible incompatibility occurs from the vector element types. We
5989 // can fix this by bitcasting the source vectors to the same type we intend
5991 for (auto &Src : Sources) {
5992 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5993 if (SrcEltTy == SmallestEltTy)
5995 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5996 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5997 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5998 Src.WindowBase *= Src.WindowScale;
6001 // Final sanity check before we try to actually produce a shuffle.
6003 for (auto Src : Sources)
6004 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6007 // The stars all align, our next step is to produce the mask for the shuffle.
6008 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6009 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
6010 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6011 SDValue Entry = Op.getOperand(i);
6012 if (Entry.isUndef())
6015 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
6016 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6018 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6019 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6021 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6022 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6023 VT.getVectorElementType().getSizeInBits());
6024 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6026 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6027 // starting at the appropriate offset.
6028 int *LaneMask = &Mask[i * ResMultiplier];
6030 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6031 ExtractBase += NumElts * (Src - Sources.begin());
6032 for (int j = 0; j < LanesDefined; ++j)
6033 LaneMask[j] = ExtractBase + j;
6036 // Final check before we try to produce nonsense...
6037 if (!isShuffleMaskLegal(Mask, ShuffleVT))
6040 // We can't handle more than two sources. This should have already
6041 // been checked before this point.
6042 assert(Sources.size() <= 2 && "Too many sources!");
6044 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6045 for (unsigned i = 0; i < Sources.size(); ++i)
6046 ShuffleOps[i] = Sources[i].ShuffleVec;
6048 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6049 ShuffleOps[1], Mask);
6050 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6053 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6054 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6055 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6056 /// are assumed to be legal.
6058 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6060 if (VT.getVectorNumElements() == 4 &&
6061 (VT.is128BitVector() || VT.is64BitVector())) {
6062 unsigned PFIndexes[4];
6063 for (unsigned i = 0; i != 4; ++i) {
6067 PFIndexes[i] = M[i];
6070 // Compute the index in the perfect shuffle table.
6071 unsigned PFTableIndex =
6072 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6073 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6074 unsigned Cost = (PFEntry >> 30);
6080 bool ReverseVEXT, isV_UNDEF;
6081 unsigned Imm, WhichResult;
6083 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6084 return (EltSize >= 32 ||
6085 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6086 isVREVMask(M, VT, 64) ||
6087 isVREVMask(M, VT, 32) ||
6088 isVREVMask(M, VT, 16) ||
6089 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6090 isVTBLMask(M, VT) ||
6091 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6092 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6095 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6096 /// the specified operations to build the shuffle.
6097 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6098 SDValue RHS, SelectionDAG &DAG,
6100 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6101 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6102 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6105 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6114 OP_VUZPL, // VUZP, left result
6115 OP_VUZPR, // VUZP, right result
6116 OP_VZIPL, // VZIP, left result
6117 OP_VZIPR, // VZIP, right result
6118 OP_VTRNL, // VTRN, left result
6119 OP_VTRNR // VTRN, right result
6122 if (OpNum == OP_COPY) {
6123 if (LHSID == (1*9+2)*9+3) return LHS;
6124 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6128 SDValue OpLHS, OpRHS;
6129 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6130 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6131 EVT VT = OpLHS.getValueType();
6134 default: llvm_unreachable("Unknown shuffle opcode!");
6136 // VREV divides the vector in half and swaps within the half.
6137 if (VT.getVectorElementType() == MVT::i32 ||
6138 VT.getVectorElementType() == MVT::f32)
6139 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6140 // vrev <4 x i16> -> VREV32
6141 if (VT.getVectorElementType() == MVT::i16)
6142 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6143 // vrev <4 x i8> -> VREV16
6144 assert(VT.getVectorElementType() == MVT::i8);
6145 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6150 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6151 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6155 return DAG.getNode(ARMISD::VEXT, dl, VT,
6157 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6160 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6161 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6164 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6165 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6168 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6169 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6173 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6174 ArrayRef<int> ShuffleMask,
6175 SelectionDAG &DAG) {
6176 // Check to see if we can use the VTBL instruction.
6177 SDValue V1 = Op.getOperand(0);
6178 SDValue V2 = Op.getOperand(1);
6181 SmallVector<SDValue, 8> VTBLMask;
6182 for (ArrayRef<int>::iterator
6183 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6184 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6186 if (V2.getNode()->isUndef())
6187 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6188 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6190 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6191 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6194 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6195 SelectionDAG &DAG) {
6197 SDValue OpLHS = Op.getOperand(0);
6198 EVT VT = OpLHS.getValueType();
6200 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6201 "Expect an v8i16/v16i8 type");
6202 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6203 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6204 // extract the first 8 bytes into the top double word and the last 8 bytes
6205 // into the bottom double word. The v8i16 case is similar.
6206 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6207 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6208 DAG.getConstant(ExtractNum, DL, MVT::i32));
6211 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6212 SDValue V1 = Op.getOperand(0);
6213 SDValue V2 = Op.getOperand(1);
6215 EVT VT = Op.getValueType();
6216 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6218 // Convert shuffles that are directly supported on NEON to target-specific
6219 // DAG nodes, instead of keeping them as shuffles and matching them again
6220 // during code selection. This is more efficient and avoids the possibility
6221 // of inconsistencies between legalization and selection.
6222 // FIXME: floating-point vectors should be canonicalized to integer vectors
6223 // of the same time so that they get CSEd properly.
6224 ArrayRef<int> ShuffleMask = SVN->getMask();
6226 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6227 if (EltSize <= 32) {
6228 if (SVN->isSplat()) {
6229 int Lane = SVN->getSplatIndex();
6230 // If this is undef splat, generate it via "just" vdup, if possible.
6231 if (Lane == -1) Lane = 0;
6233 // Test if V1 is a SCALAR_TO_VECTOR.
6234 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6235 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6237 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6238 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6240 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6241 !isa<ConstantSDNode>(V1.getOperand(0))) {
6242 bool IsScalarToVector = true;
6243 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6244 if (!V1.getOperand(i).isUndef()) {
6245 IsScalarToVector = false;
6248 if (IsScalarToVector)
6249 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6251 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6252 DAG.getConstant(Lane, dl, MVT::i32));
6257 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6260 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6261 DAG.getConstant(Imm, dl, MVT::i32));
6264 if (isVREVMask(ShuffleMask, VT, 64))
6265 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6266 if (isVREVMask(ShuffleMask, VT, 32))
6267 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6268 if (isVREVMask(ShuffleMask, VT, 16))
6269 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6271 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6272 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6273 DAG.getConstant(Imm, dl, MVT::i32));
6276 // Check for Neon shuffles that modify both input vectors in place.
6277 // If both results are used, i.e., if there are two shuffles with the same
6278 // source operands and with masks corresponding to both results of one of
6279 // these operations, DAG memoization will ensure that a single node is
6280 // used for both shuffles.
6281 unsigned WhichResult;
6283 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6284 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6287 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6288 .getValue(WhichResult);
6291 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6292 // shuffles that produce a result larger than their operands with:
6293 // shuffle(concat(v1, undef), concat(v2, undef))
6295 // shuffle(concat(v1, v2), undef)
6296 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6298 // This is useful in the general case, but there are special cases where
6299 // native shuffles produce larger results: the two-result ops.
6301 // Look through the concat when lowering them:
6302 // shuffle(concat(v1, v2), undef)
6304 // concat(VZIP(v1, v2):0, :1)
6306 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6307 SDValue SubV1 = V1->getOperand(0);
6308 SDValue SubV2 = V1->getOperand(1);
6309 EVT SubVT = SubV1.getValueType();
6311 // We expect these to have been canonicalized to -1.
6312 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6313 return i < (int)VT.getVectorNumElements();
6314 }) && "Unexpected shuffle index into UNDEF operand!");
6316 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6317 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6320 assert((WhichResult == 0) &&
6321 "In-place shuffle of concat can only have one result!");
6322 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6324 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6330 // If the shuffle is not directly supported and it has 4 elements, use
6331 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6332 unsigned NumElts = VT.getVectorNumElements();
6334 unsigned PFIndexes[4];
6335 for (unsigned i = 0; i != 4; ++i) {
6336 if (ShuffleMask[i] < 0)
6339 PFIndexes[i] = ShuffleMask[i];
6342 // Compute the index in the perfect shuffle table.
6343 unsigned PFTableIndex =
6344 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6345 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6346 unsigned Cost = (PFEntry >> 30);
6349 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6352 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6353 if (EltSize >= 32) {
6354 // Do the expansion with floating-point types, since that is what the VFP
6355 // registers are defined to use, and since i64 is not legal.
6356 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6357 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6358 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6359 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6360 SmallVector<SDValue, 8> Ops;
6361 for (unsigned i = 0; i < NumElts; ++i) {
6362 if (ShuffleMask[i] < 0)
6363 Ops.push_back(DAG.getUNDEF(EltVT));
6365 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6366 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6367 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6370 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6371 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6374 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6375 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6377 if (VT == MVT::v8i8)
6378 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6384 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6385 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6386 SDValue Lane = Op.getOperand(2);
6387 if (!isa<ConstantSDNode>(Lane))
6393 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6394 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6395 SDValue Lane = Op.getOperand(1);
6396 if (!isa<ConstantSDNode>(Lane))
6399 SDValue Vec = Op.getOperand(0);
6400 if (Op.getValueType() == MVT::i32 &&
6401 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6403 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6409 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6410 // The only time a CONCAT_VECTORS operation can have legal types is when
6411 // two 64-bit vectors are concatenated to a 128-bit vector.
6412 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6413 "unexpected CONCAT_VECTORS");
6415 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6416 SDValue Op0 = Op.getOperand(0);
6417 SDValue Op1 = Op.getOperand(1);
6419 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6420 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6421 DAG.getIntPtrConstant(0, dl));
6423 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6424 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6425 DAG.getIntPtrConstant(1, dl));
6426 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6429 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6430 /// element has been zero/sign-extended, depending on the isSigned parameter,
6431 /// from an integer type half its size.
6432 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6434 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6435 EVT VT = N->getValueType(0);
6436 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6437 SDNode *BVN = N->getOperand(0).getNode();
6438 if (BVN->getValueType(0) != MVT::v4i32 ||
6439 BVN->getOpcode() != ISD::BUILD_VECTOR)
6441 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6442 unsigned HiElt = 1 - LoElt;
6443 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6444 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6445 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6446 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6447 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6450 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6451 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6454 if (Hi0->isNullValue() && Hi1->isNullValue())
6460 if (N->getOpcode() != ISD::BUILD_VECTOR)
6463 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6464 SDNode *Elt = N->getOperand(i).getNode();
6465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6466 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6467 unsigned HalfSize = EltSize / 2;
6469 if (!isIntN(HalfSize, C->getSExtValue()))
6472 if (!isUIntN(HalfSize, C->getZExtValue()))
6483 /// isSignExtended - Check if a node is a vector value that is sign-extended
6484 /// or a constant BUILD_VECTOR with sign-extended elements.
6485 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6486 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6488 if (isExtendedBUILD_VECTOR(N, DAG, true))
6493 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6494 /// or a constant BUILD_VECTOR with zero-extended elements.
6495 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6496 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6498 if (isExtendedBUILD_VECTOR(N, DAG, false))
6503 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6504 if (OrigVT.getSizeInBits() >= 64)
6507 assert(OrigVT.isSimple() && "Expecting a simple value type");
6509 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6510 switch (OrigSimpleTy) {
6511 default: llvm_unreachable("Unexpected Vector Type");
6520 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6521 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6522 /// We insert the required extension here to get the vector to fill a D register.
6523 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6526 unsigned ExtOpcode) {
6527 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6528 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6529 // 64-bits we need to insert a new extension so that it will be 64-bits.
6530 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6531 if (OrigTy.getSizeInBits() >= 64)
6534 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6535 EVT NewVT = getExtensionTo64Bits(OrigTy);
6537 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6540 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6541 /// does not do any sign/zero extension. If the original vector is less
6542 /// than 64 bits, an appropriate extension will be added after the load to
6543 /// reach a total size of 64 bits. We have to add the extension separately
6544 /// because ARM does not have a sign/zero extending load for vectors.
6545 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6546 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6548 // The load already has the right type.
6549 if (ExtendedTy == LD->getMemoryVT())
6550 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6551 LD->getBasePtr(), LD->getPointerInfo(),
6552 LD->getAlignment(), LD->getMemOperand()->getFlags());
6554 // We need to create a zextload/sextload. We cannot just create a load
6555 // followed by a zext/zext node because LowerMUL is also run during normal
6556 // operation legalization where we can't create illegal types.
6557 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6558 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6559 LD->getMemoryVT(), LD->getAlignment(),
6560 LD->getMemOperand()->getFlags());
6563 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6564 /// extending load, or BUILD_VECTOR with extended elements, return the
6565 /// unextended value. The unextended vector should be 64 bits so that it can
6566 /// be used as an operand to a VMULL instruction. If the original vector size
6567 /// before extension is less than 64 bits we add a an extension to resize
6568 /// the vector to 64 bits.
6569 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6570 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6571 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6572 N->getOperand(0)->getValueType(0),
6576 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6577 return SkipLoadExtensionForVMULL(LD, DAG);
6579 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6580 // have been legalized as a BITCAST from v4i32.
6581 if (N->getOpcode() == ISD::BITCAST) {
6582 SDNode *BVN = N->getOperand(0).getNode();
6583 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6584 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6585 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6586 return DAG.getBuildVector(
6587 MVT::v2i32, SDLoc(N),
6588 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
6590 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6591 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6592 EVT VT = N->getValueType(0);
6593 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6594 unsigned NumElts = VT.getVectorNumElements();
6595 MVT TruncVT = MVT::getIntegerVT(EltSize);
6596 SmallVector<SDValue, 8> Ops;
6598 for (unsigned i = 0; i != NumElts; ++i) {
6599 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6600 const APInt &CInt = C->getAPIntValue();
6601 // Element types smaller than 32 bits are not legal, so use i32 elements.
6602 // The values are implicitly truncated so sext vs. zext doesn't matter.
6603 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6605 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
6608 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6609 unsigned Opcode = N->getOpcode();
6610 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6611 SDNode *N0 = N->getOperand(0).getNode();
6612 SDNode *N1 = N->getOperand(1).getNode();
6613 return N0->hasOneUse() && N1->hasOneUse() &&
6614 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6619 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6620 unsigned Opcode = N->getOpcode();
6621 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6622 SDNode *N0 = N->getOperand(0).getNode();
6623 SDNode *N1 = N->getOperand(1).getNode();
6624 return N0->hasOneUse() && N1->hasOneUse() &&
6625 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6630 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6631 // Multiplications are only custom-lowered for 128-bit vectors so that
6632 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6633 EVT VT = Op.getValueType();
6634 assert(VT.is128BitVector() && VT.isInteger() &&
6635 "unexpected type for custom-lowering ISD::MUL");
6636 SDNode *N0 = Op.getOperand(0).getNode();
6637 SDNode *N1 = Op.getOperand(1).getNode();
6638 unsigned NewOpc = 0;
6640 bool isN0SExt = isSignExtended(N0, DAG);
6641 bool isN1SExt = isSignExtended(N1, DAG);
6642 if (isN0SExt && isN1SExt)
6643 NewOpc = ARMISD::VMULLs;
6645 bool isN0ZExt = isZeroExtended(N0, DAG);
6646 bool isN1ZExt = isZeroExtended(N1, DAG);
6647 if (isN0ZExt && isN1ZExt)
6648 NewOpc = ARMISD::VMULLu;
6649 else if (isN1SExt || isN1ZExt) {
6650 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6651 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6652 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6653 NewOpc = ARMISD::VMULLs;
6655 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6656 NewOpc = ARMISD::VMULLu;
6658 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6660 NewOpc = ARMISD::VMULLu;
6666 if (VT == MVT::v2i64)
6667 // Fall through to expand this. It is not legal.
6670 // Other vector multiplications are legal.
6675 // Legalize to a VMULL instruction.
6678 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6680 Op0 = SkipExtensionForVMULL(N0, DAG);
6681 assert(Op0.getValueType().is64BitVector() &&
6682 Op1.getValueType().is64BitVector() &&
6683 "unexpected types for extended operands to VMULL");
6684 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6687 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6688 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6695 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6696 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6697 EVT Op1VT = Op1.getValueType();
6698 return DAG.getNode(N0->getOpcode(), DL, VT,
6699 DAG.getNode(NewOpc, DL, VT,
6700 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6701 DAG.getNode(NewOpc, DL, VT,
6702 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6705 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
6706 SelectionDAG &DAG) {
6707 // TODO: Should this propagate fast-math-flags?
6710 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6711 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6712 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6713 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6714 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6715 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6716 // Get reciprocal estimate.
6717 // float4 recip = vrecpeq_f32(yf);
6718 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6719 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6721 // Because char has a smaller range than uchar, we can actually get away
6722 // without any newton steps. This requires that we use a weird bias
6723 // of 0xb000, however (again, this has been exhaustively tested).
6724 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6725 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6726 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6727 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
6728 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6729 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6730 // Convert back to short.
6731 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6732 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6736 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
6737 SelectionDAG &DAG) {
6738 // TODO: Should this propagate fast-math-flags?
6741 // Convert to float.
6742 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6743 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6744 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6745 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6746 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6747 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6749 // Use reciprocal estimate and one refinement step.
6750 // float4 recip = vrecpeq_f32(yf);
6751 // recip *= vrecpsq_f32(yf, recip);
6752 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6753 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6755 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6756 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6758 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6759 // Because short has a smaller range than ushort, we can actually get away
6760 // with only a single newton step. This requires that we use a weird bias
6761 // of 89, however (again, this has been exhaustively tested).
6762 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6763 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6764 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6765 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
6766 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6767 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6768 // Convert back to integer and return.
6769 // return vmovn_s32(vcvt_s32_f32(result));
6770 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6771 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6775 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6776 EVT VT = Op.getValueType();
6777 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6778 "unexpected type for custom-lowering ISD::SDIV");
6781 SDValue N0 = Op.getOperand(0);
6782 SDValue N1 = Op.getOperand(1);
6785 if (VT == MVT::v8i8) {
6786 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6787 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6789 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6790 DAG.getIntPtrConstant(4, dl));
6791 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6792 DAG.getIntPtrConstant(4, dl));
6793 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6794 DAG.getIntPtrConstant(0, dl));
6795 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6796 DAG.getIntPtrConstant(0, dl));
6798 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6799 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6801 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6802 N0 = LowerCONCAT_VECTORS(N0, DAG);
6804 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6807 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6810 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6811 // TODO: Should this propagate fast-math-flags?
6812 EVT VT = Op.getValueType();
6813 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6814 "unexpected type for custom-lowering ISD::UDIV");
6817 SDValue N0 = Op.getOperand(0);
6818 SDValue N1 = Op.getOperand(1);
6821 if (VT == MVT::v8i8) {
6822 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6823 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6825 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6826 DAG.getIntPtrConstant(4, dl));
6827 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6828 DAG.getIntPtrConstant(4, dl));
6829 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6830 DAG.getIntPtrConstant(0, dl));
6831 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6832 DAG.getIntPtrConstant(0, dl));
6834 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6835 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6837 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6838 N0 = LowerCONCAT_VECTORS(N0, DAG);
6840 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6841 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6847 // v4i16 sdiv ... Convert to float.
6848 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6849 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6850 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6851 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6852 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6853 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6855 // Use reciprocal estimate and two refinement steps.
6856 // float4 recip = vrecpeq_f32(yf);
6857 // recip *= vrecpsq_f32(yf, recip);
6858 // recip *= vrecpsq_f32(yf, recip);
6859 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6860 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6862 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6863 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6865 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6866 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6867 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6869 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6870 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6871 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6872 // and that it will never cause us to return an answer too large).
6873 // float4 result = as_float4(as_int4(xf*recip) + 2);
6874 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6875 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6876 N1 = DAG.getConstant(2, dl, MVT::v4i32);
6877 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6878 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6879 // Convert back to integer and return.
6880 // return vmovn_u32(vcvt_s32_f32(result));
6881 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6882 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6886 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6887 EVT VT = Op.getNode()->getValueType(0);
6888 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6891 bool ExtraOp = false;
6892 switch (Op.getOpcode()) {
6893 default: llvm_unreachable("Invalid code");
6894 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6895 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6896 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6897 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6901 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6903 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6904 Op.getOperand(1), Op.getOperand(2));
6907 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6908 assert(Subtarget->isTargetDarwin());
6910 // For iOS, we want to call an alternative entry point: __sincos_stret,
6911 // return values are passed via sret.
6913 SDValue Arg = Op.getOperand(0);
6914 EVT ArgVT = Arg.getValueType();
6915 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6916 auto PtrVT = getPointerTy(DAG.getDataLayout());
6918 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6921 // Pair of floats / doubles used to pass the result.
6922 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6923 auto &DL = DAG.getDataLayout();
6926 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6928 if (ShouldUseSRet) {
6929 // Create stack object for sret.
6930 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6931 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6932 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6933 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6937 Entry.Ty = RetTy->getPointerTo();
6938 Entry.isSExt = false;
6939 Entry.isZExt = false;
6940 Entry.isSRet = true;
6941 Args.push_back(Entry);
6942 RetTy = Type::getVoidTy(*DAG.getContext());
6948 Entry.isSExt = false;
6949 Entry.isZExt = false;
6950 Args.push_back(Entry);
6952 const char *LibcallName =
6953 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6955 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6956 CallingConv::ID CC = getLibcallCallingConv(LC);
6957 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6959 TargetLowering::CallLoweringInfo CLI(DAG);
6961 .setChain(DAG.getEntryNode())
6962 .setCallee(CC, RetTy, Callee, std::move(Args))
6963 .setDiscardResult(ShouldUseSRet);
6964 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6967 return CallResult.first;
6970 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
6972 // Address of cos field.
6973 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6974 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6976 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
6978 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6979 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6980 LoadSin.getValue(0), LoadCos.getValue(0));
6983 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6985 SDValue &Chain) const {
6986 EVT VT = Op.getValueType();
6987 assert((VT == MVT::i32 || VT == MVT::i64) &&
6988 "unexpected type for custom lowering DIV");
6991 const auto &DL = DAG.getDataLayout();
6992 const auto &TLI = DAG.getTargetLoweringInfo();
6994 const char *Name = nullptr;
6996 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6998 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7000 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7002 ARMTargetLowering::ArgListTy Args;
7004 for (auto AI : {1, 0}) {
7006 Arg.Node = Op.getOperand(AI);
7007 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7008 Args.push_back(Arg);
7011 CallLoweringInfo CLI(DAG);
7014 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7015 ES, std::move(Args));
7017 return LowerCallTo(CLI).first;
7020 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7021 bool Signed) const {
7022 assert(Op.getValueType() == MVT::i32 &&
7023 "unexpected type for custom lowering DIV");
7026 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7027 DAG.getEntryNode(), Op.getOperand(1));
7029 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7032 void ARMTargetLowering::ExpandDIV_Windows(
7033 SDValue Op, SelectionDAG &DAG, bool Signed,
7034 SmallVectorImpl<SDValue> &Results) const {
7035 const auto &DL = DAG.getDataLayout();
7036 const auto &TLI = DAG.getTargetLoweringInfo();
7038 assert(Op.getValueType() == MVT::i64 &&
7039 "unexpected type for custom lowering DIV");
7042 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
7043 DAG.getConstant(0, dl, MVT::i32));
7044 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
7045 DAG.getConstant(1, dl, MVT::i32));
7046 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
7049 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
7051 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7053 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7054 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7055 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7056 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7058 Results.push_back(Lower);
7059 Results.push_back(Upper);
7062 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7063 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7064 // Acquire/Release load/store is not legal for targets without a dmb or
7065 // equivalent available.
7068 // Monotonic load/store is legal for all targets.
7072 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7073 SmallVectorImpl<SDValue> &Results,
7075 const ARMSubtarget *Subtarget) {
7077 // Under Power Management extensions, the cycle-count is:
7078 // mrc p15, #0, <Rt>, c9, c13, #0
7079 SDValue Ops[] = { N->getOperand(0), // Chain
7080 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7081 DAG.getConstant(15, DL, MVT::i32),
7082 DAG.getConstant(0, DL, MVT::i32),
7083 DAG.getConstant(9, DL, MVT::i32),
7084 DAG.getConstant(13, DL, MVT::i32),
7085 DAG.getConstant(0, DL, MVT::i32)
7088 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7089 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7090 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7091 DAG.getConstant(0, DL, MVT::i32)));
7092 Results.push_back(Cycles32.getValue(1));
7095 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7096 SDLoc dl(V.getNode());
7097 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7098 SDValue VHi = DAG.getAnyExtOrTrunc(
7099 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7102 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7103 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7104 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7105 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7107 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7110 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7111 SmallVectorImpl<SDValue> & Results,
7112 SelectionDAG &DAG) {
7113 assert(N->getValueType(0) == MVT::i64 &&
7114 "AtomicCmpSwap on types less than 64 should be legal");
7115 SDValue Ops[] = {N->getOperand(1),
7116 createGPRPairNode(DAG, N->getOperand(2)),
7117 createGPRPairNode(DAG, N->getOperand(3)),
7119 SDNode *CmpSwap = DAG.getMachineNode(
7120 ARM::CMP_SWAP_64, SDLoc(N),
7121 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7123 MachineFunction &MF = DAG.getMachineFunction();
7124 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7125 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7126 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7128 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7129 SDValue(CmpSwap, 0)));
7130 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7131 SDValue(CmpSwap, 0)));
7132 Results.push_back(SDValue(CmpSwap, 2));
7135 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7136 switch (Op.getOpcode()) {
7137 default: llvm_unreachable("Don't know how to custom lower this!");
7138 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7139 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7140 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7141 case ISD::GlobalAddress:
7142 switch (Subtarget->getTargetTriple().getObjectFormat()) {
7143 default: llvm_unreachable("unknown object format");
7145 return LowerGlobalAddressWindows(Op, DAG);
7147 return LowerGlobalAddressELF(Op, DAG);
7149 return LowerGlobalAddressDarwin(Op, DAG);
7151 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7152 case ISD::SELECT: return LowerSELECT(Op, DAG);
7153 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7154 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
7155 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
7156 case ISD::VASTART: return LowerVASTART(Op, DAG);
7157 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7158 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
7159 case ISD::SINT_TO_FP:
7160 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7161 case ISD::FP_TO_SINT:
7162 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
7163 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7164 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7165 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7166 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7167 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7168 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7169 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7171 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
7174 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
7175 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
7176 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
7177 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
7178 case ISD::SRL_PARTS:
7179 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
7181 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7182 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7183 case ISD::SETCC: return LowerVSETCC(Op, DAG);
7184 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
7185 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
7186 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7187 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7188 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7189 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7190 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7191 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7192 case ISD::MUL: return LowerMUL(Op, DAG);
7194 if (Subtarget->isTargetWindows())
7195 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7196 return LowerSDIV(Op, DAG);
7198 if (Subtarget->isTargetWindows())
7199 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7200 return LowerUDIV(Op, DAG);
7204 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7209 return LowerXALUO(Op, DAG);
7210 case ISD::ATOMIC_LOAD:
7211 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
7212 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
7214 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
7215 case ISD::DYNAMIC_STACKALLOC:
7216 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7217 return LowerDYNAMIC_STACKALLOC(Op, DAG);
7218 llvm_unreachable("Don't know how to custom lower this!");
7219 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7220 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7221 case ARMISD::WIN__DBZCHK: return SDValue();
7225 /// ReplaceNodeResults - Replace the results of node with an illegal result
7226 /// type with new values built out of custom code.
7227 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7228 SmallVectorImpl<SDValue> &Results,
7229 SelectionDAG &DAG) const {
7231 switch (N->getOpcode()) {
7233 llvm_unreachable("Don't know how to custom expand this!");
7234 case ISD::READ_REGISTER:
7235 ExpandREAD_REGISTER(N, Results, DAG);
7238 Res = ExpandBITCAST(N, DAG);
7242 Res = Expand64BitShift(N, DAG, Subtarget);
7246 Res = LowerREM(N, DAG);
7250 Res = LowerDivRem(SDValue(N, 0), DAG);
7251 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7252 Results.push_back(Res.getValue(0));
7253 Results.push_back(Res.getValue(1));
7255 case ISD::READCYCLECOUNTER:
7256 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7260 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7261 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7263 case ISD::ATOMIC_CMP_SWAP:
7264 ReplaceCMP_SWAP_64Results(N, Results, DAG);
7268 Results.push_back(Res);
7271 //===----------------------------------------------------------------------===//
7272 // ARM Scheduler Hooks
7273 //===----------------------------------------------------------------------===//
7275 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7276 /// registers the function context.
7277 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7278 MachineBasicBlock *MBB,
7279 MachineBasicBlock *DispatchBB,
7281 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7282 DebugLoc dl = MI.getDebugLoc();
7283 MachineFunction *MF = MBB->getParent();
7284 MachineRegisterInfo *MRI = &MF->getRegInfo();
7285 MachineConstantPool *MCP = MF->getConstantPool();
7286 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7287 const Function *F = MF->getFunction();
7289 bool isThumb = Subtarget->isThumb();
7290 bool isThumb2 = Subtarget->isThumb2();
7292 unsigned PCLabelId = AFI->createPICLabelUId();
7293 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7294 ARMConstantPoolValue *CPV =
7295 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7296 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7298 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7299 : &ARM::GPRRegClass;
7301 // Grab constant pool and fixed stack memory operands.
7302 MachineMemOperand *CPMMO =
7303 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7304 MachineMemOperand::MOLoad, 4, 4);
7306 MachineMemOperand *FIMMOSt =
7307 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7308 MachineMemOperand::MOStore, 4, 4);
7310 // Load the address of the dispatch MBB into the jump buffer.
7312 // Incoming value: jbuf
7313 // ldr.n r5, LCPI1_1
7316 // str r5, [$jbuf, #+4] ; &jbuf[1]
7317 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7318 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7319 .addConstantPoolIndex(CPI)
7320 .addMemOperand(CPMMO));
7321 // Set the low bit because of thumb mode.
7322 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7324 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7325 .addReg(NewVReg1, RegState::Kill)
7327 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7328 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7329 .addReg(NewVReg2, RegState::Kill)
7331 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7332 .addReg(NewVReg3, RegState::Kill)
7334 .addImm(36) // &jbuf[1] :: pc
7335 .addMemOperand(FIMMOSt));
7336 } else if (isThumb) {
7337 // Incoming value: jbuf
7338 // ldr.n r1, LCPI1_4
7342 // add r2, $jbuf, #+4 ; &jbuf[1]
7344 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7345 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7346 .addConstantPoolIndex(CPI)
7347 .addMemOperand(CPMMO));
7348 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7349 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7350 .addReg(NewVReg1, RegState::Kill)
7352 // Set the low bit because of thumb mode.
7353 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7354 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7355 .addReg(ARM::CPSR, RegState::Define)
7357 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7358 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7359 .addReg(ARM::CPSR, RegState::Define)
7360 .addReg(NewVReg2, RegState::Kill)
7361 .addReg(NewVReg3, RegState::Kill));
7362 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7363 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7365 .addImm(36); // &jbuf[1] :: pc
7366 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7367 .addReg(NewVReg4, RegState::Kill)
7368 .addReg(NewVReg5, RegState::Kill)
7370 .addMemOperand(FIMMOSt));
7372 // Incoming value: jbuf
7375 // str r1, [$jbuf, #+4] ; &jbuf[1]
7376 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7377 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7378 .addConstantPoolIndex(CPI)
7380 .addMemOperand(CPMMO));
7381 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7382 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7383 .addReg(NewVReg1, RegState::Kill)
7384 .addImm(PCLabelId));
7385 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7386 .addReg(NewVReg2, RegState::Kill)
7388 .addImm(36) // &jbuf[1] :: pc
7389 .addMemOperand(FIMMOSt));
7393 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7394 MachineBasicBlock *MBB) const {
7395 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7396 DebugLoc dl = MI.getDebugLoc();
7397 MachineFunction *MF = MBB->getParent();
7398 MachineRegisterInfo *MRI = &MF->getRegInfo();
7399 MachineFrameInfo *MFI = MF->getFrameInfo();
7400 int FI = MFI->getFunctionContextIndex();
7402 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7403 : &ARM::GPRnopcRegClass;
7405 // Get a mapping of the call site numbers to all of the landing pads they're
7407 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7408 unsigned MaxCSNum = 0;
7409 MachineModuleInfo &MMI = MF->getMMI();
7410 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7412 if (!BB->isEHPad()) continue;
7414 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7416 for (MachineBasicBlock::iterator
7417 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7418 if (!II->isEHLabel()) continue;
7420 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7421 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7423 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7424 for (SmallVectorImpl<unsigned>::iterator
7425 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7426 CSI != CSE; ++CSI) {
7427 CallSiteNumToLPad[*CSI].push_back(&*BB);
7428 MaxCSNum = std::max(MaxCSNum, *CSI);
7434 // Get an ordered list of the machine basic blocks for the jump table.
7435 std::vector<MachineBasicBlock*> LPadList;
7436 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7437 LPadList.reserve(CallSiteNumToLPad.size());
7438 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7439 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7440 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7441 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7442 LPadList.push_back(*II);
7443 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7447 assert(!LPadList.empty() &&
7448 "No landing pad destinations for the dispatch jump table!");
7450 // Create the jump table and associated information.
7451 MachineJumpTableInfo *JTI =
7452 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7453 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7455 // Create the MBBs for the dispatch code.
7457 // Shove the dispatch's address into the return slot in the function context.
7458 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7459 DispatchBB->setIsEHPad();
7461 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7462 unsigned trap_opcode;
7463 if (Subtarget->isThumb())
7464 trap_opcode = ARM::tTRAP;
7466 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7468 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7469 DispatchBB->addSuccessor(TrapBB);
7471 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7472 DispatchBB->addSuccessor(DispContBB);
7475 MF->insert(MF->end(), DispatchBB);
7476 MF->insert(MF->end(), DispContBB);
7477 MF->insert(MF->end(), TrapBB);
7479 // Insert code into the entry block that creates and registers the function
7481 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7483 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7484 MachinePointerInfo::getFixedStack(*MF, FI),
7485 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7487 MachineInstrBuilder MIB;
7488 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7490 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7491 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7493 // Add a register mask with no preserved registers. This results in all
7494 // registers being marked as clobbered.
7495 MIB.addRegMask(RI.getNoPreservedMask());
7497 bool IsPositionIndependent = isPositionIndependent();
7498 unsigned NumLPads = LPadList.size();
7499 if (Subtarget->isThumb2()) {
7500 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7501 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7504 .addMemOperand(FIMMOLd));
7506 if (NumLPads < 256) {
7507 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7509 .addImm(LPadList.size()));
7511 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7512 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7513 .addImm(NumLPads & 0xFFFF));
7515 unsigned VReg2 = VReg1;
7516 if ((NumLPads & 0xFFFF0000) != 0) {
7517 VReg2 = MRI->createVirtualRegister(TRC);
7518 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7520 .addImm(NumLPads >> 16));
7523 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7528 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7533 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7534 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7535 .addJumpTableIndex(MJTI));
7537 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7540 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7541 .addReg(NewVReg3, RegState::Kill)
7543 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7545 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7546 .addReg(NewVReg4, RegState::Kill)
7548 .addJumpTableIndex(MJTI);
7549 } else if (Subtarget->isThumb()) {
7550 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7551 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7554 .addMemOperand(FIMMOLd));
7556 if (NumLPads < 256) {
7557 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7561 MachineConstantPool *ConstantPool = MF->getConstantPool();
7562 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7563 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7565 // MachineConstantPool wants an explicit alignment.
7566 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7568 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7569 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7571 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7572 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7573 .addReg(VReg1, RegState::Define)
7574 .addConstantPoolIndex(Idx));
7575 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7580 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7585 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7586 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7587 .addReg(ARM::CPSR, RegState::Define)
7591 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7592 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7593 .addJumpTableIndex(MJTI));
7595 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7596 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7597 .addReg(ARM::CPSR, RegState::Define)
7598 .addReg(NewVReg2, RegState::Kill)
7601 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7602 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7604 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7605 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7606 .addReg(NewVReg4, RegState::Kill)
7608 .addMemOperand(JTMMOLd));
7610 unsigned NewVReg6 = NewVReg5;
7611 if (IsPositionIndependent) {
7612 NewVReg6 = MRI->createVirtualRegister(TRC);
7613 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7614 .addReg(ARM::CPSR, RegState::Define)
7615 .addReg(NewVReg5, RegState::Kill)
7619 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7620 .addReg(NewVReg6, RegState::Kill)
7621 .addJumpTableIndex(MJTI);
7623 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7624 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7627 .addMemOperand(FIMMOLd));
7629 if (NumLPads < 256) {
7630 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7633 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7634 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7635 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7636 .addImm(NumLPads & 0xFFFF));
7638 unsigned VReg2 = VReg1;
7639 if ((NumLPads & 0xFFFF0000) != 0) {
7640 VReg2 = MRI->createVirtualRegister(TRC);
7641 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7643 .addImm(NumLPads >> 16));
7646 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7650 MachineConstantPool *ConstantPool = MF->getConstantPool();
7651 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7652 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7654 // MachineConstantPool wants an explicit alignment.
7655 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7657 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7658 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7660 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7661 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7662 .addReg(VReg1, RegState::Define)
7663 .addConstantPoolIndex(Idx)
7665 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7667 .addReg(VReg1, RegState::Kill));
7670 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7675 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7677 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7679 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7680 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7681 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7682 .addJumpTableIndex(MJTI));
7684 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7685 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7686 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7688 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7689 .addReg(NewVReg3, RegState::Kill)
7692 .addMemOperand(JTMMOLd));
7694 if (IsPositionIndependent) {
7695 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7696 .addReg(NewVReg5, RegState::Kill)
7698 .addJumpTableIndex(MJTI);
7700 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7701 .addReg(NewVReg5, RegState::Kill)
7702 .addJumpTableIndex(MJTI);
7706 // Add the jump table entries as successors to the MBB.
7707 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7708 for (std::vector<MachineBasicBlock*>::iterator
7709 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7710 MachineBasicBlock *CurMBB = *I;
7711 if (SeenMBBs.insert(CurMBB).second)
7712 DispContBB->addSuccessor(CurMBB);
7715 // N.B. the order the invoke BBs are processed in doesn't matter here.
7716 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7717 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7718 for (MachineBasicBlock *BB : InvokeBBs) {
7720 // Remove the landing pad successor from the invoke block and replace it
7721 // with the new dispatch block.
7722 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7724 while (!Successors.empty()) {
7725 MachineBasicBlock *SMBB = Successors.pop_back_val();
7726 if (SMBB->isEHPad()) {
7727 BB->removeSuccessor(SMBB);
7728 MBBLPads.push_back(SMBB);
7732 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7733 BB->normalizeSuccProbs();
7735 // Find the invoke call and mark all of the callee-saved registers as
7736 // 'implicit defined' so that they're spilled. This prevents code from
7737 // moving instructions to before the EH block, where they will never be
7739 for (MachineBasicBlock::reverse_iterator
7740 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7741 if (!II->isCall()) continue;
7743 DenseMap<unsigned, bool> DefRegs;
7744 for (MachineInstr::mop_iterator
7745 OI = II->operands_begin(), OE = II->operands_end();
7747 if (!OI->isReg()) continue;
7748 DefRegs[OI->getReg()] = true;
7751 MachineInstrBuilder MIB(*MF, &*II);
7753 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7754 unsigned Reg = SavedRegs[i];
7755 if (Subtarget->isThumb2() &&
7756 !ARM::tGPRRegClass.contains(Reg) &&
7757 !ARM::hGPRRegClass.contains(Reg))
7759 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7761 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7764 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7771 // Mark all former landing pads as non-landing pads. The dispatch is the only
7773 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7774 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7775 (*I)->setIsEHPad(false);
7777 // The instruction is gone now.
7778 MI.eraseFromParent();
7782 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7783 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7784 E = MBB->succ_end(); I != E; ++I)
7787 llvm_unreachable("Expecting a BB with two successors!");
7790 /// Return the load opcode for a given load size. If load size >= 8,
7791 /// neon opcode will be returned.
7792 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7794 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7795 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7797 return LdSize == 4 ? ARM::tLDRi
7798 : LdSize == 2 ? ARM::tLDRHi
7799 : LdSize == 1 ? ARM::tLDRBi : 0;
7801 return LdSize == 4 ? ARM::t2LDR_POST
7802 : LdSize == 2 ? ARM::t2LDRH_POST
7803 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7804 return LdSize == 4 ? ARM::LDR_POST_IMM
7805 : LdSize == 2 ? ARM::LDRH_POST
7806 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7809 /// Return the store opcode for a given store size. If store size >= 8,
7810 /// neon opcode will be returned.
7811 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7813 return StSize == 16 ? ARM::VST1q32wb_fixed
7814 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7816 return StSize == 4 ? ARM::tSTRi
7817 : StSize == 2 ? ARM::tSTRHi
7818 : StSize == 1 ? ARM::tSTRBi : 0;
7820 return StSize == 4 ? ARM::t2STR_POST
7821 : StSize == 2 ? ARM::t2STRH_POST
7822 : StSize == 1 ? ARM::t2STRB_POST : 0;
7823 return StSize == 4 ? ARM::STR_POST_IMM
7824 : StSize == 2 ? ARM::STRH_POST
7825 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7828 /// Emit a post-increment load operation with given size. The instructions
7829 /// will be added to BB at Pos.
7830 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
7831 const TargetInstrInfo *TII, const DebugLoc &dl,
7832 unsigned LdSize, unsigned Data, unsigned AddrIn,
7833 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7834 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7835 assert(LdOpc != 0 && "Should have a load opcode");
7837 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7838 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7840 } else if (IsThumb1) {
7841 // load + update AddrIn
7842 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7843 .addReg(AddrIn).addImm(0));
7844 MachineInstrBuilder MIB =
7845 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7846 MIB = AddDefaultT1CC(MIB);
7847 MIB.addReg(AddrIn).addImm(LdSize);
7848 AddDefaultPred(MIB);
7849 } else if (IsThumb2) {
7850 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7851 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7854 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7855 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7856 .addReg(0).addImm(LdSize));
7860 /// Emit a post-increment store operation with given size. The instructions
7861 /// will be added to BB at Pos.
7862 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
7863 const TargetInstrInfo *TII, const DebugLoc &dl,
7864 unsigned StSize, unsigned Data, unsigned AddrIn,
7865 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7866 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7867 assert(StOpc != 0 && "Should have a store opcode");
7869 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7870 .addReg(AddrIn).addImm(0).addReg(Data));
7871 } else if (IsThumb1) {
7872 // store + update AddrIn
7873 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7874 .addReg(AddrIn).addImm(0));
7875 MachineInstrBuilder MIB =
7876 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7877 MIB = AddDefaultT1CC(MIB);
7878 MIB.addReg(AddrIn).addImm(StSize);
7879 AddDefaultPred(MIB);
7880 } else if (IsThumb2) {
7881 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7882 .addReg(Data).addReg(AddrIn).addImm(StSize));
7884 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7885 .addReg(Data).addReg(AddrIn).addReg(0)
7891 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
7892 MachineBasicBlock *BB) const {
7893 // This pseudo instruction has 3 operands: dst, src, size
7894 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7895 // Otherwise, we will generate unrolled scalar copies.
7896 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7897 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7898 MachineFunction::iterator It = ++BB->getIterator();
7900 unsigned dest = MI.getOperand(0).getReg();
7901 unsigned src = MI.getOperand(1).getReg();
7902 unsigned SizeVal = MI.getOperand(2).getImm();
7903 unsigned Align = MI.getOperand(3).getImm();
7904 DebugLoc dl = MI.getDebugLoc();
7906 MachineFunction *MF = BB->getParent();
7907 MachineRegisterInfo &MRI = MF->getRegInfo();
7908 unsigned UnitSize = 0;
7909 const TargetRegisterClass *TRC = nullptr;
7910 const TargetRegisterClass *VecTRC = nullptr;
7912 bool IsThumb1 = Subtarget->isThumb1Only();
7913 bool IsThumb2 = Subtarget->isThumb2();
7917 } else if (Align & 2) {
7920 // Check whether we can use NEON instructions.
7921 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7922 Subtarget->hasNEON()) {
7923 if ((Align % 16 == 0) && SizeVal >= 16)
7925 else if ((Align % 8 == 0) && SizeVal >= 8)
7928 // Can't use NEON instructions.
7933 // Select the correct opcode and register class for unit size load/store
7934 bool IsNeon = UnitSize >= 8;
7935 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7937 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7938 : UnitSize == 8 ? &ARM::DPRRegClass
7941 unsigned BytesLeft = SizeVal % UnitSize;
7942 unsigned LoopSize = SizeVal - BytesLeft;
7944 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7945 // Use LDR and STR to copy.
7946 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7947 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7948 unsigned srcIn = src;
7949 unsigned destIn = dest;
7950 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7951 unsigned srcOut = MRI.createVirtualRegister(TRC);
7952 unsigned destOut = MRI.createVirtualRegister(TRC);
7953 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7954 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7955 IsThumb1, IsThumb2);
7956 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7957 IsThumb1, IsThumb2);
7962 // Handle the leftover bytes with LDRB and STRB.
7963 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7964 // [destOut] = STRB_POST(scratch, destIn, 1)
7965 for (unsigned i = 0; i < BytesLeft; i++) {
7966 unsigned srcOut = MRI.createVirtualRegister(TRC);
7967 unsigned destOut = MRI.createVirtualRegister(TRC);
7968 unsigned scratch = MRI.createVirtualRegister(TRC);
7969 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7970 IsThumb1, IsThumb2);
7971 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7972 IsThumb1, IsThumb2);
7976 MI.eraseFromParent(); // The instruction is gone now.
7980 // Expand the pseudo op to a loop.
7983 // movw varEnd, # --> with thumb2
7985 // ldrcp varEnd, idx --> without thumb2
7986 // fallthrough --> loopMBB
7988 // PHI varPhi, varEnd, varLoop
7989 // PHI srcPhi, src, srcLoop
7990 // PHI destPhi, dst, destLoop
7991 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7992 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7993 // subs varLoop, varPhi, #UnitSize
7995 // fallthrough --> exitMBB
7997 // epilogue to handle left-over bytes
7998 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7999 // [destOut] = STRB_POST(scratch, destLoop, 1)
8000 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8001 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8002 MF->insert(It, loopMBB);
8003 MF->insert(It, exitMBB);
8005 // Transfer the remainder of BB and its successor edges to exitMBB.
8006 exitMBB->splice(exitMBB->begin(), BB,
8007 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8008 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8010 // Load an immediate to varEnd.
8011 unsigned varEnd = MRI.createVirtualRegister(TRC);
8012 if (Subtarget->useMovt(*MF)) {
8013 unsigned Vtmp = varEnd;
8014 if ((LoopSize & 0xFFFF0000) != 0)
8015 Vtmp = MRI.createVirtualRegister(TRC);
8016 AddDefaultPred(BuildMI(BB, dl,
8017 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
8018 Vtmp).addImm(LoopSize & 0xFFFF));
8020 if ((LoopSize & 0xFFFF0000) != 0)
8021 AddDefaultPred(BuildMI(BB, dl,
8022 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
8025 .addImm(LoopSize >> 16));
8027 MachineConstantPool *ConstantPool = MF->getConstantPool();
8028 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8029 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8031 // MachineConstantPool wants an explicit alignment.
8032 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8034 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8035 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8038 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
8039 varEnd, RegState::Define).addConstantPoolIndex(Idx));
8041 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
8042 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
8044 BB->addSuccessor(loopMBB);
8046 // Generate the loop body:
8047 // varPhi = PHI(varLoop, varEnd)
8048 // srcPhi = PHI(srcLoop, src)
8049 // destPhi = PHI(destLoop, dst)
8050 MachineBasicBlock *entryBB = BB;
8052 unsigned varLoop = MRI.createVirtualRegister(TRC);
8053 unsigned varPhi = MRI.createVirtualRegister(TRC);
8054 unsigned srcLoop = MRI.createVirtualRegister(TRC);
8055 unsigned srcPhi = MRI.createVirtualRegister(TRC);
8056 unsigned destLoop = MRI.createVirtualRegister(TRC);
8057 unsigned destPhi = MRI.createVirtualRegister(TRC);
8059 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8060 .addReg(varLoop).addMBB(loopMBB)
8061 .addReg(varEnd).addMBB(entryBB);
8062 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8063 .addReg(srcLoop).addMBB(loopMBB)
8064 .addReg(src).addMBB(entryBB);
8065 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8066 .addReg(destLoop).addMBB(loopMBB)
8067 .addReg(dest).addMBB(entryBB);
8069 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8070 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8071 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8072 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8073 IsThumb1, IsThumb2);
8074 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8075 IsThumb1, IsThumb2);
8077 // Decrement loop variable by UnitSize.
8079 MachineInstrBuilder MIB =
8080 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
8081 MIB = AddDefaultT1CC(MIB);
8082 MIB.addReg(varPhi).addImm(UnitSize);
8083 AddDefaultPred(MIB);
8085 MachineInstrBuilder MIB =
8086 BuildMI(*BB, BB->end(), dl,
8087 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8088 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
8089 MIB->getOperand(5).setReg(ARM::CPSR);
8090 MIB->getOperand(5).setIsDef(true);
8092 BuildMI(*BB, BB->end(), dl,
8093 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8094 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8096 // loopMBB can loop back to loopMBB or fall through to exitMBB.
8097 BB->addSuccessor(loopMBB);
8098 BB->addSuccessor(exitMBB);
8100 // Add epilogue to handle BytesLeft.
8102 auto StartOfExit = exitMBB->begin();
8104 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8105 // [destOut] = STRB_POST(scratch, destLoop, 1)
8106 unsigned srcIn = srcLoop;
8107 unsigned destIn = destLoop;
8108 for (unsigned i = 0; i < BytesLeft; i++) {
8109 unsigned srcOut = MRI.createVirtualRegister(TRC);
8110 unsigned destOut = MRI.createVirtualRegister(TRC);
8111 unsigned scratch = MRI.createVirtualRegister(TRC);
8112 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8113 IsThumb1, IsThumb2);
8114 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8115 IsThumb1, IsThumb2);
8120 MI.eraseFromParent(); // The instruction is gone now.
8125 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8126 MachineBasicBlock *MBB) const {
8127 const TargetMachine &TM = getTargetMachine();
8128 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8129 DebugLoc DL = MI.getDebugLoc();
8131 assert(Subtarget->isTargetWindows() &&
8132 "__chkstk is only supported on Windows");
8133 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8135 // __chkstk takes the number of words to allocate on the stack in R4, and
8136 // returns the stack adjustment in number of bytes in R4. This will not
8137 // clober any other registers (other than the obvious lr).
8139 // Although, technically, IP should be considered a register which may be
8140 // clobbered, the call itself will not touch it. Windows on ARM is a pure
8141 // thumb-2 environment, so there is no interworking required. As a result, we
8142 // do not expect a veneer to be emitted by the linker, clobbering IP.
8144 // Each module receives its own copy of __chkstk, so no import thunk is
8145 // required, again, ensuring that IP is not clobbered.
8147 // Finally, although some linkers may theoretically provide a trampoline for
8148 // out of range calls (which is quite common due to a 32M range limitation of
8149 // branches for Thumb), we can generate the long-call version via
8150 // -mcmodel=large, alleviating the need for the trampoline which may clobber
8153 switch (TM.getCodeModel()) {
8154 case CodeModel::Small:
8155 case CodeModel::Medium:
8156 case CodeModel::Default:
8157 case CodeModel::Kernel:
8158 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8159 .addImm((unsigned)ARMCC::AL).addReg(0)
8160 .addExternalSymbol("__chkstk")
8161 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8162 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8163 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8165 case CodeModel::Large:
8166 case CodeModel::JITDefault: {
8167 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8168 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8170 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8171 .addExternalSymbol("__chkstk");
8172 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8173 .addImm((unsigned)ARMCC::AL).addReg(0)
8174 .addReg(Reg, RegState::Kill)
8175 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8176 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8177 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8182 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
8184 .addReg(ARM::SP, RegState::Kill)
8185 .addReg(ARM::R4, RegState::Kill)
8186 .setMIFlags(MachineInstr::FrameSetup)));
8188 MI.eraseFromParent();
8193 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8194 MachineBasicBlock *MBB) const {
8195 DebugLoc DL = MI.getDebugLoc();
8196 MachineFunction *MF = MBB->getParent();
8197 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8199 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8200 MF->insert(++MBB->getIterator(), ContBB);
8201 ContBB->splice(ContBB->begin(), MBB,
8202 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8203 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8205 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8206 MF->push_back(TrapBB);
8207 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
8208 MBB->addSuccessor(TrapBB);
8210 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
8211 .addReg(MI.getOperand(0).getReg())
8213 AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB));
8214 MBB->addSuccessor(ContBB);
8216 MI.eraseFromParent();
8221 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8222 MachineBasicBlock *BB) const {
8223 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8224 DebugLoc dl = MI.getDebugLoc();
8225 bool isThumb2 = Subtarget->isThumb2();
8226 switch (MI.getOpcode()) {
8229 llvm_unreachable("Unexpected instr type to insert");
8232 // Thumb1 post-indexed loads are really just single-register LDMs.
8233 case ARM::tLDR_postidx: {
8234 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8235 .addOperand(MI.getOperand(1)) // Rn_wb
8236 .addOperand(MI.getOperand(2)) // Rn
8237 .addOperand(MI.getOperand(3)) // PredImm
8238 .addOperand(MI.getOperand(4)) // PredReg
8239 .addOperand(MI.getOperand(0)); // Rt
8240 MI.eraseFromParent();
8244 // The Thumb2 pre-indexed stores have the same MI operands, they just
8245 // define them differently in the .td files from the isel patterns, so
8246 // they need pseudos.
8247 case ARM::t2STR_preidx:
8248 MI.setDesc(TII->get(ARM::t2STR_PRE));
8250 case ARM::t2STRB_preidx:
8251 MI.setDesc(TII->get(ARM::t2STRB_PRE));
8253 case ARM::t2STRH_preidx:
8254 MI.setDesc(TII->get(ARM::t2STRH_PRE));
8257 case ARM::STRi_preidx:
8258 case ARM::STRBi_preidx: {
8259 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8260 : ARM::STRB_PRE_IMM;
8261 // Decode the offset.
8262 unsigned Offset = MI.getOperand(4).getImm();
8263 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8264 Offset = ARM_AM::getAM2Offset(Offset);
8268 MachineMemOperand *MMO = *MI.memoperands_begin();
8269 BuildMI(*BB, MI, dl, TII->get(NewOpc))
8270 .addOperand(MI.getOperand(0)) // Rn_wb
8271 .addOperand(MI.getOperand(1)) // Rt
8272 .addOperand(MI.getOperand(2)) // Rn
8273 .addImm(Offset) // offset (skip GPR==zero_reg)
8274 .addOperand(MI.getOperand(5)) // pred
8275 .addOperand(MI.getOperand(6))
8276 .addMemOperand(MMO);
8277 MI.eraseFromParent();
8280 case ARM::STRr_preidx:
8281 case ARM::STRBr_preidx:
8282 case ARM::STRH_preidx: {
8284 switch (MI.getOpcode()) {
8285 default: llvm_unreachable("unexpected opcode!");
8286 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8287 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8288 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8290 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8291 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8292 MIB.addOperand(MI.getOperand(i));
8293 MI.eraseFromParent();
8297 case ARM::tMOVCCr_pseudo: {
8298 // To "insert" a SELECT_CC instruction, we actually have to insert the
8299 // diamond control-flow pattern. The incoming instruction knows the
8300 // destination vreg to set, the condition code register to branch on, the
8301 // true/false values to select between, and a branch opcode to use.
8302 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8303 MachineFunction::iterator It = ++BB->getIterator();
8308 // cmpTY ccX, r1, r2
8310 // fallthrough --> copy0MBB
8311 MachineBasicBlock *thisMBB = BB;
8312 MachineFunction *F = BB->getParent();
8313 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8314 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8315 F->insert(It, copy0MBB);
8316 F->insert(It, sinkMBB);
8318 // Transfer the remainder of BB and its successor edges to sinkMBB.
8319 sinkMBB->splice(sinkMBB->begin(), BB,
8320 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8321 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8323 BB->addSuccessor(copy0MBB);
8324 BB->addSuccessor(sinkMBB);
8326 BuildMI(BB, dl, TII->get(ARM::tBcc))
8328 .addImm(MI.getOperand(3).getImm())
8329 .addReg(MI.getOperand(4).getReg());
8332 // %FalseValue = ...
8333 // # fallthrough to sinkMBB
8336 // Update machine-CFG edges
8337 BB->addSuccessor(sinkMBB);
8340 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8343 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8344 .addReg(MI.getOperand(1).getReg())
8346 .addReg(MI.getOperand(2).getReg())
8349 MI.eraseFromParent(); // The pseudo instruction is gone now.
8354 case ARM::BCCZi64: {
8355 // If there is an unconditional branch to the other successor, remove it.
8356 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8358 // Compare both parts that make up the double comparison separately for
8360 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8362 unsigned LHS1 = MI.getOperand(1).getReg();
8363 unsigned LHS2 = MI.getOperand(2).getReg();
8365 AddDefaultPred(BuildMI(BB, dl,
8366 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8367 .addReg(LHS1).addImm(0));
8368 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8369 .addReg(LHS2).addImm(0)
8370 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8372 unsigned RHS1 = MI.getOperand(3).getReg();
8373 unsigned RHS2 = MI.getOperand(4).getReg();
8374 AddDefaultPred(BuildMI(BB, dl,
8375 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8376 .addReg(LHS1).addReg(RHS1));
8377 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8378 .addReg(LHS2).addReg(RHS2)
8379 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8382 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8383 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8384 if (MI.getOperand(0).getImm() == ARMCC::NE)
8385 std::swap(destMBB, exitMBB);
8387 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8388 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8390 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8392 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8394 MI.eraseFromParent(); // The pseudo instruction is gone now.
8398 case ARM::Int_eh_sjlj_setjmp:
8399 case ARM::Int_eh_sjlj_setjmp_nofp:
8400 case ARM::tInt_eh_sjlj_setjmp:
8401 case ARM::t2Int_eh_sjlj_setjmp:
8402 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8405 case ARM::Int_eh_sjlj_setup_dispatch:
8406 EmitSjLjDispatchBlock(MI, BB);
8411 // To insert an ABS instruction, we have to insert the
8412 // diamond control-flow pattern. The incoming instruction knows the
8413 // source vreg to test against 0, the destination vreg to set,
8414 // the condition code register to branch on, the
8415 // true/false values to select between, and a branch opcode to use.
8420 // BCC (branch to SinkBB if V0 >= 0)
8421 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8422 // SinkBB: V1 = PHI(V2, V3)
8423 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8424 MachineFunction::iterator BBI = ++BB->getIterator();
8425 MachineFunction *Fn = BB->getParent();
8426 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8427 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8428 Fn->insert(BBI, RSBBB);
8429 Fn->insert(BBI, SinkBB);
8431 unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8432 unsigned int ABSDstReg = MI.getOperand(0).getReg();
8433 bool ABSSrcKIll = MI.getOperand(1).isKill();
8434 bool isThumb2 = Subtarget->isThumb2();
8435 MachineRegisterInfo &MRI = Fn->getRegInfo();
8436 // In Thumb mode S must not be specified if source register is the SP or
8437 // PC and if destination register is the SP, so restrict register class
8438 unsigned NewRsbDstReg =
8439 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8441 // Transfer the remainder of BB and its successor edges to sinkMBB.
8442 SinkBB->splice(SinkBB->begin(), BB,
8443 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8444 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8446 BB->addSuccessor(RSBBB);
8447 BB->addSuccessor(SinkBB);
8449 // fall through to SinkMBB
8450 RSBBB->addSuccessor(SinkBB);
8452 // insert a cmp at the end of BB
8453 AddDefaultPred(BuildMI(BB, dl,
8454 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8455 .addReg(ABSSrcReg).addImm(0));
8457 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8459 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8460 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8462 // insert rsbri in RSBBB
8463 // Note: BCC and rsbri will be converted into predicated rsbmi
8464 // by if-conversion pass
8465 BuildMI(*RSBBB, RSBBB->begin(), dl,
8466 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8467 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8468 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8470 // insert PHI in SinkBB,
8471 // reuse ABSDstReg to not change uses of ABS instruction
8472 BuildMI(*SinkBB, SinkBB->begin(), dl,
8473 TII->get(ARM::PHI), ABSDstReg)
8474 .addReg(NewRsbDstReg).addMBB(RSBBB)
8475 .addReg(ABSSrcReg).addMBB(BB);
8477 // remove ABS instruction
8478 MI.eraseFromParent();
8480 // return last added BB
8483 case ARM::COPY_STRUCT_BYVAL_I32:
8485 return EmitStructByval(MI, BB);
8486 case ARM::WIN__CHKSTK:
8487 return EmitLowered__chkstk(MI, BB);
8488 case ARM::WIN__DBZCHK:
8489 return EmitLowered__dbzchk(MI, BB);
8493 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8494 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8495 /// instead of as a custom inserter because we need the use list from the SDNode.
8496 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8497 MachineInstr &MI, const SDNode *Node) {
8498 bool isThumb1 = Subtarget->isThumb1Only();
8500 DebugLoc DL = MI.getDebugLoc();
8501 MachineFunction *MF = MI.getParent()->getParent();
8502 MachineRegisterInfo &MRI = MF->getRegInfo();
8503 MachineInstrBuilder MIB(*MF, MI);
8505 // If the new dst/src is unused mark it as dead.
8506 if (!Node->hasAnyUseOfValue(0)) {
8507 MI.getOperand(0).setIsDead(true);
8509 if (!Node->hasAnyUseOfValue(1)) {
8510 MI.getOperand(1).setIsDead(true);
8513 // The MEMCPY both defines and kills the scratch registers.
8514 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
8515 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8516 : &ARM::GPRRegClass);
8517 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8521 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8522 SDNode *Node) const {
8523 if (MI.getOpcode() == ARM::MEMCPY) {
8524 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8528 const MCInstrDesc *MCID = &MI.getDesc();
8529 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8530 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8531 // operand is still set to noreg. If needed, set the optional operand's
8532 // register to CPSR, and remove the redundant implicit def.
8534 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8536 // Rename pseudo opcodes.
8537 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
8539 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8540 MCID = &TII->get(NewOpc);
8542 assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
8543 "converted opcode should be the same except for cc_out");
8547 // Add the optional cc_out operand
8548 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8550 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8552 // Any ARM instruction that sets the 's' bit should specify an optional
8553 // "cc_out" operand in the last operand position.
8554 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8555 assert(!NewOpc && "Optional cc_out operand required");
8558 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8559 // since we already have an optional CPSR def.
8560 bool definesCPSR = false;
8561 bool deadCPSR = false;
8562 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
8564 const MachineOperand &MO = MI.getOperand(i);
8565 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8569 MI.RemoveOperand(i);
8574 assert(!NewOpc && "Optional cc_out operand required");
8577 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8579 assert(!MI.getOperand(ccOutIdx).getReg() &&
8580 "expect uninitialized optional cc_out operand");
8584 // If this instruction was defined with an optional CPSR def and its dag node
8585 // had a live implicit CPSR def, then activate the optional CPSR def.
8586 MachineOperand &MO = MI.getOperand(ccOutIdx);
8587 MO.setReg(ARM::CPSR);
8591 //===----------------------------------------------------------------------===//
8592 // ARM Optimization Hooks
8593 //===----------------------------------------------------------------------===//
8595 // Helper function that checks if N is a null or all ones constant.
8596 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8597 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8600 // Return true if N is conditionally 0 or all ones.
8601 // Detects these expressions where cc is an i1 value:
8603 // (select cc 0, y) [AllOnes=0]
8604 // (select cc y, 0) [AllOnes=0]
8605 // (zext cc) [AllOnes=0]
8606 // (sext cc) [AllOnes=0/1]
8607 // (select cc -1, y) [AllOnes=1]
8608 // (select cc y, -1) [AllOnes=1]
8610 // Invert is set when N is the null/all ones constant when CC is false.
8611 // OtherOp is set to the alternative value of N.
8612 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8613 SDValue &CC, bool &Invert,
8615 SelectionDAG &DAG) {
8616 switch (N->getOpcode()) {
8617 default: return false;
8619 CC = N->getOperand(0);
8620 SDValue N1 = N->getOperand(1);
8621 SDValue N2 = N->getOperand(2);
8622 if (isZeroOrAllOnes(N1, AllOnes)) {
8627 if (isZeroOrAllOnes(N2, AllOnes)) {
8634 case ISD::ZERO_EXTEND:
8635 // (zext cc) can never be the all ones value.
8639 case ISD::SIGN_EXTEND: {
8641 EVT VT = N->getValueType(0);
8642 CC = N->getOperand(0);
8643 if (CC.getValueType() != MVT::i1)
8647 // When looking for an AllOnes constant, N is an sext, and the 'other'
8649 OtherOp = DAG.getConstant(0, dl, VT);
8650 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8651 // When looking for a 0 constant, N can be zext or sext.
8652 OtherOp = DAG.getConstant(1, dl, VT);
8654 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8661 // Combine a constant select operand into its use:
8663 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8664 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8665 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8666 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8667 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8669 // The transform is rejected if the select doesn't have a constant operand that
8670 // is null, or all ones when AllOnes is set.
8672 // Also recognize sext/zext from i1:
8674 // (add (zext cc), x) -> (select cc (add x, 1), x)
8675 // (add (sext cc), x) -> (select cc (add x, -1), x)
8677 // These transformations eventually create predicated instructions.
8679 // @param N The node to transform.
8680 // @param Slct The N operand that is a select.
8681 // @param OtherOp The other N operand (x above).
8682 // @param DCI Context.
8683 // @param AllOnes Require the select constant to be all ones instead of null.
8684 // @returns The new node, or SDValue() on failure.
8686 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8687 TargetLowering::DAGCombinerInfo &DCI,
8688 bool AllOnes = false) {
8689 SelectionDAG &DAG = DCI.DAG;
8690 EVT VT = N->getValueType(0);
8691 SDValue NonConstantVal;
8694 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8695 NonConstantVal, DAG))
8698 // Slct is now know to be the desired identity constant when CC is true.
8699 SDValue TrueVal = OtherOp;
8700 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8701 OtherOp, NonConstantVal);
8702 // Unless SwapSelectOps says CC should be false.
8704 std::swap(TrueVal, FalseVal);
8706 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8707 CCOp, TrueVal, FalseVal);
8710 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8712 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8713 TargetLowering::DAGCombinerInfo &DCI) {
8714 SDValue N0 = N->getOperand(0);
8715 SDValue N1 = N->getOperand(1);
8716 if (N0.getNode()->hasOneUse())
8717 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
8719 if (N1.getNode()->hasOneUse())
8720 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
8725 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8726 // (only after legalization).
8727 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8728 TargetLowering::DAGCombinerInfo &DCI,
8729 const ARMSubtarget *Subtarget) {
8731 // Only perform optimization if after legalize, and if NEON is available. We
8732 // also expected both operands to be BUILD_VECTORs.
8733 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8734 || N0.getOpcode() != ISD::BUILD_VECTOR
8735 || N1.getOpcode() != ISD::BUILD_VECTOR)
8738 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8739 EVT VT = N->getValueType(0);
8740 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8743 // Check that the vector operands are of the right form.
8744 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8745 // operands, where N is the size of the formed vector.
8746 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8747 // index such that we have a pair wise add pattern.
8749 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8750 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8752 SDValue Vec = N0->getOperand(0)->getOperand(0);
8753 SDNode *V = Vec.getNode();
8754 unsigned nextIndex = 0;
8756 // For each operands to the ADD which are BUILD_VECTORs,
8757 // check to see if each of their operands are an EXTRACT_VECTOR with
8758 // the same vector and appropriate index.
8759 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8760 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8761 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8763 SDValue ExtVec0 = N0->getOperand(i);
8764 SDValue ExtVec1 = N1->getOperand(i);
8766 // First operand is the vector, verify its the same.
8767 if (V != ExtVec0->getOperand(0).getNode() ||
8768 V != ExtVec1->getOperand(0).getNode())
8771 // Second is the constant, verify its correct.
8772 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8773 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8775 // For the constant, we want to see all the even or all the odd.
8776 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8777 || C1->getZExtValue() != nextIndex+1)
8786 // Create VPADDL node.
8787 SelectionDAG &DAG = DCI.DAG;
8788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8792 // Build operand list.
8793 SmallVector<SDValue, 8> Ops;
8794 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8795 TLI.getPointerTy(DAG.getDataLayout())));
8797 // Input is the vector.
8800 // Get widened type and narrowed type.
8802 unsigned numElem = VT.getVectorNumElements();
8804 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8805 switch (inputLaneType.getSimpleVT().SimpleTy) {
8806 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8807 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8808 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8810 llvm_unreachable("Invalid vector element type for padd optimization.");
8813 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8814 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8815 return DAG.getNode(ExtOp, dl, VT, tmp);
8818 static SDValue findMUL_LOHI(SDValue V) {
8819 if (V->getOpcode() == ISD::UMUL_LOHI ||
8820 V->getOpcode() == ISD::SMUL_LOHI)
8825 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8826 TargetLowering::DAGCombinerInfo &DCI,
8827 const ARMSubtarget *Subtarget) {
8829 // Look for multiply add opportunities.
8830 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8831 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8832 // a glue link from the first add to the second add.
8833 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8834 // a S/UMLAL instruction.
8837 // / \ [no multiline comment]
8843 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8844 SDValue AddcOp0 = AddcNode->getOperand(0);
8845 SDValue AddcOp1 = AddcNode->getOperand(1);
8847 // Check if the two operands are from the same mul_lohi node.
8848 if (AddcOp0.getNode() == AddcOp1.getNode())
8851 assert(AddcNode->getNumValues() == 2 &&
8852 AddcNode->getValueType(0) == MVT::i32 &&
8853 "Expect ADDC with two result values. First: i32");
8855 // Check that we have a glued ADDC node.
8856 if (AddcNode->getValueType(1) != MVT::Glue)
8859 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8860 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8861 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8862 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8863 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8866 // Look for the glued ADDE.
8867 SDNode* AddeNode = AddcNode->getGluedUser();
8871 // Make sure it is really an ADDE.
8872 if (AddeNode->getOpcode() != ISD::ADDE)
8875 assert(AddeNode->getNumOperands() == 3 &&
8876 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8877 "ADDE node has the wrong inputs");
8879 // Check for the triangle shape.
8880 SDValue AddeOp0 = AddeNode->getOperand(0);
8881 SDValue AddeOp1 = AddeNode->getOperand(1);
8883 // Make sure that the ADDE operands are not coming from the same node.
8884 if (AddeOp0.getNode() == AddeOp1.getNode())
8887 // Find the MUL_LOHI node walking up ADDE's operands.
8888 bool IsLeftOperandMUL = false;
8889 SDValue MULOp = findMUL_LOHI(AddeOp0);
8890 if (MULOp == SDValue())
8891 MULOp = findMUL_LOHI(AddeOp1);
8893 IsLeftOperandMUL = true;
8894 if (MULOp == SDValue())
8897 // Figure out the right opcode.
8898 unsigned Opc = MULOp->getOpcode();
8899 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8901 // Figure out the high and low input values to the MLAL node.
8902 SDValue* HiAdd = nullptr;
8903 SDValue* LoMul = nullptr;
8904 SDValue* LowAdd = nullptr;
8906 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8907 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8910 if (IsLeftOperandMUL)
8916 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8917 // whose low result is fed to the ADDC we are checking.
8919 if (AddcOp0 == MULOp.getValue(0)) {
8923 if (AddcOp1 == MULOp.getValue(0)) {
8931 // Create the merged node.
8932 SelectionDAG &DAG = DCI.DAG;
8934 // Build operand list.
8935 SmallVector<SDValue, 8> Ops;
8936 Ops.push_back(LoMul->getOperand(0));
8937 Ops.push_back(LoMul->getOperand(1));
8938 Ops.push_back(*LowAdd);
8939 Ops.push_back(*HiAdd);
8941 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8942 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8944 // Replace the ADDs' nodes uses by the MLA node's values.
8945 SDValue HiMLALResult(MLALNode.getNode(), 1);
8946 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8948 SDValue LoMLALResult(MLALNode.getNode(), 0);
8949 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8951 // Return original node to notify the driver to stop replacing.
8952 SDValue resNode(AddcNode, 0);
8956 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode,
8957 TargetLowering::DAGCombinerInfo &DCI,
8958 const ARMSubtarget *Subtarget) {
8959 // UMAAL is similar to UMLAL except that it adds two unsigned values.
8960 // While trying to combine for the other MLAL nodes, first search for the
8961 // chance to use UMAAL. Check if Addc uses another addc node which can first
8962 // be combined into a UMLAL. The other pattern is AddcNode being combined
8963 // into an UMLAL and then using another addc is handled in ISelDAGToDAG.
8965 if (!Subtarget->hasV6Ops())
8966 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8968 SDNode *PrevAddc = nullptr;
8969 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC)
8970 PrevAddc = AddcNode->getOperand(0).getNode();
8971 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC)
8972 PrevAddc = AddcNode->getOperand(1).getNode();
8974 // If there's no addc chains, just return a search for any MLAL.
8975 if (PrevAddc == nullptr)
8976 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8978 // Try to convert the addc operand to an MLAL and if that fails try to
8979 // combine AddcNode.
8980 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget);
8981 if (MLAL != SDValue(PrevAddc, 0))
8982 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8984 // Find the converted UMAAL or quit if it doesn't exist.
8985 SDNode *UmlalNode = nullptr;
8987 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
8988 UmlalNode = AddcNode->getOperand(0).getNode();
8989 AddHi = AddcNode->getOperand(1);
8990 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
8991 UmlalNode = AddcNode->getOperand(1).getNode();
8992 AddHi = AddcNode->getOperand(0);
8997 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
8998 // the ADDC as well as Zero.
8999 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3));
9001 if (!Zero || Zero->getZExtValue() != 0)
9004 // Check that we have a glued ADDC node.
9005 if (AddcNode->getValueType(1) != MVT::Glue)
9008 // Look for the glued ADDE.
9009 SDNode* AddeNode = AddcNode->getGluedUser();
9013 if ((AddeNode->getOperand(0).getNode() == Zero &&
9014 AddeNode->getOperand(1).getNode() == UmlalNode) ||
9015 (AddeNode->getOperand(0).getNode() == UmlalNode &&
9016 AddeNode->getOperand(1).getNode() == Zero)) {
9018 SelectionDAG &DAG = DCI.DAG;
9019 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9020 UmlalNode->getOperand(2), AddHi };
9021 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9022 DAG.getVTList(MVT::i32, MVT::i32), Ops);
9024 // Replace the ADDs' nodes uses by the UMAAL node's values.
9025 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9026 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9028 // Return original node to notify the driver to stop replacing.
9029 return SDValue(AddcNode, 0);
9034 /// PerformADDCCombine - Target-specific dag combine transform from
9035 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or
9036 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9037 static SDValue PerformADDCCombine(SDNode *N,
9038 TargetLowering::DAGCombinerInfo &DCI,
9039 const ARMSubtarget *Subtarget) {
9041 if (Subtarget->isThumb1Only()) return SDValue();
9043 // Only perform the checks after legalize when the pattern is available.
9044 if (DCI.isBeforeLegalize()) return SDValue();
9046 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9049 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9050 /// operands N0 and N1. This is a helper for PerformADDCombine that is
9051 /// called with the default operands, and if that fails, with commuted
9053 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9054 TargetLowering::DAGCombinerInfo &DCI,
9055 const ARMSubtarget *Subtarget){
9057 // Attempt to create vpaddl for this add.
9058 if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
9061 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9062 if (N0.getNode()->hasOneUse())
9063 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9068 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9070 static SDValue PerformADDCombine(SDNode *N,
9071 TargetLowering::DAGCombinerInfo &DCI,
9072 const ARMSubtarget *Subtarget) {
9073 SDValue N0 = N->getOperand(0);
9074 SDValue N1 = N->getOperand(1);
9076 // First try with the default operand order.
9077 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9080 // If that didn't work, try again with the operands commuted.
9081 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9084 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9086 static SDValue PerformSUBCombine(SDNode *N,
9087 TargetLowering::DAGCombinerInfo &DCI) {
9088 SDValue N0 = N->getOperand(0);
9089 SDValue N1 = N->getOperand(1);
9091 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9092 if (N1.getNode()->hasOneUse())
9093 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9099 /// PerformVMULCombine
9100 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9101 /// special multiplier accumulator forwarding.
9107 // However, for (A + B) * (A + B),
9114 static SDValue PerformVMULCombine(SDNode *N,
9115 TargetLowering::DAGCombinerInfo &DCI,
9116 const ARMSubtarget *Subtarget) {
9117 if (!Subtarget->hasVMLxForwarding())
9120 SelectionDAG &DAG = DCI.DAG;
9121 SDValue N0 = N->getOperand(0);
9122 SDValue N1 = N->getOperand(1);
9123 unsigned Opcode = N0.getOpcode();
9124 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9125 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9126 Opcode = N1.getOpcode();
9127 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9128 Opcode != ISD::FADD && Opcode != ISD::FSUB)
9136 EVT VT = N->getValueType(0);
9138 SDValue N00 = N0->getOperand(0);
9139 SDValue N01 = N0->getOperand(1);
9140 return DAG.getNode(Opcode, DL, VT,
9141 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9142 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9145 static SDValue PerformMULCombine(SDNode *N,
9146 TargetLowering::DAGCombinerInfo &DCI,
9147 const ARMSubtarget *Subtarget) {
9148 SelectionDAG &DAG = DCI.DAG;
9150 if (Subtarget->isThumb1Only())
9153 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9156 EVT VT = N->getValueType(0);
9157 if (VT.is64BitVector() || VT.is128BitVector())
9158 return PerformVMULCombine(N, DCI, Subtarget);
9162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9166 int64_t MulAmt = C->getSExtValue();
9167 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9169 ShiftAmt = ShiftAmt & (32 - 1);
9170 SDValue V = N->getOperand(0);
9174 MulAmt >>= ShiftAmt;
9177 if (isPowerOf2_32(MulAmt - 1)) {
9178 // (mul x, 2^N + 1) => (add (shl x, N), x)
9179 Res = DAG.getNode(ISD::ADD, DL, VT,
9181 DAG.getNode(ISD::SHL, DL, VT,
9183 DAG.getConstant(Log2_32(MulAmt - 1), DL,
9185 } else if (isPowerOf2_32(MulAmt + 1)) {
9186 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9187 Res = DAG.getNode(ISD::SUB, DL, VT,
9188 DAG.getNode(ISD::SHL, DL, VT,
9190 DAG.getConstant(Log2_32(MulAmt + 1), DL,
9196 uint64_t MulAmtAbs = -MulAmt;
9197 if (isPowerOf2_32(MulAmtAbs + 1)) {
9198 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9199 Res = DAG.getNode(ISD::SUB, DL, VT,
9201 DAG.getNode(ISD::SHL, DL, VT,
9203 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9205 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9206 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9207 Res = DAG.getNode(ISD::ADD, DL, VT,
9209 DAG.getNode(ISD::SHL, DL, VT,
9211 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9213 Res = DAG.getNode(ISD::SUB, DL, VT,
9214 DAG.getConstant(0, DL, MVT::i32), Res);
9221 Res = DAG.getNode(ISD::SHL, DL, VT,
9222 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9224 // Do not add new nodes to DAG combiner worklist.
9225 DCI.CombineTo(N, Res, false);
9229 static SDValue PerformANDCombine(SDNode *N,
9230 TargetLowering::DAGCombinerInfo &DCI,
9231 const ARMSubtarget *Subtarget) {
9233 // Attempt to use immediate-form VBIC
9234 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9236 EVT VT = N->getValueType(0);
9237 SelectionDAG &DAG = DCI.DAG;
9239 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9242 APInt SplatBits, SplatUndef;
9243 unsigned SplatBitSize;
9246 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9247 if (SplatBitSize <= 64) {
9249 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9250 SplatUndef.getZExtValue(), SplatBitSize,
9251 DAG, dl, VbicVT, VT.is128BitVector(),
9253 if (Val.getNode()) {
9255 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9256 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9257 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9262 if (!Subtarget->isThumb1Only()) {
9263 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9264 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9271 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
9272 static SDValue PerformORCombine(SDNode *N,
9273 TargetLowering::DAGCombinerInfo &DCI,
9274 const ARMSubtarget *Subtarget) {
9275 // Attempt to use immediate-form VORR
9276 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9278 EVT VT = N->getValueType(0);
9279 SelectionDAG &DAG = DCI.DAG;
9281 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9284 APInt SplatBits, SplatUndef;
9285 unsigned SplatBitSize;
9287 if (BVN && Subtarget->hasNEON() &&
9288 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9289 if (SplatBitSize <= 64) {
9291 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9292 SplatUndef.getZExtValue(), SplatBitSize,
9293 DAG, dl, VorrVT, VT.is128BitVector(),
9295 if (Val.getNode()) {
9297 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9298 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9299 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9304 if (!Subtarget->isThumb1Only()) {
9305 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9306 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9310 // The code below optimizes (or (and X, Y), Z).
9311 // The AND operand needs to have a single user to make these optimizations
9313 SDValue N0 = N->getOperand(0);
9314 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9316 SDValue N1 = N->getOperand(1);
9318 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9319 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9320 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9322 unsigned SplatBitSize;
9325 APInt SplatBits0, SplatBits1;
9326 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9327 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9328 // Ensure that the second operand of both ands are constants
9329 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9330 HasAnyUndefs) && !HasAnyUndefs) {
9331 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9332 HasAnyUndefs) && !HasAnyUndefs) {
9333 // Ensure that the bit width of the constants are the same and that
9334 // the splat arguments are logical inverses as per the pattern we
9335 // are trying to simplify.
9336 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9337 SplatBits0 == ~SplatBits1) {
9338 // Canonicalize the vector type to make instruction selection
9340 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9341 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9345 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9351 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9354 // BFI is only available on V6T2+
9355 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9359 // 1) or (and A, mask), val => ARMbfi A, val, mask
9360 // iff (val & mask) == val
9362 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9363 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9364 // && mask == ~mask2
9365 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9366 // && ~mask == mask2
9367 // (i.e., copy a bitfield value into another bitfield of the same width)
9372 SDValue N00 = N0.getOperand(0);
9374 // The value and the mask need to be constants so we can verify this is
9375 // actually a bitfield set. If the mask is 0xffff, we can do better
9376 // via a movt instruction, so don't use BFI in that case.
9377 SDValue MaskOp = N0.getOperand(1);
9378 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9381 unsigned Mask = MaskC->getZExtValue();
9385 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9386 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9388 unsigned Val = N1C->getZExtValue();
9389 if ((Val & ~Mask) != Val)
9392 if (ARM::isBitFieldInvertedMask(Mask)) {
9393 Val >>= countTrailingZeros(~Mask);
9395 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9396 DAG.getConstant(Val, DL, MVT::i32),
9397 DAG.getConstant(Mask, DL, MVT::i32));
9399 // Do not add new nodes to DAG combiner worklist.
9400 DCI.CombineTo(N, Res, false);
9403 } else if (N1.getOpcode() == ISD::AND) {
9404 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9405 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9408 unsigned Mask2 = N11C->getZExtValue();
9410 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9412 if (ARM::isBitFieldInvertedMask(Mask) &&
9414 // The pack halfword instruction works better for masks that fit it,
9415 // so use that when it's available.
9416 if (Subtarget->hasT2ExtractPack() &&
9417 (Mask == 0xffff || Mask == 0xffff0000))
9420 unsigned amt = countTrailingZeros(Mask2);
9421 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9422 DAG.getConstant(amt, DL, MVT::i32));
9423 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9424 DAG.getConstant(Mask, DL, MVT::i32));
9425 // Do not add new nodes to DAG combiner worklist.
9426 DCI.CombineTo(N, Res, false);
9428 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9430 // The pack halfword instruction works better for masks that fit it,
9431 // so use that when it's available.
9432 if (Subtarget->hasT2ExtractPack() &&
9433 (Mask2 == 0xffff || Mask2 == 0xffff0000))
9436 unsigned lsb = countTrailingZeros(Mask);
9437 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9438 DAG.getConstant(lsb, DL, MVT::i32));
9439 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9440 DAG.getConstant(Mask2, DL, MVT::i32));
9441 // Do not add new nodes to DAG combiner worklist.
9442 DCI.CombineTo(N, Res, false);
9447 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9448 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9449 ARM::isBitFieldInvertedMask(~Mask)) {
9450 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9451 // where lsb(mask) == #shamt and masked bits of B are known zero.
9452 SDValue ShAmt = N00.getOperand(1);
9453 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9454 unsigned LSB = countTrailingZeros(Mask);
9458 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9459 DAG.getConstant(~Mask, DL, MVT::i32));
9461 // Do not add new nodes to DAG combiner worklist.
9462 DCI.CombineTo(N, Res, false);
9468 static SDValue PerformXORCombine(SDNode *N,
9469 TargetLowering::DAGCombinerInfo &DCI,
9470 const ARMSubtarget *Subtarget) {
9471 EVT VT = N->getValueType(0);
9472 SelectionDAG &DAG = DCI.DAG;
9474 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9477 if (!Subtarget->isThumb1Only()) {
9478 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9479 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9486 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9487 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9488 // their position in "to" (Rd).
9489 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9490 assert(N->getOpcode() == ARMISD::BFI);
9492 SDValue From = N->getOperand(1);
9493 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9494 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9496 // If the Base came from a SHR #C, we can deduce that it is really testing bit
9497 // #C in the base of the SHR.
9498 if (From->getOpcode() == ISD::SRL &&
9499 isa<ConstantSDNode>(From->getOperand(1))) {
9500 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9501 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9502 FromMask <<= Shift.getLimitedValue(31);
9503 From = From->getOperand(0);
9509 // If A and B contain one contiguous set of bits, does A | B == A . B?
9511 // Neither A nor B must be zero.
9512 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9513 unsigned LastActiveBitInA = A.countTrailingZeros();
9514 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9515 return LastActiveBitInA - 1 == FirstActiveBitInB;
9518 static SDValue FindBFIToCombineWith(SDNode *N) {
9519 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9521 APInt ToMask, FromMask;
9522 SDValue From = ParseBFI(N, ToMask, FromMask);
9523 SDValue To = N->getOperand(0);
9525 // Now check for a compatible BFI to merge with. We can pass through BFIs that
9526 // aren't compatible, but not if they set the same bit in their destination as
9527 // we do (or that of any BFI we're going to combine with).
9529 APInt CombinedToMask = ToMask;
9530 while (V.getOpcode() == ARMISD::BFI) {
9531 APInt NewToMask, NewFromMask;
9532 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9533 if (NewFrom != From) {
9534 // This BFI has a different base. Keep going.
9535 CombinedToMask |= NewToMask;
9536 V = V.getOperand(0);
9540 // Do the written bits conflict with any we've seen so far?
9541 if ((NewToMask & CombinedToMask).getBoolValue())
9542 // Conflicting bits - bail out because going further is unsafe.
9545 // Are the new bits contiguous when combined with the old bits?
9546 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9547 BitsProperlyConcatenate(FromMask, NewFromMask))
9549 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9550 BitsProperlyConcatenate(NewFromMask, FromMask))
9553 // We've seen a write to some bits, so track it.
9554 CombinedToMask |= NewToMask;
9556 V = V.getOperand(0);
9562 static SDValue PerformBFICombine(SDNode *N,
9563 TargetLowering::DAGCombinerInfo &DCI) {
9564 SDValue N1 = N->getOperand(1);
9565 if (N1.getOpcode() == ISD::AND) {
9566 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9567 // the bits being cleared by the AND are not demanded by the BFI.
9568 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9571 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9572 unsigned LSB = countTrailingZeros(~InvMask);
9573 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9575 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9576 "undefined behavior");
9577 unsigned Mask = (1u << Width) - 1;
9578 unsigned Mask2 = N11C->getZExtValue();
9579 if ((Mask & (~Mask2)) == 0)
9580 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9581 N->getOperand(0), N1.getOperand(0),
9583 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9584 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9585 // Keep track of any consecutive bits set that all come from the same base
9586 // value. We can combine these together into a single BFI.
9587 SDValue CombineBFI = FindBFIToCombineWith(N);
9588 if (CombineBFI == SDValue())
9591 // We've found a BFI.
9592 APInt ToMask1, FromMask1;
9593 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9595 APInt ToMask2, FromMask2;
9596 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9597 assert(From1 == From2);
9600 // First, unlink CombineBFI.
9601 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9602 // Then create a new BFI, combining the two together.
9603 APInt NewFromMask = FromMask1 | FromMask2;
9604 APInt NewToMask = ToMask1 | ToMask2;
9606 EVT VT = N->getValueType(0);
9609 if (NewFromMask[0] == 0)
9610 From1 = DCI.DAG.getNode(
9611 ISD::SRL, dl, VT, From1,
9612 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9613 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9614 DCI.DAG.getConstant(~NewToMask, dl, VT));
9619 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9620 /// ARMISD::VMOVRRD.
9621 static SDValue PerformVMOVRRDCombine(SDNode *N,
9622 TargetLowering::DAGCombinerInfo &DCI,
9623 const ARMSubtarget *Subtarget) {
9624 // vmovrrd(vmovdrr x, y) -> x,y
9625 SDValue InDouble = N->getOperand(0);
9626 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9627 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9629 // vmovrrd(load f64) -> (load i32), (load i32)
9630 SDNode *InNode = InDouble.getNode();
9631 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9632 InNode->getValueType(0) == MVT::f64 &&
9633 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9634 !cast<LoadSDNode>(InNode)->isVolatile()) {
9635 // TODO: Should this be done for non-FrameIndex operands?
9636 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9638 SelectionDAG &DAG = DCI.DAG;
9640 SDValue BasePtr = LD->getBasePtr();
9642 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
9643 LD->getAlignment(), LD->getMemOperand()->getFlags());
9645 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9646 DAG.getConstant(4, DL, MVT::i32));
9647 SDValue NewLD2 = DAG.getLoad(
9648 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
9649 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
9651 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9652 if (DCI.DAG.getDataLayout().isBigEndian())
9653 std::swap (NewLD1, NewLD2);
9654 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9661 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9662 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9663 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9664 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9665 SDValue Op0 = N->getOperand(0);
9666 SDValue Op1 = N->getOperand(1);
9667 if (Op0.getOpcode() == ISD::BITCAST)
9668 Op0 = Op0.getOperand(0);
9669 if (Op1.getOpcode() == ISD::BITCAST)
9670 Op1 = Op1.getOperand(0);
9671 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9672 Op0.getNode() == Op1.getNode() &&
9673 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9674 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9675 N->getValueType(0), Op0.getOperand(0));
9679 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9680 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9681 /// i64 vector to have f64 elements, since the value can then be loaded
9682 /// directly into a VFP register.
9683 static bool hasNormalLoadOperand(SDNode *N) {
9684 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9685 for (unsigned i = 0; i < NumElts; ++i) {
9686 SDNode *Elt = N->getOperand(i).getNode();
9687 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9693 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9694 /// ISD::BUILD_VECTOR.
9695 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9696 TargetLowering::DAGCombinerInfo &DCI,
9697 const ARMSubtarget *Subtarget) {
9698 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9699 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9700 // into a pair of GPRs, which is fine when the value is used as a scalar,
9701 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9702 SelectionDAG &DAG = DCI.DAG;
9703 if (N->getNumOperands() == 2)
9704 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
9707 // Load i64 elements as f64 values so that type legalization does not split
9708 // them up into i32 values.
9709 EVT VT = N->getValueType(0);
9710 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9713 SmallVector<SDValue, 8> Ops;
9714 unsigned NumElts = VT.getVectorNumElements();
9715 for (unsigned i = 0; i < NumElts; ++i) {
9716 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9718 // Make the DAGCombiner fold the bitcast.
9719 DCI.AddToWorklist(V.getNode());
9721 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9722 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
9723 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9726 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9728 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9729 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9730 // At that time, we may have inserted bitcasts from integer to float.
9731 // If these bitcasts have survived DAGCombine, change the lowering of this
9732 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9733 // force to use floating point types.
9735 // Make sure we can change the type of the vector.
9736 // This is possible iff:
9737 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9738 // 1.1. Vector is used only once.
9739 // 1.2. Use is a bit convert to an integer type.
9740 // 2. The size of its operands are 32-bits (64-bits are not legal).
9741 EVT VT = N->getValueType(0);
9742 EVT EltVT = VT.getVectorElementType();
9744 // Check 1.1. and 2.
9745 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9748 // By construction, the input type must be float.
9749 assert(EltVT == MVT::f32 && "Unexpected type!");
9752 SDNode *Use = *N->use_begin();
9753 if (Use->getOpcode() != ISD::BITCAST ||
9754 Use->getValueType(0).isFloatingPoint())
9757 // Check profitability.
9758 // Model is, if more than half of the relevant operands are bitcast from
9759 // i32, turn the build_vector into a sequence of insert_vector_elt.
9760 // Relevant operands are everything that is not statically
9761 // (i.e., at compile time) bitcasted.
9762 unsigned NumOfBitCastedElts = 0;
9763 unsigned NumElts = VT.getVectorNumElements();
9764 unsigned NumOfRelevantElts = NumElts;
9765 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9766 SDValue Elt = N->getOperand(Idx);
9767 if (Elt->getOpcode() == ISD::BITCAST) {
9768 // Assume only bit cast to i32 will go away.
9769 if (Elt->getOperand(0).getValueType() == MVT::i32)
9770 ++NumOfBitCastedElts;
9771 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
9772 // Constants are statically casted, thus do not count them as
9773 // relevant operands.
9774 --NumOfRelevantElts;
9777 // Check if more than half of the elements require a non-free bitcast.
9778 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9781 SelectionDAG &DAG = DCI.DAG;
9782 // Create the new vector type.
9783 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9784 // Check if the type is legal.
9785 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9786 if (!TLI.isTypeLegal(VecVT))
9790 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9791 // => BITCAST INSERT_VECTOR_ELT
9792 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9794 SDValue Vec = DAG.getUNDEF(VecVT);
9796 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9797 SDValue V = N->getOperand(Idx);
9800 if (V.getOpcode() == ISD::BITCAST &&
9801 V->getOperand(0).getValueType() == MVT::i32)
9802 // Fold obvious case.
9803 V = V.getOperand(0);
9805 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9806 // Make the DAGCombiner fold the bitcasts.
9807 DCI.AddToWorklist(V.getNode());
9809 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9810 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9812 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9813 // Make the DAGCombiner fold the bitcasts.
9814 DCI.AddToWorklist(Vec.getNode());
9818 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9819 /// ISD::INSERT_VECTOR_ELT.
9820 static SDValue PerformInsertEltCombine(SDNode *N,
9821 TargetLowering::DAGCombinerInfo &DCI) {
9822 // Bitcast an i64 load inserted into a vector to f64.
9823 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9824 EVT VT = N->getValueType(0);
9825 SDNode *Elt = N->getOperand(1).getNode();
9826 if (VT.getVectorElementType() != MVT::i64 ||
9827 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9830 SelectionDAG &DAG = DCI.DAG;
9832 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9833 VT.getVectorNumElements());
9834 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9835 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9836 // Make the DAGCombiner fold the bitcasts.
9837 DCI.AddToWorklist(Vec.getNode());
9838 DCI.AddToWorklist(V.getNode());
9839 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9840 Vec, V, N->getOperand(2));
9841 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9844 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9845 /// ISD::VECTOR_SHUFFLE.
9846 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9847 // The LLVM shufflevector instruction does not require the shuffle mask
9848 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9849 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9850 // operands do not match the mask length, they are extended by concatenating
9851 // them with undef vectors. That is probably the right thing for other
9852 // targets, but for NEON it is better to concatenate two double-register
9853 // size vector operands into a single quad-register size vector. Do that
9854 // transformation here:
9855 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9856 // shuffle(concat(v1, v2), undef)
9857 SDValue Op0 = N->getOperand(0);
9858 SDValue Op1 = N->getOperand(1);
9859 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9860 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9861 Op0.getNumOperands() != 2 ||
9862 Op1.getNumOperands() != 2)
9864 SDValue Concat0Op1 = Op0.getOperand(1);
9865 SDValue Concat1Op1 = Op1.getOperand(1);
9866 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
9868 // Skip the transformation if any of the types are illegal.
9869 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9870 EVT VT = N->getValueType(0);
9871 if (!TLI.isTypeLegal(VT) ||
9872 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9873 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9876 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9877 Op0.getOperand(0), Op1.getOperand(0));
9878 // Translate the shuffle mask.
9879 SmallVector<int, 16> NewMask;
9880 unsigned NumElts = VT.getVectorNumElements();
9881 unsigned HalfElts = NumElts/2;
9882 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9883 for (unsigned n = 0; n < NumElts; ++n) {
9884 int MaskElt = SVN->getMaskElt(n);
9886 if (MaskElt < (int)HalfElts)
9888 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9889 NewElt = HalfElts + MaskElt - NumElts;
9890 NewMask.push_back(NewElt);
9892 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9893 DAG.getUNDEF(VT), NewMask);
9896 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9897 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9898 /// base address updates.
9899 /// For generic load/stores, the memory type is assumed to be a vector.
9900 /// The caller is assumed to have checked legality.
9901 static SDValue CombineBaseUpdate(SDNode *N,
9902 TargetLowering::DAGCombinerInfo &DCI) {
9903 SelectionDAG &DAG = DCI.DAG;
9904 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9905 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9906 const bool isStore = N->getOpcode() == ISD::STORE;
9907 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9908 SDValue Addr = N->getOperand(AddrOpIdx);
9909 MemSDNode *MemN = cast<MemSDNode>(N);
9912 // Search for a use of the address operand that is an increment.
9913 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9914 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9916 if (User->getOpcode() != ISD::ADD ||
9917 UI.getUse().getResNo() != Addr.getResNo())
9920 // Check that the add is independent of the load/store. Otherwise, folding
9921 // it would create a cycle.
9922 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9925 // Find the new opcode for the updating load/store.
9926 bool isLoadOp = true;
9927 bool isLaneOp = false;
9928 unsigned NewOpc = 0;
9929 unsigned NumVecs = 0;
9931 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9933 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9934 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9936 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9938 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9940 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9942 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9943 NumVecs = 2; isLaneOp = true; break;
9944 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9945 NumVecs = 3; isLaneOp = true; break;
9946 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9947 NumVecs = 4; isLaneOp = true; break;
9948 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9949 NumVecs = 1; isLoadOp = false; break;
9950 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9951 NumVecs = 2; isLoadOp = false; break;
9952 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9953 NumVecs = 3; isLoadOp = false; break;
9954 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9955 NumVecs = 4; isLoadOp = false; break;
9956 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9957 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9958 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9959 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9960 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9961 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9965 switch (N->getOpcode()) {
9966 default: llvm_unreachable("unexpected opcode for Neon base update");
9967 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9968 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9969 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9970 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9971 NumVecs = 1; isLaneOp = false; break;
9972 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9973 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9977 // Find the size of memory referenced by the load/store.
9980 VecTy = N->getValueType(0);
9981 } else if (isIntrinsic) {
9982 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9984 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9985 VecTy = N->getOperand(1).getValueType();
9988 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9990 NumBytes /= VecTy.getVectorNumElements();
9992 // If the increment is a constant, it must match the memory ref size.
9993 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9994 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9995 uint64_t IncVal = CInc->getZExtValue();
9996 if (IncVal != NumBytes)
9998 } else if (NumBytes >= 3 * 16) {
9999 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10000 // separate instructions that make it harder to use a non-constant update.
10004 // OK, we found an ADD we can fold into the base update.
10005 // Now, create a _UPD node, taking care of not breaking alignment.
10007 EVT AlignedVecTy = VecTy;
10008 unsigned Alignment = MemN->getAlignment();
10010 // If this is a less-than-standard-aligned load/store, change the type to
10011 // match the standard alignment.
10012 // The alignment is overlooked when selecting _UPD variants; and it's
10013 // easier to introduce bitcasts here than fix that.
10014 // There are 3 ways to get to this base-update combine:
10015 // - intrinsics: they are assumed to be properly aligned (to the standard
10016 // alignment of the memory type), so we don't need to do anything.
10017 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10018 // intrinsics, so, likewise, there's nothing to do.
10019 // - generic load/store instructions: the alignment is specified as an
10020 // explicit operand, rather than implicitly as the standard alignment
10021 // of the memory type (like the intrisics). We need to change the
10022 // memory type to match the explicit alignment. That way, we don't
10023 // generate non-standard-aligned ARMISD::VLDx nodes.
10024 if (isa<LSBaseSDNode>(N)) {
10025 if (Alignment == 0)
10027 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10028 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10029 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10030 assert(!isLaneOp && "Unexpected generic load/store lane.");
10031 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10032 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10034 // Don't set an explicit alignment on regular load/stores that we want
10035 // to transform to VLD/VST 1_UPD nodes.
10036 // This matches the behavior of regular load/stores, which only get an
10037 // explicit alignment if the MMO alignment is larger than the standard
10038 // alignment of the memory type.
10039 // Intrinsics, however, always get an explicit alignment, set to the
10040 // alignment of the MMO.
10044 // Create the new updating load/store node.
10045 // First, create an SDVTList for the new updating node's results.
10047 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10049 for (n = 0; n < NumResultVecs; ++n)
10050 Tys[n] = AlignedVecTy;
10051 Tys[n++] = MVT::i32;
10052 Tys[n] = MVT::Other;
10053 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10055 // Then, gather the new node's operands.
10056 SmallVector<SDValue, 8> Ops;
10057 Ops.push_back(N->getOperand(0)); // incoming chain
10058 Ops.push_back(N->getOperand(AddrOpIdx));
10059 Ops.push_back(Inc);
10061 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10062 // Try to match the intrinsic's signature
10063 Ops.push_back(StN->getValue());
10065 // Loads (and of course intrinsics) match the intrinsics' signature,
10066 // so just add all but the alignment operand.
10067 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10068 Ops.push_back(N->getOperand(i));
10071 // For all node types, the alignment operand is always the last one.
10072 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10074 // If this is a non-standard-aligned STORE, the penultimate operand is the
10075 // stored value. Bitcast it to the aligned type.
10076 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10077 SDValue &StVal = Ops[Ops.size()-2];
10078 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10081 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
10083 MemN->getMemOperand());
10085 // Update the uses.
10086 SmallVector<SDValue, 5> NewResults;
10087 for (unsigned i = 0; i < NumResultVecs; ++i)
10088 NewResults.push_back(SDValue(UpdN.getNode(), i));
10090 // If this is an non-standard-aligned LOAD, the first result is the loaded
10091 // value. Bitcast it to the expected result type.
10092 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10093 SDValue &LdVal = NewResults[0];
10094 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10097 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10098 DCI.CombineTo(N, NewResults);
10099 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10106 static SDValue PerformVLDCombine(SDNode *N,
10107 TargetLowering::DAGCombinerInfo &DCI) {
10108 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10111 return CombineBaseUpdate(N, DCI);
10114 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10115 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10116 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
10118 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10119 SelectionDAG &DAG = DCI.DAG;
10120 EVT VT = N->getValueType(0);
10121 // vldN-dup instructions only support 64-bit vectors for N > 1.
10122 if (!VT.is64BitVector())
10125 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10126 SDNode *VLD = N->getOperand(0).getNode();
10127 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10129 unsigned NumVecs = 0;
10130 unsigned NewOpc = 0;
10131 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10132 if (IntNo == Intrinsic::arm_neon_vld2lane) {
10134 NewOpc = ARMISD::VLD2DUP;
10135 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10137 NewOpc = ARMISD::VLD3DUP;
10138 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10140 NewOpc = ARMISD::VLD4DUP;
10145 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10146 // numbers match the load.
10147 unsigned VLDLaneNo =
10148 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10149 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10151 // Ignore uses of the chain result.
10152 if (UI.getUse().getResNo() == NumVecs)
10154 SDNode *User = *UI;
10155 if (User->getOpcode() != ARMISD::VDUPLANE ||
10156 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10160 // Create the vldN-dup node.
10163 for (n = 0; n < NumVecs; ++n)
10165 Tys[n] = MVT::Other;
10166 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10167 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10168 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10169 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10170 Ops, VLDMemInt->getMemoryVT(),
10171 VLDMemInt->getMemOperand());
10173 // Update the uses.
10174 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10176 unsigned ResNo = UI.getUse().getResNo();
10177 // Ignore uses of the chain result.
10178 if (ResNo == NumVecs)
10180 SDNode *User = *UI;
10181 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10184 // Now the vldN-lane intrinsic is dead except for its chain result.
10185 // Update uses of the chain.
10186 std::vector<SDValue> VLDDupResults;
10187 for (unsigned n = 0; n < NumVecs; ++n)
10188 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10189 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10190 DCI.CombineTo(VLD, VLDDupResults);
10195 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10196 /// ARMISD::VDUPLANE.
10197 static SDValue PerformVDUPLANECombine(SDNode *N,
10198 TargetLowering::DAGCombinerInfo &DCI) {
10199 SDValue Op = N->getOperand(0);
10201 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
10202 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
10203 if (CombineVLDDUP(N, DCI))
10204 return SDValue(N, 0);
10206 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
10207 // redundant. Ignore bit_converts for now; element sizes are checked below.
10208 while (Op.getOpcode() == ISD::BITCAST)
10209 Op = Op.getOperand(0);
10210 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
10213 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
10214 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
10215 // The canonical VMOV for a zero vector uses a 32-bit element size.
10216 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10218 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
10220 EVT VT = N->getValueType(0);
10221 if (EltSize > VT.getVectorElementType().getSizeInBits())
10224 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
10227 static SDValue PerformLOADCombine(SDNode *N,
10228 TargetLowering::DAGCombinerInfo &DCI) {
10229 EVT VT = N->getValueType(0);
10231 // If this is a legal vector load, try to combine it into a VLD1_UPD.
10232 if (ISD::isNormalLoad(N) && VT.isVector() &&
10233 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10234 return CombineBaseUpdate(N, DCI);
10239 /// PerformSTORECombine - Target-specific dag combine xforms for
10241 static SDValue PerformSTORECombine(SDNode *N,
10242 TargetLowering::DAGCombinerInfo &DCI) {
10243 StoreSDNode *St = cast<StoreSDNode>(N);
10244 if (St->isVolatile())
10247 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
10248 // pack all of the elements in one place. Next, store to memory in fewer
10250 SDValue StVal = St->getValue();
10251 EVT VT = StVal.getValueType();
10252 if (St->isTruncatingStore() && VT.isVector()) {
10253 SelectionDAG &DAG = DCI.DAG;
10254 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10255 EVT StVT = St->getMemoryVT();
10256 unsigned NumElems = VT.getVectorNumElements();
10257 assert(StVT != VT && "Cannot truncate to the same type");
10258 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
10259 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
10261 // From, To sizes and ElemCount must be pow of two
10262 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
10264 // We are going to use the original vector elt for storing.
10265 // Accumulated smaller vector elements must be a multiple of the store size.
10266 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
10268 unsigned SizeRatio = FromEltSz / ToEltSz;
10269 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
10271 // Create a type on which we perform the shuffle.
10272 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
10273 NumElems*SizeRatio);
10274 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
10277 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
10278 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
10279 for (unsigned i = 0; i < NumElems; ++i)
10280 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
10281 ? (i + 1) * SizeRatio - 1
10284 // Can't shuffle using an illegal type.
10285 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10287 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10288 DAG.getUNDEF(WideVec.getValueType()),
10290 // At this point all of the data is stored at the bottom of the
10291 // register. We now need to save it to mem.
10293 // Find the largest store unit
10294 MVT StoreType = MVT::i8;
10295 for (MVT Tp : MVT::integer_valuetypes()) {
10296 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10299 // Didn't find a legal store type.
10300 if (!TLI.isTypeLegal(StoreType))
10303 // Bitcast the original vector into a vector of store-size units
10304 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10305 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10306 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10307 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10308 SmallVector<SDValue, 8> Chains;
10309 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10310 TLI.getPointerTy(DAG.getDataLayout()));
10311 SDValue BasePtr = St->getBasePtr();
10313 // Perform one or more big stores into memory.
10314 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10315 for (unsigned I = 0; I < E; I++) {
10316 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10317 StoreType, ShuffWide,
10318 DAG.getIntPtrConstant(I, DL));
10319 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10320 St->getPointerInfo(), St->getAlignment(),
10321 St->getMemOperand()->getFlags());
10322 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10324 Chains.push_back(Ch);
10326 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10329 if (!ISD::isNormalStore(St))
10332 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10333 // ARM stores of arguments in the same cache line.
10334 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10335 StVal.getNode()->hasOneUse()) {
10336 SelectionDAG &DAG = DCI.DAG;
10337 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10339 SDValue BasePtr = St->getBasePtr();
10340 SDValue NewST1 = DAG.getStore(
10341 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
10342 BasePtr, St->getPointerInfo(), St->getAlignment(),
10343 St->getMemOperand()->getFlags());
10345 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10346 DAG.getConstant(4, DL, MVT::i32));
10347 return DAG.getStore(NewST1.getValue(0), DL,
10348 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10349 OffsetPtr, St->getPointerInfo(),
10350 std::min(4U, St->getAlignment() / 2),
10351 St->getMemOperand()->getFlags());
10354 if (StVal.getValueType() == MVT::i64 &&
10355 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10357 // Bitcast an i64 store extracted from a vector to f64.
10358 // Otherwise, the i64 value will be legalized to a pair of i32 values.
10359 SelectionDAG &DAG = DCI.DAG;
10361 SDValue IntVec = StVal.getOperand(0);
10362 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10363 IntVec.getValueType().getVectorNumElements());
10364 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10365 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10366 Vec, StVal.getOperand(1));
10368 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10369 // Make the DAGCombiner fold the bitcasts.
10370 DCI.AddToWorklist(Vec.getNode());
10371 DCI.AddToWorklist(ExtElt.getNode());
10372 DCI.AddToWorklist(V.getNode());
10373 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10374 St->getPointerInfo(), St->getAlignment(),
10375 St->getMemOperand()->getFlags(), St->getAAInfo());
10378 // If this is a legal vector store, try to combine it into a VST1_UPD.
10379 if (ISD::isNormalStore(N) && VT.isVector() &&
10380 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10381 return CombineBaseUpdate(N, DCI);
10386 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10387 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10388 /// when the VMUL has a constant operand that is a power of 2.
10390 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10391 /// vmul.f32 d16, d17, d16
10392 /// vcvt.s32.f32 d16, d16
10394 /// vcvt.s32.f32 d16, d16, #3
10395 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10396 const ARMSubtarget *Subtarget) {
10397 if (!Subtarget->hasNEON())
10400 SDValue Op = N->getOperand(0);
10401 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10402 Op.getOpcode() != ISD::FMUL)
10405 SDValue ConstVec = Op->getOperand(1);
10406 if (!isa<BuildVectorSDNode>(ConstVec))
10409 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10410 uint32_t FloatBits = FloatTy.getSizeInBits();
10411 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10412 uint32_t IntBits = IntTy.getSizeInBits();
10413 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10414 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10415 // These instructions only exist converting from f32 to i32. We can handle
10416 // smaller integers by generating an extra truncate, but larger ones would
10417 // be lossy. We also can't handle more then 4 lanes, since these intructions
10418 // only support v2i32/v4i32 types.
10422 BitVector UndefElements;
10423 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10424 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10425 if (C == -1 || C == 0 || C > 32)
10429 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10430 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10431 Intrinsic::arm_neon_vcvtfp2fxu;
10432 SDValue FixConv = DAG.getNode(
10433 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10434 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10435 DAG.getConstant(C, dl, MVT::i32));
10437 if (IntBits < FloatBits)
10438 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10443 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10444 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10445 /// when the VDIV has a constant operand that is a power of 2.
10447 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10448 /// vcvt.f32.s32 d16, d16
10449 /// vdiv.f32 d16, d17, d16
10451 /// vcvt.f32.s32 d16, d16, #3
10452 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10453 const ARMSubtarget *Subtarget) {
10454 if (!Subtarget->hasNEON())
10457 SDValue Op = N->getOperand(0);
10458 unsigned OpOpcode = Op.getNode()->getOpcode();
10459 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
10460 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10463 SDValue ConstVec = N->getOperand(1);
10464 if (!isa<BuildVectorSDNode>(ConstVec))
10467 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10468 uint32_t FloatBits = FloatTy.getSizeInBits();
10469 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10470 uint32_t IntBits = IntTy.getSizeInBits();
10471 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10472 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10473 // These instructions only exist converting from i32 to f32. We can handle
10474 // smaller integers by generating an extra extend, but larger ones would
10475 // be lossy. We also can't handle more then 4 lanes, since these intructions
10476 // only support v2i32/v4i32 types.
10480 BitVector UndefElements;
10481 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10482 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10483 if (C == -1 || C == 0 || C > 32)
10487 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10488 SDValue ConvInput = Op.getOperand(0);
10489 if (IntBits < FloatBits)
10490 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10491 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10494 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10495 Intrinsic::arm_neon_vcvtfxu2fp;
10496 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10498 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10499 ConvInput, DAG.getConstant(C, dl, MVT::i32));
10502 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10503 /// operand of a vector shift operation, where all the elements of the
10504 /// build_vector must have the same constant integer value.
10505 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10506 // Ignore bit_converts.
10507 while (Op.getOpcode() == ISD::BITCAST)
10508 Op = Op.getOperand(0);
10509 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10510 APInt SplatBits, SplatUndef;
10511 unsigned SplatBitSize;
10513 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10514 HasAnyUndefs, ElementBits) ||
10515 SplatBitSize > ElementBits)
10517 Cnt = SplatBits.getSExtValue();
10521 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10522 /// operand of a vector shift left operation. That value must be in the range:
10523 /// 0 <= Value < ElementBits for a left shift; or
10524 /// 0 <= Value <= ElementBits for a long left shift.
10525 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10526 assert(VT.isVector() && "vector shift count is not a vector type");
10527 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10528 if (! getVShiftImm(Op, ElementBits, Cnt))
10530 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10533 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10534 /// operand of a vector shift right operation. For a shift opcode, the value
10535 /// is positive, but for an intrinsic the value count must be negative. The
10536 /// absolute value must be in the range:
10537 /// 1 <= |Value| <= ElementBits for a right shift; or
10538 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
10539 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10541 assert(VT.isVector() && "vector shift count is not a vector type");
10542 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10543 if (! getVShiftImm(Op, ElementBits, Cnt))
10546 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10547 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10554 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10555 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10556 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10559 // Don't do anything for most intrinsics.
10562 // Vector shifts: check for immediate versions and lower them.
10563 // Note: This is done during DAG combining instead of DAG legalizing because
10564 // the build_vectors for 64-bit vector element shift counts are generally
10565 // not legal, and it is hard to see their values after they get legalized to
10566 // loads from a constant pool.
10567 case Intrinsic::arm_neon_vshifts:
10568 case Intrinsic::arm_neon_vshiftu:
10569 case Intrinsic::arm_neon_vrshifts:
10570 case Intrinsic::arm_neon_vrshiftu:
10571 case Intrinsic::arm_neon_vrshiftn:
10572 case Intrinsic::arm_neon_vqshifts:
10573 case Intrinsic::arm_neon_vqshiftu:
10574 case Intrinsic::arm_neon_vqshiftsu:
10575 case Intrinsic::arm_neon_vqshiftns:
10576 case Intrinsic::arm_neon_vqshiftnu:
10577 case Intrinsic::arm_neon_vqshiftnsu:
10578 case Intrinsic::arm_neon_vqrshiftns:
10579 case Intrinsic::arm_neon_vqrshiftnu:
10580 case Intrinsic::arm_neon_vqrshiftnsu: {
10581 EVT VT = N->getOperand(1).getValueType();
10583 unsigned VShiftOpc = 0;
10586 case Intrinsic::arm_neon_vshifts:
10587 case Intrinsic::arm_neon_vshiftu:
10588 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10589 VShiftOpc = ARMISD::VSHL;
10592 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10593 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10594 ARMISD::VSHRs : ARMISD::VSHRu);
10599 case Intrinsic::arm_neon_vrshifts:
10600 case Intrinsic::arm_neon_vrshiftu:
10601 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10605 case Intrinsic::arm_neon_vqshifts:
10606 case Intrinsic::arm_neon_vqshiftu:
10607 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10611 case Intrinsic::arm_neon_vqshiftsu:
10612 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10614 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10616 case Intrinsic::arm_neon_vrshiftn:
10617 case Intrinsic::arm_neon_vqshiftns:
10618 case Intrinsic::arm_neon_vqshiftnu:
10619 case Intrinsic::arm_neon_vqshiftnsu:
10620 case Intrinsic::arm_neon_vqrshiftns:
10621 case Intrinsic::arm_neon_vqrshiftnu:
10622 case Intrinsic::arm_neon_vqrshiftnsu:
10623 // Narrowing shifts require an immediate right shift.
10624 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10626 llvm_unreachable("invalid shift count for narrowing vector shift "
10630 llvm_unreachable("unhandled vector shift");
10634 case Intrinsic::arm_neon_vshifts:
10635 case Intrinsic::arm_neon_vshiftu:
10636 // Opcode already set above.
10638 case Intrinsic::arm_neon_vrshifts:
10639 VShiftOpc = ARMISD::VRSHRs; break;
10640 case Intrinsic::arm_neon_vrshiftu:
10641 VShiftOpc = ARMISD::VRSHRu; break;
10642 case Intrinsic::arm_neon_vrshiftn:
10643 VShiftOpc = ARMISD::VRSHRN; break;
10644 case Intrinsic::arm_neon_vqshifts:
10645 VShiftOpc = ARMISD::VQSHLs; break;
10646 case Intrinsic::arm_neon_vqshiftu:
10647 VShiftOpc = ARMISD::VQSHLu; break;
10648 case Intrinsic::arm_neon_vqshiftsu:
10649 VShiftOpc = ARMISD::VQSHLsu; break;
10650 case Intrinsic::arm_neon_vqshiftns:
10651 VShiftOpc = ARMISD::VQSHRNs; break;
10652 case Intrinsic::arm_neon_vqshiftnu:
10653 VShiftOpc = ARMISD::VQSHRNu; break;
10654 case Intrinsic::arm_neon_vqshiftnsu:
10655 VShiftOpc = ARMISD::VQSHRNsu; break;
10656 case Intrinsic::arm_neon_vqrshiftns:
10657 VShiftOpc = ARMISD::VQRSHRNs; break;
10658 case Intrinsic::arm_neon_vqrshiftnu:
10659 VShiftOpc = ARMISD::VQRSHRNu; break;
10660 case Intrinsic::arm_neon_vqrshiftnsu:
10661 VShiftOpc = ARMISD::VQRSHRNsu; break;
10665 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10666 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10669 case Intrinsic::arm_neon_vshiftins: {
10670 EVT VT = N->getOperand(1).getValueType();
10672 unsigned VShiftOpc = 0;
10674 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10675 VShiftOpc = ARMISD::VSLI;
10676 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10677 VShiftOpc = ARMISD::VSRI;
10679 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10683 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10684 N->getOperand(1), N->getOperand(2),
10685 DAG.getConstant(Cnt, dl, MVT::i32));
10688 case Intrinsic::arm_neon_vqrshifts:
10689 case Intrinsic::arm_neon_vqrshiftu:
10690 // No immediate versions of these to check for.
10697 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10698 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10699 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10700 /// vector element shift counts are generally not legal, and it is hard to see
10701 /// their values after they get legalized to loads from a constant pool.
10702 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10703 const ARMSubtarget *ST) {
10704 EVT VT = N->getValueType(0);
10705 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10706 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10707 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10708 SDValue N1 = N->getOperand(1);
10709 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10710 SDValue N0 = N->getOperand(0);
10711 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10712 DAG.MaskedValueIsZero(N0.getOperand(0),
10713 APInt::getHighBitsSet(32, 16)))
10714 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10718 // Nothing to be done for scalar shifts.
10719 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10720 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10723 assert(ST->hasNEON() && "unexpected vector shift");
10726 switch (N->getOpcode()) {
10727 default: llvm_unreachable("unexpected shift opcode");
10730 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10732 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10733 DAG.getConstant(Cnt, dl, MVT::i32));
10739 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10740 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10741 ARMISD::VSHRs : ARMISD::VSHRu);
10743 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10744 DAG.getConstant(Cnt, dl, MVT::i32));
10750 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10751 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10752 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10753 const ARMSubtarget *ST) {
10754 SDValue N0 = N->getOperand(0);
10756 // Check for sign- and zero-extensions of vector extract operations of 8-
10757 // and 16-bit vector elements. NEON supports these directly. They are
10758 // handled during DAG combining because type legalization will promote them
10759 // to 32-bit types and it is messy to recognize the operations after that.
10760 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10761 SDValue Vec = N0.getOperand(0);
10762 SDValue Lane = N0.getOperand(1);
10763 EVT VT = N->getValueType(0);
10764 EVT EltVT = N0.getValueType();
10765 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10767 if (VT == MVT::i32 &&
10768 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10769 TLI.isTypeLegal(Vec.getValueType()) &&
10770 isa<ConstantSDNode>(Lane)) {
10773 switch (N->getOpcode()) {
10774 default: llvm_unreachable("unexpected opcode");
10775 case ISD::SIGN_EXTEND:
10776 Opc = ARMISD::VGETLANEs;
10778 case ISD::ZERO_EXTEND:
10779 case ISD::ANY_EXTEND:
10780 Opc = ARMISD::VGETLANEu;
10783 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10790 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10792 if (Op.getOpcode() == ARMISD::BFI) {
10793 // Conservatively, we can recurse down the first operand
10794 // and just mask out all affected bits.
10795 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10797 // The operand to BFI is already a mask suitable for removing the bits it
10799 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10800 const APInt &Mask = CI->getAPIntValue();
10805 if (Op.getOpcode() == ARMISD::CMOV) {
10806 APInt KZ2(KnownZero.getBitWidth(), 0);
10807 APInt KO2(KnownOne.getBitWidth(), 0);
10808 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10809 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10815 return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10818 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10819 // If we have a CMOV, OR and AND combination such as:
10824 // * CN is a single bit;
10825 // * All bits covered by CM are known zero in y
10827 // Then we can convert this into a sequence of BFI instructions. This will
10828 // always be a win if CM is a single bit, will always be no worse than the
10829 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10830 // three bits (due to the extra IT instruction).
10832 SDValue Op0 = CMOV->getOperand(0);
10833 SDValue Op1 = CMOV->getOperand(1);
10834 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10835 auto CC = CCNode->getAPIntValue().getLimitedValue();
10836 SDValue CmpZ = CMOV->getOperand(4);
10838 // The compare must be against zero.
10839 if (!isNullConstant(CmpZ->getOperand(1)))
10842 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10843 SDValue And = CmpZ->getOperand(0);
10844 if (And->getOpcode() != ISD::AND)
10846 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10847 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10849 SDValue X = And->getOperand(0);
10851 if (CC == ARMCC::EQ) {
10852 // We're performing an "equal to zero" compare. Swap the operands so we
10853 // canonicalize on a "not equal to zero" compare.
10854 std::swap(Op0, Op1);
10856 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10859 if (Op1->getOpcode() != ISD::OR)
10862 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10865 SDValue Y = Op1->getOperand(0);
10870 // Now, is it profitable to continue?
10871 APInt OrCI = OrC->getAPIntValue();
10872 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10873 if (OrCI.countPopulation() > Heuristic)
10876 // Lastly, can we determine that the bits defined by OrCI
10878 APInt KnownZero, KnownOne;
10879 computeKnownBits(DAG, Y, KnownZero, KnownOne);
10880 if ((OrCI & KnownZero) != OrCI)
10883 // OK, we can do the combine.
10886 EVT VT = X.getValueType();
10887 unsigned BitInX = AndC->getAPIntValue().logBase2();
10890 // We must shift X first.
10891 X = DAG.getNode(ISD::SRL, dl, VT, X,
10892 DAG.getConstant(BitInX, dl, VT));
10895 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10896 BitInY < NumActiveBits; ++BitInY) {
10897 if (OrCI[BitInY] == 0)
10899 APInt Mask(VT.getSizeInBits(), 0);
10900 Mask.setBit(BitInY);
10901 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10902 // Confusingly, the operand is an *inverted* mask.
10903 DAG.getConstant(~Mask, dl, VT));
10909 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
10911 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
10912 SDValue Cmp = N->getOperand(4);
10913 if (Cmp.getOpcode() != ARMISD::CMPZ)
10914 // Only looking at NE cases.
10917 EVT VT = N->getValueType(0);
10919 SDValue LHS = Cmp.getOperand(0);
10920 SDValue RHS = Cmp.getOperand(1);
10921 SDValue Chain = N->getOperand(0);
10922 SDValue BB = N->getOperand(1);
10923 SDValue ARMcc = N->getOperand(2);
10924 ARMCC::CondCodes CC =
10925 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10927 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
10928 // -> (brcond Chain BB CC CPSR Cmp)
10929 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
10930 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
10931 LHS->getOperand(0)->hasOneUse()) {
10932 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
10933 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
10934 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
10935 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
10936 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
10937 (LHS01C && LHS01C->getZExtValue() == 1) &&
10938 (LHS1C && LHS1C->getZExtValue() == 1) &&
10939 (RHSC && RHSC->getZExtValue() == 0)) {
10940 return DAG.getNode(
10941 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
10942 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
10949 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10951 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10952 SDValue Cmp = N->getOperand(4);
10953 if (Cmp.getOpcode() != ARMISD::CMPZ)
10954 // Only looking at EQ and NE cases.
10957 EVT VT = N->getValueType(0);
10959 SDValue LHS = Cmp.getOperand(0);
10960 SDValue RHS = Cmp.getOperand(1);
10961 SDValue FalseVal = N->getOperand(0);
10962 SDValue TrueVal = N->getOperand(1);
10963 SDValue ARMcc = N->getOperand(2);
10964 ARMCC::CondCodes CC =
10965 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10967 // BFI is only available on V6T2+.
10968 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10969 SDValue R = PerformCMOVToBFICombine(N, DAG);
10990 /// FIXME: Turn this into a target neutral optimization?
10992 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10993 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10994 N->getOperand(3), Cmp);
10995 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10997 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10998 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10999 N->getOperand(3), NewCmp);
11002 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11003 // -> (cmov F T CC CPSR Cmp)
11004 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11005 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11006 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11007 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11008 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11009 (LHS1C && LHS1C->getZExtValue() == 1) &&
11010 (RHSC && RHSC->getZExtValue() == 0)) {
11011 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11012 LHS->getOperand(2), LHS->getOperand(3),
11013 LHS->getOperand(4));
11017 if (Res.getNode()) {
11018 APInt KnownZero, KnownOne;
11019 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11020 // Capture demanded bits information that would be otherwise lost.
11021 if (KnownZero == 0xfffffffe)
11022 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11023 DAG.getValueType(MVT::i1));
11024 else if (KnownZero == 0xffffff00)
11025 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11026 DAG.getValueType(MVT::i8));
11027 else if (KnownZero == 0xffff0000)
11028 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11029 DAG.getValueType(MVT::i16));
11035 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11036 DAGCombinerInfo &DCI) const {
11037 switch (N->getOpcode()) {
11039 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
11040 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
11041 case ISD::SUB: return PerformSUBCombine(N, DCI);
11042 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
11043 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
11044 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
11045 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
11046 case ARMISD::BFI: return PerformBFICombine(N, DCI);
11047 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11048 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11049 case ISD::STORE: return PerformSTORECombine(N, DCI);
11050 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11051 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11052 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11053 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11054 case ISD::FP_TO_SINT:
11055 case ISD::FP_TO_UINT:
11056 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11058 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11059 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11062 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
11063 case ISD::SIGN_EXTEND:
11064 case ISD::ZERO_EXTEND:
11065 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11066 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11067 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11068 case ISD::LOAD: return PerformLOADCombine(N, DCI);
11069 case ARMISD::VLD2DUP:
11070 case ARMISD::VLD3DUP:
11071 case ARMISD::VLD4DUP:
11072 return PerformVLDCombine(N, DCI);
11073 case ARMISD::BUILD_VECTOR:
11074 return PerformARMBUILD_VECTORCombine(N, DCI);
11075 case ISD::INTRINSIC_VOID:
11076 case ISD::INTRINSIC_W_CHAIN:
11077 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11078 case Intrinsic::arm_neon_vld1:
11079 case Intrinsic::arm_neon_vld2:
11080 case Intrinsic::arm_neon_vld3:
11081 case Intrinsic::arm_neon_vld4:
11082 case Intrinsic::arm_neon_vld2lane:
11083 case Intrinsic::arm_neon_vld3lane:
11084 case Intrinsic::arm_neon_vld4lane:
11085 case Intrinsic::arm_neon_vst1:
11086 case Intrinsic::arm_neon_vst2:
11087 case Intrinsic::arm_neon_vst3:
11088 case Intrinsic::arm_neon_vst4:
11089 case Intrinsic::arm_neon_vst2lane:
11090 case Intrinsic::arm_neon_vst3lane:
11091 case Intrinsic::arm_neon_vst4lane:
11092 return PerformVLDCombine(N, DCI);
11100 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11102 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11105 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11108 bool *Fast) const {
11109 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11110 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11112 switch (VT.getSimpleVT().SimpleTy) {
11118 // Unaligned access can use (for example) LRDB, LRDH, LDR
11119 if (AllowsUnaligned) {
11121 *Fast = Subtarget->hasV7Ops();
11128 // For any little-endian targets with neon, we can support unaligned ld/st
11129 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
11130 // A big-endian target may also explicitly support unaligned accesses
11131 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
11141 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
11142 unsigned AlignCheck) {
11143 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
11144 (DstAlign == 0 || DstAlign % AlignCheck == 0));
11147 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
11148 unsigned DstAlign, unsigned SrcAlign,
11149 bool IsMemset, bool ZeroMemset,
11151 MachineFunction &MF) const {
11152 const Function *F = MF.getFunction();
11154 // See if we can use NEON instructions for this...
11155 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
11156 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11159 (memOpAlign(SrcAlign, DstAlign, 16) ||
11160 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
11162 } else if (Size >= 8 &&
11163 (memOpAlign(SrcAlign, DstAlign, 8) ||
11164 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
11170 // Lowering to i32/i16 if the size permits.
11173 else if (Size >= 2)
11176 // Let the target-independent logic figure it out.
11180 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11181 if (Val.getOpcode() != ISD::LOAD)
11184 EVT VT1 = Val.getValueType();
11185 if (!VT1.isSimple() || !VT1.isInteger() ||
11186 !VT2.isSimple() || !VT2.isInteger())
11189 switch (VT1.getSimpleVT().SimpleTy) {
11194 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
11201 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
11202 EVT VT = ExtVal.getValueType();
11204 if (!isTypeLegal(VT))
11207 // Don't create a loadext if we can fold the extension into a wide/long
11209 // If there's more than one user instruction, the loadext is desirable no
11210 // matter what. There can be two uses by the same instruction.
11211 if (ExtVal->use_empty() ||
11212 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
11215 SDNode *U = *ExtVal->use_begin();
11216 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
11217 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
11223 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
11224 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11227 if (!isTypeLegal(EVT::getEVT(Ty1)))
11230 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
11232 // Assuming the caller doesn't have a zeroext or signext return parameter,
11233 // truncation all the way down to i1 is valid.
11238 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
11242 unsigned Scale = 1;
11243 switch (VT.getSimpleVT().SimpleTy) {
11244 default: return false;
11259 if ((V & (Scale - 1)) != 0)
11262 return V == (V & ((1LL << 5) - 1));
11265 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
11266 const ARMSubtarget *Subtarget) {
11267 bool isNeg = false;
11273 switch (VT.getSimpleVT().SimpleTy) {
11274 default: return false;
11279 // + imm12 or - imm8
11281 return V == (V & ((1LL << 8) - 1));
11282 return V == (V & ((1LL << 12) - 1));
11285 // Same as ARM mode. FIXME: NEON?
11286 if (!Subtarget->hasVFP2())
11291 return V == (V & ((1LL << 8) - 1));
11295 /// isLegalAddressImmediate - Return true if the integer value can be used
11296 /// as the offset of the target addressing mode for load / store of the
11298 static bool isLegalAddressImmediate(int64_t V, EVT VT,
11299 const ARMSubtarget *Subtarget) {
11303 if (!VT.isSimple())
11306 if (Subtarget->isThumb1Only())
11307 return isLegalT1AddressImmediate(V, VT);
11308 else if (Subtarget->isThumb2())
11309 return isLegalT2AddressImmediate(V, VT, Subtarget);
11314 switch (VT.getSimpleVT().SimpleTy) {
11315 default: return false;
11320 return V == (V & ((1LL << 12) - 1));
11323 return V == (V & ((1LL << 8) - 1));
11326 if (!Subtarget->hasVFP2()) // FIXME: NEON?
11331 return V == (V & ((1LL << 8) - 1));
11335 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
11337 int Scale = AM.Scale;
11341 switch (VT.getSimpleVT().SimpleTy) {
11342 default: return false;
11350 Scale = Scale & ~1;
11351 return Scale == 2 || Scale == 4 || Scale == 8;
11354 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11358 // Note, we allow "void" uses (basically, uses that aren't loads or
11359 // stores), because arm allows folding a scale into many arithmetic
11360 // operations. This should be made more precise and revisited later.
11362 // Allow r << imm, but the imm has to be a multiple of two.
11363 if (Scale & 1) return false;
11364 return isPowerOf2_32(Scale);
11368 /// isLegalAddressingMode - Return true if the addressing mode represented
11369 /// by AM is legal for this target, for a load/store of the specified type.
11370 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11371 const AddrMode &AM, Type *Ty,
11372 unsigned AS) const {
11373 EVT VT = getValueType(DL, Ty, true);
11374 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11377 // Can never fold addr of global into load/store.
11381 switch (AM.Scale) {
11382 case 0: // no scale reg, must be "r+i" or "r", or "i".
11385 if (Subtarget->isThumb1Only())
11389 // ARM doesn't support any R+R*scale+imm addr modes.
11393 if (!VT.isSimple())
11396 if (Subtarget->isThumb2())
11397 return isLegalT2ScaledAddressingMode(AM, VT);
11399 int Scale = AM.Scale;
11400 switch (VT.getSimpleVT().SimpleTy) {
11401 default: return false;
11405 if (Scale < 0) Scale = -Scale;
11409 return isPowerOf2_32(Scale & ~1);
11413 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11418 // Note, we allow "void" uses (basically, uses that aren't loads or
11419 // stores), because arm allows folding a scale into many arithmetic
11420 // operations. This should be made more precise and revisited later.
11422 // Allow r << imm, but the imm has to be a multiple of two.
11423 if (Scale & 1) return false;
11424 return isPowerOf2_32(Scale);
11430 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11431 /// icmp immediate, that is the target has icmp instructions which can compare
11432 /// a register against the immediate without having to materialize the
11433 /// immediate into a register.
11434 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11435 // Thumb2 and ARM modes can use cmn for negative immediates.
11436 if (!Subtarget->isThumb())
11437 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11438 if (Subtarget->isThumb2())
11439 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11440 // Thumb1 doesn't have cmn, and only 8-bit immediates.
11441 return Imm >= 0 && Imm <= 255;
11444 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11445 /// *or sub* immediate, that is the target has add or sub instructions which can
11446 /// add a register with the immediate without having to materialize the
11447 /// immediate into a register.
11448 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11449 // Same encoding for add/sub, just flip the sign.
11450 int64_t AbsImm = std::abs(Imm);
11451 if (!Subtarget->isThumb())
11452 return ARM_AM::getSOImmVal(AbsImm) != -1;
11453 if (Subtarget->isThumb2())
11454 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11455 // Thumb1 only has 8-bit unsigned immediate.
11456 return AbsImm >= 0 && AbsImm <= 255;
11459 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11460 bool isSEXTLoad, SDValue &Base,
11461 SDValue &Offset, bool &isInc,
11462 SelectionDAG &DAG) {
11463 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11466 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11467 // AddressingMode 3
11468 Base = Ptr->getOperand(0);
11469 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11470 int RHSC = (int)RHS->getZExtValue();
11471 if (RHSC < 0 && RHSC > -256) {
11472 assert(Ptr->getOpcode() == ISD::ADD);
11474 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11478 isInc = (Ptr->getOpcode() == ISD::ADD);
11479 Offset = Ptr->getOperand(1);
11481 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11482 // AddressingMode 2
11483 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11484 int RHSC = (int)RHS->getZExtValue();
11485 if (RHSC < 0 && RHSC > -0x1000) {
11486 assert(Ptr->getOpcode() == ISD::ADD);
11488 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11489 Base = Ptr->getOperand(0);
11494 if (Ptr->getOpcode() == ISD::ADD) {
11496 ARM_AM::ShiftOpc ShOpcVal=
11497 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11498 if (ShOpcVal != ARM_AM::no_shift) {
11499 Base = Ptr->getOperand(1);
11500 Offset = Ptr->getOperand(0);
11502 Base = Ptr->getOperand(0);
11503 Offset = Ptr->getOperand(1);
11508 isInc = (Ptr->getOpcode() == ISD::ADD);
11509 Base = Ptr->getOperand(0);
11510 Offset = Ptr->getOperand(1);
11514 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11518 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11519 bool isSEXTLoad, SDValue &Base,
11520 SDValue &Offset, bool &isInc,
11521 SelectionDAG &DAG) {
11522 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11525 Base = Ptr->getOperand(0);
11526 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11527 int RHSC = (int)RHS->getZExtValue();
11528 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11529 assert(Ptr->getOpcode() == ISD::ADD);
11531 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11533 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11534 isInc = Ptr->getOpcode() == ISD::ADD;
11535 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11543 /// getPreIndexedAddressParts - returns true by value, base pointer and
11544 /// offset pointer and addressing mode by reference if the node's address
11545 /// can be legally represented as pre-indexed load / store address.
11547 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11549 ISD::MemIndexedMode &AM,
11550 SelectionDAG &DAG) const {
11551 if (Subtarget->isThumb1Only())
11556 bool isSEXTLoad = false;
11557 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11558 Ptr = LD->getBasePtr();
11559 VT = LD->getMemoryVT();
11560 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11561 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11562 Ptr = ST->getBasePtr();
11563 VT = ST->getMemoryVT();
11568 bool isLegal = false;
11569 if (Subtarget->isThumb2())
11570 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11571 Offset, isInc, DAG);
11573 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11574 Offset, isInc, DAG);
11578 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11582 /// getPostIndexedAddressParts - returns true by value, base pointer and
11583 /// offset pointer and addressing mode by reference if this node can be
11584 /// combined with a load / store to form a post-indexed load / store.
11585 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11588 ISD::MemIndexedMode &AM,
11589 SelectionDAG &DAG) const {
11592 bool isSEXTLoad = false, isNonExt;
11593 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11594 VT = LD->getMemoryVT();
11595 Ptr = LD->getBasePtr();
11596 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11597 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
11598 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11599 VT = ST->getMemoryVT();
11600 Ptr = ST->getBasePtr();
11601 isNonExt = !ST->isTruncatingStore();
11605 if (Subtarget->isThumb1Only()) {
11606 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
11607 // must be non-extending/truncating, i32, with an offset of 4.
11608 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
11609 if (Op->getOpcode() != ISD::ADD || !isNonExt)
11611 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11612 if (!RHS || RHS->getZExtValue() != 4)
11615 Offset = Op->getOperand(1);
11616 Base = Op->getOperand(0);
11617 AM = ISD::POST_INC;
11622 bool isLegal = false;
11623 if (Subtarget->isThumb2())
11624 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11627 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11633 // Swap base ptr and offset to catch more post-index load / store when
11634 // it's legal. In Thumb2 mode, offset must be an immediate.
11635 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11636 !Subtarget->isThumb2())
11637 std::swap(Base, Offset);
11639 // Post-indexed load / store update the base pointer.
11644 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11648 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11651 const SelectionDAG &DAG,
11652 unsigned Depth) const {
11653 unsigned BitWidth = KnownOne.getBitWidth();
11654 KnownZero = KnownOne = APInt(BitWidth, 0);
11655 switch (Op.getOpcode()) {
11661 // These nodes' second result is a boolean
11662 if (Op.getResNo() == 0)
11664 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11666 case ARMISD::CMOV: {
11667 // Bits are known zero/one if known on the LHS and RHS.
11668 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11669 if (KnownZero == 0 && KnownOne == 0) return;
11671 APInt KnownZeroRHS, KnownOneRHS;
11672 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11673 KnownZero &= KnownZeroRHS;
11674 KnownOne &= KnownOneRHS;
11677 case ISD::INTRINSIC_W_CHAIN: {
11678 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11679 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11682 case Intrinsic::arm_ldaex:
11683 case Intrinsic::arm_ldrex: {
11684 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11685 unsigned MemBits = VT.getScalarType().getSizeInBits();
11686 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11694 //===----------------------------------------------------------------------===//
11695 // ARM Inline Assembly Support
11696 //===----------------------------------------------------------------------===//
11698 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11699 // Looking for "rev" which is V6+.
11700 if (!Subtarget->hasV6Ops())
11703 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11704 std::string AsmStr = IA->getAsmString();
11705 SmallVector<StringRef, 4> AsmPieces;
11706 SplitString(AsmStr, AsmPieces, ";\n");
11708 switch (AsmPieces.size()) {
11709 default: return false;
11711 AsmStr = AsmPieces[0];
11713 SplitString(AsmStr, AsmPieces, " \t,");
11716 if (AsmPieces.size() == 3 &&
11717 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11718 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11719 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11720 if (Ty && Ty->getBitWidth() == 32)
11721 return IntrinsicLowering::LowerToByteSwap(CI);
11729 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
11730 // At this point, we have to lower this constraint to something else, so we
11731 // lower it to an "r" or "w". However, by doing this we will force the result
11732 // to be in register, while the X constraint is much more permissive.
11734 // Although we are correct (we are free to emit anything, without
11735 // constraints), we might break use cases that would expect us to be more
11736 // efficient and emit something else.
11737 if (!Subtarget->hasVFP2())
11739 if (ConstraintVT.isFloatingPoint())
11741 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
11742 (ConstraintVT.getSizeInBits() == 64 ||
11743 ConstraintVT.getSizeInBits() == 128))
11749 /// getConstraintType - Given a constraint letter, return the type of
11750 /// constraint it is for this target.
11751 ARMTargetLowering::ConstraintType
11752 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11753 if (Constraint.size() == 1) {
11754 switch (Constraint[0]) {
11756 case 'l': return C_RegisterClass;
11757 case 'w': return C_RegisterClass;
11758 case 'h': return C_RegisterClass;
11759 case 'x': return C_RegisterClass;
11760 case 't': return C_RegisterClass;
11761 case 'j': return C_Other; // Constant for movw.
11762 // An address with a single base register. Due to the way we
11763 // currently handle addresses it is the same as an 'r' memory constraint.
11764 case 'Q': return C_Memory;
11766 } else if (Constraint.size() == 2) {
11767 switch (Constraint[0]) {
11769 // All 'U+' constraints are addresses.
11770 case 'U': return C_Memory;
11773 return TargetLowering::getConstraintType(Constraint);
11776 /// Examine constraint type and operand type and determine a weight value.
11777 /// This object must already have been set up with the operand type
11778 /// and the current alternative constraint selected.
11779 TargetLowering::ConstraintWeight
11780 ARMTargetLowering::getSingleConstraintMatchWeight(
11781 AsmOperandInfo &info, const char *constraint) const {
11782 ConstraintWeight weight = CW_Invalid;
11783 Value *CallOperandVal = info.CallOperandVal;
11784 // If we don't have a value, we can't do a match,
11785 // but allow it at the lowest weight.
11786 if (!CallOperandVal)
11788 Type *type = CallOperandVal->getType();
11789 // Look at the constraint type.
11790 switch (*constraint) {
11792 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11795 if (type->isIntegerTy()) {
11796 if (Subtarget->isThumb())
11797 weight = CW_SpecificReg;
11799 weight = CW_Register;
11803 if (type->isFloatingPointTy())
11804 weight = CW_Register;
11810 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11811 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11812 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11813 if (Constraint.size() == 1) {
11814 // GCC ARM Constraint Letters
11815 switch (Constraint[0]) {
11816 case 'l': // Low regs or general regs.
11817 if (Subtarget->isThumb())
11818 return RCPair(0U, &ARM::tGPRRegClass);
11819 return RCPair(0U, &ARM::GPRRegClass);
11820 case 'h': // High regs or no regs.
11821 if (Subtarget->isThumb())
11822 return RCPair(0U, &ARM::hGPRRegClass);
11825 if (Subtarget->isThumb1Only())
11826 return RCPair(0U, &ARM::tGPRRegClass);
11827 return RCPair(0U, &ARM::GPRRegClass);
11829 if (VT == MVT::Other)
11831 if (VT == MVT::f32)
11832 return RCPair(0U, &ARM::SPRRegClass);
11833 if (VT.getSizeInBits() == 64)
11834 return RCPair(0U, &ARM::DPRRegClass);
11835 if (VT.getSizeInBits() == 128)
11836 return RCPair(0U, &ARM::QPRRegClass);
11839 if (VT == MVT::Other)
11841 if (VT == MVT::f32)
11842 return RCPair(0U, &ARM::SPR_8RegClass);
11843 if (VT.getSizeInBits() == 64)
11844 return RCPair(0U, &ARM::DPR_8RegClass);
11845 if (VT.getSizeInBits() == 128)
11846 return RCPair(0U, &ARM::QPR_8RegClass);
11849 if (VT == MVT::f32)
11850 return RCPair(0U, &ARM::SPRRegClass);
11854 if (StringRef("{cc}").equals_lower(Constraint))
11855 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11857 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11860 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11861 /// vector. If it is invalid, don't add anything to Ops.
11862 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11863 std::string &Constraint,
11864 std::vector<SDValue>&Ops,
11865 SelectionDAG &DAG) const {
11868 // Currently only support length 1 constraints.
11869 if (Constraint.length() != 1) return;
11871 char ConstraintLetter = Constraint[0];
11872 switch (ConstraintLetter) {
11875 case 'I': case 'J': case 'K': case 'L':
11876 case 'M': case 'N': case 'O':
11877 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11881 int64_t CVal64 = C->getSExtValue();
11882 int CVal = (int) CVal64;
11883 // None of these constraints allow values larger than 32 bits. Check
11884 // that the value fits in an int.
11885 if (CVal != CVal64)
11888 switch (ConstraintLetter) {
11890 // Constant suitable for movw, must be between 0 and
11892 if (Subtarget->hasV6T2Ops())
11893 if (CVal >= 0 && CVal <= 65535)
11897 if (Subtarget->isThumb1Only()) {
11898 // This must be a constant between 0 and 255, for ADD
11900 if (CVal >= 0 && CVal <= 255)
11902 } else if (Subtarget->isThumb2()) {
11903 // A constant that can be used as an immediate value in a
11904 // data-processing instruction.
11905 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11908 // A constant that can be used as an immediate value in a
11909 // data-processing instruction.
11910 if (ARM_AM::getSOImmVal(CVal) != -1)
11916 if (Subtarget->isThumb1Only()) {
11917 // This must be a constant between -255 and -1, for negated ADD
11918 // immediates. This can be used in GCC with an "n" modifier that
11919 // prints the negated value, for use with SUB instructions. It is
11920 // not useful otherwise but is implemented for compatibility.
11921 if (CVal >= -255 && CVal <= -1)
11924 // This must be a constant between -4095 and 4095. It is not clear
11925 // what this constraint is intended for. Implemented for
11926 // compatibility with GCC.
11927 if (CVal >= -4095 && CVal <= 4095)
11933 if (Subtarget->isThumb1Only()) {
11934 // A 32-bit value where only one byte has a nonzero value. Exclude
11935 // zero to match GCC. This constraint is used by GCC internally for
11936 // constants that can be loaded with a move/shift combination.
11937 // It is not useful otherwise but is implemented for compatibility.
11938 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11940 } else if (Subtarget->isThumb2()) {
11941 // A constant whose bitwise inverse can be used as an immediate
11942 // value in a data-processing instruction. This can be used in GCC
11943 // with a "B" modifier that prints the inverted value, for use with
11944 // BIC and MVN instructions. It is not useful otherwise but is
11945 // implemented for compatibility.
11946 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11949 // A constant whose bitwise inverse can be used as an immediate
11950 // value in a data-processing instruction. This can be used in GCC
11951 // with a "B" modifier that prints the inverted value, for use with
11952 // BIC and MVN instructions. It is not useful otherwise but is
11953 // implemented for compatibility.
11954 if (ARM_AM::getSOImmVal(~CVal) != -1)
11960 if (Subtarget->isThumb1Only()) {
11961 // This must be a constant between -7 and 7,
11962 // for 3-operand ADD/SUB immediate instructions.
11963 if (CVal >= -7 && CVal < 7)
11965 } else if (Subtarget->isThumb2()) {
11966 // A constant whose negation can be used as an immediate value in a
11967 // data-processing instruction. This can be used in GCC with an "n"
11968 // modifier that prints the negated value, for use with SUB
11969 // instructions. It is not useful otherwise but is implemented for
11971 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11974 // A constant whose negation can be used as an immediate value in a
11975 // data-processing instruction. This can be used in GCC with an "n"
11976 // modifier that prints the negated value, for use with SUB
11977 // instructions. It is not useful otherwise but is implemented for
11979 if (ARM_AM::getSOImmVal(-CVal) != -1)
11985 if (Subtarget->isThumb1Only()) {
11986 // This must be a multiple of 4 between 0 and 1020, for
11987 // ADD sp + immediate.
11988 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11991 // A power of two or a constant between 0 and 32. This is used in
11992 // GCC for the shift amount on shifted register operands, but it is
11993 // useful in general for any shift amounts.
11994 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12000 if (Subtarget->isThumb()) { // FIXME thumb2
12001 // This must be a constant between 0 and 31, for shift amounts.
12002 if (CVal >= 0 && CVal <= 31)
12008 if (Subtarget->isThumb()) { // FIXME thumb2
12009 // This must be a multiple of 4 between -508 and 508, for
12010 // ADD/SUB sp = sp + immediate.
12011 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12016 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12020 if (Result.getNode()) {
12021 Ops.push_back(Result);
12024 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12027 static RTLIB::Libcall getDivRemLibcall(
12028 const SDNode *N, MVT::SimpleValueType SVT) {
12029 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12030 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
12031 "Unhandled Opcode in getDivRemLibcall");
12032 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12033 N->getOpcode() == ISD::SREM;
12036 default: llvm_unreachable("Unexpected request for libcall!");
12037 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
12038 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12039 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12040 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12045 static TargetLowering::ArgListTy getDivRemArgList(
12046 const SDNode *N, LLVMContext *Context) {
12047 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12048 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
12049 "Unhandled Opcode in getDivRemArgList");
12050 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12051 N->getOpcode() == ISD::SREM;
12052 TargetLowering::ArgListTy Args;
12053 TargetLowering::ArgListEntry Entry;
12054 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12055 EVT ArgVT = N->getOperand(i).getValueType();
12056 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12057 Entry.Node = N->getOperand(i);
12059 Entry.isSExt = isSigned;
12060 Entry.isZExt = !isSigned;
12061 Args.push_back(Entry);
12066 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12067 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12068 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) &&
12069 "Register-based DivRem lowering only");
12070 unsigned Opcode = Op->getOpcode();
12071 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12072 "Invalid opcode for Div/Rem lowering");
12073 bool isSigned = (Opcode == ISD::SDIVREM);
12074 EVT VT = Op->getValueType(0);
12075 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12077 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12078 VT.getSimpleVT().SimpleTy);
12079 SDValue InChain = DAG.getEntryNode();
12081 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12084 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12085 getPointerTy(DAG.getDataLayout()));
12087 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12090 TargetLowering::CallLoweringInfo CLI(DAG);
12091 CLI.setDebugLoc(dl).setChain(InChain)
12092 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
12093 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
12095 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
12096 return CallInfo.first;
12099 // Lowers REM using divmod helpers
12100 // see RTABI section 4.2/4.3
12101 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
12102 // Build return types (div and rem)
12103 std::vector<Type*> RetTyParams;
12104 Type *RetTyElement;
12106 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
12107 default: llvm_unreachable("Unexpected request for libcall!");
12108 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
12109 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
12110 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
12111 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
12114 RetTyParams.push_back(RetTyElement);
12115 RetTyParams.push_back(RetTyElement);
12116 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
12117 Type *RetTy = StructType::get(*DAG.getContext(), ret);
12119 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
12121 SDValue InChain = DAG.getEntryNode();
12122 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
12123 bool isSigned = N->getOpcode() == ISD::SREM;
12124 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12125 getPointerTy(DAG.getDataLayout()));
12128 CallLoweringInfo CLI(DAG);
12129 CLI.setChain(InChain)
12130 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
12131 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
12132 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12134 // Return second (rem) result operand (first contains div)
12135 SDNode *ResNode = CallResult.first.getNode();
12136 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
12137 return ResNode->getOperand(1);
12141 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
12142 assert(Subtarget->isTargetWindows() && "unsupported target platform");
12146 SDValue Chain = Op.getOperand(0);
12147 SDValue Size = Op.getOperand(1);
12149 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
12150 DAG.getConstant(2, DL, MVT::i32));
12153 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
12154 Flag = Chain.getValue(1);
12156 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12157 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
12159 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
12160 Chain = NewSP.getValue(1);
12162 SDValue Ops[2] = { NewSP, Chain };
12163 return DAG.getMergeValues(Ops, DL);
12166 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12167 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
12168 "Unexpected type for custom-lowering FP_EXTEND");
12171 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
12173 SDValue SrcVal = Op.getOperand(0);
12174 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12178 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12179 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
12180 Subtarget->isFPOnlySP() &&
12181 "Unexpected type for custom-lowering FP_ROUND");
12184 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
12186 SDValue SrcVal = Op.getOperand(0);
12187 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12192 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12193 // The ARM target isn't yet aware of offsets.
12197 bool ARM::isBitFieldInvertedMask(unsigned v) {
12198 if (v == 0xffffffff)
12201 // there can be 1's on either or both "outsides", all the "inside"
12202 // bits must be 0's
12203 return isShiftedMask_32(~v);
12206 /// isFPImmLegal - Returns true if the target can instruction select the
12207 /// specified FP immediate natively. If false, the legalizer will
12208 /// materialize the FP immediate as a load from a constant pool.
12209 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12210 if (!Subtarget->hasVFP3())
12212 if (VT == MVT::f32)
12213 return ARM_AM::getFP32Imm(Imm) != -1;
12214 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
12215 return ARM_AM::getFP64Imm(Imm) != -1;
12219 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
12220 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
12221 /// specified in the intrinsic calls.
12222 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12224 unsigned Intrinsic) const {
12225 switch (Intrinsic) {
12226 case Intrinsic::arm_neon_vld1:
12227 case Intrinsic::arm_neon_vld2:
12228 case Intrinsic::arm_neon_vld3:
12229 case Intrinsic::arm_neon_vld4:
12230 case Intrinsic::arm_neon_vld2lane:
12231 case Intrinsic::arm_neon_vld3lane:
12232 case Intrinsic::arm_neon_vld4lane: {
12233 Info.opc = ISD::INTRINSIC_W_CHAIN;
12234 // Conservatively set memVT to the entire set of vectors loaded.
12235 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12236 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
12237 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12238 Info.ptrVal = I.getArgOperand(0);
12240 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12241 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12242 Info.vol = false; // volatile loads with NEON intrinsics not supported
12243 Info.readMem = true;
12244 Info.writeMem = false;
12247 case Intrinsic::arm_neon_vst1:
12248 case Intrinsic::arm_neon_vst2:
12249 case Intrinsic::arm_neon_vst3:
12250 case Intrinsic::arm_neon_vst4:
12251 case Intrinsic::arm_neon_vst2lane:
12252 case Intrinsic::arm_neon_vst3lane:
12253 case Intrinsic::arm_neon_vst4lane: {
12254 Info.opc = ISD::INTRINSIC_VOID;
12255 // Conservatively set memVT to the entire set of vectors stored.
12256 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12257 unsigned NumElts = 0;
12258 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
12259 Type *ArgTy = I.getArgOperand(ArgI)->getType();
12260 if (!ArgTy->isVectorTy())
12262 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
12264 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12265 Info.ptrVal = I.getArgOperand(0);
12267 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12268 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12269 Info.vol = false; // volatile stores with NEON intrinsics not supported
12270 Info.readMem = false;
12271 Info.writeMem = true;
12274 case Intrinsic::arm_ldaex:
12275 case Intrinsic::arm_ldrex: {
12276 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12277 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
12278 Info.opc = ISD::INTRINSIC_W_CHAIN;
12279 Info.memVT = MVT::getVT(PtrTy->getElementType());
12280 Info.ptrVal = I.getArgOperand(0);
12282 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12284 Info.readMem = true;
12285 Info.writeMem = false;
12288 case Intrinsic::arm_stlex:
12289 case Intrinsic::arm_strex: {
12290 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12291 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
12292 Info.opc = ISD::INTRINSIC_W_CHAIN;
12293 Info.memVT = MVT::getVT(PtrTy->getElementType());
12294 Info.ptrVal = I.getArgOperand(1);
12296 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12298 Info.readMem = false;
12299 Info.writeMem = true;
12302 case Intrinsic::arm_stlexd:
12303 case Intrinsic::arm_strexd: {
12304 Info.opc = ISD::INTRINSIC_W_CHAIN;
12305 Info.memVT = MVT::i64;
12306 Info.ptrVal = I.getArgOperand(2);
12310 Info.readMem = false;
12311 Info.writeMem = true;
12314 case Intrinsic::arm_ldaexd:
12315 case Intrinsic::arm_ldrexd: {
12316 Info.opc = ISD::INTRINSIC_W_CHAIN;
12317 Info.memVT = MVT::i64;
12318 Info.ptrVal = I.getArgOperand(0);
12322 Info.readMem = true;
12323 Info.writeMem = false;
12333 /// \brief Returns true if it is beneficial to convert a load of a constant
12334 /// to just the constant itself.
12335 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12337 assert(Ty->isIntegerTy());
12339 unsigned Bits = Ty->getPrimitiveSizeInBits();
12340 if (Bits == 0 || Bits > 32)
12345 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
12346 ARM_MB::MemBOpt Domain) const {
12347 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12349 // First, if the target has no DMB, see what fallback we can use.
12350 if (!Subtarget->hasDataBarrier()) {
12351 // Some ARMv6 cpus can support data barriers with an mcr instruction.
12352 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
12354 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
12355 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
12356 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
12357 Builder.getInt32(0), Builder.getInt32(7),
12358 Builder.getInt32(10), Builder.getInt32(5)};
12359 return Builder.CreateCall(MCR, args);
12361 // Instead of using barriers, atomic accesses on these subtargets use
12363 llvm_unreachable("makeDMB on a target so old that it has no barriers");
12366 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
12367 // Only a full system barrier exists in the M-class architectures.
12368 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
12369 Constant *CDomain = Builder.getInt32(Domain);
12370 return Builder.CreateCall(DMB, CDomain);
12374 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
12375 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
12376 AtomicOrdering Ord, bool IsStore,
12377 bool IsLoad) const {
12379 case AtomicOrdering::NotAtomic:
12380 case AtomicOrdering::Unordered:
12381 llvm_unreachable("Invalid fence: unordered/non-atomic");
12382 case AtomicOrdering::Monotonic:
12383 case AtomicOrdering::Acquire:
12384 return nullptr; // Nothing to do
12385 case AtomicOrdering::SequentiallyConsistent:
12387 return nullptr; // Nothing to do
12389 case AtomicOrdering::Release:
12390 case AtomicOrdering::AcquireRelease:
12391 if (Subtarget->preferISHSTBarriers())
12392 return makeDMB(Builder, ARM_MB::ISHST);
12393 // FIXME: add a comment with a link to documentation justifying this.
12395 return makeDMB(Builder, ARM_MB::ISH);
12397 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12400 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12401 AtomicOrdering Ord, bool IsStore,
12402 bool IsLoad) const {
12404 case AtomicOrdering::NotAtomic:
12405 case AtomicOrdering::Unordered:
12406 llvm_unreachable("Invalid fence: unordered/not-atomic");
12407 case AtomicOrdering::Monotonic:
12408 case AtomicOrdering::Release:
12409 return nullptr; // Nothing to do
12410 case AtomicOrdering::Acquire:
12411 case AtomicOrdering::AcquireRelease:
12412 case AtomicOrdering::SequentiallyConsistent:
12413 return makeDMB(Builder, ARM_MB::ISH);
12415 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12418 // Loads and stores less than 64-bits are already atomic; ones above that
12419 // are doomed anyway, so defer to the default libcall and blame the OS when
12420 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12421 // anything for those.
12422 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12423 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12424 return (Size == 64) && !Subtarget->isMClass();
12427 // Loads and stores less than 64-bits are already atomic; ones above that
12428 // are doomed anyway, so defer to the default libcall and blame the OS when
12429 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12430 // anything for those.
12431 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12432 // guarantee, see DDI0406C ARM architecture reference manual,
12433 // sections A8.8.72-74 LDRD)
12434 TargetLowering::AtomicExpansionKind
12435 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12436 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12437 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12438 : AtomicExpansionKind::None;
12441 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12442 // and up to 64 bits on the non-M profiles
12443 TargetLowering::AtomicExpansionKind
12444 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12445 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12446 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12447 ? AtomicExpansionKind::LLSC
12448 : AtomicExpansionKind::None;
12451 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12452 AtomicCmpXchgInst *AI) const {
12453 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12454 // implement cmpxchg without spilling. If the address being exchanged is also
12455 // on the stack and close enough to the spill slot, this can lead to a
12456 // situation where the monitor always gets cleared and the atomic operation
12457 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12458 return getTargetMachine().getOptLevel() != 0;
12461 bool ARMTargetLowering::shouldInsertFencesForAtomic(
12462 const Instruction *I) const {
12463 return InsertFencesForAtomic;
12466 // This has so far only been implemented for MachO.
12467 bool ARMTargetLowering::useLoadStackGuardNode() const {
12468 return Subtarget->isTargetMachO();
12471 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12472 unsigned &Cost) const {
12473 // If we do not have NEON, vector types are not natively supported.
12474 if (!Subtarget->hasNEON())
12477 // Floating point values and vector values map to the same register file.
12478 // Therefore, although we could do a store extract of a vector type, this is
12479 // better to leave at float as we have more freedom in the addressing mode for
12481 if (VectorTy->isFPOrFPVectorTy())
12484 // If the index is unknown at compile time, this is very expensive to lower
12485 // and it is not possible to combine the store with the extract.
12486 if (!isa<ConstantInt>(Idx))
12489 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12490 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12491 // We can do a store + vector extract on any vector that fits perfectly in a D
12493 if (BitWidth == 64 || BitWidth == 128) {
12500 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12501 return Subtarget->hasV6T2Ops();
12504 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12505 return Subtarget->hasV6T2Ops();
12508 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12509 AtomicOrdering Ord) const {
12510 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12511 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12512 bool IsAcquire = isAcquireOrStronger(Ord);
12514 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12515 // intrinsic must return {i32, i32} and we have to recombine them into a
12516 // single i64 here.
12517 if (ValTy->getPrimitiveSizeInBits() == 64) {
12518 Intrinsic::ID Int =
12519 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12520 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12522 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12523 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12525 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12526 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12527 if (!Subtarget->isLittle())
12528 std::swap (Lo, Hi);
12529 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12530 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12531 return Builder.CreateOr(
12532 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12535 Type *Tys[] = { Addr->getType() };
12536 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12537 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12539 return Builder.CreateTruncOrBitCast(
12540 Builder.CreateCall(Ldrex, Addr),
12541 cast<PointerType>(Addr->getType())->getElementType());
12544 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12545 IRBuilder<> &Builder) const {
12546 if (!Subtarget->hasV7Ops())
12548 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12549 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12552 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12554 AtomicOrdering Ord) const {
12555 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12556 bool IsRelease = isReleaseOrStronger(Ord);
12558 // Since the intrinsics must have legal type, the i64 intrinsics take two
12559 // parameters: "i32, i32". We must marshal Val into the appropriate form
12560 // before the call.
12561 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12562 Intrinsic::ID Int =
12563 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12564 Function *Strex = Intrinsic::getDeclaration(M, Int);
12565 Type *Int32Ty = Type::getInt32Ty(M->getContext());
12567 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12568 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12569 if (!Subtarget->isLittle())
12570 std::swap (Lo, Hi);
12571 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12572 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12575 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12576 Type *Tys[] = { Addr->getType() };
12577 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12579 return Builder.CreateCall(
12580 Strex, {Builder.CreateZExtOrBitCast(
12581 Val, Strex->getFunctionType()->getParamType(0)),
12585 /// \brief Lower an interleaved load into a vldN intrinsic.
12587 /// E.g. Lower an interleaved load (Factor = 2):
12588 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12589 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
12590 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
12593 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12594 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12595 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12596 bool ARMTargetLowering::lowerInterleavedLoad(
12597 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12598 ArrayRef<unsigned> Indices, unsigned Factor) const {
12599 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12600 "Invalid interleave factor");
12601 assert(!Shuffles.empty() && "Empty shufflevector input");
12602 assert(Shuffles.size() == Indices.size() &&
12603 "Unmatched number of shufflevectors and indices");
12605 VectorType *VecTy = Shuffles[0]->getType();
12606 Type *EltTy = VecTy->getVectorElementType();
12608 const DataLayout &DL = LI->getModule()->getDataLayout();
12609 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12610 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12612 // Skip if we do not have NEON and skip illegal vector types and vector types
12613 // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12614 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12617 // A pointer vector can not be the return type of the ldN intrinsics. Need to
12618 // load integer vectors first and then convert to pointer vectors.
12619 if (EltTy->isPointerTy())
12621 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12623 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12624 Intrinsic::arm_neon_vld3,
12625 Intrinsic::arm_neon_vld4};
12627 IRBuilder<> Builder(LI);
12628 SmallVector<Value *, 2> Ops;
12630 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12631 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12632 Ops.push_back(Builder.getInt32(LI->getAlignment()));
12634 Type *Tys[] = { VecTy, Int8Ptr };
12635 Function *VldnFunc =
12636 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12637 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12639 // Replace uses of each shufflevector with the corresponding vector loaded
12641 for (unsigned i = 0; i < Shuffles.size(); i++) {
12642 ShuffleVectorInst *SV = Shuffles[i];
12643 unsigned Index = Indices[i];
12645 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12647 // Convert the integer vector to pointer vector if the element is pointer.
12648 if (EltTy->isPointerTy())
12649 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12651 SV->replaceAllUsesWith(SubVec);
12657 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12659 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12660 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12661 unsigned NumElts) {
12662 SmallVector<Constant *, 16> Mask;
12663 for (unsigned i = 0; i < NumElts; i++)
12664 Mask.push_back(Builder.getInt32(Start + i));
12666 return ConstantVector::get(Mask);
12669 /// \brief Lower an interleaved store into a vstN intrinsic.
12671 /// E.g. Lower an interleaved store (Factor = 3):
12672 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12673 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12674 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12677 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12678 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12679 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12680 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12682 /// Note that the new shufflevectors will be removed and we'll only generate one
12683 /// vst3 instruction in CodeGen.
12684 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12685 ShuffleVectorInst *SVI,
12686 unsigned Factor) const {
12687 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12688 "Invalid interleave factor");
12690 VectorType *VecTy = SVI->getType();
12691 assert(VecTy->getVectorNumElements() % Factor == 0 &&
12692 "Invalid interleaved store");
12694 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12695 Type *EltTy = VecTy->getVectorElementType();
12696 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12698 const DataLayout &DL = SI->getModule()->getDataLayout();
12699 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12700 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12702 // Skip if we do not have NEON and skip illegal vector types and vector types
12703 // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12704 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12708 Value *Op0 = SVI->getOperand(0);
12709 Value *Op1 = SVI->getOperand(1);
12710 IRBuilder<> Builder(SI);
12712 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12713 // vectors to integer vectors.
12714 if (EltTy->isPointerTy()) {
12715 Type *IntTy = DL.getIntPtrType(EltTy);
12717 // Convert to the corresponding integer vector.
12719 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12720 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12721 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12723 SubVecTy = VectorType::get(IntTy, NumSubElts);
12726 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12727 Intrinsic::arm_neon_vst3,
12728 Intrinsic::arm_neon_vst4};
12729 SmallVector<Value *, 6> Ops;
12731 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12732 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12734 Type *Tys[] = { Int8Ptr, SubVecTy };
12735 Function *VstNFunc = Intrinsic::getDeclaration(
12736 SI->getModule(), StoreInts[Factor - 2], Tys);
12738 // Split the shufflevector operands into sub vectors for the new vstN call.
12739 for (unsigned i = 0; i < Factor; i++)
12740 Ops.push_back(Builder.CreateShuffleVector(
12741 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12743 Ops.push_back(Builder.getInt32(SI->getAlignment()));
12744 Builder.CreateCall(VstNFunc, Ops);
12756 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12757 uint64_t &Members) {
12758 if (auto *ST = dyn_cast<StructType>(Ty)) {
12759 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12760 uint64_t SubMembers = 0;
12761 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12763 Members += SubMembers;
12765 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12766 uint64_t SubMembers = 0;
12767 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12769 Members += SubMembers * AT->getNumElements();
12770 } else if (Ty->isFloatTy()) {
12771 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12775 } else if (Ty->isDoubleTy()) {
12776 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12780 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12787 return VT->getBitWidth() == 64;
12789 return VT->getBitWidth() == 128;
12791 switch (VT->getBitWidth()) {
12804 return (Members > 0 && Members <= 4);
12807 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12808 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12809 /// passing according to AAPCS rules.
12810 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12811 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12812 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12813 CallingConv::ARM_AAPCS_VFP)
12816 HABaseType Base = HA_UNKNOWN;
12817 uint64_t Members = 0;
12818 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12819 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12821 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12822 return IsHA || IsIntArray;
12825 unsigned ARMTargetLowering::getExceptionPointerRegister(
12826 const Constant *PersonalityFn) const {
12827 // Platforms which do not use SjLj EH may return values in these registers
12828 // via the personality function.
12829 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12832 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12833 const Constant *PersonalityFn) const {
12834 // Platforms which do not use SjLj EH may return values in these registers
12835 // via the personality function.
12836 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12839 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12840 // Update IsSplitCSR in ARMFunctionInfo.
12841 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12842 AFI->setIsSplitCSR(true);
12845 void ARMTargetLowering::insertCopiesSplitCSR(
12846 MachineBasicBlock *Entry,
12847 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12848 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12849 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12853 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12854 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12855 MachineBasicBlock::iterator MBBI = Entry->begin();
12856 for (const MCPhysReg *I = IStart; *I; ++I) {
12857 const TargetRegisterClass *RC = nullptr;
12858 if (ARM::GPRRegClass.contains(*I))
12859 RC = &ARM::GPRRegClass;
12860 else if (ARM::DPRRegClass.contains(*I))
12861 RC = &ARM::DPRRegClass;
12863 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12865 unsigned NewVR = MRI->createVirtualRegister(RC);
12866 // Create copy from CSR to a virtual register.
12867 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12868 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12869 // nounwind. If we want to generalize this later, we may need to emit
12870 // CFI pseudo-instructions.
12871 assert(Entry->getParent()->getFunction()->hasFnAttribute(
12872 Attribute::NoUnwind) &&
12873 "Function should be nounwind in insertCopiesSplitCSR!");
12874 Entry->addLiveIn(*I);
12875 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12878 // Insert the copy-back instructions right before the terminator.
12879 for (auto *Exit : Exits)
12880 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12881 TII->get(TargetOpcode::COPY), *I)