1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (VT.isInteger()) {
147 setOperationAction(ISD::SABSDIFF, VT, Legal);
148 setOperationAction(ISD::UABSDIFF, VT, Legal);
150 if (!VT.isFloatingPoint() &&
151 VT != MVT::v2i64 && VT != MVT::v1i64)
152 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153 setOperationAction(Opcode, VT, Legal);
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPRRegClass);
159 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163 addRegisterClass(VT, &ARM::DPairRegClass);
164 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168 const ARMSubtarget &STI)
169 : TargetLowering(TM), Subtarget(&STI) {
170 RegInfo = Subtarget->getRegisterInfo();
171 Itins = Subtarget->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179 static const struct {
180 const RTLIB::Libcall Op;
181 const char * const Name;
182 const ISD::CondCode Cond;
184 // Single-precision floating-point arithmetic.
185 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
190 // Double-precision floating-point arithmetic.
191 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
196 // Single-precision comparisons.
197 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
198 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
199 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
200 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
201 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
202 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
203 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
204 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
206 // Double-precision comparisons.
207 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
208 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
209 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
210 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
211 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
212 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
213 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
214 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
216 // Floating-point to integer conversions.
217 // i64 conversions are done via library routines even when generating VFP
218 // instructions, so use the same ones.
219 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
220 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
222 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
224 // Conversions between floating types.
225 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
226 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
228 // Integer to floating-point conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232 // e.g., __floatunsidf vs. __floatunssidfvfp.
233 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
234 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
236 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
239 for (const auto &LC : LibraryCalls) {
240 setLibcallName(LC.Op, LC.Name);
241 if (LC.Cond != ISD::SETCC_INVALID)
242 setCmpLibcallCC(LC.Op, LC.Cond);
246 // Set the correct calling convention for ARMv7k WatchOS. It's just
247 // AAPCS_VFP for functions as simple as libcalls.
248 if (Subtarget->isTargetWatchOS()) {
249 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
250 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, nullptr);
256 setLibcallName(RTLIB::SRL_I128, nullptr);
257 setLibcallName(RTLIB::SRA_I128, nullptr);
260 if (Subtarget->isAAPCS_ABI() &&
261 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
262 Subtarget->isTargetAndroid())) {
263 static const struct {
264 const RTLIB::Libcall Op;
265 const char * const Name;
266 const CallingConv::ID CC;
267 const ISD::CondCode Cond;
269 // Double-precision floating-point arithmetic helper functions
270 // RTABI chapter 4.1.2, Table 2
271 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
274 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 // Double-precision floating-point comparison helper functions
277 // RTABI chapter 4.1.2, Table 3
278 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
280 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
282 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
284 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
287 // Single-precision floating-point arithmetic helper functions
288 // RTABI chapter 4.1.2, Table 4
289 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 // Single-precision floating-point comparison helper functions
295 // RTABI chapter 4.1.2, Table 5
296 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
298 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
300 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
301 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
302 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
303 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
305 // Floating-point to integer conversions.
306 // RTABI chapter 4.1.2, Table 6
307 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 // Conversions between floating types.
317 // RTABI chapter 4.1.2, Table 7
318 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 // Integer to floating-point conversions.
323 // RTABI chapter 4.1.2, Table 8
324 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 // Long long helper functions
334 // RTABI chapter 4.2, Table 9
335 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 // Integer division functions
341 // RTABI chapter 4.3.1
342 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 for (const auto &LC : LibraryCalls) {
353 setLibcallName(LC.Op, LC.Name);
354 setLibcallCallingConv(LC.Op, LC.CC);
355 if (LC.Cond != ISD::SETCC_INVALID)
356 setCmpLibcallCC(LC.Op, LC.Cond);
359 // EABI dependent RTLIB
360 if (TM.Options.EABIVersion == EABI::EABI4 ||
361 TM.Options.EABIVersion == EABI::EABI5) {
362 static const struct {
363 const RTLIB::Libcall Op;
364 const char *const Name;
365 const CallingConv::ID CC;
366 const ISD::CondCode Cond;
367 } MemOpsLibraryCalls[] = {
369 // RTABI chapter 4.3.4
370 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375 for (const auto &LC : MemOpsLibraryCalls) {
376 setLibcallName(LC.Op, LC.Name);
377 setLibcallCallingConv(LC.Op, LC.CC);
378 if (LC.Cond != ISD::SETCC_INVALID)
379 setCmpLibcallCC(LC.Op, LC.Cond);
384 if (Subtarget->isTargetWindows()) {
385 static const struct {
386 const RTLIB::Libcall Op;
387 const char * const Name;
388 const CallingConv::ID CC;
390 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
391 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
392 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
393 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
394 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
395 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
396 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
397 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
398 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
399 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
400 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
401 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
404 for (const auto &LC : LibraryCalls) {
405 setLibcallName(LC.Op, LC.Name);
406 setLibcallCallingConv(LC.Op, LC.CC);
410 // Use divmod compiler-rt calls for iOS 5.0 and later.
411 if (Subtarget->isTargetWatchOS() ||
412 (Subtarget->isTargetIOS() &&
413 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
414 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
415 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
418 // The half <-> float conversion functions are always soft-float, but are
419 // needed for some targets which use a hard-float calling convention by
421 if (Subtarget->isAAPCS_ABI()) {
422 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
424 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
426 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
427 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
428 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
431 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
432 // a __gnu_ prefix (which is the default).
433 if (Subtarget->isTargetAEABI()) {
434 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
435 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
436 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f");
439 if (Subtarget->isThumb1Only())
440 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
442 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
443 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
444 !Subtarget->isThumb1Only()) {
445 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
446 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
449 for (MVT VT : MVT::vector_valuetypes()) {
450 for (MVT InnerVT : MVT::vector_valuetypes()) {
451 setTruncStoreAction(VT, InnerVT, Expand);
452 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
453 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
454 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
457 setOperationAction(ISD::MULHS, VT, Expand);
458 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
459 setOperationAction(ISD::MULHU, VT, Expand);
460 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
462 setOperationAction(ISD::BSWAP, VT, Expand);
465 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
466 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
468 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
469 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
471 if (Subtarget->hasNEON()) {
472 addDRTypeForNEON(MVT::v2f32);
473 addDRTypeForNEON(MVT::v8i8);
474 addDRTypeForNEON(MVT::v4i16);
475 addDRTypeForNEON(MVT::v2i32);
476 addDRTypeForNEON(MVT::v1i64);
478 addQRTypeForNEON(MVT::v4f32);
479 addQRTypeForNEON(MVT::v2f64);
480 addQRTypeForNEON(MVT::v16i8);
481 addQRTypeForNEON(MVT::v8i16);
482 addQRTypeForNEON(MVT::v4i32);
483 addQRTypeForNEON(MVT::v2i64);
485 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
486 // neither Neon nor VFP support any arithmetic operations on it.
487 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
488 // supported for v4f32.
489 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
490 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
491 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
492 // FIXME: Code duplication: FDIV and FREM are expanded always, see
493 // ARMTargetLowering::addTypeForNEON method for details.
494 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
495 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
496 // FIXME: Create unittest.
497 // In another words, find a way when "copysign" appears in DAG with vector
499 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
500 // FIXME: Code duplication: SETCC has custom operation action, see
501 // ARMTargetLowering::addTypeForNEON method for details.
502 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
503 // FIXME: Create unittest for FNEG and for FABS.
504 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
505 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
506 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
507 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
508 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
510 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
511 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
514 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
516 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
517 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
518 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
519 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
520 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
521 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
522 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
524 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
526 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
527 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
528 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
529 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
530 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
531 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
532 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
533 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
534 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
535 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
536 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
537 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
538 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
540 // Mark v2f32 intrinsics.
541 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
543 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
544 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
545 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
546 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
547 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
548 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
549 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
550 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
551 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
552 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
553 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
554 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
555 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
557 // Neon does not support some operations on v1i64 and v2i64 types.
558 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
559 // Custom handling for some quad-vector types to detect VMULL.
560 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
561 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
562 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
563 // Custom handling for some vector types to avoid expensive expansions
564 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
565 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
566 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
567 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
568 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
569 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
570 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
571 // a destination type that is wider than the source, and nor does
572 // it have a FP_TO_[SU]INT instruction with a narrower destination than
574 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
576 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
577 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
579 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
580 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
582 // NEON does not have single instruction CTPOP for vectors with element
583 // types wider than 8-bits. However, custom lowering can leverage the
584 // v8i8/v16i8 vcnt instruction.
585 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
586 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
587 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
588 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
590 // NEON does not have single instruction CTTZ for vectors.
591 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
592 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
593 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
594 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
596 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
597 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
598 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
599 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
608 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
609 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
611 // NEON only has FMA instructions as of VFP4.
612 if (!Subtarget->hasVFP4()) {
613 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
614 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
617 setTargetDAGCombine(ISD::INTRINSIC_VOID);
618 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
619 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
620 setTargetDAGCombine(ISD::SHL);
621 setTargetDAGCombine(ISD::SRL);
622 setTargetDAGCombine(ISD::SRA);
623 setTargetDAGCombine(ISD::SIGN_EXTEND);
624 setTargetDAGCombine(ISD::ZERO_EXTEND);
625 setTargetDAGCombine(ISD::ANY_EXTEND);
626 setTargetDAGCombine(ISD::BUILD_VECTOR);
627 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
628 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
629 setTargetDAGCombine(ISD::STORE);
630 setTargetDAGCombine(ISD::FP_TO_SINT);
631 setTargetDAGCombine(ISD::FP_TO_UINT);
632 setTargetDAGCombine(ISD::FDIV);
633 setTargetDAGCombine(ISD::LOAD);
635 // It is legal to extload from v4i8 to v4i16 or v4i32.
636 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
638 for (MVT VT : MVT::integer_vector_valuetypes()) {
639 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
640 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
641 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
646 // ARM and Thumb2 support UMLAL/SMLAL.
647 if (!Subtarget->isThumb1Only())
648 setTargetDAGCombine(ISD::ADDC);
650 if (Subtarget->isFPOnlySP()) {
651 // When targeting a floating-point unit with only single-precision
652 // operations, f64 is legal for the few double-precision instructions which
653 // are present However, no double-precision operations other than moves,
654 // loads and stores are provided by the hardware.
655 setOperationAction(ISD::FADD, MVT::f64, Expand);
656 setOperationAction(ISD::FSUB, MVT::f64, Expand);
657 setOperationAction(ISD::FMUL, MVT::f64, Expand);
658 setOperationAction(ISD::FMA, MVT::f64, Expand);
659 setOperationAction(ISD::FDIV, MVT::f64, Expand);
660 setOperationAction(ISD::FREM, MVT::f64, Expand);
661 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
662 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
663 setOperationAction(ISD::FNEG, MVT::f64, Expand);
664 setOperationAction(ISD::FABS, MVT::f64, Expand);
665 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
666 setOperationAction(ISD::FSIN, MVT::f64, Expand);
667 setOperationAction(ISD::FCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
669 setOperationAction(ISD::FPOW, MVT::f64, Expand);
670 setOperationAction(ISD::FLOG, MVT::f64, Expand);
671 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
672 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
673 setOperationAction(ISD::FEXP, MVT::f64, Expand);
674 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
675 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
676 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
677 setOperationAction(ISD::FRINT, MVT::f64, Expand);
678 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
679 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
680 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
682 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
683 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
684 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
685 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
686 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
687 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
690 computeRegisterProperties(Subtarget->getRegisterInfo());
692 // ARM does not have floating-point extending loads.
693 for (MVT VT : MVT::fp_valuetypes()) {
694 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
695 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
698 // ... or truncating stores
699 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
700 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
701 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
703 // ARM does not have i1 sign extending load.
704 for (MVT VT : MVT::integer_valuetypes())
705 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
707 // ARM supports all 4 flavors of integer indexed load / store.
708 if (!Subtarget->isThumb1Only()) {
709 for (unsigned im = (unsigned)ISD::PRE_INC;
710 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
711 setIndexedLoadAction(im, MVT::i1, Legal);
712 setIndexedLoadAction(im, MVT::i8, Legal);
713 setIndexedLoadAction(im, MVT::i16, Legal);
714 setIndexedLoadAction(im, MVT::i32, Legal);
715 setIndexedStoreAction(im, MVT::i1, Legal);
716 setIndexedStoreAction(im, MVT::i8, Legal);
717 setIndexedStoreAction(im, MVT::i16, Legal);
718 setIndexedStoreAction(im, MVT::i32, Legal);
722 setOperationAction(ISD::SADDO, MVT::i32, Custom);
723 setOperationAction(ISD::UADDO, MVT::i32, Custom);
724 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
725 setOperationAction(ISD::USUBO, MVT::i32, Custom);
727 // i64 operation support.
728 setOperationAction(ISD::MUL, MVT::i64, Expand);
729 setOperationAction(ISD::MULHU, MVT::i32, Expand);
730 if (Subtarget->isThumb1Only()) {
731 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
732 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
734 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
735 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
736 setOperationAction(ISD::MULHS, MVT::i32, Expand);
738 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
739 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
740 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
741 setOperationAction(ISD::SRL, MVT::i64, Custom);
742 setOperationAction(ISD::SRA, MVT::i64, Custom);
744 if (!Subtarget->isThumb1Only()) {
745 // FIXME: We should do this for Thumb1 as well.
746 setOperationAction(ISD::ADDC, MVT::i32, Custom);
747 setOperationAction(ISD::ADDE, MVT::i32, Custom);
748 setOperationAction(ISD::SUBC, MVT::i32, Custom);
749 setOperationAction(ISD::SUBE, MVT::i32, Custom);
752 if (!Subtarget->isThumb1Only())
753 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
755 // ARM does not have ROTL.
756 setOperationAction(ISD::ROTL, MVT::i32, Expand);
757 for (MVT VT : MVT::vector_valuetypes()) {
758 setOperationAction(ISD::ROTL, VT, Expand);
759 setOperationAction(ISD::ROTR, VT, Expand);
761 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
762 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
763 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
764 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
766 // These just redirect to CTTZ and CTLZ on ARM.
767 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
768 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
770 // @llvm.readcyclecounter requires the Performance Monitors extension.
771 // Default to the 0 expansion on unsupported platforms.
772 // FIXME: Technically there are older ARM CPUs that have
773 // implementation-specific ways of obtaining this information.
774 if (Subtarget->hasPerfMon())
775 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
777 // Only ARMv6 has BSWAP.
778 if (!Subtarget->hasV6Ops())
779 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
781 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
782 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
783 // These are expanded into libcalls if the cpu doesn't have HW divider.
784 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
785 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
788 setOperationAction(ISD::SREM, MVT::i32, Expand);
789 setOperationAction(ISD::UREM, MVT::i32, Expand);
790 // Register based DivRem for AEABI (RTABI 4.2)
791 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
792 setOperationAction(ISD::SREM, MVT::i64, Custom);
793 setOperationAction(ISD::UREM, MVT::i64, Custom);
795 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
796 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
797 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
798 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
799 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
800 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
801 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
802 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
804 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
805 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
806 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
807 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
808 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
809 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
810 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
811 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
813 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
814 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
816 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
817 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
820 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
821 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
822 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
823 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
825 setOperationAction(ISD::TRAP, MVT::Other, Legal);
827 // Use the default implementation.
828 setOperationAction(ISD::VASTART, MVT::Other, Custom);
829 setOperationAction(ISD::VAARG, MVT::Other, Expand);
830 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
831 setOperationAction(ISD::VAEND, MVT::Other, Expand);
832 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
833 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
835 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
836 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
838 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
840 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
841 // the default expansion. If we are targeting a single threaded system,
842 // then set them all for expand so we can lower them later into their
844 if (TM.Options.ThreadModel == ThreadModel::Single)
845 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
846 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
847 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
848 // to ldrex/strex loops already.
849 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
851 // On v8, we have particularly efficient implementations of atomic fences
852 // if they can be combined with nearby atomic loads and stores.
853 if (!Subtarget->hasV8Ops()) {
854 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
855 setInsertFencesForAtomic(true);
858 // If there's anything we can use as a barrier, go through custom lowering
860 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
861 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
863 // Set them all for expansion, which will force libcalls.
864 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
865 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
866 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
867 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
868 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
869 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
870 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
871 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
872 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
873 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
874 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
875 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
876 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
877 // Unordered/Monotonic case.
878 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
879 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
882 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
884 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
885 if (!Subtarget->hasV6Ops()) {
886 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
887 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
889 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
891 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892 !Subtarget->isThumb1Only()) {
893 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
894 // iff target supports vfp2.
895 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
896 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
899 // We want to custom lower some of our intrinsics.
900 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
901 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
902 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
903 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
904 if (Subtarget->useSjLjEH())
905 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
907 setOperationAction(ISD::SETCC, MVT::i32, Expand);
908 setOperationAction(ISD::SETCC, MVT::f32, Expand);
909 setOperationAction(ISD::SETCC, MVT::f64, Expand);
910 setOperationAction(ISD::SELECT, MVT::i32, Custom);
911 setOperationAction(ISD::SELECT, MVT::f32, Custom);
912 setOperationAction(ISD::SELECT, MVT::f64, Custom);
913 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
914 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
915 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
917 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
918 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
919 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
920 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
921 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
923 // We don't support sin/cos/fmod/copysign/pow
924 setOperationAction(ISD::FSIN, MVT::f64, Expand);
925 setOperationAction(ISD::FSIN, MVT::f32, Expand);
926 setOperationAction(ISD::FCOS, MVT::f32, Expand);
927 setOperationAction(ISD::FCOS, MVT::f64, Expand);
928 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
929 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
930 setOperationAction(ISD::FREM, MVT::f64, Expand);
931 setOperationAction(ISD::FREM, MVT::f32, Expand);
932 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
933 !Subtarget->isThumb1Only()) {
934 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
935 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
937 setOperationAction(ISD::FPOW, MVT::f64, Expand);
938 setOperationAction(ISD::FPOW, MVT::f32, Expand);
940 if (!Subtarget->hasVFP4()) {
941 setOperationAction(ISD::FMA, MVT::f64, Expand);
942 setOperationAction(ISD::FMA, MVT::f32, Expand);
945 // Various VFP goodness
946 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
947 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
948 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
949 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
950 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
953 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
954 if (!Subtarget->hasFP16()) {
955 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
956 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
960 // Combine sin / cos into one node or libcall if possible.
961 if (Subtarget->hasSinCos()) {
962 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
963 setLibcallName(RTLIB::SINCOS_F64, "sincos");
964 if (Subtarget->isTargetWatchOS()) {
965 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
966 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
968 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
969 // For iOS, we don't want to the normal expansion of a libcall to
970 // sincos. We want to issue a libcall to __sincos_stret.
971 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
972 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
976 // FP-ARMv8 implements a lot of rounding-like FP operations.
977 if (Subtarget->hasFPARMv8()) {
978 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
979 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
980 setOperationAction(ISD::FROUND, MVT::f32, Legal);
981 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
982 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
983 setOperationAction(ISD::FRINT, MVT::f32, Legal);
984 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
985 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
986 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
987 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
988 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
989 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
991 if (!Subtarget->isFPOnlySP()) {
992 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
993 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
994 setOperationAction(ISD::FROUND, MVT::f64, Legal);
995 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
996 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
997 setOperationAction(ISD::FRINT, MVT::f64, Legal);
998 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
999 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1003 if (Subtarget->hasNEON()) {
1004 // vmin and vmax aren't available in a scalar form, so we use
1005 // a NEON instruction with an undef lane instead.
1006 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1007 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1008 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1009 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1010 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1011 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1014 // We have target-specific dag combine patterns for the following nodes:
1015 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1016 setTargetDAGCombine(ISD::ADD);
1017 setTargetDAGCombine(ISD::SUB);
1018 setTargetDAGCombine(ISD::MUL);
1019 setTargetDAGCombine(ISD::AND);
1020 setTargetDAGCombine(ISD::OR);
1021 setTargetDAGCombine(ISD::XOR);
1023 if (Subtarget->hasV6Ops())
1024 setTargetDAGCombine(ISD::SRL);
1026 setStackPointerRegisterToSaveRestore(ARM::SP);
1028 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1029 !Subtarget->hasVFP2())
1030 setSchedulingPreference(Sched::RegPressure);
1032 setSchedulingPreference(Sched::Hybrid);
1034 //// temporary - rewrite interface to use type
1035 MaxStoresPerMemset = 8;
1036 MaxStoresPerMemsetOptSize = 4;
1037 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1038 MaxStoresPerMemcpyOptSize = 2;
1039 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1040 MaxStoresPerMemmoveOptSize = 2;
1042 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1043 // are at least 4 bytes aligned.
1044 setMinStackArgumentAlignment(4);
1046 // Prefer likely predicted branches to selects on out-of-order cores.
1047 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1049 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1052 bool ARMTargetLowering::useSoftFloat() const {
1053 return Subtarget->useSoftFloat();
1056 // FIXME: It might make sense to define the representative register class as the
1057 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1058 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1059 // SPR's representative would be DPR_VFP2. This should work well if register
1060 // pressure tracking were modified such that a register use would increment the
1061 // pressure of the register class's representative and all of it's super
1062 // classes' representatives transitively. We have not implemented this because
1063 // of the difficulty prior to coalescing of modeling operand register classes
1064 // due to the common occurrence of cross class copies and subregister insertions
1066 std::pair<const TargetRegisterClass *, uint8_t>
1067 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1069 const TargetRegisterClass *RRC = nullptr;
1071 switch (VT.SimpleTy) {
1073 return TargetLowering::findRepresentativeClass(TRI, VT);
1074 // Use DPR as representative register class for all floating point
1075 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1076 // the cost is 1 for both f32 and f64.
1077 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1078 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1079 RRC = &ARM::DPRRegClass;
1080 // When NEON is used for SP, only half of the register file is available
1081 // because operations that define both SP and DP results will be constrained
1082 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1083 // coalescing by double-counting the SP regs. See the FIXME above.
1084 if (Subtarget->useNEONForSinglePrecisionFP())
1087 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1088 case MVT::v4f32: case MVT::v2f64:
1089 RRC = &ARM::DPRRegClass;
1093 RRC = &ARM::DPRRegClass;
1097 RRC = &ARM::DPRRegClass;
1101 return std::make_pair(RRC, Cost);
1104 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1105 switch ((ARMISD::NodeType)Opcode) {
1106 case ARMISD::FIRST_NUMBER: break;
1107 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1108 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1109 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1110 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1111 case ARMISD::CALL: return "ARMISD::CALL";
1112 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1113 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1114 case ARMISD::tCALL: return "ARMISD::tCALL";
1115 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1116 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1117 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1118 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1119 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1120 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1121 case ARMISD::CMP: return "ARMISD::CMP";
1122 case ARMISD::CMN: return "ARMISD::CMN";
1123 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1124 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1125 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1126 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1127 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1129 case ARMISD::CMOV: return "ARMISD::CMOV";
1131 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1132 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1133 case ARMISD::RRX: return "ARMISD::RRX";
1135 case ARMISD::ADDC: return "ARMISD::ADDC";
1136 case ARMISD::ADDE: return "ARMISD::ADDE";
1137 case ARMISD::SUBC: return "ARMISD::SUBC";
1138 case ARMISD::SUBE: return "ARMISD::SUBE";
1140 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1141 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1143 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1144 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1145 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1147 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1149 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1151 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1153 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1155 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1157 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1158 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1160 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1161 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1162 case ARMISD::VCGE: return "ARMISD::VCGE";
1163 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1164 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1165 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1166 case ARMISD::VCGT: return "ARMISD::VCGT";
1167 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1168 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1169 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1170 case ARMISD::VTST: return "ARMISD::VTST";
1172 case ARMISD::VSHL: return "ARMISD::VSHL";
1173 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1174 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1175 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1176 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1177 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1178 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1179 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1180 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1181 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1182 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1183 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1184 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1185 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1186 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1187 case ARMISD::VSLI: return "ARMISD::VSLI";
1188 case ARMISD::VSRI: return "ARMISD::VSRI";
1189 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1190 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1191 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1192 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1193 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1194 case ARMISD::VDUP: return "ARMISD::VDUP";
1195 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1196 case ARMISD::VEXT: return "ARMISD::VEXT";
1197 case ARMISD::VREV64: return "ARMISD::VREV64";
1198 case ARMISD::VREV32: return "ARMISD::VREV32";
1199 case ARMISD::VREV16: return "ARMISD::VREV16";
1200 case ARMISD::VZIP: return "ARMISD::VZIP";
1201 case ARMISD::VUZP: return "ARMISD::VUZP";
1202 case ARMISD::VTRN: return "ARMISD::VTRN";
1203 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1204 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1205 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1206 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1207 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1208 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1209 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1210 case ARMISD::BFI: return "ARMISD::BFI";
1211 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1212 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1213 case ARMISD::VBSL: return "ARMISD::VBSL";
1214 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1215 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1216 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1217 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1218 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1219 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1220 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1221 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1222 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1223 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1224 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1225 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1226 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1227 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1228 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1229 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1230 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1231 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1232 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1233 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1234 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1239 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1242 return getPointerTy(DL);
1243 return VT.changeVectorElementTypeToInteger();
1246 /// getRegClassFor - Return the register class that should be used for the
1247 /// specified value type.
1248 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1249 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1250 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1251 // load / store 4 to 8 consecutive D registers.
1252 if (Subtarget->hasNEON()) {
1253 if (VT == MVT::v4i64)
1254 return &ARM::QQPRRegClass;
1255 if (VT == MVT::v8i64)
1256 return &ARM::QQQQPRRegClass;
1258 return TargetLowering::getRegClassFor(VT);
1261 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1262 // source/dest is aligned and the copy size is large enough. We therefore want
1263 // to align such objects passed to memory intrinsics.
1264 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1265 unsigned &PrefAlign) const {
1266 if (!isa<MemIntrinsic>(CI))
1269 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1270 // cycle faster than 4-byte aligned LDM.
1271 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1275 // Create a fast isel object.
1277 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1278 const TargetLibraryInfo *libInfo) const {
1279 return ARM::createFastISel(funcInfo, libInfo);
1282 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1283 unsigned NumVals = N->getNumValues();
1285 return Sched::RegPressure;
1287 for (unsigned i = 0; i != NumVals; ++i) {
1288 EVT VT = N->getValueType(i);
1289 if (VT == MVT::Glue || VT == MVT::Other)
1291 if (VT.isFloatingPoint() || VT.isVector())
1295 if (!N->isMachineOpcode())
1296 return Sched::RegPressure;
1298 // Load are scheduled for latency even if there instruction itinerary
1299 // is not available.
1300 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1301 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1303 if (MCID.getNumDefs() == 0)
1304 return Sched::RegPressure;
1305 if (!Itins->isEmpty() &&
1306 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1309 return Sched::RegPressure;
1312 //===----------------------------------------------------------------------===//
1314 //===----------------------------------------------------------------------===//
1316 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1317 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1319 default: llvm_unreachable("Unknown condition code!");
1320 case ISD::SETNE: return ARMCC::NE;
1321 case ISD::SETEQ: return ARMCC::EQ;
1322 case ISD::SETGT: return ARMCC::GT;
1323 case ISD::SETGE: return ARMCC::GE;
1324 case ISD::SETLT: return ARMCC::LT;
1325 case ISD::SETLE: return ARMCC::LE;
1326 case ISD::SETUGT: return ARMCC::HI;
1327 case ISD::SETUGE: return ARMCC::HS;
1328 case ISD::SETULT: return ARMCC::LO;
1329 case ISD::SETULE: return ARMCC::LS;
1333 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1334 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1335 ARMCC::CondCodes &CondCode2) {
1336 CondCode2 = ARMCC::AL;
1338 default: llvm_unreachable("Unknown FP condition!");
1340 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1342 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1344 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1345 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1346 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1347 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1348 case ISD::SETO: CondCode = ARMCC::VC; break;
1349 case ISD::SETUO: CondCode = ARMCC::VS; break;
1350 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1351 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1352 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1354 case ISD::SETULT: CondCode = ARMCC::LT; break;
1356 case ISD::SETULE: CondCode = ARMCC::LE; break;
1358 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1362 //===----------------------------------------------------------------------===//
1363 // Calling Convention Implementation
1364 //===----------------------------------------------------------------------===//
1366 #include "ARMGenCallingConv.inc"
1368 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1369 /// account presence of floating point hardware and calling convention
1370 /// limitations, such as support for variadic functions.
1372 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1373 bool isVarArg) const {
1376 llvm_unreachable("Unsupported calling convention");
1377 case CallingConv::ARM_AAPCS:
1378 case CallingConv::ARM_APCS:
1379 case CallingConv::GHC:
1381 case CallingConv::ARM_AAPCS_VFP:
1382 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1383 case CallingConv::C:
1384 if (!Subtarget->isAAPCS_ABI())
1385 return CallingConv::ARM_APCS;
1386 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1387 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1389 return CallingConv::ARM_AAPCS_VFP;
1391 return CallingConv::ARM_AAPCS;
1392 case CallingConv::Fast:
1393 if (!Subtarget->isAAPCS_ABI()) {
1394 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1395 return CallingConv::Fast;
1396 return CallingConv::ARM_APCS;
1397 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1398 return CallingConv::ARM_AAPCS_VFP;
1400 return CallingConv::ARM_AAPCS;
1404 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1405 /// CallingConvention.
1406 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1408 bool isVarArg) const {
1409 switch (getEffectiveCallingConv(CC, isVarArg)) {
1411 llvm_unreachable("Unsupported calling convention");
1412 case CallingConv::ARM_APCS:
1413 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1414 case CallingConv::ARM_AAPCS:
1415 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1416 case CallingConv::ARM_AAPCS_VFP:
1417 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1418 case CallingConv::Fast:
1419 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1420 case CallingConv::GHC:
1421 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1425 /// LowerCallResult - Lower the result values of a call into the
1426 /// appropriate copies out of appropriate physical registers.
1428 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1429 CallingConv::ID CallConv, bool isVarArg,
1430 const SmallVectorImpl<ISD::InputArg> &Ins,
1431 SDLoc dl, SelectionDAG &DAG,
1432 SmallVectorImpl<SDValue> &InVals,
1433 bool isThisReturn, SDValue ThisVal) const {
1435 // Assign locations to each value returned by this call.
1436 SmallVector<CCValAssign, 16> RVLocs;
1437 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1438 *DAG.getContext(), Call);
1439 CCInfo.AnalyzeCallResult(Ins,
1440 CCAssignFnForNode(CallConv, /* Return*/ true,
1443 // Copy all of the result registers out of their specified physreg.
1444 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1445 CCValAssign VA = RVLocs[i];
1447 // Pass 'this' value directly from the argument to return value, to avoid
1448 // reg unit interference
1449 if (i == 0 && isThisReturn) {
1450 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1451 "unexpected return calling convention register assignment");
1452 InVals.push_back(ThisVal);
1457 if (VA.needsCustom()) {
1458 // Handle f64 or half of a v2f64.
1459 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1461 Chain = Lo.getValue(1);
1462 InFlag = Lo.getValue(2);
1463 VA = RVLocs[++i]; // skip ahead to next loc
1464 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1466 Chain = Hi.getValue(1);
1467 InFlag = Hi.getValue(2);
1468 if (!Subtarget->isLittle())
1470 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1472 if (VA.getLocVT() == MVT::v2f64) {
1473 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1474 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1475 DAG.getConstant(0, dl, MVT::i32));
1477 VA = RVLocs[++i]; // skip ahead to next loc
1478 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1479 Chain = Lo.getValue(1);
1480 InFlag = Lo.getValue(2);
1481 VA = RVLocs[++i]; // skip ahead to next loc
1482 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1483 Chain = Hi.getValue(1);
1484 InFlag = Hi.getValue(2);
1485 if (!Subtarget->isLittle())
1487 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1488 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1489 DAG.getConstant(1, dl, MVT::i32));
1492 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1494 Chain = Val.getValue(1);
1495 InFlag = Val.getValue(2);
1498 switch (VA.getLocInfo()) {
1499 default: llvm_unreachable("Unknown loc info!");
1500 case CCValAssign::Full: break;
1501 case CCValAssign::BCvt:
1502 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1506 InVals.push_back(Val);
1512 /// LowerMemOpCallTo - Store the argument to the stack.
1514 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1515 SDValue StackPtr, SDValue Arg,
1516 SDLoc dl, SelectionDAG &DAG,
1517 const CCValAssign &VA,
1518 ISD::ArgFlagsTy Flags) const {
1519 unsigned LocMemOffset = VA.getLocMemOffset();
1520 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1521 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1523 return DAG.getStore(
1524 Chain, dl, Arg, PtrOff,
1525 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1529 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1530 SDValue Chain, SDValue &Arg,
1531 RegsToPassVector &RegsToPass,
1532 CCValAssign &VA, CCValAssign &NextVA,
1534 SmallVectorImpl<SDValue> &MemOpChains,
1535 ISD::ArgFlagsTy Flags) const {
1537 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1538 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1539 unsigned id = Subtarget->isLittle() ? 0 : 1;
1540 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1542 if (NextVA.isRegLoc())
1543 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1545 assert(NextVA.isMemLoc());
1546 if (!StackPtr.getNode())
1547 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1548 getPointerTy(DAG.getDataLayout()));
1550 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1556 /// LowerCall - Lowering a call into a callseq_start <-
1557 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1560 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1561 SmallVectorImpl<SDValue> &InVals) const {
1562 SelectionDAG &DAG = CLI.DAG;
1564 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1565 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1566 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1567 SDValue Chain = CLI.Chain;
1568 SDValue Callee = CLI.Callee;
1569 bool &isTailCall = CLI.IsTailCall;
1570 CallingConv::ID CallConv = CLI.CallConv;
1571 bool doesNotRet = CLI.DoesNotReturn;
1572 bool isVarArg = CLI.IsVarArg;
1574 MachineFunction &MF = DAG.getMachineFunction();
1575 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1576 bool isThisReturn = false;
1577 bool isSibCall = false;
1578 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1580 // Disable tail calls if they're not supported.
1581 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1585 // Check if it's really possible to do a tail call.
1586 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1587 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1588 Outs, OutVals, Ins, DAG);
1589 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1590 report_fatal_error("failed to perform tail call elimination on a call "
1591 "site marked musttail");
1592 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1593 // detected sibcalls.
1600 // Analyze operands of the call, assigning locations to each operand.
1601 SmallVector<CCValAssign, 16> ArgLocs;
1602 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1603 *DAG.getContext(), Call);
1604 CCInfo.AnalyzeCallOperands(Outs,
1605 CCAssignFnForNode(CallConv, /* Return*/ false,
1608 // Get a count of how many bytes are to be pushed on the stack.
1609 unsigned NumBytes = CCInfo.getNextStackOffset();
1611 // For tail calls, memory operands are available in our caller's stack.
1615 // Adjust the stack pointer for the new arguments...
1616 // These operations are automatically eliminated by the prolog/epilog pass
1618 Chain = DAG.getCALLSEQ_START(Chain,
1619 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1622 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1624 RegsToPassVector RegsToPass;
1625 SmallVector<SDValue, 8> MemOpChains;
1627 // Walk the register/memloc assignments, inserting copies/loads. In the case
1628 // of tail call optimization, arguments are handled later.
1629 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1631 ++i, ++realArgIdx) {
1632 CCValAssign &VA = ArgLocs[i];
1633 SDValue Arg = OutVals[realArgIdx];
1634 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1635 bool isByVal = Flags.isByVal();
1637 // Promote the value if needed.
1638 switch (VA.getLocInfo()) {
1639 default: llvm_unreachable("Unknown loc info!");
1640 case CCValAssign::Full: break;
1641 case CCValAssign::SExt:
1642 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1644 case CCValAssign::ZExt:
1645 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1647 case CCValAssign::AExt:
1648 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1650 case CCValAssign::BCvt:
1651 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1655 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1656 if (VA.needsCustom()) {
1657 if (VA.getLocVT() == MVT::v2f64) {
1658 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1659 DAG.getConstant(0, dl, MVT::i32));
1660 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1661 DAG.getConstant(1, dl, MVT::i32));
1663 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1664 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1666 VA = ArgLocs[++i]; // skip ahead to next loc
1667 if (VA.isRegLoc()) {
1668 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1669 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1671 assert(VA.isMemLoc());
1673 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1674 dl, DAG, VA, Flags));
1677 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1678 StackPtr, MemOpChains, Flags);
1680 } else if (VA.isRegLoc()) {
1681 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1682 assert(VA.getLocVT() == MVT::i32 &&
1683 "unexpected calling convention register assignment");
1684 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1685 "unexpected use of 'returned'");
1686 isThisReturn = true;
1688 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1689 } else if (isByVal) {
1690 assert(VA.isMemLoc());
1691 unsigned offset = 0;
1693 // True if this byval aggregate will be split between registers
1695 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1696 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1698 if (CurByValIdx < ByValArgsCount) {
1700 unsigned RegBegin, RegEnd;
1701 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1704 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1706 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1707 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1708 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1709 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1710 MachinePointerInfo(),
1711 false, false, false,
1712 DAG.InferPtrAlignment(AddArg));
1713 MemOpChains.push_back(Load.getValue(1));
1714 RegsToPass.push_back(std::make_pair(j, Load));
1717 // If parameter size outsides register area, "offset" value
1718 // helps us to calculate stack slot for remained part properly.
1719 offset = RegEnd - RegBegin;
1721 CCInfo.nextInRegsParam();
1724 if (Flags.getByValSize() > 4*offset) {
1725 auto PtrVT = getPointerTy(DAG.getDataLayout());
1726 unsigned LocMemOffset = VA.getLocMemOffset();
1727 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1728 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1729 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1730 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1731 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1733 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1736 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1737 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1738 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1741 } else if (!isSibCall) {
1742 assert(VA.isMemLoc());
1744 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1745 dl, DAG, VA, Flags));
1749 if (!MemOpChains.empty())
1750 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1752 // Build a sequence of copy-to-reg nodes chained together with token chain
1753 // and flag operands which copy the outgoing args into the appropriate regs.
1755 // Tail call byval lowering might overwrite argument registers so in case of
1756 // tail call optimization the copies to registers are lowered later.
1758 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1759 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1760 RegsToPass[i].second, InFlag);
1761 InFlag = Chain.getValue(1);
1764 // For tail calls lower the arguments to the 'real' stack slot.
1766 // Force all the incoming stack arguments to be loaded from the stack
1767 // before any new outgoing arguments are stored to the stack, because the
1768 // outgoing stack slots may alias the incoming argument stack slots, and
1769 // the alias isn't otherwise explicit. This is slightly more conservative
1770 // than necessary, because it means that each store effectively depends
1771 // on every argument instead of just those arguments it would clobber.
1773 // Do not flag preceding copytoreg stuff together with the following stuff.
1775 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1776 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1777 RegsToPass[i].second, InFlag);
1778 InFlag = Chain.getValue(1);
1783 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1784 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1785 // node so that legalize doesn't hack it.
1786 bool isDirect = false;
1787 bool isARMFunc = false;
1788 bool isLocalARMFunc = false;
1789 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1790 auto PtrVt = getPointerTy(DAG.getDataLayout());
1792 if (Subtarget->genLongCalls()) {
1793 assert((Subtarget->isTargetWindows() ||
1794 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1795 "long-calls with non-static relocation model!");
1796 // Handle a global address or an external symbol. If it's not one of
1797 // those, the target's already in a register, so we don't need to do
1799 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1800 const GlobalValue *GV = G->getGlobal();
1801 // Create a constant pool entry for the callee address
1802 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1803 ARMConstantPoolValue *CPV =
1804 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1806 // Get the address of the callee into a register
1807 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1808 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1809 Callee = DAG.getLoad(
1810 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1811 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1813 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1814 const char *Sym = S->getSymbol();
1816 // Create a constant pool entry for the callee address
1817 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1818 ARMConstantPoolValue *CPV =
1819 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1820 ARMPCLabelIndex, 0);
1821 // Get the address of the callee into a register
1822 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1823 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1824 Callee = DAG.getLoad(
1825 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1826 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1829 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1830 const GlobalValue *GV = G->getGlobal();
1832 bool isDef = GV->isStrongDefinitionForLinker();
1833 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1834 getTargetMachine().getRelocationModel() != Reloc::Static;
1835 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1836 // ARM call to a local ARM function is predicable.
1837 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1838 // tBX takes a register source operand.
1839 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1840 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1841 Callee = DAG.getNode(
1842 ARMISD::WrapperPIC, dl, PtrVt,
1843 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1844 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1845 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1846 false, false, true, 0);
1847 } else if (Subtarget->isTargetCOFF()) {
1848 assert(Subtarget->isTargetWindows() &&
1849 "Windows is the only supported COFF target");
1850 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1851 ? ARMII::MO_DLLIMPORT
1852 : ARMII::MO_NO_FLAG;
1854 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1855 if (GV->hasDLLImportStorageClass())
1857 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1858 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1859 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1860 false, false, false, 0);
1862 // On ELF targets for PIC code, direct calls should go through the PLT
1863 unsigned OpFlags = 0;
1864 if (Subtarget->isTargetELF() &&
1865 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1866 OpFlags = ARMII::MO_PLT;
1867 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1869 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1871 bool isStub = Subtarget->isTargetMachO() &&
1872 getTargetMachine().getRelocationModel() != Reloc::Static;
1873 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1874 // tBX takes a register source operand.
1875 const char *Sym = S->getSymbol();
1876 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1877 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1878 ARMConstantPoolValue *CPV =
1879 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1880 ARMPCLabelIndex, 4);
1881 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1882 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1883 Callee = DAG.getLoad(
1884 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1885 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1887 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1888 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1890 unsigned OpFlags = 0;
1891 // On ELF targets for PIC code, direct calls should go through the PLT
1892 if (Subtarget->isTargetELF() &&
1893 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1894 OpFlags = ARMII::MO_PLT;
1895 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1899 // FIXME: handle tail calls differently.
1901 if (Subtarget->isThumb()) {
1902 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1903 CallOpc = ARMISD::CALL_NOLINK;
1905 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1907 if (!isDirect && !Subtarget->hasV5TOps())
1908 CallOpc = ARMISD::CALL_NOLINK;
1909 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1910 // Emit regular call when code size is the priority
1911 !MF.getFunction()->optForMinSize())
1912 // "mov lr, pc; b _foo" to avoid confusing the RSP
1913 CallOpc = ARMISD::CALL_NOLINK;
1915 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1918 std::vector<SDValue> Ops;
1919 Ops.push_back(Chain);
1920 Ops.push_back(Callee);
1922 // Add argument registers to the end of the list so that they are known live
1924 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1925 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1926 RegsToPass[i].second.getValueType()));
1928 // Add a register mask operand representing the call-preserved registers.
1930 const uint32_t *Mask;
1931 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1933 // For 'this' returns, use the R0-preserving mask if applicable
1934 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1936 // Set isThisReturn to false if the calling convention is not one that
1937 // allows 'returned' to be modeled in this way, so LowerCallResult does
1938 // not try to pass 'this' straight through
1939 isThisReturn = false;
1940 Mask = ARI->getCallPreservedMask(MF, CallConv);
1943 Mask = ARI->getCallPreservedMask(MF, CallConv);
1945 assert(Mask && "Missing call preserved mask for calling convention");
1946 Ops.push_back(DAG.getRegisterMask(Mask));
1949 if (InFlag.getNode())
1950 Ops.push_back(InFlag);
1952 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1954 MF.getFrameInfo()->setHasTailCall();
1955 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1958 // Returns a chain and a flag for retval copy to use.
1959 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1960 InFlag = Chain.getValue(1);
1962 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1963 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1965 InFlag = Chain.getValue(1);
1967 // Handle result values, copying them out of physregs into vregs that we
1969 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1970 InVals, isThisReturn,
1971 isThisReturn ? OutVals[0] : SDValue());
1974 /// HandleByVal - Every parameter *after* a byval parameter is passed
1975 /// on the stack. Remember the next parameter register to allocate,
1976 /// and then confiscate the rest of the parameter registers to insure
1978 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1979 unsigned Align) const {
1980 assert((State->getCallOrPrologue() == Prologue ||
1981 State->getCallOrPrologue() == Call) &&
1982 "unhandled ParmContext");
1984 // Byval (as with any stack) slots are always at least 4 byte aligned.
1985 Align = std::max(Align, 4U);
1987 unsigned Reg = State->AllocateReg(GPRArgRegs);
1991 unsigned AlignInRegs = Align / 4;
1992 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1993 for (unsigned i = 0; i < Waste; ++i)
1994 Reg = State->AllocateReg(GPRArgRegs);
1999 unsigned Excess = 4 * (ARM::R4 - Reg);
2001 // Special case when NSAA != SP and parameter size greater than size of
2002 // all remained GPR regs. In that case we can't split parameter, we must
2003 // send it to stack. We also must set NCRN to R4, so waste all
2004 // remained registers.
2005 const unsigned NSAAOffset = State->getNextStackOffset();
2006 if (NSAAOffset != 0 && Size > Excess) {
2007 while (State->AllocateReg(GPRArgRegs))
2012 // First register for byval parameter is the first register that wasn't
2013 // allocated before this method call, so it would be "reg".
2014 // If parameter is small enough to be saved in range [reg, r4), then
2015 // the end (first after last) register would be reg + param-size-in-regs,
2016 // else parameter would be splitted between registers and stack,
2017 // end register would be r4 in this case.
2018 unsigned ByValRegBegin = Reg;
2019 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2020 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2021 // Note, first register is allocated in the beginning of function already,
2022 // allocate remained amount of registers we need.
2023 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2024 State->AllocateReg(GPRArgRegs);
2025 // A byval parameter that is split between registers and memory needs its
2026 // size truncated here.
2027 // In the case where the entire structure fits in registers, we set the
2028 // size in memory to zero.
2029 Size = std::max<int>(Size - Excess, 0);
2032 /// MatchingStackOffset - Return true if the given stack call argument is
2033 /// already available in the same position (relatively) of the caller's
2034 /// incoming argument stack.
2036 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2037 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2038 const TargetInstrInfo *TII) {
2039 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2041 if (Arg.getOpcode() == ISD::CopyFromReg) {
2042 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2043 if (!TargetRegisterInfo::isVirtualRegister(VR))
2045 MachineInstr *Def = MRI->getVRegDef(VR);
2048 if (!Flags.isByVal()) {
2049 if (!TII->isLoadFromStackSlot(Def, FI))
2054 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2055 if (Flags.isByVal())
2056 // ByVal argument is passed in as a pointer but it's now being
2057 // dereferenced. e.g.
2058 // define @foo(%struct.X* %A) {
2059 // tail call @bar(%struct.X* byval %A)
2062 SDValue Ptr = Ld->getBasePtr();
2063 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2066 FI = FINode->getIndex();
2070 assert(FI != INT_MAX);
2071 if (!MFI->isFixedObjectIndex(FI))
2073 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2076 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2077 /// for tail call optimization. Targets which want to do tail call
2078 /// optimization should implement this function.
2080 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2081 CallingConv::ID CalleeCC,
2083 bool isCalleeStructRet,
2084 bool isCallerStructRet,
2085 const SmallVectorImpl<ISD::OutputArg> &Outs,
2086 const SmallVectorImpl<SDValue> &OutVals,
2087 const SmallVectorImpl<ISD::InputArg> &Ins,
2088 SelectionDAG& DAG) const {
2089 const Function *CallerF = DAG.getMachineFunction().getFunction();
2090 CallingConv::ID CallerCC = CallerF->getCallingConv();
2091 bool CCMatch = CallerCC == CalleeCC;
2093 assert(Subtarget->supportsTailCall());
2095 // Look for obvious safe cases to perform tail call optimization that do not
2096 // require ABI changes. This is what gcc calls sibcall.
2098 // Do not sibcall optimize vararg calls unless the call site is not passing
2100 if (isVarArg && !Outs.empty())
2103 // Exception-handling functions need a special set of instructions to indicate
2104 // a return to the hardware. Tail-calling another function would probably
2106 if (CallerF->hasFnAttribute("interrupt"))
2109 // Also avoid sibcall optimization if either caller or callee uses struct
2110 // return semantics.
2111 if (isCalleeStructRet || isCallerStructRet)
2114 // Externally-defined functions with weak linkage should not be
2115 // tail-called on ARM when the OS does not support dynamic
2116 // pre-emption of symbols, as the AAELF spec requires normal calls
2117 // to undefined weak functions to be replaced with a NOP or jump to the
2118 // next instruction. The behaviour of branch instructions in this
2119 // situation (as used for tail calls) is implementation-defined, so we
2120 // cannot rely on the linker replacing the tail call with a return.
2121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2122 const GlobalValue *GV = G->getGlobal();
2123 const Triple &TT = getTargetMachine().getTargetTriple();
2124 if (GV->hasExternalWeakLinkage() &&
2125 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2129 // If the calling conventions do not match, then we'd better make sure the
2130 // results are returned in the same way as what the caller expects.
2132 SmallVector<CCValAssign, 16> RVLocs1;
2133 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2134 *DAG.getContext(), Call);
2135 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2137 SmallVector<CCValAssign, 16> RVLocs2;
2138 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2139 *DAG.getContext(), Call);
2140 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2142 if (RVLocs1.size() != RVLocs2.size())
2144 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2145 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2147 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2149 if (RVLocs1[i].isRegLoc()) {
2150 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2153 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2159 // If Caller's vararg or byval argument has been split between registers and
2160 // stack, do not perform tail call, since part of the argument is in caller's
2162 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2163 getInfo<ARMFunctionInfo>();
2164 if (AFI_Caller->getArgRegsSaveSize())
2167 // If the callee takes no arguments then go on to check the results of the
2169 if (!Outs.empty()) {
2170 // Check if stack adjustment is needed. For now, do not do this if any
2171 // argument is passed on the stack.
2172 SmallVector<CCValAssign, 16> ArgLocs;
2173 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2174 *DAG.getContext(), Call);
2175 CCInfo.AnalyzeCallOperands(Outs,
2176 CCAssignFnForNode(CalleeCC, false, isVarArg));
2177 if (CCInfo.getNextStackOffset()) {
2178 MachineFunction &MF = DAG.getMachineFunction();
2180 // Check if the arguments are already laid out in the right way as
2181 // the caller's fixed stack objects.
2182 MachineFrameInfo *MFI = MF.getFrameInfo();
2183 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2184 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2185 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2187 ++i, ++realArgIdx) {
2188 CCValAssign &VA = ArgLocs[i];
2189 EVT RegVT = VA.getLocVT();
2190 SDValue Arg = OutVals[realArgIdx];
2191 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2192 if (VA.getLocInfo() == CCValAssign::Indirect)
2194 if (VA.needsCustom()) {
2195 // f64 and vector types are split into multiple registers or
2196 // register/stack-slot combinations. The types will not match
2197 // the registers; give up on memory f64 refs until we figure
2198 // out what to do about this.
2201 if (!ArgLocs[++i].isRegLoc())
2203 if (RegVT == MVT::v2f64) {
2204 if (!ArgLocs[++i].isRegLoc())
2206 if (!ArgLocs[++i].isRegLoc())
2209 } else if (!VA.isRegLoc()) {
2210 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2222 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2223 MachineFunction &MF, bool isVarArg,
2224 const SmallVectorImpl<ISD::OutputArg> &Outs,
2225 LLVMContext &Context) const {
2226 SmallVector<CCValAssign, 16> RVLocs;
2227 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2228 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2232 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2233 SDLoc DL, SelectionDAG &DAG) {
2234 const MachineFunction &MF = DAG.getMachineFunction();
2235 const Function *F = MF.getFunction();
2237 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2239 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2240 // version of the "preferred return address". These offsets affect the return
2241 // instruction if this is a return from PL1 without hypervisor extensions.
2242 // IRQ/FIQ: +4 "subs pc, lr, #4"
2243 // SWI: 0 "subs pc, lr, #0"
2244 // ABORT: +4 "subs pc, lr, #4"
2245 // UNDEF: +4/+2 "subs pc, lr, #0"
2246 // UNDEF varies depending on where the exception came from ARM or Thumb
2247 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2250 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2253 else if (IntKind == "SWI" || IntKind == "UNDEF")
2256 report_fatal_error("Unsupported interrupt attribute. If present, value "
2257 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2259 RetOps.insert(RetOps.begin() + 1,
2260 DAG.getConstant(LROffset, DL, MVT::i32, false));
2262 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2266 ARMTargetLowering::LowerReturn(SDValue Chain,
2267 CallingConv::ID CallConv, bool isVarArg,
2268 const SmallVectorImpl<ISD::OutputArg> &Outs,
2269 const SmallVectorImpl<SDValue> &OutVals,
2270 SDLoc dl, SelectionDAG &DAG) const {
2272 // CCValAssign - represent the assignment of the return value to a location.
2273 SmallVector<CCValAssign, 16> RVLocs;
2275 // CCState - Info about the registers and stack slots.
2276 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2277 *DAG.getContext(), Call);
2279 // Analyze outgoing return values.
2280 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2284 SmallVector<SDValue, 4> RetOps;
2285 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2286 bool isLittleEndian = Subtarget->isLittle();
2288 MachineFunction &MF = DAG.getMachineFunction();
2289 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2290 AFI->setReturnRegsCount(RVLocs.size());
2292 // Copy the result values into the output registers.
2293 for (unsigned i = 0, realRVLocIdx = 0;
2295 ++i, ++realRVLocIdx) {
2296 CCValAssign &VA = RVLocs[i];
2297 assert(VA.isRegLoc() && "Can only return in registers!");
2299 SDValue Arg = OutVals[realRVLocIdx];
2301 switch (VA.getLocInfo()) {
2302 default: llvm_unreachable("Unknown loc info!");
2303 case CCValAssign::Full: break;
2304 case CCValAssign::BCvt:
2305 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2309 if (VA.needsCustom()) {
2310 if (VA.getLocVT() == MVT::v2f64) {
2311 // Extract the first half and return it in two registers.
2312 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2313 DAG.getConstant(0, dl, MVT::i32));
2314 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2315 DAG.getVTList(MVT::i32, MVT::i32), Half);
2317 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2318 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2320 Flag = Chain.getValue(1);
2321 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2322 VA = RVLocs[++i]; // skip ahead to next loc
2323 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2324 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2326 Flag = Chain.getValue(1);
2327 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2328 VA = RVLocs[++i]; // skip ahead to next loc
2330 // Extract the 2nd half and fall through to handle it as an f64 value.
2331 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2332 DAG.getConstant(1, dl, MVT::i32));
2334 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2336 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2337 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2338 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2339 fmrrd.getValue(isLittleEndian ? 0 : 1),
2341 Flag = Chain.getValue(1);
2342 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2343 VA = RVLocs[++i]; // skip ahead to next loc
2344 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2345 fmrrd.getValue(isLittleEndian ? 1 : 0),
2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2350 // Guarantee that all emitted copies are
2351 // stuck together, avoiding something bad.
2352 Flag = Chain.getValue(1);
2353 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2356 // Update chain and glue.
2359 RetOps.push_back(Flag);
2361 // CPUs which aren't M-class use a special sequence to return from
2362 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2363 // though we use "subs pc, lr, #N").
2365 // M-class CPUs actually use a normal return sequence with a special
2366 // (hardware-provided) value in LR, so the normal code path works.
2367 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2368 !Subtarget->isMClass()) {
2369 if (Subtarget->isThumb1Only())
2370 report_fatal_error("interrupt attribute is not supported in Thumb1");
2371 return LowerInterruptReturn(RetOps, dl, DAG);
2374 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2377 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2378 if (N->getNumValues() != 1)
2380 if (!N->hasNUsesOfValue(1, 0))
2383 SDValue TCChain = Chain;
2384 SDNode *Copy = *N->use_begin();
2385 if (Copy->getOpcode() == ISD::CopyToReg) {
2386 // If the copy has a glue operand, we conservatively assume it isn't safe to
2387 // perform a tail call.
2388 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2390 TCChain = Copy->getOperand(0);
2391 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2392 SDNode *VMov = Copy;
2393 // f64 returned in a pair of GPRs.
2394 SmallPtrSet<SDNode*, 2> Copies;
2395 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2397 if (UI->getOpcode() != ISD::CopyToReg)
2401 if (Copies.size() > 2)
2404 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2406 SDValue UseChain = UI->getOperand(0);
2407 if (Copies.count(UseChain.getNode()))
2411 // We are at the top of this chain.
2412 // If the copy has a glue operand, we conservatively assume it
2413 // isn't safe to perform a tail call.
2414 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2420 } else if (Copy->getOpcode() == ISD::BITCAST) {
2421 // f32 returned in a single GPR.
2422 if (!Copy->hasOneUse())
2424 Copy = *Copy->use_begin();
2425 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2427 // If the copy has a glue operand, we conservatively assume it isn't safe to
2428 // perform a tail call.
2429 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2431 TCChain = Copy->getOperand(0);
2436 bool HasRet = false;
2437 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2439 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2440 UI->getOpcode() != ARMISD::INTRET_FLAG)
2452 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2453 if (!Subtarget->supportsTailCall())
2457 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2458 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2464 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2465 // and pass the lower and high parts through.
2466 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2468 SDValue WriteValue = Op->getOperand(2);
2470 // This function is only supposed to be called for i64 type argument.
2471 assert(WriteValue.getValueType() == MVT::i64
2472 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2474 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2475 DAG.getConstant(0, DL, MVT::i32));
2476 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2477 DAG.getConstant(1, DL, MVT::i32));
2478 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2479 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2482 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2483 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2484 // one of the above mentioned nodes. It has to be wrapped because otherwise
2485 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2486 // be used to form addressing mode. These wrapped nodes will be selected
2488 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2489 EVT PtrVT = Op.getValueType();
2490 // FIXME there is no actual debug info here
2492 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2494 if (CP->isMachineConstantPoolEntry())
2495 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2496 CP->getAlignment());
2498 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2499 CP->getAlignment());
2500 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2503 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2504 return MachineJumpTableInfo::EK_Inline;
2507 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2508 SelectionDAG &DAG) const {
2509 MachineFunction &MF = DAG.getMachineFunction();
2510 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2511 unsigned ARMPCLabelIndex = 0;
2513 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2514 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2515 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2517 if (RelocM == Reloc::Static) {
2518 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2520 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2521 ARMPCLabelIndex = AFI->createPICLabelUId();
2522 ARMConstantPoolValue *CPV =
2523 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2524 ARMCP::CPBlockAddress, PCAdj);
2525 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2527 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2529 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2530 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2531 false, false, false, 0);
2532 if (RelocM == Reloc::Static)
2534 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2535 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2538 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2540 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2541 SelectionDAG &DAG) const {
2543 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2544 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2545 MachineFunction &MF = DAG.getMachineFunction();
2546 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2547 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2548 ARMConstantPoolValue *CPV =
2549 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2550 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2551 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2552 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2554 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2555 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2556 false, false, false, 0);
2557 SDValue Chain = Argument.getValue(1);
2559 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2560 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2562 // call __tls_get_addr.
2565 Entry.Node = Argument;
2566 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2567 Args.push_back(Entry);
2569 // FIXME: is there useful debug info available here?
2570 TargetLowering::CallLoweringInfo CLI(DAG);
2571 CLI.setDebugLoc(dl).setChain(Chain)
2572 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2573 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2576 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2577 return CallResult.first;
2580 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2581 // "local exec" model.
2583 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2585 TLSModel::Model model) const {
2586 const GlobalValue *GV = GA->getGlobal();
2589 SDValue Chain = DAG.getEntryNode();
2590 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2591 // Get the Thread Pointer
2592 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2594 if (model == TLSModel::InitialExec) {
2595 MachineFunction &MF = DAG.getMachineFunction();
2596 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2597 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2598 // Initial exec model.
2599 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2600 ARMConstantPoolValue *CPV =
2601 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2602 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2604 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2605 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2606 Offset = DAG.getLoad(
2607 PtrVT, dl, Chain, Offset,
2608 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2610 Chain = Offset.getValue(1);
2612 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2613 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2615 Offset = DAG.getLoad(
2616 PtrVT, dl, Chain, Offset,
2617 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2621 assert(model == TLSModel::LocalExec);
2622 ARMConstantPoolValue *CPV =
2623 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2624 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2625 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2626 Offset = DAG.getLoad(
2627 PtrVT, dl, Chain, Offset,
2628 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2632 // The address of the thread local variable is the add of the thread
2633 // pointer with the offset of the variable.
2634 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2638 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2639 // TODO: implement the "local dynamic" model
2640 assert(Subtarget->isTargetELF() &&
2641 "TLS not implemented for non-ELF targets");
2642 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2643 if (DAG.getTarget().Options.EmulatedTLS)
2644 return LowerToTLSEmulatedModel(GA, DAG);
2646 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2649 case TLSModel::GeneralDynamic:
2650 case TLSModel::LocalDynamic:
2651 return LowerToTLSGeneralDynamicModel(GA, DAG);
2652 case TLSModel::InitialExec:
2653 case TLSModel::LocalExec:
2654 return LowerToTLSExecModels(GA, DAG, model);
2656 llvm_unreachable("bogus TLS model");
2659 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2660 SelectionDAG &DAG) const {
2661 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2663 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2664 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2666 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2668 MachineFunction &MF = DAG.getMachineFunction();
2669 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2670 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2671 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2673 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2674 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2675 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2676 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2677 /*AddCurrentAddress=*/UseGOT_PREL);
2678 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2679 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2680 SDValue Result = DAG.getLoad(
2681 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2684 SDValue Chain = Result.getValue(1);
2685 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2686 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2688 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2689 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2690 false, false, false, 0);
2694 // If we have T2 ops, we can materialize the address directly via movt/movw
2695 // pair. This is always cheaper.
2696 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2698 // FIXME: Once remat is capable of dealing with instructions with register
2699 // operands, expand this into two nodes.
2700 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2701 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2703 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2704 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2706 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2707 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2712 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2713 SelectionDAG &DAG) const {
2714 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2716 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2717 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2719 if (Subtarget->useMovt(DAG.getMachineFunction()))
2722 // FIXME: Once remat is capable of dealing with instructions with register
2723 // operands, expand this into multiple nodes
2725 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2727 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2728 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2730 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2731 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2732 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2733 false, false, false, 0);
2737 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2738 SelectionDAG &DAG) const {
2739 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2740 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2741 "Windows on ARM expects to use movw/movt");
2743 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2744 const ARMII::TOF TargetFlags =
2745 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2746 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2752 // FIXME: Once remat is capable of dealing with instructions with register
2753 // operands, expand this into two nodes.
2754 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2755 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2757 if (GV->hasDLLImportStorageClass())
2758 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2759 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2760 false, false, false, 0);
2765 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2767 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2768 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2769 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2770 Op.getOperand(1), Val);
2774 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2776 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2777 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2780 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2781 SelectionDAG &DAG) const {
2783 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2788 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2789 const ARMSubtarget *Subtarget) const {
2790 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2793 default: return SDValue(); // Don't custom lower most intrinsics.
2794 case Intrinsic::arm_rbit: {
2795 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2796 "RBIT intrinsic must have i32 type!");
2797 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2799 case Intrinsic::arm_thread_pointer: {
2800 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2801 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2803 case Intrinsic::eh_sjlj_lsda: {
2804 MachineFunction &MF = DAG.getMachineFunction();
2805 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2806 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2807 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2808 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2810 unsigned PCAdj = (RelocM != Reloc::PIC_)
2811 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2812 ARMConstantPoolValue *CPV =
2813 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2814 ARMCP::CPLSDA, PCAdj);
2815 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2816 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2817 SDValue Result = DAG.getLoad(
2818 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2819 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2822 if (RelocM == Reloc::PIC_) {
2823 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2824 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2828 case Intrinsic::arm_neon_vmulls:
2829 case Intrinsic::arm_neon_vmullu: {
2830 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2831 ? ARMISD::VMULLs : ARMISD::VMULLu;
2832 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2833 Op.getOperand(1), Op.getOperand(2));
2835 case Intrinsic::arm_neon_vminnm:
2836 case Intrinsic::arm_neon_vmaxnm: {
2837 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2838 ? ISD::FMINNUM : ISD::FMAXNUM;
2839 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2840 Op.getOperand(1), Op.getOperand(2));
2842 case Intrinsic::arm_neon_vminu:
2843 case Intrinsic::arm_neon_vmaxu: {
2844 if (Op.getValueType().isFloatingPoint())
2846 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2847 ? ISD::UMIN : ISD::UMAX;
2848 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2849 Op.getOperand(1), Op.getOperand(2));
2851 case Intrinsic::arm_neon_vmins:
2852 case Intrinsic::arm_neon_vmaxs: {
2853 // v{min,max}s is overloaded between signed integers and floats.
2854 if (!Op.getValueType().isFloatingPoint()) {
2855 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2856 ? ISD::SMIN : ISD::SMAX;
2857 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2858 Op.getOperand(1), Op.getOperand(2));
2860 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2861 ? ISD::FMINNAN : ISD::FMAXNAN;
2862 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2863 Op.getOperand(1), Op.getOperand(2));
2868 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2869 const ARMSubtarget *Subtarget) {
2870 // FIXME: handle "fence singlethread" more efficiently.
2872 if (!Subtarget->hasDataBarrier()) {
2873 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2874 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2876 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2877 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2878 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2879 DAG.getConstant(0, dl, MVT::i32));
2882 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2883 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2884 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2885 if (Subtarget->isMClass()) {
2886 // Only a full system barrier exists in the M-class architectures.
2887 Domain = ARM_MB::SY;
2888 } else if (Subtarget->isSwift() && Ord == Release) {
2889 // Swift happens to implement ISHST barriers in a way that's compatible with
2890 // Release semantics but weaker than ISH so we'd be fools not to use
2891 // it. Beware: other processors probably don't!
2892 Domain = ARM_MB::ISHST;
2895 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2896 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2897 DAG.getConstant(Domain, dl, MVT::i32));
2900 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2901 const ARMSubtarget *Subtarget) {
2902 // ARM pre v5TE and Thumb1 does not have preload instructions.
2903 if (!(Subtarget->isThumb2() ||
2904 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2905 // Just preserve the chain.
2906 return Op.getOperand(0);
2909 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2911 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2912 // ARMv7 with MP extension has PLDW.
2913 return Op.getOperand(0);
2915 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2916 if (Subtarget->isThumb()) {
2918 isRead = ~isRead & 1;
2919 isData = ~isData & 1;
2922 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2923 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2924 DAG.getConstant(isData, dl, MVT::i32));
2927 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2928 MachineFunction &MF = DAG.getMachineFunction();
2929 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2931 // vastart just stores the address of the VarArgsFrameIndex slot into the
2932 // memory location argument.
2934 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2935 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2936 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2937 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2938 MachinePointerInfo(SV), false, false, 0);
2942 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2943 SDValue &Root, SelectionDAG &DAG,
2945 MachineFunction &MF = DAG.getMachineFunction();
2946 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2948 const TargetRegisterClass *RC;
2949 if (AFI->isThumb1OnlyFunction())
2950 RC = &ARM::tGPRRegClass;
2952 RC = &ARM::GPRRegClass;
2954 // Transform the arguments stored in physical registers into virtual ones.
2955 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2956 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2959 if (NextVA.isMemLoc()) {
2960 MachineFrameInfo *MFI = MF.getFrameInfo();
2961 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2963 // Create load node to retrieve arguments from the stack.
2964 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2965 ArgValue2 = DAG.getLoad(
2966 MVT::i32, dl, Root, FIN,
2967 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2970 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2971 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2973 if (!Subtarget->isLittle())
2974 std::swap (ArgValue, ArgValue2);
2975 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2978 // The remaining GPRs hold either the beginning of variable-argument
2979 // data, or the beginning of an aggregate passed by value (usually
2980 // byval). Either way, we allocate stack slots adjacent to the data
2981 // provided by our caller, and store the unallocated registers there.
2982 // If this is a variadic function, the va_list pointer will begin with
2983 // these values; otherwise, this reassembles a (byval) structure that
2984 // was split between registers and memory.
2985 // Return: The frame index registers were stored into.
2987 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2988 SDLoc dl, SDValue &Chain,
2989 const Value *OrigArg,
2990 unsigned InRegsParamRecordIdx,
2992 unsigned ArgSize) const {
2993 // Currently, two use-cases possible:
2994 // Case #1. Non-var-args function, and we meet first byval parameter.
2995 // Setup first unallocated register as first byval register;
2996 // eat all remained registers
2997 // (these two actions are performed by HandleByVal method).
2998 // Then, here, we initialize stack frame with
2999 // "store-reg" instructions.
3000 // Case #2. Var-args function, that doesn't contain byval parameters.
3001 // The same: eat all remained unallocated registers,
3002 // initialize stack frame.
3004 MachineFunction &MF = DAG.getMachineFunction();
3005 MachineFrameInfo *MFI = MF.getFrameInfo();
3006 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3007 unsigned RBegin, REnd;
3008 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3009 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3011 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3012 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3017 ArgOffset = -4 * (ARM::R4 - RBegin);
3019 auto PtrVT = getPointerTy(DAG.getDataLayout());
3020 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3021 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3023 SmallVector<SDValue, 4> MemOps;
3024 const TargetRegisterClass *RC =
3025 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3027 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3028 unsigned VReg = MF.addLiveIn(Reg, RC);
3029 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3031 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3032 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3033 MemOps.push_back(Store);
3034 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3037 if (!MemOps.empty())
3038 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3042 // Setup stack frame, the va_list pointer will start from.
3044 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3045 SDLoc dl, SDValue &Chain,
3047 unsigned TotalArgRegsSaveSize,
3048 bool ForceMutable) const {
3049 MachineFunction &MF = DAG.getMachineFunction();
3050 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3052 // Try to store any remaining integer argument regs
3053 // to their spots on the stack so that they may be loaded by deferencing
3054 // the result of va_next.
3055 // If there is no regs to be stored, just point address after last
3056 // argument passed via stack.
3057 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3058 CCInfo.getInRegsParamsCount(),
3059 CCInfo.getNextStackOffset(), 4);
3060 AFI->setVarArgsFrameIndex(FrameIndex);
3064 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3065 CallingConv::ID CallConv, bool isVarArg,
3066 const SmallVectorImpl<ISD::InputArg>
3068 SDLoc dl, SelectionDAG &DAG,
3069 SmallVectorImpl<SDValue> &InVals)
3071 MachineFunction &MF = DAG.getMachineFunction();
3072 MachineFrameInfo *MFI = MF.getFrameInfo();
3074 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3076 // Assign locations to all of the incoming arguments.
3077 SmallVector<CCValAssign, 16> ArgLocs;
3078 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3079 *DAG.getContext(), Prologue);
3080 CCInfo.AnalyzeFormalArguments(Ins,
3081 CCAssignFnForNode(CallConv, /* Return*/ false,
3084 SmallVector<SDValue, 16> ArgValues;
3086 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3087 unsigned CurArgIdx = 0;
3089 // Initially ArgRegsSaveSize is zero.
3090 // Then we increase this value each time we meet byval parameter.
3091 // We also increase this value in case of varargs function.
3092 AFI->setArgRegsSaveSize(0);
3094 // Calculate the amount of stack space that we need to allocate to store
3095 // byval and variadic arguments that are passed in registers.
3096 // We need to know this before we allocate the first byval or variadic
3097 // argument, as they will be allocated a stack slot below the CFA (Canonical
3098 // Frame Address, the stack pointer at entry to the function).
3099 unsigned ArgRegBegin = ARM::R4;
3100 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3101 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3104 CCValAssign &VA = ArgLocs[i];
3105 unsigned Index = VA.getValNo();
3106 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3107 if (!Flags.isByVal())
3110 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3111 unsigned RBegin, REnd;
3112 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3113 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3115 CCInfo.nextInRegsParam();
3117 CCInfo.rewindByValRegsInfo();
3119 int lastInsIndex = -1;
3120 if (isVarArg && MFI->hasVAStart()) {
3121 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3122 if (RegIdx != array_lengthof(GPRArgRegs))
3123 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3126 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3127 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3128 auto PtrVT = getPointerTy(DAG.getDataLayout());
3130 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3131 CCValAssign &VA = ArgLocs[i];
3132 if (Ins[VA.getValNo()].isOrigArg()) {
3133 std::advance(CurOrigArg,
3134 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3135 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3137 // Arguments stored in registers.
3138 if (VA.isRegLoc()) {
3139 EVT RegVT = VA.getLocVT();
3141 if (VA.needsCustom()) {
3142 // f64 and vector types are split up into multiple registers or
3143 // combinations of registers and stack slots.
3144 if (VA.getLocVT() == MVT::v2f64) {
3145 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3147 VA = ArgLocs[++i]; // skip ahead to next loc
3149 if (VA.isMemLoc()) {
3150 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3151 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3152 ArgValue2 = DAG.getLoad(
3153 MVT::f64, dl, Chain, FIN,
3154 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3155 false, false, false, 0);
3157 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3160 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3161 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3162 ArgValue, ArgValue1,
3163 DAG.getIntPtrConstant(0, dl));
3164 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3165 ArgValue, ArgValue2,
3166 DAG.getIntPtrConstant(1, dl));
3168 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3171 const TargetRegisterClass *RC;
3173 if (RegVT == MVT::f32)
3174 RC = &ARM::SPRRegClass;
3175 else if (RegVT == MVT::f64)
3176 RC = &ARM::DPRRegClass;
3177 else if (RegVT == MVT::v2f64)
3178 RC = &ARM::QPRRegClass;
3179 else if (RegVT == MVT::i32)
3180 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3181 : &ARM::GPRRegClass;
3183 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3185 // Transform the arguments in physical registers into virtual ones.
3186 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3187 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3190 // If this is an 8 or 16-bit value, it is really passed promoted
3191 // to 32 bits. Insert an assert[sz]ext to capture this, then
3192 // truncate to the right size.
3193 switch (VA.getLocInfo()) {
3194 default: llvm_unreachable("Unknown loc info!");
3195 case CCValAssign::Full: break;
3196 case CCValAssign::BCvt:
3197 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3199 case CCValAssign::SExt:
3200 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3201 DAG.getValueType(VA.getValVT()));
3202 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3204 case CCValAssign::ZExt:
3205 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3206 DAG.getValueType(VA.getValVT()));
3207 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3211 InVals.push_back(ArgValue);
3213 } else { // VA.isRegLoc()
3216 assert(VA.isMemLoc());
3217 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3219 int index = VA.getValNo();
3221 // Some Ins[] entries become multiple ArgLoc[] entries.
3222 // Process them only once.
3223 if (index != lastInsIndex)
3225 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3226 // FIXME: For now, all byval parameter objects are marked mutable.
3227 // This can be changed with more analysis.
3228 // In case of tail call optimization mark all arguments mutable.
3229 // Since they could be overwritten by lowering of arguments in case of
3231 if (Flags.isByVal()) {
3232 assert(Ins[index].isOrigArg() &&
3233 "Byval arguments cannot be implicit");
3234 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3236 int FrameIndex = StoreByValRegs(
3237 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3238 VA.getLocMemOffset(), Flags.getByValSize());
3239 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3240 CCInfo.nextInRegsParam();
3242 unsigned FIOffset = VA.getLocMemOffset();
3243 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3246 // Create load nodes to retrieve arguments from the stack.
3247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3248 InVals.push_back(DAG.getLoad(
3249 VA.getValVT(), dl, Chain, FIN,
3250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3251 false, false, false, 0));
3253 lastInsIndex = index;
3259 if (isVarArg && MFI->hasVAStart())
3260 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3261 CCInfo.getNextStackOffset(),
3262 TotalArgRegsSaveSize);
3264 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3269 /// isFloatingPointZero - Return true if this is +0.0.
3270 static bool isFloatingPointZero(SDValue Op) {
3271 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3272 return CFP->getValueAPF().isPosZero();
3273 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3274 // Maybe this has already been legalized into the constant pool?
3275 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3276 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3277 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3278 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3279 return CFP->getValueAPF().isPosZero();
3281 } else if (Op->getOpcode() == ISD::BITCAST &&
3282 Op->getValueType(0) == MVT::f64) {
3283 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3284 // created by LowerConstantFP().
3285 SDValue BitcastOp = Op->getOperand(0);
3286 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3287 isNullConstant(BitcastOp->getOperand(0)))
3293 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3294 /// the given operands.
3296 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3297 SDValue &ARMcc, SelectionDAG &DAG,
3299 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3300 unsigned C = RHSC->getZExtValue();
3301 if (!isLegalICmpImmediate(C)) {
3302 // Constant does not fit, try adjusting it by one?
3307 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3308 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3309 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3314 if (C != 0 && isLegalICmpImmediate(C-1)) {
3315 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3316 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3321 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3322 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3323 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3328 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3329 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3330 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3337 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3338 ARMISD::NodeType CompareType;
3341 CompareType = ARMISD::CMP;
3346 CompareType = ARMISD::CMPZ;
3349 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3350 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3353 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3355 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3357 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3359 if (!isFloatingPointZero(RHS))
3360 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3362 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3363 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3366 /// duplicateCmp - Glue values can have only one use, so this function
3367 /// duplicates a comparison node.
3369 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3370 unsigned Opc = Cmp.getOpcode();
3372 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3373 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3375 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3376 Cmp = Cmp.getOperand(0);
3377 Opc = Cmp.getOpcode();
3378 if (Opc == ARMISD::CMPFP)
3379 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3381 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3382 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3384 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3387 std::pair<SDValue, SDValue>
3388 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3389 SDValue &ARMcc) const {
3390 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3392 SDValue Value, OverflowCmp;
3393 SDValue LHS = Op.getOperand(0);
3394 SDValue RHS = Op.getOperand(1);
3397 // FIXME: We are currently always generating CMPs because we don't support
3398 // generating CMN through the backend. This is not as good as the natural
3399 // CMP case because it causes a register dependency and cannot be folded
3402 switch (Op.getOpcode()) {
3404 llvm_unreachable("Unknown overflow instruction!");
3406 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3407 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3408 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3411 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3412 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3413 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3416 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3417 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3418 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3421 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3422 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3423 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3427 return std::make_pair(Value, OverflowCmp);
3432 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3433 // Let legalize expand this if it isn't a legal type yet.
3434 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3437 SDValue Value, OverflowCmp;
3439 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3440 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3442 // We use 0 and 1 as false and true values.
3443 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3444 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3445 EVT VT = Op.getValueType();
3447 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3448 ARMcc, CCR, OverflowCmp);
3450 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3451 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3455 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3456 SDValue Cond = Op.getOperand(0);
3457 SDValue SelectTrue = Op.getOperand(1);
3458 SDValue SelectFalse = Op.getOperand(2);
3460 unsigned Opc = Cond.getOpcode();
3462 if (Cond.getResNo() == 1 &&
3463 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3464 Opc == ISD::USUBO)) {
3465 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3468 SDValue Value, OverflowCmp;
3470 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3471 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3472 EVT VT = Op.getValueType();
3474 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3480 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3481 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3483 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3484 const ConstantSDNode *CMOVTrue =
3485 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3486 const ConstantSDNode *CMOVFalse =
3487 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3489 if (CMOVTrue && CMOVFalse) {
3490 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3491 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3495 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3497 False = SelectFalse;
3498 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3503 if (True.getNode() && False.getNode()) {
3504 EVT VT = Op.getValueType();
3505 SDValue ARMcc = Cond.getOperand(2);
3506 SDValue CCR = Cond.getOperand(3);
3507 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3508 assert(True.getValueType() == VT);
3509 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3514 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3515 // undefined bits before doing a full-word comparison with zero.
3516 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3517 DAG.getConstant(1, dl, Cond.getValueType()));
3519 return DAG.getSelectCC(dl, Cond,
3520 DAG.getConstant(0, dl, Cond.getValueType()),
3521 SelectTrue, SelectFalse, ISD::SETNE);
3524 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3525 bool &swpCmpOps, bool &swpVselOps) {
3526 // Start by selecting the GE condition code for opcodes that return true for
3528 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3530 CondCode = ARMCC::GE;
3532 // and GT for opcodes that return false for 'equality'.
3533 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3535 CondCode = ARMCC::GT;
3537 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3538 // to swap the compare operands.
3539 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3543 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3544 // If we have an unordered opcode, we need to swap the operands to the VSEL
3545 // instruction (effectively negating the condition).
3547 // This also has the effect of swapping which one of 'less' or 'greater'
3548 // returns true, so we also swap the compare operands. It also switches
3549 // whether we return true for 'equality', so we compensate by picking the
3550 // opposite condition code to our original choice.
3551 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3552 CC == ISD::SETUGT) {
3553 swpCmpOps = !swpCmpOps;
3554 swpVselOps = !swpVselOps;
3555 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3558 // 'ordered' is 'anything but unordered', so use the VS condition code and
3559 // swap the VSEL operands.
3560 if (CC == ISD::SETO) {
3561 CondCode = ARMCC::VS;
3565 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3566 // code and swap the VSEL operands.
3567 if (CC == ISD::SETUNE) {
3568 CondCode = ARMCC::EQ;
3573 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3574 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3575 SDValue Cmp, SelectionDAG &DAG) const {
3576 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3577 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3578 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3579 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3580 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3582 SDValue TrueLow = TrueVal.getValue(0);
3583 SDValue TrueHigh = TrueVal.getValue(1);
3584 SDValue FalseLow = FalseVal.getValue(0);
3585 SDValue FalseHigh = FalseVal.getValue(1);
3587 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3589 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3590 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3592 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3594 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3599 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3600 EVT VT = Op.getValueType();
3601 SDValue LHS = Op.getOperand(0);
3602 SDValue RHS = Op.getOperand(1);
3603 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3604 SDValue TrueVal = Op.getOperand(2);
3605 SDValue FalseVal = Op.getOperand(3);
3608 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3609 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3612 // If softenSetCCOperands only returned one value, we should compare it to
3614 if (!RHS.getNode()) {
3615 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3620 if (LHS.getValueType() == MVT::i32) {
3621 // Try to generate VSEL on ARMv8.
3622 // The VSEL instruction can't use all the usual ARM condition
3623 // codes: it only has two bits to select the condition code, so it's
3624 // constrained to use only GE, GT, VS and EQ.
3626 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3627 // swap the operands of the previous compare instruction (effectively
3628 // inverting the compare condition, swapping 'less' and 'greater') and
3629 // sometimes need to swap the operands to the VSEL (which inverts the
3630 // condition in the sense of firing whenever the previous condition didn't)
3631 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3632 TrueVal.getValueType() == MVT::f64)) {
3633 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3634 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3635 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3636 CC = ISD::getSetCCInverse(CC, true);
3637 std::swap(TrueVal, FalseVal);
3642 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3643 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3644 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3647 ARMCC::CondCodes CondCode, CondCode2;
3648 FPCCToARMCC(CC, CondCode, CondCode2);
3650 // Try to generate VMAXNM/VMINNM on ARMv8.
3651 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3652 TrueVal.getValueType() == MVT::f64)) {
3653 bool swpCmpOps = false;
3654 bool swpVselOps = false;
3655 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3657 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3658 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3660 std::swap(LHS, RHS);
3662 std::swap(TrueVal, FalseVal);
3666 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3667 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3668 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3669 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3670 if (CondCode2 != ARMCC::AL) {
3671 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3672 // FIXME: Needs another CMP because flag can have but one use.
3673 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3674 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3679 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3680 /// to morph to an integer compare sequence.
3681 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3682 const ARMSubtarget *Subtarget) {
3683 SDNode *N = Op.getNode();
3684 if (!N->hasOneUse())
3685 // Otherwise it requires moving the value from fp to integer registers.
3687 if (!N->getNumValues())
3689 EVT VT = Op.getValueType();
3690 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3691 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3692 // vmrs are very slow, e.g. cortex-a8.
3695 if (isFloatingPointZero(Op)) {
3699 return ISD::isNormalLoad(N);
3702 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3703 if (isFloatingPointZero(Op))
3704 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3706 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3707 return DAG.getLoad(MVT::i32, SDLoc(Op),
3708 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3709 Ld->isVolatile(), Ld->isNonTemporal(),
3710 Ld->isInvariant(), Ld->getAlignment());
3712 llvm_unreachable("Unknown VFP cmp argument!");
3715 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3716 SDValue &RetVal1, SDValue &RetVal2) {
3719 if (isFloatingPointZero(Op)) {
3720 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3721 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3725 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3726 SDValue Ptr = Ld->getBasePtr();
3727 RetVal1 = DAG.getLoad(MVT::i32, dl,
3728 Ld->getChain(), Ptr,
3729 Ld->getPointerInfo(),
3730 Ld->isVolatile(), Ld->isNonTemporal(),
3731 Ld->isInvariant(), Ld->getAlignment());
3733 EVT PtrType = Ptr.getValueType();
3734 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3735 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3736 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3737 RetVal2 = DAG.getLoad(MVT::i32, dl,
3738 Ld->getChain(), NewPtr,
3739 Ld->getPointerInfo().getWithOffset(4),
3740 Ld->isVolatile(), Ld->isNonTemporal(),
3741 Ld->isInvariant(), NewAlign);
3745 llvm_unreachable("Unknown VFP cmp argument!");
3748 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3749 /// f32 and even f64 comparisons to integer ones.
3751 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3752 SDValue Chain = Op.getOperand(0);
3753 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3754 SDValue LHS = Op.getOperand(2);
3755 SDValue RHS = Op.getOperand(3);
3756 SDValue Dest = Op.getOperand(4);
3759 bool LHSSeenZero = false;
3760 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3761 bool RHSSeenZero = false;
3762 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3763 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3764 // If unsafe fp math optimization is enabled and there are no other uses of
3765 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3766 // to an integer comparison.
3767 if (CC == ISD::SETOEQ)
3769 else if (CC == ISD::SETUNE)
3772 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3774 if (LHS.getValueType() == MVT::f32) {
3775 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3776 bitcastf32Toi32(LHS, DAG), Mask);
3777 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3778 bitcastf32Toi32(RHS, DAG), Mask);
3779 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3780 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3781 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3782 Chain, Dest, ARMcc, CCR, Cmp);
3787 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3788 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3789 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3790 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3791 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3792 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3793 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3794 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3795 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3801 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3802 SDValue Chain = Op.getOperand(0);
3803 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3804 SDValue LHS = Op.getOperand(2);
3805 SDValue RHS = Op.getOperand(3);
3806 SDValue Dest = Op.getOperand(4);
3809 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3810 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3813 // If softenSetCCOperands only returned one value, we should compare it to
3815 if (!RHS.getNode()) {
3816 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3821 if (LHS.getValueType() == MVT::i32) {
3823 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3824 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3825 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3826 Chain, Dest, ARMcc, CCR, Cmp);
3829 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3831 if (getTargetMachine().Options.UnsafeFPMath &&
3832 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3833 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3834 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3835 if (Result.getNode())
3839 ARMCC::CondCodes CondCode, CondCode2;
3840 FPCCToARMCC(CC, CondCode, CondCode2);
3842 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3843 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3844 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3845 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3846 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3847 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3848 if (CondCode2 != ARMCC::AL) {
3849 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3850 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3851 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3856 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3857 SDValue Chain = Op.getOperand(0);
3858 SDValue Table = Op.getOperand(1);
3859 SDValue Index = Op.getOperand(2);
3862 EVT PTy = getPointerTy(DAG.getDataLayout());
3863 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3864 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3865 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3866 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3867 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3868 if (Subtarget->isThumb2()) {
3869 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3870 // which does another jump to the destination. This also makes it easier
3871 // to translate it to TBB / TBH later.
3872 // FIXME: This might not work if the function is extremely large.
3873 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3874 Addr, Op.getOperand(2), JTI);
3876 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3878 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3879 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3880 false, false, false, 0);
3881 Chain = Addr.getValue(1);
3882 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3883 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3886 DAG.getLoad(PTy, dl, Chain, Addr,
3887 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3888 false, false, false, 0);
3889 Chain = Addr.getValue(1);
3890 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3894 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3895 EVT VT = Op.getValueType();
3898 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3899 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3901 return DAG.UnrollVectorOp(Op.getNode());
3904 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3905 "Invalid type for custom lowering!");
3906 if (VT != MVT::v4i16)
3907 return DAG.UnrollVectorOp(Op.getNode());
3909 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3910 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3913 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3914 EVT VT = Op.getValueType();
3916 return LowerVectorFP_TO_INT(Op, DAG);
3917 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3919 if (Op.getOpcode() == ISD::FP_TO_SINT)
3920 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3923 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3925 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3926 /*isSigned*/ false, SDLoc(Op)).first;
3932 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3933 EVT VT = Op.getValueType();
3936 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3937 if (VT.getVectorElementType() == MVT::f32)
3939 return DAG.UnrollVectorOp(Op.getNode());
3942 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3943 "Invalid type for custom lowering!");
3944 if (VT != MVT::v4f32)
3945 return DAG.UnrollVectorOp(Op.getNode());
3949 switch (Op.getOpcode()) {
3950 default: llvm_unreachable("Invalid opcode!");
3951 case ISD::SINT_TO_FP:
3952 CastOpc = ISD::SIGN_EXTEND;
3953 Opc = ISD::SINT_TO_FP;
3955 case ISD::UINT_TO_FP:
3956 CastOpc = ISD::ZERO_EXTEND;
3957 Opc = ISD::UINT_TO_FP;
3961 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3962 return DAG.getNode(Opc, dl, VT, Op);
3965 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3966 EVT VT = Op.getValueType();
3968 return LowerVectorINT_TO_FP(Op, DAG);
3969 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3971 if (Op.getOpcode() == ISD::SINT_TO_FP)
3972 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3975 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3977 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3978 /*isSigned*/ false, SDLoc(Op)).first;
3984 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3985 // Implement fcopysign with a fabs and a conditional fneg.
3986 SDValue Tmp0 = Op.getOperand(0);
3987 SDValue Tmp1 = Op.getOperand(1);
3989 EVT VT = Op.getValueType();
3990 EVT SrcVT = Tmp1.getValueType();
3991 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3992 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3993 bool UseNEON = !InGPR && Subtarget->hasNEON();
3996 // Use VBSL to copy the sign bit.
3997 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3998 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3999 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4000 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4002 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4003 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4004 DAG.getConstant(32, dl, MVT::i32));
4005 else /*if (VT == MVT::f32)*/
4006 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4007 if (SrcVT == MVT::f32) {
4008 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4010 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4011 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4012 DAG.getConstant(32, dl, MVT::i32));
4013 } else if (VT == MVT::f32)
4014 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4015 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4016 DAG.getConstant(32, dl, MVT::i32));
4017 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4018 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4020 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4022 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4023 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4024 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4026 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4027 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4028 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4029 if (VT == MVT::f32) {
4030 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4031 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4032 DAG.getConstant(0, dl, MVT::i32));
4034 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4040 // Bitcast operand 1 to i32.
4041 if (SrcVT == MVT::f64)
4042 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4044 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4046 // Or in the signbit with integer operations.
4047 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4048 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4049 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4050 if (VT == MVT::f32) {
4051 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4052 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4053 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4054 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4057 // f64: Or the high part with signbit and then combine two parts.
4058 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4060 SDValue Lo = Tmp0.getValue(0);
4061 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4062 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4063 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4066 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4067 MachineFunction &MF = DAG.getMachineFunction();
4068 MachineFrameInfo *MFI = MF.getFrameInfo();
4069 MFI->setReturnAddressIsTaken(true);
4071 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4074 EVT VT = Op.getValueType();
4076 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4078 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4079 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4080 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4081 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4082 MachinePointerInfo(), false, false, false, 0);
4085 // Return LR, which contains the return address. Mark it an implicit live-in.
4086 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4087 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4090 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4091 const ARMBaseRegisterInfo &ARI =
4092 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4093 MachineFunction &MF = DAG.getMachineFunction();
4094 MachineFrameInfo *MFI = MF.getFrameInfo();
4095 MFI->setFrameAddressIsTaken(true);
4097 EVT VT = Op.getValueType();
4098 SDLoc dl(Op); // FIXME probably not meaningful
4099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4100 unsigned FrameReg = ARI.getFrameRegister(MF);
4101 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4103 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4104 MachinePointerInfo(),
4105 false, false, false, 0);
4109 // FIXME? Maybe this could be a TableGen attribute on some registers and
4110 // this table could be generated automatically from RegInfo.
4111 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4112 SelectionDAG &DAG) const {
4113 unsigned Reg = StringSwitch<unsigned>(RegName)
4114 .Case("sp", ARM::SP)
4118 report_fatal_error(Twine("Invalid register name \""
4119 + StringRef(RegName) + "\"."));
4122 // Result is 64 bit value so split into two 32 bit values and return as a
4124 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4125 SelectionDAG &DAG) {
4128 // This function is only supposed to be called for i64 type destination.
4129 assert(N->getValueType(0) == MVT::i64
4130 && "ExpandREAD_REGISTER called for non-i64 type result.");
4132 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4133 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4137 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4139 Results.push_back(Read.getOperand(0));
4142 /// ExpandBITCAST - If the target supports VFP, this function is called to
4143 /// expand a bit convert where either the source or destination type is i64 to
4144 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4145 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4146 /// vectors), since the legalizer won't know what to do with that.
4147 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4148 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4150 SDValue Op = N->getOperand(0);
4152 // This function is only supposed to be called for i64 types, either as the
4153 // source or destination of the bit convert.
4154 EVT SrcVT = Op.getValueType();
4155 EVT DstVT = N->getValueType(0);
4156 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4157 "ExpandBITCAST called for non-i64 type");
4159 // Turn i64->f64 into VMOVDRR.
4160 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4161 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4162 DAG.getConstant(0, dl, MVT::i32));
4163 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4164 DAG.getConstant(1, dl, MVT::i32));
4165 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4166 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4169 // Turn f64->i64 into VMOVRRD.
4170 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4172 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4173 SrcVT.getVectorNumElements() > 1)
4174 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4175 DAG.getVTList(MVT::i32, MVT::i32),
4176 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4178 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4179 DAG.getVTList(MVT::i32, MVT::i32), Op);
4180 // Merge the pieces into a single i64 value.
4181 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4187 /// getZeroVector - Returns a vector of specified type with all zero elements.
4188 /// Zero vectors are used to represent vector negation and in those cases
4189 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4190 /// not support i64 elements, so sometimes the zero vectors will need to be
4191 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4193 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4194 assert(VT.isVector() && "Expected a vector type");
4195 // The canonical modified immediate encoding of a zero vector is....0!
4196 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4197 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4198 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4199 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4202 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4203 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4204 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4205 SelectionDAG &DAG) const {
4206 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4207 EVT VT = Op.getValueType();
4208 unsigned VTBits = VT.getSizeInBits();
4210 SDValue ShOpLo = Op.getOperand(0);
4211 SDValue ShOpHi = Op.getOperand(1);
4212 SDValue ShAmt = Op.getOperand(2);
4214 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4216 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4218 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4219 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4220 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4221 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4222 DAG.getConstant(VTBits, dl, MVT::i32));
4223 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4224 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4225 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4227 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4228 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4229 ISD::SETGE, ARMcc, DAG, dl);
4230 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4231 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4234 SDValue Ops[2] = { Lo, Hi };
4235 return DAG.getMergeValues(Ops, dl);
4238 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4239 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4240 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4241 SelectionDAG &DAG) const {
4242 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4243 EVT VT = Op.getValueType();
4244 unsigned VTBits = VT.getSizeInBits();
4246 SDValue ShOpLo = Op.getOperand(0);
4247 SDValue ShOpHi = Op.getOperand(1);
4248 SDValue ShAmt = Op.getOperand(2);
4251 assert(Op.getOpcode() == ISD::SHL_PARTS);
4252 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4253 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4254 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4255 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4256 DAG.getConstant(VTBits, dl, MVT::i32));
4257 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4258 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4260 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4261 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4262 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4263 ISD::SETGE, ARMcc, DAG, dl);
4264 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4265 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4268 SDValue Ops[2] = { Lo, Hi };
4269 return DAG.getMergeValues(Ops, dl);
4272 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4273 SelectionDAG &DAG) const {
4274 // The rounding mode is in bits 23:22 of the FPSCR.
4275 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4276 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4277 // so that the shift + and get folded into a bitfield extract.
4279 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4280 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4282 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4283 DAG.getConstant(1U << 22, dl, MVT::i32));
4284 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4285 DAG.getConstant(22, dl, MVT::i32));
4286 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4287 DAG.getConstant(3, dl, MVT::i32));
4290 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4291 const ARMSubtarget *ST) {
4293 EVT VT = N->getValueType(0);
4294 if (VT.isVector()) {
4295 assert(ST->hasNEON());
4297 // Compute the least significant set bit: LSB = X & -X
4298 SDValue X = N->getOperand(0);
4299 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4300 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4302 EVT ElemTy = VT.getVectorElementType();
4304 if (ElemTy == MVT::i8) {
4305 // Compute with: cttz(x) = ctpop(lsb - 1)
4306 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4307 DAG.getTargetConstant(1, dl, ElemTy));
4308 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4309 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4312 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4313 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4314 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4315 unsigned NumBits = ElemTy.getSizeInBits();
4316 SDValue WidthMinus1 =
4317 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4318 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4319 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4320 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4323 // Compute with: cttz(x) = ctpop(lsb - 1)
4325 // Since we can only compute the number of bits in a byte with vcnt.8, we
4326 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4331 if (ElemTy == MVT::i64) {
4332 // Load constant 0xffff'ffff'ffff'ffff to register.
4333 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4334 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4335 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4337 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4338 DAG.getTargetConstant(1, dl, ElemTy));
4339 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4342 // Count #bits with vcnt.8.
4343 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4344 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4345 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4347 // Gather the #bits with vpaddl (pairwise add.)
4348 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4349 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4350 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4352 if (ElemTy == MVT::i16)
4355 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4356 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4357 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4359 if (ElemTy == MVT::i32)
4362 assert(ElemTy == MVT::i64);
4363 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4364 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4369 if (!ST->hasV6T2Ops())
4372 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4373 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4376 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4377 /// for each 16-bit element from operand, repeated. The basic idea is to
4378 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4380 /// Trace for v4i16:
4381 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4382 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4383 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4384 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4385 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4386 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4387 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4388 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4389 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4390 EVT VT = N->getValueType(0);
4393 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4394 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4395 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4396 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4397 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4398 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4401 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4402 /// bit-count for each 16-bit element from the operand. We need slightly
4403 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4404 /// 64/128-bit registers.
4406 /// Trace for v4i16:
4407 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4408 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4409 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4410 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4411 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4412 EVT VT = N->getValueType(0);
4415 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4416 if (VT.is64BitVector()) {
4417 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4418 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4419 DAG.getIntPtrConstant(0, DL));
4421 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4422 BitCounts, DAG.getIntPtrConstant(0, DL));
4423 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4427 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4428 /// bit-count for each 32-bit element from the operand. The idea here is
4429 /// to split the vector into 16-bit elements, leverage the 16-bit count
4430 /// routine, and then combine the results.
4432 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4433 /// input = [v0 v1 ] (vi: 32-bit elements)
4434 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4435 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4436 /// vrev: N0 = [k1 k0 k3 k2 ]
4438 /// N1 =+[k1 k0 k3 k2 ]
4440 /// N2 =+[k1 k3 k0 k2 ]
4442 /// Extended =+[k1 k3 k0 k2 ]
4444 /// Extracted=+[k1 k3 ]
4446 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4447 EVT VT = N->getValueType(0);
4450 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4452 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4453 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4454 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4455 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4456 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4458 if (VT.is64BitVector()) {
4459 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4460 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4461 DAG.getIntPtrConstant(0, DL));
4463 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4464 DAG.getIntPtrConstant(0, DL));
4465 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4469 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4470 const ARMSubtarget *ST) {
4471 EVT VT = N->getValueType(0);
4473 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4474 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4475 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4476 "Unexpected type for custom ctpop lowering");
4478 if (VT.getVectorElementType() == MVT::i32)
4479 return lowerCTPOP32BitElements(N, DAG);
4481 return lowerCTPOP16BitElements(N, DAG);
4484 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4485 const ARMSubtarget *ST) {
4486 EVT VT = N->getValueType(0);
4492 // Lower vector shifts on NEON to use VSHL.
4493 assert(ST->hasNEON() && "unexpected vector shift");
4495 // Left shifts translate directly to the vshiftu intrinsic.
4496 if (N->getOpcode() == ISD::SHL)
4497 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4498 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4500 N->getOperand(0), N->getOperand(1));
4502 assert((N->getOpcode() == ISD::SRA ||
4503 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4505 // NEON uses the same intrinsics for both left and right shifts. For
4506 // right shifts, the shift amounts are negative, so negate the vector of
4508 EVT ShiftVT = N->getOperand(1).getValueType();
4509 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4510 getZeroVector(ShiftVT, DAG, dl),
4512 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4513 Intrinsic::arm_neon_vshifts :
4514 Intrinsic::arm_neon_vshiftu);
4515 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4516 DAG.getConstant(vshiftInt, dl, MVT::i32),
4517 N->getOperand(0), NegatedCount);
4520 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4521 const ARMSubtarget *ST) {
4522 EVT VT = N->getValueType(0);
4525 // We can get here for a node like i32 = ISD::SHL i32, i64
4529 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4530 "Unknown shift to lower!");
4532 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4533 if (!isOneConstant(N->getOperand(1)))
4536 // If we are in thumb mode, we don't have RRX.
4537 if (ST->isThumb1Only()) return SDValue();
4539 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4540 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4541 DAG.getConstant(0, dl, MVT::i32));
4542 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4543 DAG.getConstant(1, dl, MVT::i32));
4545 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4546 // captures the result into a carry flag.
4547 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4548 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4550 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4551 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4553 // Merge the pieces into a single i64 value.
4554 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4557 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4558 SDValue TmpOp0, TmpOp1;
4559 bool Invert = false;
4563 SDValue Op0 = Op.getOperand(0);
4564 SDValue Op1 = Op.getOperand(1);
4565 SDValue CC = Op.getOperand(2);
4566 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4567 EVT VT = Op.getValueType();
4568 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4571 if (CmpVT.getVectorElementType() == MVT::i64)
4572 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4573 // but it's possible that our operands are 64-bit but our result is 32-bit.
4574 // Bail in this case.
4577 if (Op1.getValueType().isFloatingPoint()) {
4578 switch (SetCCOpcode) {
4579 default: llvm_unreachable("Illegal FP comparison");
4581 case ISD::SETNE: Invert = true; // Fallthrough
4583 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4585 case ISD::SETLT: Swap = true; // Fallthrough
4587 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4589 case ISD::SETLE: Swap = true; // Fallthrough
4591 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4592 case ISD::SETUGE: Swap = true; // Fallthrough
4593 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4594 case ISD::SETUGT: Swap = true; // Fallthrough
4595 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4596 case ISD::SETUEQ: Invert = true; // Fallthrough
4598 // Expand this to (OLT | OGT).
4602 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4603 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4605 case ISD::SETUO: Invert = true; // Fallthrough
4607 // Expand this to (OLT | OGE).
4611 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4612 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4616 // Integer comparisons.
4617 switch (SetCCOpcode) {
4618 default: llvm_unreachable("Illegal integer comparison");
4619 case ISD::SETNE: Invert = true;
4620 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4621 case ISD::SETLT: Swap = true;
4622 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4623 case ISD::SETLE: Swap = true;
4624 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4625 case ISD::SETULT: Swap = true;
4626 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4627 case ISD::SETULE: Swap = true;
4628 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4631 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4632 if (Opc == ARMISD::VCEQ) {
4635 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4637 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4640 // Ignore bitconvert.
4641 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4642 AndOp = AndOp.getOperand(0);
4644 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4646 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4647 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4654 std::swap(Op0, Op1);
4656 // If one of the operands is a constant vector zero, attempt to fold the
4657 // comparison to a specialized compare-against-zero form.
4659 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4661 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4662 if (Opc == ARMISD::VCGE)
4663 Opc = ARMISD::VCLEZ;
4664 else if (Opc == ARMISD::VCGT)
4665 Opc = ARMISD::VCLTZ;
4670 if (SingleOp.getNode()) {
4673 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4675 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4677 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4679 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4681 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4683 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4686 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4689 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4692 Result = DAG.getNOT(dl, Result, VT);
4697 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4698 /// valid vector constant for a NEON instruction with a "modified immediate"
4699 /// operand (e.g., VMOV). If so, return the encoded value.
4700 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4701 unsigned SplatBitSize, SelectionDAG &DAG,
4702 SDLoc dl, EVT &VT, bool is128Bits,
4703 NEONModImmType type) {
4704 unsigned OpCmode, Imm;
4706 // SplatBitSize is set to the smallest size that splats the vector, so a
4707 // zero vector will always have SplatBitSize == 8. However, NEON modified
4708 // immediate instructions others than VMOV do not support the 8-bit encoding
4709 // of a zero vector, and the default encoding of zero is supposed to be the
4714 switch (SplatBitSize) {
4716 if (type != VMOVModImm)
4718 // Any 1-byte value is OK. Op=0, Cmode=1110.
4719 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4722 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4726 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4727 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4728 if ((SplatBits & ~0xff) == 0) {
4729 // Value = 0x00nn: Op=x, Cmode=100x.
4734 if ((SplatBits & ~0xff00) == 0) {
4735 // Value = 0xnn00: Op=x, Cmode=101x.
4737 Imm = SplatBits >> 8;
4743 // NEON's 32-bit VMOV supports splat values where:
4744 // * only one byte is nonzero, or
4745 // * the least significant byte is 0xff and the second byte is nonzero, or
4746 // * the least significant 2 bytes are 0xff and the third is nonzero.
4747 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4748 if ((SplatBits & ~0xff) == 0) {
4749 // Value = 0x000000nn: Op=x, Cmode=000x.
4754 if ((SplatBits & ~0xff00) == 0) {
4755 // Value = 0x0000nn00: Op=x, Cmode=001x.
4757 Imm = SplatBits >> 8;
4760 if ((SplatBits & ~0xff0000) == 0) {
4761 // Value = 0x00nn0000: Op=x, Cmode=010x.
4763 Imm = SplatBits >> 16;
4766 if ((SplatBits & ~0xff000000) == 0) {
4767 // Value = 0xnn000000: Op=x, Cmode=011x.
4769 Imm = SplatBits >> 24;
4773 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4774 if (type == OtherModImm) return SDValue();
4776 if ((SplatBits & ~0xffff) == 0 &&
4777 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4778 // Value = 0x0000nnff: Op=x, Cmode=1100.
4780 Imm = SplatBits >> 8;
4784 if ((SplatBits & ~0xffffff) == 0 &&
4785 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4786 // Value = 0x00nnffff: Op=x, Cmode=1101.
4788 Imm = SplatBits >> 16;
4792 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4793 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4794 // VMOV.I32. A (very) minor optimization would be to replicate the value
4795 // and fall through here to test for a valid 64-bit splat. But, then the
4796 // caller would also need to check and handle the change in size.
4800 if (type != VMOVModImm)
4802 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4803 uint64_t BitMask = 0xff;
4805 unsigned ImmMask = 1;
4807 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4808 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4811 } else if ((SplatBits & BitMask) != 0) {
4818 if (DAG.getDataLayout().isBigEndian())
4819 // swap higher and lower 32 bit word
4820 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4822 // Op=1, Cmode=1110.
4824 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4829 llvm_unreachable("unexpected size for isNEONModifiedImm");
4832 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4833 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4836 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4837 const ARMSubtarget *ST) const {
4841 bool IsDouble = Op.getValueType() == MVT::f64;
4842 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4844 // Use the default (constant pool) lowering for double constants when we have
4846 if (IsDouble && Subtarget->isFPOnlySP())
4849 // Try splatting with a VMOV.f32...
4850 APFloat FPVal = CFP->getValueAPF();
4851 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4854 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4855 // We have code in place to select a valid ConstantFP already, no need to
4860 // It's a float and we are trying to use NEON operations where
4861 // possible. Lower it to a splat followed by an extract.
4863 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4864 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4866 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4867 DAG.getConstant(0, DL, MVT::i32));
4870 // The rest of our options are NEON only, make sure that's allowed before
4872 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4876 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4878 // It wouldn't really be worth bothering for doubles except for one very
4879 // important value, which does happen to match: 0.0. So make sure we don't do
4881 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4884 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4885 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4886 VMovVT, false, VMOVModImm);
4887 if (NewVal != SDValue()) {
4889 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4892 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4894 // It's a float: cast and extract a vector element.
4895 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4897 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4898 DAG.getConstant(0, DL, MVT::i32));
4901 // Finally, try a VMVN.i32
4902 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4904 if (NewVal != SDValue()) {
4906 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4909 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4911 // It's a float: cast and extract a vector element.
4912 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4914 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4915 DAG.getConstant(0, DL, MVT::i32));
4921 // check if an VEXT instruction can handle the shuffle mask when the
4922 // vector sources of the shuffle are the same.
4923 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4924 unsigned NumElts = VT.getVectorNumElements();
4926 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4932 // If this is a VEXT shuffle, the immediate value is the index of the first
4933 // element. The other shuffle indices must be the successive elements after
4935 unsigned ExpectedElt = Imm;
4936 for (unsigned i = 1; i < NumElts; ++i) {
4937 // Increment the expected index. If it wraps around, just follow it
4938 // back to index zero and keep going.
4940 if (ExpectedElt == NumElts)
4943 if (M[i] < 0) continue; // ignore UNDEF indices
4944 if (ExpectedElt != static_cast<unsigned>(M[i]))
4952 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4953 bool &ReverseVEXT, unsigned &Imm) {
4954 unsigned NumElts = VT.getVectorNumElements();
4955 ReverseVEXT = false;
4957 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4963 // If this is a VEXT shuffle, the immediate value is the index of the first
4964 // element. The other shuffle indices must be the successive elements after
4966 unsigned ExpectedElt = Imm;
4967 for (unsigned i = 1; i < NumElts; ++i) {
4968 // Increment the expected index. If it wraps around, it may still be
4969 // a VEXT but the source vectors must be swapped.
4971 if (ExpectedElt == NumElts * 2) {
4976 if (M[i] < 0) continue; // ignore UNDEF indices
4977 if (ExpectedElt != static_cast<unsigned>(M[i]))
4981 // Adjust the index value if the source operands will be swapped.
4988 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4989 /// instruction with the specified blocksize. (The order of the elements
4990 /// within each block of the vector is reversed.)
4991 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4992 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4993 "Only possible block sizes for VREV are: 16, 32, 64");
4995 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4999 unsigned NumElts = VT.getVectorNumElements();
5000 unsigned BlockElts = M[0] + 1;
5001 // If the first shuffle index is UNDEF, be optimistic.
5003 BlockElts = BlockSize / EltSz;
5005 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5008 for (unsigned i = 0; i < NumElts; ++i) {
5009 if (M[i] < 0) continue; // ignore UNDEF indices
5010 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5017 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5018 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5019 // range, then 0 is placed into the resulting vector. So pretty much any mask
5020 // of 8 elements can work here.
5021 return VT == MVT::v8i8 && M.size() == 8;
5024 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5025 // checking that pairs of elements in the shuffle mask represent the same index
5026 // in each vector, incrementing the expected index by 2 at each step.
5027 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5028 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5030 // WhichResult gives the offset for each element in the mask based on which
5031 // of the two results it belongs to.
5033 // The transpose can be represented either as:
5034 // result1 = shufflevector v1, v2, result1_shuffle_mask
5035 // result2 = shufflevector v1, v2, result2_shuffle_mask
5036 // where v1/v2 and the shuffle masks have the same number of elements
5037 // (here WhichResult (see below) indicates which result is being checked)
5040 // results = shufflevector v1, v2, shuffle_mask
5041 // where both results are returned in one vector and the shuffle mask has twice
5042 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5043 // want to check the low half and high half of the shuffle mask as if it were
5045 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5046 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5050 unsigned NumElts = VT.getVectorNumElements();
5051 if (M.size() != NumElts && M.size() != NumElts*2)
5054 // If the mask is twice as long as the input vector then we need to check the
5055 // upper and lower parts of the mask with a matching value for WhichResult
5056 // FIXME: A mask with only even values will be rejected in case the first
5057 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5058 // M[0] is used to determine WhichResult
5059 for (unsigned i = 0; i < M.size(); i += NumElts) {
5060 if (M.size() == NumElts * 2)
5061 WhichResult = i / NumElts;
5063 WhichResult = M[i] == 0 ? 0 : 1;
5064 for (unsigned j = 0; j < NumElts; j += 2) {
5065 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5066 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5071 if (M.size() == NumElts*2)
5077 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5078 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5079 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5080 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5081 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5085 unsigned NumElts = VT.getVectorNumElements();
5086 if (M.size() != NumElts && M.size() != NumElts*2)
5089 for (unsigned i = 0; i < M.size(); i += NumElts) {
5090 if (M.size() == NumElts * 2)
5091 WhichResult = i / NumElts;
5093 WhichResult = M[i] == 0 ? 0 : 1;
5094 for (unsigned j = 0; j < NumElts; j += 2) {
5095 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5096 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5101 if (M.size() == NumElts*2)
5107 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5108 // that the mask elements are either all even and in steps of size 2 or all odd
5109 // and in steps of size 2.
5110 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5111 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5113 // Requires similar checks to that of isVTRNMask with
5114 // respect the how results are returned.
5115 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5116 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5120 unsigned NumElts = VT.getVectorNumElements();
5121 if (M.size() != NumElts && M.size() != NumElts*2)
5124 for (unsigned i = 0; i < M.size(); i += NumElts) {
5125 WhichResult = M[i] == 0 ? 0 : 1;
5126 for (unsigned j = 0; j < NumElts; ++j) {
5127 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5132 if (M.size() == NumElts*2)
5135 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5136 if (VT.is64BitVector() && EltSz == 32)
5142 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5143 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5144 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5145 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5146 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5150 unsigned NumElts = VT.getVectorNumElements();
5151 if (M.size() != NumElts && M.size() != NumElts*2)
5154 unsigned Half = NumElts / 2;
5155 for (unsigned i = 0; i < M.size(); i += NumElts) {
5156 WhichResult = M[i] == 0 ? 0 : 1;
5157 for (unsigned j = 0; j < NumElts; j += Half) {
5158 unsigned Idx = WhichResult;
5159 for (unsigned k = 0; k < Half; ++k) {
5160 int MIdx = M[i + j + k];
5161 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5168 if (M.size() == NumElts*2)
5171 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5172 if (VT.is64BitVector() && EltSz == 32)
5178 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5179 // that pairs of elements of the shufflemask represent the same index in each
5180 // vector incrementing sequentially through the vectors.
5181 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5182 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5184 // Requires similar checks to that of isVTRNMask with respect the how results
5186 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5187 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5191 unsigned NumElts = VT.getVectorNumElements();
5192 if (M.size() != NumElts && M.size() != NumElts*2)
5195 for (unsigned i = 0; i < M.size(); i += NumElts) {
5196 WhichResult = M[i] == 0 ? 0 : 1;
5197 unsigned Idx = WhichResult * NumElts / 2;
5198 for (unsigned j = 0; j < NumElts; j += 2) {
5199 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5200 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5206 if (M.size() == NumElts*2)
5209 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5210 if (VT.is64BitVector() && EltSz == 32)
5216 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5217 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5218 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5219 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5220 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5224 unsigned NumElts = VT.getVectorNumElements();
5225 if (M.size() != NumElts && M.size() != NumElts*2)
5228 for (unsigned i = 0; i < M.size(); i += NumElts) {
5229 WhichResult = M[i] == 0 ? 0 : 1;
5230 unsigned Idx = WhichResult * NumElts / 2;
5231 for (unsigned j = 0; j < NumElts; j += 2) {
5232 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5233 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5239 if (M.size() == NumElts*2)
5242 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5243 if (VT.is64BitVector() && EltSz == 32)
5249 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5250 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5251 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5252 unsigned &WhichResult,
5255 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5256 return ARMISD::VTRN;
5257 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5258 return ARMISD::VUZP;
5259 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5260 return ARMISD::VZIP;
5263 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5264 return ARMISD::VTRN;
5265 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5266 return ARMISD::VUZP;
5267 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5268 return ARMISD::VZIP;
5273 /// \return true if this is a reverse operation on an vector.
5274 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5275 unsigned NumElts = VT.getVectorNumElements();
5276 // Make sure the mask has the right size.
5277 if (NumElts != M.size())
5280 // Look for <15, ..., 3, -1, 1, 0>.
5281 for (unsigned i = 0; i != NumElts; ++i)
5282 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5288 // If N is an integer constant that can be moved into a register in one
5289 // instruction, return an SDValue of such a constant (will become a MOV
5290 // instruction). Otherwise return null.
5291 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5292 const ARMSubtarget *ST, SDLoc dl) {
5294 if (!isa<ConstantSDNode>(N))
5296 Val = cast<ConstantSDNode>(N)->getZExtValue();
5298 if (ST->isThumb1Only()) {
5299 if (Val <= 255 || ~Val <= 255)
5300 return DAG.getConstant(Val, dl, MVT::i32);
5302 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5303 return DAG.getConstant(Val, dl, MVT::i32);
5308 // If this is a case we can't handle, return null and let the default
5309 // expansion code take care of it.
5310 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5311 const ARMSubtarget *ST) const {
5312 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5314 EVT VT = Op.getValueType();
5316 APInt SplatBits, SplatUndef;
5317 unsigned SplatBitSize;
5319 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5320 if (SplatBitSize <= 64) {
5321 // Check if an immediate VMOV works.
5323 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5324 SplatUndef.getZExtValue(), SplatBitSize,
5325 DAG, dl, VmovVT, VT.is128BitVector(),
5327 if (Val.getNode()) {
5328 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5329 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5332 // Try an immediate VMVN.
5333 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5334 Val = isNEONModifiedImm(NegatedImm,
5335 SplatUndef.getZExtValue(), SplatBitSize,
5336 DAG, dl, VmovVT, VT.is128BitVector(),
5338 if (Val.getNode()) {
5339 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5340 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5343 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5344 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5345 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5347 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5348 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5354 // Scan through the operands to see if only one value is used.
5356 // As an optimisation, even if more than one value is used it may be more
5357 // profitable to splat with one value then change some lanes.
5359 // Heuristically we decide to do this if the vector has a "dominant" value,
5360 // defined as splatted to more than half of the lanes.
5361 unsigned NumElts = VT.getVectorNumElements();
5362 bool isOnlyLowElement = true;
5363 bool usesOnlyOneValue = true;
5364 bool hasDominantValue = false;
5365 bool isConstant = true;
5367 // Map of the number of times a particular SDValue appears in the
5369 DenseMap<SDValue, unsigned> ValueCounts;
5371 for (unsigned i = 0; i < NumElts; ++i) {
5372 SDValue V = Op.getOperand(i);
5373 if (V.getOpcode() == ISD::UNDEF)
5376 isOnlyLowElement = false;
5377 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5380 ValueCounts.insert(std::make_pair(V, 0));
5381 unsigned &Count = ValueCounts[V];
5383 // Is this value dominant? (takes up more than half of the lanes)
5384 if (++Count > (NumElts / 2)) {
5385 hasDominantValue = true;
5389 if (ValueCounts.size() != 1)
5390 usesOnlyOneValue = false;
5391 if (!Value.getNode() && ValueCounts.size() > 0)
5392 Value = ValueCounts.begin()->first;
5394 if (ValueCounts.size() == 0)
5395 return DAG.getUNDEF(VT);
5397 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5398 // Keep going if we are hitting this case.
5399 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5400 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5402 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5404 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5405 // i32 and try again.
5406 if (hasDominantValue && EltSize <= 32) {
5410 // If we are VDUPing a value that comes directly from a vector, that will
5411 // cause an unnecessary move to and from a GPR, where instead we could
5412 // just use VDUPLANE. We can only do this if the lane being extracted
5413 // is at a constant index, as the VDUP from lane instructions only have
5414 // constant-index forms.
5415 ConstantSDNode *constIndex;
5416 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5417 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5418 // We need to create a new undef vector to use for the VDUPLANE if the
5419 // size of the vector from which we get the value is different than the
5420 // size of the vector that we need to create. We will insert the element
5421 // such that the register coalescer will remove unnecessary copies.
5422 if (VT != Value->getOperand(0).getValueType()) {
5423 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5424 VT.getVectorNumElements();
5425 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5426 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5427 Value, DAG.getConstant(index, dl, MVT::i32)),
5428 DAG.getConstant(index, dl, MVT::i32));
5430 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5431 Value->getOperand(0), Value->getOperand(1));
5433 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5435 if (!usesOnlyOneValue) {
5436 // The dominant value was splatted as 'N', but we now have to insert
5437 // all differing elements.
5438 for (unsigned I = 0; I < NumElts; ++I) {
5439 if (Op.getOperand(I) == Value)
5441 SmallVector<SDValue, 3> Ops;
5443 Ops.push_back(Op.getOperand(I));
5444 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5445 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5450 if (VT.getVectorElementType().isFloatingPoint()) {
5451 SmallVector<SDValue, 8> Ops;
5452 for (unsigned i = 0; i < NumElts; ++i)
5453 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5455 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5456 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5457 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5459 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5461 if (usesOnlyOneValue) {
5462 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5463 if (isConstant && Val.getNode())
5464 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5468 // If all elements are constants and the case above didn't get hit, fall back
5469 // to the default expansion, which will generate a load from the constant
5474 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5476 SDValue shuffle = ReconstructShuffle(Op, DAG);
5477 if (shuffle != SDValue())
5481 // Vectors with 32- or 64-bit elements can be built by directly assigning
5482 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5483 // will be legalized.
5484 if (EltSize >= 32) {
5485 // Do the expansion with floating-point types, since that is what the VFP
5486 // registers are defined to use, and since i64 is not legal.
5487 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5488 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5489 SmallVector<SDValue, 8> Ops;
5490 for (unsigned i = 0; i < NumElts; ++i)
5491 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5492 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5493 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5496 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5497 // know the default expansion would otherwise fall back on something even
5498 // worse. For a vector with one or two non-undef values, that's
5499 // scalar_to_vector for the elements followed by a shuffle (provided the
5500 // shuffle is valid for the target) and materialization element by element
5501 // on the stack followed by a load for everything else.
5502 if (!isConstant && !usesOnlyOneValue) {
5503 SDValue Vec = DAG.getUNDEF(VT);
5504 for (unsigned i = 0 ; i < NumElts; ++i) {
5505 SDValue V = Op.getOperand(i);
5506 if (V.getOpcode() == ISD::UNDEF)
5508 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5509 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5517 // Gather data to see if the operation can be modelled as a
5518 // shuffle in combination with VEXTs.
5519 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5520 SelectionDAG &DAG) const {
5521 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5523 EVT VT = Op.getValueType();
5524 unsigned NumElts = VT.getVectorNumElements();
5526 struct ShuffleSourceInfo {
5531 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5532 // be compatible with the shuffle we intend to construct. As a result
5533 // ShuffleVec will be some sliding window into the original Vec.
5536 // Code should guarantee that element i in Vec starts at element "WindowBase
5537 // + i * WindowScale in ShuffleVec".
5541 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5542 ShuffleSourceInfo(SDValue Vec)
5543 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5547 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5549 SmallVector<ShuffleSourceInfo, 2> Sources;
5550 for (unsigned i = 0; i < NumElts; ++i) {
5551 SDValue V = Op.getOperand(i);
5552 if (V.getOpcode() == ISD::UNDEF)
5554 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5555 // A shuffle can only come from building a vector from various
5556 // elements of other vectors.
5558 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5559 // Furthermore, shuffles require a constant mask, whereas extractelts
5560 // accept variable indices.
5564 // Add this element source to the list if it's not already there.
5565 SDValue SourceVec = V.getOperand(0);
5566 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5567 if (Source == Sources.end())
5568 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5570 // Update the minimum and maximum lane number seen.
5571 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5572 Source->MinElt = std::min(Source->MinElt, EltNo);
5573 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5576 // Currently only do something sane when at most two source vectors
5578 if (Sources.size() > 2)
5581 // Find out the smallest element size among result and two sources, and use
5582 // it as element size to build the shuffle_vector.
5583 EVT SmallestEltTy = VT.getVectorElementType();
5584 for (auto &Source : Sources) {
5585 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5586 if (SrcEltTy.bitsLT(SmallestEltTy))
5587 SmallestEltTy = SrcEltTy;
5589 unsigned ResMultiplier =
5590 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5591 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5592 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5594 // If the source vector is too wide or too narrow, we may nevertheless be able
5595 // to construct a compatible shuffle either by concatenating it with UNDEF or
5596 // extracting a suitable range of elements.
5597 for (auto &Src : Sources) {
5598 EVT SrcVT = Src.ShuffleVec.getValueType();
5600 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5603 // This stage of the search produces a source with the same element type as
5604 // the original, but with a total width matching the BUILD_VECTOR output.
5605 EVT EltVT = SrcVT.getVectorElementType();
5606 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5607 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5609 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5610 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5612 // We can pad out the smaller vector for free, so if it's part of a
5615 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5616 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5620 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5623 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5624 // Span too large for a VEXT to cope
5628 if (Src.MinElt >= NumSrcElts) {
5629 // The extraction can just take the second half
5631 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5632 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5633 Src.WindowBase = -NumSrcElts;
5634 } else if (Src.MaxElt < NumSrcElts) {
5635 // The extraction can just take the first half
5637 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5638 DAG.getConstant(0, dl, MVT::i32));
5640 // An actual VEXT is needed
5642 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5643 DAG.getConstant(0, dl, MVT::i32));
5645 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5646 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5648 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5650 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5651 Src.WindowBase = -Src.MinElt;
5655 // Another possible incompatibility occurs from the vector element types. We
5656 // can fix this by bitcasting the source vectors to the same type we intend
5658 for (auto &Src : Sources) {
5659 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5660 if (SrcEltTy == SmallestEltTy)
5662 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5663 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5664 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5665 Src.WindowBase *= Src.WindowScale;
5668 // Final sanity check before we try to actually produce a shuffle.
5670 for (auto Src : Sources)
5671 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5674 // The stars all align, our next step is to produce the mask for the shuffle.
5675 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5676 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5677 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5678 SDValue Entry = Op.getOperand(i);
5679 if (Entry.getOpcode() == ISD::UNDEF)
5682 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5683 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5685 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5686 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5688 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5689 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5690 VT.getVectorElementType().getSizeInBits());
5691 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5693 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5694 // starting at the appropriate offset.
5695 int *LaneMask = &Mask[i * ResMultiplier];
5697 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5698 ExtractBase += NumElts * (Src - Sources.begin());
5699 for (int j = 0; j < LanesDefined; ++j)
5700 LaneMask[j] = ExtractBase + j;
5703 // Final check before we try to produce nonsense...
5704 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5707 // We can't handle more than two sources. This should have already
5708 // been checked before this point.
5709 assert(Sources.size() <= 2 && "Too many sources!");
5711 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5712 for (unsigned i = 0; i < Sources.size(); ++i)
5713 ShuffleOps[i] = Sources[i].ShuffleVec;
5715 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5716 ShuffleOps[1], &Mask[0]);
5717 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5720 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5721 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5722 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5723 /// are assumed to be legal.
5725 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5727 if (VT.getVectorNumElements() == 4 &&
5728 (VT.is128BitVector() || VT.is64BitVector())) {
5729 unsigned PFIndexes[4];
5730 for (unsigned i = 0; i != 4; ++i) {
5734 PFIndexes[i] = M[i];
5737 // Compute the index in the perfect shuffle table.
5738 unsigned PFTableIndex =
5739 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5740 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5741 unsigned Cost = (PFEntry >> 30);
5747 bool ReverseVEXT, isV_UNDEF;
5748 unsigned Imm, WhichResult;
5750 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5751 return (EltSize >= 32 ||
5752 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5753 isVREVMask(M, VT, 64) ||
5754 isVREVMask(M, VT, 32) ||
5755 isVREVMask(M, VT, 16) ||
5756 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5757 isVTBLMask(M, VT) ||
5758 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5759 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5762 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5763 /// the specified operations to build the shuffle.
5764 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5765 SDValue RHS, SelectionDAG &DAG,
5767 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5768 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5769 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5772 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5781 OP_VUZPL, // VUZP, left result
5782 OP_VUZPR, // VUZP, right result
5783 OP_VZIPL, // VZIP, left result
5784 OP_VZIPR, // VZIP, right result
5785 OP_VTRNL, // VTRN, left result
5786 OP_VTRNR // VTRN, right result
5789 if (OpNum == OP_COPY) {
5790 if (LHSID == (1*9+2)*9+3) return LHS;
5791 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5795 SDValue OpLHS, OpRHS;
5796 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5797 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5798 EVT VT = OpLHS.getValueType();
5801 default: llvm_unreachable("Unknown shuffle opcode!");
5803 // VREV divides the vector in half and swaps within the half.
5804 if (VT.getVectorElementType() == MVT::i32 ||
5805 VT.getVectorElementType() == MVT::f32)
5806 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5807 // vrev <4 x i16> -> VREV32
5808 if (VT.getVectorElementType() == MVT::i16)
5809 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5810 // vrev <4 x i8> -> VREV16
5811 assert(VT.getVectorElementType() == MVT::i8);
5812 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5817 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5818 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5822 return DAG.getNode(ARMISD::VEXT, dl, VT,
5824 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5827 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5828 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5831 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5832 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5835 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5836 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5840 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5841 ArrayRef<int> ShuffleMask,
5842 SelectionDAG &DAG) {
5843 // Check to see if we can use the VTBL instruction.
5844 SDValue V1 = Op.getOperand(0);
5845 SDValue V2 = Op.getOperand(1);
5848 SmallVector<SDValue, 8> VTBLMask;
5849 for (ArrayRef<int>::iterator
5850 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5851 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5853 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5854 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5855 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5857 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5858 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5861 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5862 SelectionDAG &DAG) {
5864 SDValue OpLHS = Op.getOperand(0);
5865 EVT VT = OpLHS.getValueType();
5867 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5868 "Expect an v8i16/v16i8 type");
5869 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5870 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5871 // extract the first 8 bytes into the top double word and the last 8 bytes
5872 // into the bottom double word. The v8i16 case is similar.
5873 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5874 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5875 DAG.getConstant(ExtractNum, DL, MVT::i32));
5878 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5879 SDValue V1 = Op.getOperand(0);
5880 SDValue V2 = Op.getOperand(1);
5882 EVT VT = Op.getValueType();
5883 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5885 // Convert shuffles that are directly supported on NEON to target-specific
5886 // DAG nodes, instead of keeping them as shuffles and matching them again
5887 // during code selection. This is more efficient and avoids the possibility
5888 // of inconsistencies between legalization and selection.
5889 // FIXME: floating-point vectors should be canonicalized to integer vectors
5890 // of the same time so that they get CSEd properly.
5891 ArrayRef<int> ShuffleMask = SVN->getMask();
5893 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5894 if (EltSize <= 32) {
5895 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5896 int Lane = SVN->getSplatIndex();
5897 // If this is undef splat, generate it via "just" vdup, if possible.
5898 if (Lane == -1) Lane = 0;
5900 // Test if V1 is a SCALAR_TO_VECTOR.
5901 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5902 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5904 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5905 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5907 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5908 !isa<ConstantSDNode>(V1.getOperand(0))) {
5909 bool IsScalarToVector = true;
5910 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5911 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5912 IsScalarToVector = false;
5915 if (IsScalarToVector)
5916 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5918 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5919 DAG.getConstant(Lane, dl, MVT::i32));
5924 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5927 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5928 DAG.getConstant(Imm, dl, MVT::i32));
5931 if (isVREVMask(ShuffleMask, VT, 64))
5932 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5933 if (isVREVMask(ShuffleMask, VT, 32))
5934 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5935 if (isVREVMask(ShuffleMask, VT, 16))
5936 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5938 if (V2->getOpcode() == ISD::UNDEF &&
5939 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5940 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5941 DAG.getConstant(Imm, dl, MVT::i32));
5944 // Check for Neon shuffles that modify both input vectors in place.
5945 // If both results are used, i.e., if there are two shuffles with the same
5946 // source operands and with masks corresponding to both results of one of
5947 // these operations, DAG memoization will ensure that a single node is
5948 // used for both shuffles.
5949 unsigned WhichResult;
5951 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5952 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5955 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5956 .getValue(WhichResult);
5959 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5960 // shuffles that produce a result larger than their operands with:
5961 // shuffle(concat(v1, undef), concat(v2, undef))
5963 // shuffle(concat(v1, v2), undef)
5964 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5966 // This is useful in the general case, but there are special cases where
5967 // native shuffles produce larger results: the two-result ops.
5969 // Look through the concat when lowering them:
5970 // shuffle(concat(v1, v2), undef)
5972 // concat(VZIP(v1, v2):0, :1)
5974 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5975 V2->getOpcode() == ISD::UNDEF) {
5976 SDValue SubV1 = V1->getOperand(0);
5977 SDValue SubV2 = V1->getOperand(1);
5978 EVT SubVT = SubV1.getValueType();
5980 // We expect these to have been canonicalized to -1.
5981 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5982 return i < (int)VT.getVectorNumElements();
5983 }) && "Unexpected shuffle index into UNDEF operand!");
5985 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5986 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5989 assert((WhichResult == 0) &&
5990 "In-place shuffle of concat can only have one result!");
5991 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5993 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5999 // If the shuffle is not directly supported and it has 4 elements, use
6000 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6001 unsigned NumElts = VT.getVectorNumElements();
6003 unsigned PFIndexes[4];
6004 for (unsigned i = 0; i != 4; ++i) {
6005 if (ShuffleMask[i] < 0)
6008 PFIndexes[i] = ShuffleMask[i];
6011 // Compute the index in the perfect shuffle table.
6012 unsigned PFTableIndex =
6013 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6014 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6015 unsigned Cost = (PFEntry >> 30);
6018 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6021 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6022 if (EltSize >= 32) {
6023 // Do the expansion with floating-point types, since that is what the VFP
6024 // registers are defined to use, and since i64 is not legal.
6025 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6026 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6027 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6028 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6029 SmallVector<SDValue, 8> Ops;
6030 for (unsigned i = 0; i < NumElts; ++i) {
6031 if (ShuffleMask[i] < 0)
6032 Ops.push_back(DAG.getUNDEF(EltVT));
6034 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6035 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6036 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6039 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6040 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6043 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6044 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6046 if (VT == MVT::v8i8) {
6047 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6048 if (NewOp.getNode())
6055 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6056 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6057 SDValue Lane = Op.getOperand(2);
6058 if (!isa<ConstantSDNode>(Lane))
6064 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6065 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6066 SDValue Lane = Op.getOperand(1);
6067 if (!isa<ConstantSDNode>(Lane))
6070 SDValue Vec = Op.getOperand(0);
6071 if (Op.getValueType() == MVT::i32 &&
6072 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6074 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6080 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6081 // The only time a CONCAT_VECTORS operation can have legal types is when
6082 // two 64-bit vectors are concatenated to a 128-bit vector.
6083 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6084 "unexpected CONCAT_VECTORS");
6086 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6087 SDValue Op0 = Op.getOperand(0);
6088 SDValue Op1 = Op.getOperand(1);
6089 if (Op0.getOpcode() != ISD::UNDEF)
6090 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6091 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6092 DAG.getIntPtrConstant(0, dl));
6093 if (Op1.getOpcode() != ISD::UNDEF)
6094 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6095 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6096 DAG.getIntPtrConstant(1, dl));
6097 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6100 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6101 /// element has been zero/sign-extended, depending on the isSigned parameter,
6102 /// from an integer type half its size.
6103 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6105 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6106 EVT VT = N->getValueType(0);
6107 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6108 SDNode *BVN = N->getOperand(0).getNode();
6109 if (BVN->getValueType(0) != MVT::v4i32 ||
6110 BVN->getOpcode() != ISD::BUILD_VECTOR)
6112 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6113 unsigned HiElt = 1 - LoElt;
6114 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6115 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6116 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6117 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6118 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6121 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6122 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6125 if (Hi0->isNullValue() && Hi1->isNullValue())
6131 if (N->getOpcode() != ISD::BUILD_VECTOR)
6134 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6135 SDNode *Elt = N->getOperand(i).getNode();
6136 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6137 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6138 unsigned HalfSize = EltSize / 2;
6140 if (!isIntN(HalfSize, C->getSExtValue()))
6143 if (!isUIntN(HalfSize, C->getZExtValue()))
6154 /// isSignExtended - Check if a node is a vector value that is sign-extended
6155 /// or a constant BUILD_VECTOR with sign-extended elements.
6156 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6157 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6159 if (isExtendedBUILD_VECTOR(N, DAG, true))
6164 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6165 /// or a constant BUILD_VECTOR with zero-extended elements.
6166 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6167 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6169 if (isExtendedBUILD_VECTOR(N, DAG, false))
6174 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6175 if (OrigVT.getSizeInBits() >= 64)
6178 assert(OrigVT.isSimple() && "Expecting a simple value type");
6180 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6181 switch (OrigSimpleTy) {
6182 default: llvm_unreachable("Unexpected Vector Type");
6191 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6192 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6193 /// We insert the required extension here to get the vector to fill a D register.
6194 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6197 unsigned ExtOpcode) {
6198 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6199 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6200 // 64-bits we need to insert a new extension so that it will be 64-bits.
6201 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6202 if (OrigTy.getSizeInBits() >= 64)
6205 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6206 EVT NewVT = getExtensionTo64Bits(OrigTy);
6208 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6211 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6212 /// does not do any sign/zero extension. If the original vector is less
6213 /// than 64 bits, an appropriate extension will be added after the load to
6214 /// reach a total size of 64 bits. We have to add the extension separately
6215 /// because ARM does not have a sign/zero extending load for vectors.
6216 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6217 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6219 // The load already has the right type.
6220 if (ExtendedTy == LD->getMemoryVT())
6221 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6222 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6223 LD->isNonTemporal(), LD->isInvariant(),
6224 LD->getAlignment());
6226 // We need to create a zextload/sextload. We cannot just create a load
6227 // followed by a zext/zext node because LowerMUL is also run during normal
6228 // operation legalization where we can't create illegal types.
6229 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6230 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6231 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6232 LD->isNonTemporal(), LD->getAlignment());
6235 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6236 /// extending load, or BUILD_VECTOR with extended elements, return the
6237 /// unextended value. The unextended vector should be 64 bits so that it can
6238 /// be used as an operand to a VMULL instruction. If the original vector size
6239 /// before extension is less than 64 bits we add a an extension to resize
6240 /// the vector to 64 bits.
6241 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6242 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6243 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6244 N->getOperand(0)->getValueType(0),
6248 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6249 return SkipLoadExtensionForVMULL(LD, DAG);
6251 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6252 // have been legalized as a BITCAST from v4i32.
6253 if (N->getOpcode() == ISD::BITCAST) {
6254 SDNode *BVN = N->getOperand(0).getNode();
6255 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6256 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6257 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6258 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6259 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6261 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6262 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6263 EVT VT = N->getValueType(0);
6264 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6265 unsigned NumElts = VT.getVectorNumElements();
6266 MVT TruncVT = MVT::getIntegerVT(EltSize);
6267 SmallVector<SDValue, 8> Ops;
6269 for (unsigned i = 0; i != NumElts; ++i) {
6270 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6271 const APInt &CInt = C->getAPIntValue();
6272 // Element types smaller than 32 bits are not legal, so use i32 elements.
6273 // The values are implicitly truncated so sext vs. zext doesn't matter.
6274 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6276 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6277 MVT::getVectorVT(TruncVT, NumElts), Ops);
6280 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6281 unsigned Opcode = N->getOpcode();
6282 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6283 SDNode *N0 = N->getOperand(0).getNode();
6284 SDNode *N1 = N->getOperand(1).getNode();
6285 return N0->hasOneUse() && N1->hasOneUse() &&
6286 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6291 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6292 unsigned Opcode = N->getOpcode();
6293 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6294 SDNode *N0 = N->getOperand(0).getNode();
6295 SDNode *N1 = N->getOperand(1).getNode();
6296 return N0->hasOneUse() && N1->hasOneUse() &&
6297 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6302 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6303 // Multiplications are only custom-lowered for 128-bit vectors so that
6304 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6305 EVT VT = Op.getValueType();
6306 assert(VT.is128BitVector() && VT.isInteger() &&
6307 "unexpected type for custom-lowering ISD::MUL");
6308 SDNode *N0 = Op.getOperand(0).getNode();
6309 SDNode *N1 = Op.getOperand(1).getNode();
6310 unsigned NewOpc = 0;
6312 bool isN0SExt = isSignExtended(N0, DAG);
6313 bool isN1SExt = isSignExtended(N1, DAG);
6314 if (isN0SExt && isN1SExt)
6315 NewOpc = ARMISD::VMULLs;
6317 bool isN0ZExt = isZeroExtended(N0, DAG);
6318 bool isN1ZExt = isZeroExtended(N1, DAG);
6319 if (isN0ZExt && isN1ZExt)
6320 NewOpc = ARMISD::VMULLu;
6321 else if (isN1SExt || isN1ZExt) {
6322 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6323 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6324 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6325 NewOpc = ARMISD::VMULLs;
6327 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6328 NewOpc = ARMISD::VMULLu;
6330 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6332 NewOpc = ARMISD::VMULLu;
6338 if (VT == MVT::v2i64)
6339 // Fall through to expand this. It is not legal.
6342 // Other vector multiplications are legal.
6347 // Legalize to a VMULL instruction.
6350 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6352 Op0 = SkipExtensionForVMULL(N0, DAG);
6353 assert(Op0.getValueType().is64BitVector() &&
6354 Op1.getValueType().is64BitVector() &&
6355 "unexpected types for extended operands to VMULL");
6356 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6359 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6360 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6367 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6368 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6369 EVT Op1VT = Op1.getValueType();
6370 return DAG.getNode(N0->getOpcode(), DL, VT,
6371 DAG.getNode(NewOpc, DL, VT,
6372 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6373 DAG.getNode(NewOpc, DL, VT,
6374 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6378 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6379 // TODO: Should this propagate fast-math-flags?
6382 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6383 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6384 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6385 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6386 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6387 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6388 // Get reciprocal estimate.
6389 // float4 recip = vrecpeq_f32(yf);
6390 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6391 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6393 // Because char has a smaller range than uchar, we can actually get away
6394 // without any newton steps. This requires that we use a weird bias
6395 // of 0xb000, however (again, this has been exhaustively tested).
6396 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6397 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6398 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6399 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6400 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6401 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6402 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6403 // Convert back to short.
6404 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6405 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6410 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6411 // TODO: Should this propagate fast-math-flags?
6414 // Convert to float.
6415 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6416 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6417 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6418 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6419 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6420 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6422 // Use reciprocal estimate and one refinement step.
6423 // float4 recip = vrecpeq_f32(yf);
6424 // recip *= vrecpsq_f32(yf, recip);
6425 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6426 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6428 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6429 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6431 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6432 // Because short has a smaller range than ushort, we can actually get away
6433 // with only a single newton step. This requires that we use a weird bias
6434 // of 89, however (again, this has been exhaustively tested).
6435 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6436 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6437 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6438 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6439 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6440 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6441 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6442 // Convert back to integer and return.
6443 // return vmovn_s32(vcvt_s32_f32(result));
6444 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6445 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6449 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6450 EVT VT = Op.getValueType();
6451 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6452 "unexpected type for custom-lowering ISD::SDIV");
6455 SDValue N0 = Op.getOperand(0);
6456 SDValue N1 = Op.getOperand(1);
6459 if (VT == MVT::v8i8) {
6460 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6461 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6463 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6464 DAG.getIntPtrConstant(4, dl));
6465 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6466 DAG.getIntPtrConstant(4, dl));
6467 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6468 DAG.getIntPtrConstant(0, dl));
6469 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6470 DAG.getIntPtrConstant(0, dl));
6472 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6473 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6475 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6476 N0 = LowerCONCAT_VECTORS(N0, DAG);
6478 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6481 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6484 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6485 // TODO: Should this propagate fast-math-flags?
6486 EVT VT = Op.getValueType();
6487 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6488 "unexpected type for custom-lowering ISD::UDIV");
6491 SDValue N0 = Op.getOperand(0);
6492 SDValue N1 = Op.getOperand(1);
6495 if (VT == MVT::v8i8) {
6496 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6497 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6499 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6500 DAG.getIntPtrConstant(4, dl));
6501 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6502 DAG.getIntPtrConstant(4, dl));
6503 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6504 DAG.getIntPtrConstant(0, dl));
6505 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6506 DAG.getIntPtrConstant(0, dl));
6508 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6509 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6511 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6512 N0 = LowerCONCAT_VECTORS(N0, DAG);
6514 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6515 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6521 // v4i16 sdiv ... Convert to float.
6522 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6523 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6524 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6525 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6526 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6527 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6529 // Use reciprocal estimate and two refinement steps.
6530 // float4 recip = vrecpeq_f32(yf);
6531 // recip *= vrecpsq_f32(yf, recip);
6532 // recip *= vrecpsq_f32(yf, recip);
6533 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6534 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6536 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6537 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6539 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6540 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6541 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6543 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6544 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6545 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6546 // and that it will never cause us to return an answer too large).
6547 // float4 result = as_float4(as_int4(xf*recip) + 2);
6548 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6549 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6550 N1 = DAG.getConstant(2, dl, MVT::i32);
6551 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6552 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6553 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6554 // Convert back to integer and return.
6555 // return vmovn_u32(vcvt_s32_f32(result));
6556 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6557 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6561 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6562 EVT VT = Op.getNode()->getValueType(0);
6563 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6566 bool ExtraOp = false;
6567 switch (Op.getOpcode()) {
6568 default: llvm_unreachable("Invalid code");
6569 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6570 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6571 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6572 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6576 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6578 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6579 Op.getOperand(1), Op.getOperand(2));
6582 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6583 assert(Subtarget->isTargetDarwin());
6585 // For iOS, we want to call an alternative entry point: __sincos_stret,
6586 // return values are passed via sret.
6588 SDValue Arg = Op.getOperand(0);
6589 EVT ArgVT = Arg.getValueType();
6590 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6591 auto PtrVT = getPointerTy(DAG.getDataLayout());
6593 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6596 // Pair of floats / doubles used to pass the result.
6597 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6598 auto &DL = DAG.getDataLayout();
6601 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6603 if (ShouldUseSRet) {
6604 // Create stack object for sret.
6605 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6606 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6607 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6608 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6612 Entry.Ty = RetTy->getPointerTo();
6613 Entry.isSExt = false;
6614 Entry.isZExt = false;
6615 Entry.isSRet = true;
6616 Args.push_back(Entry);
6617 RetTy = Type::getVoidTy(*DAG.getContext());
6623 Entry.isSExt = false;
6624 Entry.isZExt = false;
6625 Args.push_back(Entry);
6627 const char *LibcallName =
6628 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6630 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6631 CallingConv::ID CC = getLibcallCallingConv(LC);
6632 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6634 TargetLowering::CallLoweringInfo CLI(DAG);
6636 .setChain(DAG.getEntryNode())
6637 .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6638 .setDiscardResult(ShouldUseSRet);
6639 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6642 return CallResult.first;
6644 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6645 MachinePointerInfo(), false, false, false, 0);
6647 // Address of cos field.
6648 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6649 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6650 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6651 MachinePointerInfo(), false, false, false, 0);
6653 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6654 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6655 LoadSin.getValue(0), LoadCos.getValue(0));
6658 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6660 SDValue &Chain) const {
6661 EVT VT = Op.getValueType();
6662 assert((VT == MVT::i32 || VT == MVT::i64) &&
6663 "unexpected type for custom lowering DIV");
6666 const auto &DL = DAG.getDataLayout();
6667 const auto &TLI = DAG.getTargetLoweringInfo();
6669 const char *Name = nullptr;
6671 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6673 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6675 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6677 ARMTargetLowering::ArgListTy Args;
6679 for (auto AI : {1, 0}) {
6681 Arg.Node = Op.getOperand(AI);
6682 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6683 Args.push_back(Arg);
6686 CallLoweringInfo CLI(DAG);
6689 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6690 ES, std::move(Args), 0);
6692 return LowerCallTo(CLI).first;
6695 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6696 bool Signed) const {
6697 assert(Op.getValueType() == MVT::i32 &&
6698 "unexpected type for custom lowering DIV");
6701 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6702 DAG.getEntryNode(), Op.getOperand(1));
6704 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6707 void ARMTargetLowering::ExpandDIV_Windows(
6708 SDValue Op, SelectionDAG &DAG, bool Signed,
6709 SmallVectorImpl<SDValue> &Results) const {
6710 const auto &DL = DAG.getDataLayout();
6711 const auto &TLI = DAG.getTargetLoweringInfo();
6713 assert(Op.getValueType() == MVT::i64 &&
6714 "unexpected type for custom lowering DIV");
6717 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6718 DAG.getConstant(0, dl, MVT::i32));
6719 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6720 DAG.getConstant(1, dl, MVT::i32));
6721 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6724 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6726 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6728 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6729 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6730 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6731 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6733 Results.push_back(Lower);
6734 Results.push_back(Upper);
6737 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6738 // Monotonic load/store is legal for all targets
6739 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6742 // Acquire/Release load/store is not legal for targets without a
6743 // dmb or equivalent available.
6747 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6748 SmallVectorImpl<SDValue> &Results,
6750 const ARMSubtarget *Subtarget) {
6752 // Under Power Management extensions, the cycle-count is:
6753 // mrc p15, #0, <Rt>, c9, c13, #0
6754 SDValue Ops[] = { N->getOperand(0), // Chain
6755 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6756 DAG.getConstant(15, DL, MVT::i32),
6757 DAG.getConstant(0, DL, MVT::i32),
6758 DAG.getConstant(9, DL, MVT::i32),
6759 DAG.getConstant(13, DL, MVT::i32),
6760 DAG.getConstant(0, DL, MVT::i32)
6763 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6764 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6765 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6766 DAG.getConstant(0, DL, MVT::i32)));
6767 Results.push_back(Cycles32.getValue(1));
6770 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6771 switch (Op.getOpcode()) {
6772 default: llvm_unreachable("Don't know how to custom lower this!");
6773 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6774 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6775 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6776 case ISD::GlobalAddress:
6777 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6778 default: llvm_unreachable("unknown object format");
6780 return LowerGlobalAddressWindows(Op, DAG);
6782 return LowerGlobalAddressELF(Op, DAG);
6784 return LowerGlobalAddressDarwin(Op, DAG);
6786 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6787 case ISD::SELECT: return LowerSELECT(Op, DAG);
6788 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6789 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6790 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6791 case ISD::VASTART: return LowerVASTART(Op, DAG);
6792 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6793 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6794 case ISD::SINT_TO_FP:
6795 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6796 case ISD::FP_TO_SINT:
6797 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6798 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6799 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6800 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6801 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6802 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6803 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6804 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6806 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6809 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6810 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6811 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6812 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6813 case ISD::SRL_PARTS:
6814 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6816 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6817 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6818 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6819 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6820 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6821 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6822 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6823 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6824 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6825 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6826 case ISD::MUL: return LowerMUL(Op, DAG);
6827 case ISD::SDIV: return LowerSDIV(Op, DAG);
6828 case ISD::UDIV: return LowerUDIV(Op, DAG);
6832 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6837 return LowerXALUO(Op, DAG);
6838 case ISD::ATOMIC_LOAD:
6839 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6840 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6842 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6843 case ISD::DYNAMIC_STACKALLOC:
6844 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6845 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6846 llvm_unreachable("Don't know how to custom lower this!");
6847 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6848 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6849 case ARMISD::WIN__DBZCHK: return SDValue();
6853 /// ReplaceNodeResults - Replace the results of node with an illegal result
6854 /// type with new values built out of custom code.
6855 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6856 SmallVectorImpl<SDValue> &Results,
6857 SelectionDAG &DAG) const {
6859 switch (N->getOpcode()) {
6861 llvm_unreachable("Don't know how to custom expand this!");
6862 case ISD::READ_REGISTER:
6863 ExpandREAD_REGISTER(N, Results, DAG);
6866 Res = ExpandBITCAST(N, DAG);
6870 Res = Expand64BitShift(N, DAG, Subtarget);
6874 Res = LowerREM(N, DAG);
6876 case ISD::READCYCLECOUNTER:
6877 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6881 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6882 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6886 Results.push_back(Res);
6889 //===----------------------------------------------------------------------===//
6890 // ARM Scheduler Hooks
6891 //===----------------------------------------------------------------------===//
6893 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6894 /// registers the function context.
6895 void ARMTargetLowering::
6896 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6897 MachineBasicBlock *DispatchBB, int FI) const {
6898 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6899 DebugLoc dl = MI->getDebugLoc();
6900 MachineFunction *MF = MBB->getParent();
6901 MachineRegisterInfo *MRI = &MF->getRegInfo();
6902 MachineConstantPool *MCP = MF->getConstantPool();
6903 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6904 const Function *F = MF->getFunction();
6906 bool isThumb = Subtarget->isThumb();
6907 bool isThumb2 = Subtarget->isThumb2();
6909 unsigned PCLabelId = AFI->createPICLabelUId();
6910 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6911 ARMConstantPoolValue *CPV =
6912 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6913 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6915 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6916 : &ARM::GPRRegClass;
6918 // Grab constant pool and fixed stack memory operands.
6919 MachineMemOperand *CPMMO =
6920 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6921 MachineMemOperand::MOLoad, 4, 4);
6923 MachineMemOperand *FIMMOSt =
6924 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6925 MachineMemOperand::MOStore, 4, 4);
6927 // Load the address of the dispatch MBB into the jump buffer.
6929 // Incoming value: jbuf
6930 // ldr.n r5, LCPI1_1
6933 // str r5, [$jbuf, #+4] ; &jbuf[1]
6934 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6935 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6936 .addConstantPoolIndex(CPI)
6937 .addMemOperand(CPMMO));
6938 // Set the low bit because of thumb mode.
6939 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6941 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6942 .addReg(NewVReg1, RegState::Kill)
6944 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6945 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6946 .addReg(NewVReg2, RegState::Kill)
6948 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6949 .addReg(NewVReg3, RegState::Kill)
6951 .addImm(36) // &jbuf[1] :: pc
6952 .addMemOperand(FIMMOSt));
6953 } else if (isThumb) {
6954 // Incoming value: jbuf
6955 // ldr.n r1, LCPI1_4
6959 // add r2, $jbuf, #+4 ; &jbuf[1]
6961 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6962 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6963 .addConstantPoolIndex(CPI)
6964 .addMemOperand(CPMMO));
6965 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6966 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6967 .addReg(NewVReg1, RegState::Kill)
6969 // Set the low bit because of thumb mode.
6970 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6971 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6972 .addReg(ARM::CPSR, RegState::Define)
6974 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6975 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6976 .addReg(ARM::CPSR, RegState::Define)
6977 .addReg(NewVReg2, RegState::Kill)
6978 .addReg(NewVReg3, RegState::Kill));
6979 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6980 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6982 .addImm(36); // &jbuf[1] :: pc
6983 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6984 .addReg(NewVReg4, RegState::Kill)
6985 .addReg(NewVReg5, RegState::Kill)
6987 .addMemOperand(FIMMOSt));
6989 // Incoming value: jbuf
6992 // str r1, [$jbuf, #+4] ; &jbuf[1]
6993 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6994 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6995 .addConstantPoolIndex(CPI)
6997 .addMemOperand(CPMMO));
6998 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6999 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7000 .addReg(NewVReg1, RegState::Kill)
7001 .addImm(PCLabelId));
7002 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7003 .addReg(NewVReg2, RegState::Kill)
7005 .addImm(36) // &jbuf[1] :: pc
7006 .addMemOperand(FIMMOSt));
7010 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7011 MachineBasicBlock *MBB) const {
7012 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7013 DebugLoc dl = MI->getDebugLoc();
7014 MachineFunction *MF = MBB->getParent();
7015 MachineRegisterInfo *MRI = &MF->getRegInfo();
7016 MachineFrameInfo *MFI = MF->getFrameInfo();
7017 int FI = MFI->getFunctionContextIndex();
7019 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7020 : &ARM::GPRnopcRegClass;
7022 // Get a mapping of the call site numbers to all of the landing pads they're
7024 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7025 unsigned MaxCSNum = 0;
7026 MachineModuleInfo &MMI = MF->getMMI();
7027 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7029 if (!BB->isEHPad()) continue;
7031 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7033 for (MachineBasicBlock::iterator
7034 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7035 if (!II->isEHLabel()) continue;
7037 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7038 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7040 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7041 for (SmallVectorImpl<unsigned>::iterator
7042 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7043 CSI != CSE; ++CSI) {
7044 CallSiteNumToLPad[*CSI].push_back(&*BB);
7045 MaxCSNum = std::max(MaxCSNum, *CSI);
7051 // Get an ordered list of the machine basic blocks for the jump table.
7052 std::vector<MachineBasicBlock*> LPadList;
7053 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7054 LPadList.reserve(CallSiteNumToLPad.size());
7055 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7056 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7057 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7058 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7059 LPadList.push_back(*II);
7060 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7064 assert(!LPadList.empty() &&
7065 "No landing pad destinations for the dispatch jump table!");
7067 // Create the jump table and associated information.
7068 MachineJumpTableInfo *JTI =
7069 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7070 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7071 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7073 // Create the MBBs for the dispatch code.
7075 // Shove the dispatch's address into the return slot in the function context.
7076 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7077 DispatchBB->setIsEHPad();
7079 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7080 unsigned trap_opcode;
7081 if (Subtarget->isThumb())
7082 trap_opcode = ARM::tTRAP;
7084 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7086 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7087 DispatchBB->addSuccessor(TrapBB);
7089 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7090 DispatchBB->addSuccessor(DispContBB);
7093 MF->insert(MF->end(), DispatchBB);
7094 MF->insert(MF->end(), DispContBB);
7095 MF->insert(MF->end(), TrapBB);
7097 // Insert code into the entry block that creates and registers the function
7099 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7101 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7102 MachinePointerInfo::getFixedStack(*MF, FI),
7103 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7105 MachineInstrBuilder MIB;
7106 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7108 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7109 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7111 // Add a register mask with no preserved registers. This results in all
7112 // registers being marked as clobbered.
7113 MIB.addRegMask(RI.getNoPreservedMask());
7115 unsigned NumLPads = LPadList.size();
7116 if (Subtarget->isThumb2()) {
7117 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7118 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7121 .addMemOperand(FIMMOLd));
7123 if (NumLPads < 256) {
7124 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7126 .addImm(LPadList.size()));
7128 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7129 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7130 .addImm(NumLPads & 0xFFFF));
7132 unsigned VReg2 = VReg1;
7133 if ((NumLPads & 0xFFFF0000) != 0) {
7134 VReg2 = MRI->createVirtualRegister(TRC);
7135 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7137 .addImm(NumLPads >> 16));
7140 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7145 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7150 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7151 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7152 .addJumpTableIndex(MJTI));
7154 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7157 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7158 .addReg(NewVReg3, RegState::Kill)
7160 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7162 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7163 .addReg(NewVReg4, RegState::Kill)
7165 .addJumpTableIndex(MJTI);
7166 } else if (Subtarget->isThumb()) {
7167 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7168 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7171 .addMemOperand(FIMMOLd));
7173 if (NumLPads < 256) {
7174 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7178 MachineConstantPool *ConstantPool = MF->getConstantPool();
7179 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7180 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7182 // MachineConstantPool wants an explicit alignment.
7183 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7185 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7186 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7188 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7189 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7190 .addReg(VReg1, RegState::Define)
7191 .addConstantPoolIndex(Idx));
7192 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7197 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7202 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7203 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7204 .addReg(ARM::CPSR, RegState::Define)
7208 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7209 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7210 .addJumpTableIndex(MJTI));
7212 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7213 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7214 .addReg(ARM::CPSR, RegState::Define)
7215 .addReg(NewVReg2, RegState::Kill)
7218 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7219 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7221 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7222 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7223 .addReg(NewVReg4, RegState::Kill)
7225 .addMemOperand(JTMMOLd));
7227 unsigned NewVReg6 = NewVReg5;
7228 if (RelocM == Reloc::PIC_) {
7229 NewVReg6 = MRI->createVirtualRegister(TRC);
7230 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7231 .addReg(ARM::CPSR, RegState::Define)
7232 .addReg(NewVReg5, RegState::Kill)
7236 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7237 .addReg(NewVReg6, RegState::Kill)
7238 .addJumpTableIndex(MJTI);
7240 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7241 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7244 .addMemOperand(FIMMOLd));
7246 if (NumLPads < 256) {
7247 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7250 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7251 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7252 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7253 .addImm(NumLPads & 0xFFFF));
7255 unsigned VReg2 = VReg1;
7256 if ((NumLPads & 0xFFFF0000) != 0) {
7257 VReg2 = MRI->createVirtualRegister(TRC);
7258 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7260 .addImm(NumLPads >> 16));
7263 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7267 MachineConstantPool *ConstantPool = MF->getConstantPool();
7268 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7269 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7271 // MachineConstantPool wants an explicit alignment.
7272 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7274 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7275 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7277 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7278 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7279 .addReg(VReg1, RegState::Define)
7280 .addConstantPoolIndex(Idx)
7282 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7284 .addReg(VReg1, RegState::Kill));
7287 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7292 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7294 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7296 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7297 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7298 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7299 .addJumpTableIndex(MJTI));
7301 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7302 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7303 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7305 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7306 .addReg(NewVReg3, RegState::Kill)
7309 .addMemOperand(JTMMOLd));
7311 if (RelocM == Reloc::PIC_) {
7312 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7313 .addReg(NewVReg5, RegState::Kill)
7315 .addJumpTableIndex(MJTI);
7317 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7318 .addReg(NewVReg5, RegState::Kill)
7319 .addJumpTableIndex(MJTI);
7323 // Add the jump table entries as successors to the MBB.
7324 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7325 for (std::vector<MachineBasicBlock*>::iterator
7326 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7327 MachineBasicBlock *CurMBB = *I;
7328 if (SeenMBBs.insert(CurMBB).second)
7329 DispContBB->addSuccessor(CurMBB);
7332 // N.B. the order the invoke BBs are processed in doesn't matter here.
7333 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7334 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7335 for (MachineBasicBlock *BB : InvokeBBs) {
7337 // Remove the landing pad successor from the invoke block and replace it
7338 // with the new dispatch block.
7339 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7341 while (!Successors.empty()) {
7342 MachineBasicBlock *SMBB = Successors.pop_back_val();
7343 if (SMBB->isEHPad()) {
7344 BB->removeSuccessor(SMBB);
7345 MBBLPads.push_back(SMBB);
7349 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7351 // Find the invoke call and mark all of the callee-saved registers as
7352 // 'implicit defined' so that they're spilled. This prevents code from
7353 // moving instructions to before the EH block, where they will never be
7355 for (MachineBasicBlock::reverse_iterator
7356 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7357 if (!II->isCall()) continue;
7359 DenseMap<unsigned, bool> DefRegs;
7360 for (MachineInstr::mop_iterator
7361 OI = II->operands_begin(), OE = II->operands_end();
7363 if (!OI->isReg()) continue;
7364 DefRegs[OI->getReg()] = true;
7367 MachineInstrBuilder MIB(*MF, &*II);
7369 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7370 unsigned Reg = SavedRegs[i];
7371 if (Subtarget->isThumb2() &&
7372 !ARM::tGPRRegClass.contains(Reg) &&
7373 !ARM::hGPRRegClass.contains(Reg))
7375 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7377 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7380 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7387 // Mark all former landing pads as non-landing pads. The dispatch is the only
7389 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7390 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7391 (*I)->setIsEHPad(false);
7393 // The instruction is gone now.
7394 MI->eraseFromParent();
7398 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7399 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7400 E = MBB->succ_end(); I != E; ++I)
7403 llvm_unreachable("Expecting a BB with two successors!");
7406 /// Return the load opcode for a given load size. If load size >= 8,
7407 /// neon opcode will be returned.
7408 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7410 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7411 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7413 return LdSize == 4 ? ARM::tLDRi
7414 : LdSize == 2 ? ARM::tLDRHi
7415 : LdSize == 1 ? ARM::tLDRBi : 0;
7417 return LdSize == 4 ? ARM::t2LDR_POST
7418 : LdSize == 2 ? ARM::t2LDRH_POST
7419 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7420 return LdSize == 4 ? ARM::LDR_POST_IMM
7421 : LdSize == 2 ? ARM::LDRH_POST
7422 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7425 /// Return the store opcode for a given store size. If store size >= 8,
7426 /// neon opcode will be returned.
7427 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7429 return StSize == 16 ? ARM::VST1q32wb_fixed
7430 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7432 return StSize == 4 ? ARM::tSTRi
7433 : StSize == 2 ? ARM::tSTRHi
7434 : StSize == 1 ? ARM::tSTRBi : 0;
7436 return StSize == 4 ? ARM::t2STR_POST
7437 : StSize == 2 ? ARM::t2STRH_POST
7438 : StSize == 1 ? ARM::t2STRB_POST : 0;
7439 return StSize == 4 ? ARM::STR_POST_IMM
7440 : StSize == 2 ? ARM::STRH_POST
7441 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7444 /// Emit a post-increment load operation with given size. The instructions
7445 /// will be added to BB at Pos.
7446 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7447 const TargetInstrInfo *TII, DebugLoc dl,
7448 unsigned LdSize, unsigned Data, unsigned AddrIn,
7449 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7450 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7451 assert(LdOpc != 0 && "Should have a load opcode");
7453 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7454 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7456 } else if (IsThumb1) {
7457 // load + update AddrIn
7458 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7459 .addReg(AddrIn).addImm(0));
7460 MachineInstrBuilder MIB =
7461 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7462 MIB = AddDefaultT1CC(MIB);
7463 MIB.addReg(AddrIn).addImm(LdSize);
7464 AddDefaultPred(MIB);
7465 } else if (IsThumb2) {
7466 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7467 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7470 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7471 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7472 .addReg(0).addImm(LdSize));
7476 /// Emit a post-increment store operation with given size. The instructions
7477 /// will be added to BB at Pos.
7478 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7479 const TargetInstrInfo *TII, DebugLoc dl,
7480 unsigned StSize, unsigned Data, unsigned AddrIn,
7481 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7482 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7483 assert(StOpc != 0 && "Should have a store opcode");
7485 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7486 .addReg(AddrIn).addImm(0).addReg(Data));
7487 } else if (IsThumb1) {
7488 // store + update AddrIn
7489 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7490 .addReg(AddrIn).addImm(0));
7491 MachineInstrBuilder MIB =
7492 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7493 MIB = AddDefaultT1CC(MIB);
7494 MIB.addReg(AddrIn).addImm(StSize);
7495 AddDefaultPred(MIB);
7496 } else if (IsThumb2) {
7497 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7498 .addReg(Data).addReg(AddrIn).addImm(StSize));
7500 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7501 .addReg(Data).addReg(AddrIn).addReg(0)
7507 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7508 MachineBasicBlock *BB) const {
7509 // This pseudo instruction has 3 operands: dst, src, size
7510 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7511 // Otherwise, we will generate unrolled scalar copies.
7512 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7513 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7514 MachineFunction::iterator It = ++BB->getIterator();
7516 unsigned dest = MI->getOperand(0).getReg();
7517 unsigned src = MI->getOperand(1).getReg();
7518 unsigned SizeVal = MI->getOperand(2).getImm();
7519 unsigned Align = MI->getOperand(3).getImm();
7520 DebugLoc dl = MI->getDebugLoc();
7522 MachineFunction *MF = BB->getParent();
7523 MachineRegisterInfo &MRI = MF->getRegInfo();
7524 unsigned UnitSize = 0;
7525 const TargetRegisterClass *TRC = nullptr;
7526 const TargetRegisterClass *VecTRC = nullptr;
7528 bool IsThumb1 = Subtarget->isThumb1Only();
7529 bool IsThumb2 = Subtarget->isThumb2();
7533 } else if (Align & 2) {
7536 // Check whether we can use NEON instructions.
7537 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7538 Subtarget->hasNEON()) {
7539 if ((Align % 16 == 0) && SizeVal >= 16)
7541 else if ((Align % 8 == 0) && SizeVal >= 8)
7544 // Can't use NEON instructions.
7549 // Select the correct opcode and register class for unit size load/store
7550 bool IsNeon = UnitSize >= 8;
7551 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7553 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7554 : UnitSize == 8 ? &ARM::DPRRegClass
7557 unsigned BytesLeft = SizeVal % UnitSize;
7558 unsigned LoopSize = SizeVal - BytesLeft;
7560 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7561 // Use LDR and STR to copy.
7562 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7563 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7564 unsigned srcIn = src;
7565 unsigned destIn = dest;
7566 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7567 unsigned srcOut = MRI.createVirtualRegister(TRC);
7568 unsigned destOut = MRI.createVirtualRegister(TRC);
7569 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7570 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7571 IsThumb1, IsThumb2);
7572 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7573 IsThumb1, IsThumb2);
7578 // Handle the leftover bytes with LDRB and STRB.
7579 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7580 // [destOut] = STRB_POST(scratch, destIn, 1)
7581 for (unsigned i = 0; i < BytesLeft; i++) {
7582 unsigned srcOut = MRI.createVirtualRegister(TRC);
7583 unsigned destOut = MRI.createVirtualRegister(TRC);
7584 unsigned scratch = MRI.createVirtualRegister(TRC);
7585 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7586 IsThumb1, IsThumb2);
7587 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7588 IsThumb1, IsThumb2);
7592 MI->eraseFromParent(); // The instruction is gone now.
7596 // Expand the pseudo op to a loop.
7599 // movw varEnd, # --> with thumb2
7601 // ldrcp varEnd, idx --> without thumb2
7602 // fallthrough --> loopMBB
7604 // PHI varPhi, varEnd, varLoop
7605 // PHI srcPhi, src, srcLoop
7606 // PHI destPhi, dst, destLoop
7607 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7608 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7609 // subs varLoop, varPhi, #UnitSize
7611 // fallthrough --> exitMBB
7613 // epilogue to handle left-over bytes
7614 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7615 // [destOut] = STRB_POST(scratch, destLoop, 1)
7616 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7617 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7618 MF->insert(It, loopMBB);
7619 MF->insert(It, exitMBB);
7621 // Transfer the remainder of BB and its successor edges to exitMBB.
7622 exitMBB->splice(exitMBB->begin(), BB,
7623 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7624 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7626 // Load an immediate to varEnd.
7627 unsigned varEnd = MRI.createVirtualRegister(TRC);
7628 if (Subtarget->useMovt(*MF)) {
7629 unsigned Vtmp = varEnd;
7630 if ((LoopSize & 0xFFFF0000) != 0)
7631 Vtmp = MRI.createVirtualRegister(TRC);
7632 AddDefaultPred(BuildMI(BB, dl,
7633 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7634 Vtmp).addImm(LoopSize & 0xFFFF));
7636 if ((LoopSize & 0xFFFF0000) != 0)
7637 AddDefaultPred(BuildMI(BB, dl,
7638 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7641 .addImm(LoopSize >> 16));
7643 MachineConstantPool *ConstantPool = MF->getConstantPool();
7644 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7645 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7647 // MachineConstantPool wants an explicit alignment.
7648 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7650 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7651 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7654 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7655 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7657 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7658 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7660 BB->addSuccessor(loopMBB);
7662 // Generate the loop body:
7663 // varPhi = PHI(varLoop, varEnd)
7664 // srcPhi = PHI(srcLoop, src)
7665 // destPhi = PHI(destLoop, dst)
7666 MachineBasicBlock *entryBB = BB;
7668 unsigned varLoop = MRI.createVirtualRegister(TRC);
7669 unsigned varPhi = MRI.createVirtualRegister(TRC);
7670 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7671 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7672 unsigned destLoop = MRI.createVirtualRegister(TRC);
7673 unsigned destPhi = MRI.createVirtualRegister(TRC);
7675 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7676 .addReg(varLoop).addMBB(loopMBB)
7677 .addReg(varEnd).addMBB(entryBB);
7678 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7679 .addReg(srcLoop).addMBB(loopMBB)
7680 .addReg(src).addMBB(entryBB);
7681 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7682 .addReg(destLoop).addMBB(loopMBB)
7683 .addReg(dest).addMBB(entryBB);
7685 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7686 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7687 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7688 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7689 IsThumb1, IsThumb2);
7690 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7691 IsThumb1, IsThumb2);
7693 // Decrement loop variable by UnitSize.
7695 MachineInstrBuilder MIB =
7696 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7697 MIB = AddDefaultT1CC(MIB);
7698 MIB.addReg(varPhi).addImm(UnitSize);
7699 AddDefaultPred(MIB);
7701 MachineInstrBuilder MIB =
7702 BuildMI(*BB, BB->end(), dl,
7703 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7704 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7705 MIB->getOperand(5).setReg(ARM::CPSR);
7706 MIB->getOperand(5).setIsDef(true);
7708 BuildMI(*BB, BB->end(), dl,
7709 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7710 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7712 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7713 BB->addSuccessor(loopMBB);
7714 BB->addSuccessor(exitMBB);
7716 // Add epilogue to handle BytesLeft.
7718 MachineInstr *StartOfExit = exitMBB->begin();
7720 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7721 // [destOut] = STRB_POST(scratch, destLoop, 1)
7722 unsigned srcIn = srcLoop;
7723 unsigned destIn = destLoop;
7724 for (unsigned i = 0; i < BytesLeft; i++) {
7725 unsigned srcOut = MRI.createVirtualRegister(TRC);
7726 unsigned destOut = MRI.createVirtualRegister(TRC);
7727 unsigned scratch = MRI.createVirtualRegister(TRC);
7728 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7729 IsThumb1, IsThumb2);
7730 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7731 IsThumb1, IsThumb2);
7736 MI->eraseFromParent(); // The instruction is gone now.
7741 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7742 MachineBasicBlock *MBB) const {
7743 const TargetMachine &TM = getTargetMachine();
7744 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7745 DebugLoc DL = MI->getDebugLoc();
7747 assert(Subtarget->isTargetWindows() &&
7748 "__chkstk is only supported on Windows");
7749 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7751 // __chkstk takes the number of words to allocate on the stack in R4, and
7752 // returns the stack adjustment in number of bytes in R4. This will not
7753 // clober any other registers (other than the obvious lr).
7755 // Although, technically, IP should be considered a register which may be
7756 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7757 // thumb-2 environment, so there is no interworking required. As a result, we
7758 // do not expect a veneer to be emitted by the linker, clobbering IP.
7760 // Each module receives its own copy of __chkstk, so no import thunk is
7761 // required, again, ensuring that IP is not clobbered.
7763 // Finally, although some linkers may theoretically provide a trampoline for
7764 // out of range calls (which is quite common due to a 32M range limitation of
7765 // branches for Thumb), we can generate the long-call version via
7766 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7769 switch (TM.getCodeModel()) {
7770 case CodeModel::Small:
7771 case CodeModel::Medium:
7772 case CodeModel::Default:
7773 case CodeModel::Kernel:
7774 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7775 .addImm((unsigned)ARMCC::AL).addReg(0)
7776 .addExternalSymbol("__chkstk")
7777 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7778 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7779 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7781 case CodeModel::Large:
7782 case CodeModel::JITDefault: {
7783 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7784 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7786 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7787 .addExternalSymbol("__chkstk");
7788 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7789 .addImm((unsigned)ARMCC::AL).addReg(0)
7790 .addReg(Reg, RegState::Kill)
7791 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7792 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7793 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7798 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7800 .addReg(ARM::SP).addReg(ARM::R4)));
7802 MI->eraseFromParent();
7807 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7808 MachineBasicBlock *MBB) const {
7809 DebugLoc DL = MI->getDebugLoc();
7810 MachineFunction *MF = MBB->getParent();
7811 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7813 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7814 MF->push_back(ContBB);
7815 ContBB->splice(ContBB->begin(), MBB,
7816 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7817 MBB->addSuccessor(ContBB);
7819 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7820 MF->push_back(TrapBB);
7821 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7822 MBB->addSuccessor(TrapBB);
7824 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7825 .addReg(MI->getOperand(0).getReg())
7828 MI->eraseFromParent();
7833 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7834 MachineBasicBlock *BB) const {
7835 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7836 DebugLoc dl = MI->getDebugLoc();
7837 bool isThumb2 = Subtarget->isThumb2();
7838 switch (MI->getOpcode()) {
7841 llvm_unreachable("Unexpected instr type to insert");
7843 // The Thumb2 pre-indexed stores have the same MI operands, they just
7844 // define them differently in the .td files from the isel patterns, so
7845 // they need pseudos.
7846 case ARM::t2STR_preidx:
7847 MI->setDesc(TII->get(ARM::t2STR_PRE));
7849 case ARM::t2STRB_preidx:
7850 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7852 case ARM::t2STRH_preidx:
7853 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7856 case ARM::STRi_preidx:
7857 case ARM::STRBi_preidx: {
7858 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7859 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7860 // Decode the offset.
7861 unsigned Offset = MI->getOperand(4).getImm();
7862 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7863 Offset = ARM_AM::getAM2Offset(Offset);
7867 MachineMemOperand *MMO = *MI->memoperands_begin();
7868 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7869 .addOperand(MI->getOperand(0)) // Rn_wb
7870 .addOperand(MI->getOperand(1)) // Rt
7871 .addOperand(MI->getOperand(2)) // Rn
7872 .addImm(Offset) // offset (skip GPR==zero_reg)
7873 .addOperand(MI->getOperand(5)) // pred
7874 .addOperand(MI->getOperand(6))
7875 .addMemOperand(MMO);
7876 MI->eraseFromParent();
7879 case ARM::STRr_preidx:
7880 case ARM::STRBr_preidx:
7881 case ARM::STRH_preidx: {
7883 switch (MI->getOpcode()) {
7884 default: llvm_unreachable("unexpected opcode!");
7885 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7886 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7887 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7889 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7890 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7891 MIB.addOperand(MI->getOperand(i));
7892 MI->eraseFromParent();
7896 case ARM::tMOVCCr_pseudo: {
7897 // To "insert" a SELECT_CC instruction, we actually have to insert the
7898 // diamond control-flow pattern. The incoming instruction knows the
7899 // destination vreg to set, the condition code register to branch on, the
7900 // true/false values to select between, and a branch opcode to use.
7901 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7902 MachineFunction::iterator It = ++BB->getIterator();
7907 // cmpTY ccX, r1, r2
7909 // fallthrough --> copy0MBB
7910 MachineBasicBlock *thisMBB = BB;
7911 MachineFunction *F = BB->getParent();
7912 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7913 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7914 F->insert(It, copy0MBB);
7915 F->insert(It, sinkMBB);
7917 // Transfer the remainder of BB and its successor edges to sinkMBB.
7918 sinkMBB->splice(sinkMBB->begin(), BB,
7919 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7920 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7922 BB->addSuccessor(copy0MBB);
7923 BB->addSuccessor(sinkMBB);
7925 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7926 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7929 // %FalseValue = ...
7930 // # fallthrough to sinkMBB
7933 // Update machine-CFG edges
7934 BB->addSuccessor(sinkMBB);
7937 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7940 BuildMI(*BB, BB->begin(), dl,
7941 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7942 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7943 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7945 MI->eraseFromParent(); // The pseudo instruction is gone now.
7950 case ARM::BCCZi64: {
7951 // If there is an unconditional branch to the other successor, remove it.
7952 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7954 // Compare both parts that make up the double comparison separately for
7956 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7958 unsigned LHS1 = MI->getOperand(1).getReg();
7959 unsigned LHS2 = MI->getOperand(2).getReg();
7961 AddDefaultPred(BuildMI(BB, dl,
7962 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7963 .addReg(LHS1).addImm(0));
7964 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7965 .addReg(LHS2).addImm(0)
7966 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7968 unsigned RHS1 = MI->getOperand(3).getReg();
7969 unsigned RHS2 = MI->getOperand(4).getReg();
7970 AddDefaultPred(BuildMI(BB, dl,
7971 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7972 .addReg(LHS1).addReg(RHS1));
7973 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7974 .addReg(LHS2).addReg(RHS2)
7975 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7978 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7979 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7980 if (MI->getOperand(0).getImm() == ARMCC::NE)
7981 std::swap(destMBB, exitMBB);
7983 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7984 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7986 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7988 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7990 MI->eraseFromParent(); // The pseudo instruction is gone now.
7994 case ARM::Int_eh_sjlj_setjmp:
7995 case ARM::Int_eh_sjlj_setjmp_nofp:
7996 case ARM::tInt_eh_sjlj_setjmp:
7997 case ARM::t2Int_eh_sjlj_setjmp:
7998 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8001 case ARM::Int_eh_sjlj_setup_dispatch:
8002 EmitSjLjDispatchBlock(MI, BB);
8007 // To insert an ABS instruction, we have to insert the
8008 // diamond control-flow pattern. The incoming instruction knows the
8009 // source vreg to test against 0, the destination vreg to set,
8010 // the condition code register to branch on, the
8011 // true/false values to select between, and a branch opcode to use.
8016 // BCC (branch to SinkBB if V0 >= 0)
8017 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8018 // SinkBB: V1 = PHI(V2, V3)
8019 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8020 MachineFunction::iterator BBI = ++BB->getIterator();
8021 MachineFunction *Fn = BB->getParent();
8022 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8023 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8024 Fn->insert(BBI, RSBBB);
8025 Fn->insert(BBI, SinkBB);
8027 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8028 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8029 bool ABSSrcKIll = MI->getOperand(1).isKill();
8030 bool isThumb2 = Subtarget->isThumb2();
8031 MachineRegisterInfo &MRI = Fn->getRegInfo();
8032 // In Thumb mode S must not be specified if source register is the SP or
8033 // PC and if destination register is the SP, so restrict register class
8034 unsigned NewRsbDstReg =
8035 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8037 // Transfer the remainder of BB and its successor edges to sinkMBB.
8038 SinkBB->splice(SinkBB->begin(), BB,
8039 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8040 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8042 BB->addSuccessor(RSBBB);
8043 BB->addSuccessor(SinkBB);
8045 // fall through to SinkMBB
8046 RSBBB->addSuccessor(SinkBB);
8048 // insert a cmp at the end of BB
8049 AddDefaultPred(BuildMI(BB, dl,
8050 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8051 .addReg(ABSSrcReg).addImm(0));
8053 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8055 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8056 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8058 // insert rsbri in RSBBB
8059 // Note: BCC and rsbri will be converted into predicated rsbmi
8060 // by if-conversion pass
8061 BuildMI(*RSBBB, RSBBB->begin(), dl,
8062 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8063 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8064 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8066 // insert PHI in SinkBB,
8067 // reuse ABSDstReg to not change uses of ABS instruction
8068 BuildMI(*SinkBB, SinkBB->begin(), dl,
8069 TII->get(ARM::PHI), ABSDstReg)
8070 .addReg(NewRsbDstReg).addMBB(RSBBB)
8071 .addReg(ABSSrcReg).addMBB(BB);
8073 // remove ABS instruction
8074 MI->eraseFromParent();
8076 // return last added BB
8079 case ARM::COPY_STRUCT_BYVAL_I32:
8081 return EmitStructByval(MI, BB);
8082 case ARM::WIN__CHKSTK:
8083 return EmitLowered__chkstk(MI, BB);
8084 case ARM::WIN__DBZCHK:
8085 return EmitLowered__dbzchk(MI, BB);
8089 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8090 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8091 /// instead of as a custom inserter because we need the use list from the SDNode.
8092 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8093 MachineInstr *MI, const SDNode *Node) {
8094 bool isThumb1 = Subtarget->isThumb1Only();
8096 DebugLoc DL = MI->getDebugLoc();
8097 MachineFunction *MF = MI->getParent()->getParent();
8098 MachineRegisterInfo &MRI = MF->getRegInfo();
8099 MachineInstrBuilder MIB(*MF, MI);
8101 // If the new dst/src is unused mark it as dead.
8102 if (!Node->hasAnyUseOfValue(0)) {
8103 MI->getOperand(0).setIsDead(true);
8105 if (!Node->hasAnyUseOfValue(1)) {
8106 MI->getOperand(1).setIsDead(true);
8109 // The MEMCPY both defines and kills the scratch registers.
8110 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8111 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8112 : &ARM::GPRRegClass);
8113 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8117 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8118 SDNode *Node) const {
8119 if (MI->getOpcode() == ARM::MEMCPY) {
8120 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8124 const MCInstrDesc *MCID = &MI->getDesc();
8125 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8126 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8127 // operand is still set to noreg. If needed, set the optional operand's
8128 // register to CPSR, and remove the redundant implicit def.
8130 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8132 // Rename pseudo opcodes.
8133 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8135 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8136 MCID = &TII->get(NewOpc);
8138 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8139 "converted opcode should be the same except for cc_out");
8143 // Add the optional cc_out operand
8144 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8146 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8148 // Any ARM instruction that sets the 's' bit should specify an optional
8149 // "cc_out" operand in the last operand position.
8150 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8151 assert(!NewOpc && "Optional cc_out operand required");
8154 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8155 // since we already have an optional CPSR def.
8156 bool definesCPSR = false;
8157 bool deadCPSR = false;
8158 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8160 const MachineOperand &MO = MI->getOperand(i);
8161 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8165 MI->RemoveOperand(i);
8170 assert(!NewOpc && "Optional cc_out operand required");
8173 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8175 assert(!MI->getOperand(ccOutIdx).getReg() &&
8176 "expect uninitialized optional cc_out operand");
8180 // If this instruction was defined with an optional CPSR def and its dag node
8181 // had a live implicit CPSR def, then activate the optional CPSR def.
8182 MachineOperand &MO = MI->getOperand(ccOutIdx);
8183 MO.setReg(ARM::CPSR);
8187 //===----------------------------------------------------------------------===//
8188 // ARM Optimization Hooks
8189 //===----------------------------------------------------------------------===//
8191 // Helper function that checks if N is a null or all ones constant.
8192 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8193 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8196 // Return true if N is conditionally 0 or all ones.
8197 // Detects these expressions where cc is an i1 value:
8199 // (select cc 0, y) [AllOnes=0]
8200 // (select cc y, 0) [AllOnes=0]
8201 // (zext cc) [AllOnes=0]
8202 // (sext cc) [AllOnes=0/1]
8203 // (select cc -1, y) [AllOnes=1]
8204 // (select cc y, -1) [AllOnes=1]
8206 // Invert is set when N is the null/all ones constant when CC is false.
8207 // OtherOp is set to the alternative value of N.
8208 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8209 SDValue &CC, bool &Invert,
8211 SelectionDAG &DAG) {
8212 switch (N->getOpcode()) {
8213 default: return false;
8215 CC = N->getOperand(0);
8216 SDValue N1 = N->getOperand(1);
8217 SDValue N2 = N->getOperand(2);
8218 if (isZeroOrAllOnes(N1, AllOnes)) {
8223 if (isZeroOrAllOnes(N2, AllOnes)) {
8230 case ISD::ZERO_EXTEND:
8231 // (zext cc) can never be the all ones value.
8235 case ISD::SIGN_EXTEND: {
8237 EVT VT = N->getValueType(0);
8238 CC = N->getOperand(0);
8239 if (CC.getValueType() != MVT::i1)
8243 // When looking for an AllOnes constant, N is an sext, and the 'other'
8245 OtherOp = DAG.getConstant(0, dl, VT);
8246 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8247 // When looking for a 0 constant, N can be zext or sext.
8248 OtherOp = DAG.getConstant(1, dl, VT);
8250 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8257 // Combine a constant select operand into its use:
8259 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8260 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8261 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8262 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8263 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8265 // The transform is rejected if the select doesn't have a constant operand that
8266 // is null, or all ones when AllOnes is set.
8268 // Also recognize sext/zext from i1:
8270 // (add (zext cc), x) -> (select cc (add x, 1), x)
8271 // (add (sext cc), x) -> (select cc (add x, -1), x)
8273 // These transformations eventually create predicated instructions.
8275 // @param N The node to transform.
8276 // @param Slct The N operand that is a select.
8277 // @param OtherOp The other N operand (x above).
8278 // @param DCI Context.
8279 // @param AllOnes Require the select constant to be all ones instead of null.
8280 // @returns The new node, or SDValue() on failure.
8282 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8283 TargetLowering::DAGCombinerInfo &DCI,
8284 bool AllOnes = false) {
8285 SelectionDAG &DAG = DCI.DAG;
8286 EVT VT = N->getValueType(0);
8287 SDValue NonConstantVal;
8290 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8291 NonConstantVal, DAG))
8294 // Slct is now know to be the desired identity constant when CC is true.
8295 SDValue TrueVal = OtherOp;
8296 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8297 OtherOp, NonConstantVal);
8298 // Unless SwapSelectOps says CC should be false.
8300 std::swap(TrueVal, FalseVal);
8302 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8303 CCOp, TrueVal, FalseVal);
8306 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8308 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8309 TargetLowering::DAGCombinerInfo &DCI) {
8310 SDValue N0 = N->getOperand(0);
8311 SDValue N1 = N->getOperand(1);
8312 if (N0.getNode()->hasOneUse()) {
8313 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8314 if (Result.getNode())
8317 if (N1.getNode()->hasOneUse()) {
8318 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8319 if (Result.getNode())
8325 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8326 // (only after legalization).
8327 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8328 TargetLowering::DAGCombinerInfo &DCI,
8329 const ARMSubtarget *Subtarget) {
8331 // Only perform optimization if after legalize, and if NEON is available. We
8332 // also expected both operands to be BUILD_VECTORs.
8333 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8334 || N0.getOpcode() != ISD::BUILD_VECTOR
8335 || N1.getOpcode() != ISD::BUILD_VECTOR)
8338 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8339 EVT VT = N->getValueType(0);
8340 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8343 // Check that the vector operands are of the right form.
8344 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8345 // operands, where N is the size of the formed vector.
8346 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8347 // index such that we have a pair wise add pattern.
8349 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8350 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8352 SDValue Vec = N0->getOperand(0)->getOperand(0);
8353 SDNode *V = Vec.getNode();
8354 unsigned nextIndex = 0;
8356 // For each operands to the ADD which are BUILD_VECTORs,
8357 // check to see if each of their operands are an EXTRACT_VECTOR with
8358 // the same vector and appropriate index.
8359 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8360 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8361 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8363 SDValue ExtVec0 = N0->getOperand(i);
8364 SDValue ExtVec1 = N1->getOperand(i);
8366 // First operand is the vector, verify its the same.
8367 if (V != ExtVec0->getOperand(0).getNode() ||
8368 V != ExtVec1->getOperand(0).getNode())
8371 // Second is the constant, verify its correct.
8372 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8373 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8375 // For the constant, we want to see all the even or all the odd.
8376 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8377 || C1->getZExtValue() != nextIndex+1)
8386 // Create VPADDL node.
8387 SelectionDAG &DAG = DCI.DAG;
8388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8392 // Build operand list.
8393 SmallVector<SDValue, 8> Ops;
8394 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8395 TLI.getPointerTy(DAG.getDataLayout())));
8397 // Input is the vector.
8400 // Get widened type and narrowed type.
8402 unsigned numElem = VT.getVectorNumElements();
8404 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8405 switch (inputLaneType.getSimpleVT().SimpleTy) {
8406 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8407 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8408 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8410 llvm_unreachable("Invalid vector element type for padd optimization.");
8413 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8414 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8415 return DAG.getNode(ExtOp, dl, VT, tmp);
8418 static SDValue findMUL_LOHI(SDValue V) {
8419 if (V->getOpcode() == ISD::UMUL_LOHI ||
8420 V->getOpcode() == ISD::SMUL_LOHI)
8425 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8426 TargetLowering::DAGCombinerInfo &DCI,
8427 const ARMSubtarget *Subtarget) {
8429 if (Subtarget->isThumb1Only()) return SDValue();
8431 // Only perform the checks after legalize when the pattern is available.
8432 if (DCI.isBeforeLegalize()) return SDValue();
8434 // Look for multiply add opportunities.
8435 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8436 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8437 // a glue link from the first add to the second add.
8438 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8439 // a S/UMLAL instruction.
8442 // / \ [no multiline comment]
8448 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8449 SDValue AddcOp0 = AddcNode->getOperand(0);
8450 SDValue AddcOp1 = AddcNode->getOperand(1);
8452 // Check if the two operands are from the same mul_lohi node.
8453 if (AddcOp0.getNode() == AddcOp1.getNode())
8456 assert(AddcNode->getNumValues() == 2 &&
8457 AddcNode->getValueType(0) == MVT::i32 &&
8458 "Expect ADDC with two result values. First: i32");
8460 // Check that we have a glued ADDC node.
8461 if (AddcNode->getValueType(1) != MVT::Glue)
8464 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8465 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8466 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8467 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8468 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8471 // Look for the glued ADDE.
8472 SDNode* AddeNode = AddcNode->getGluedUser();
8476 // Make sure it is really an ADDE.
8477 if (AddeNode->getOpcode() != ISD::ADDE)
8480 assert(AddeNode->getNumOperands() == 3 &&
8481 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8482 "ADDE node has the wrong inputs");
8484 // Check for the triangle shape.
8485 SDValue AddeOp0 = AddeNode->getOperand(0);
8486 SDValue AddeOp1 = AddeNode->getOperand(1);
8488 // Make sure that the ADDE operands are not coming from the same node.
8489 if (AddeOp0.getNode() == AddeOp1.getNode())
8492 // Find the MUL_LOHI node walking up ADDE's operands.
8493 bool IsLeftOperandMUL = false;
8494 SDValue MULOp = findMUL_LOHI(AddeOp0);
8495 if (MULOp == SDValue())
8496 MULOp = findMUL_LOHI(AddeOp1);
8498 IsLeftOperandMUL = true;
8499 if (MULOp == SDValue())
8502 // Figure out the right opcode.
8503 unsigned Opc = MULOp->getOpcode();
8504 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8506 // Figure out the high and low input values to the MLAL node.
8507 SDValue* HiAdd = nullptr;
8508 SDValue* LoMul = nullptr;
8509 SDValue* LowAdd = nullptr;
8511 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8512 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8515 if (IsLeftOperandMUL)
8521 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8522 // whose low result is fed to the ADDC we are checking.
8524 if (AddcOp0 == MULOp.getValue(0)) {
8528 if (AddcOp1 == MULOp.getValue(0)) {
8536 // Create the merged node.
8537 SelectionDAG &DAG = DCI.DAG;
8539 // Build operand list.
8540 SmallVector<SDValue, 8> Ops;
8541 Ops.push_back(LoMul->getOperand(0));
8542 Ops.push_back(LoMul->getOperand(1));
8543 Ops.push_back(*LowAdd);
8544 Ops.push_back(*HiAdd);
8546 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8547 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8549 // Replace the ADDs' nodes uses by the MLA node's values.
8550 SDValue HiMLALResult(MLALNode.getNode(), 1);
8551 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8553 SDValue LoMLALResult(MLALNode.getNode(), 0);
8554 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8556 // Return original node to notify the driver to stop replacing.
8557 SDValue resNode(AddcNode, 0);
8561 /// PerformADDCCombine - Target-specific dag combine transform from
8562 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8563 static SDValue PerformADDCCombine(SDNode *N,
8564 TargetLowering::DAGCombinerInfo &DCI,
8565 const ARMSubtarget *Subtarget) {
8567 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8571 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8572 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8573 /// called with the default operands, and if that fails, with commuted
8575 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8576 TargetLowering::DAGCombinerInfo &DCI,
8577 const ARMSubtarget *Subtarget){
8579 // Attempt to create vpaddl for this add.
8580 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8581 if (Result.getNode())
8584 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8585 if (N0.getNode()->hasOneUse()) {
8586 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8587 if (Result.getNode()) return Result;
8592 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8594 static SDValue PerformADDCombine(SDNode *N,
8595 TargetLowering::DAGCombinerInfo &DCI,
8596 const ARMSubtarget *Subtarget) {
8597 SDValue N0 = N->getOperand(0);
8598 SDValue N1 = N->getOperand(1);
8600 // First try with the default operand order.
8601 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8602 if (Result.getNode())
8605 // If that didn't work, try again with the operands commuted.
8606 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8609 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8611 static SDValue PerformSUBCombine(SDNode *N,
8612 TargetLowering::DAGCombinerInfo &DCI) {
8613 SDValue N0 = N->getOperand(0);
8614 SDValue N1 = N->getOperand(1);
8616 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8617 if (N1.getNode()->hasOneUse()) {
8618 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8619 if (Result.getNode()) return Result;
8625 /// PerformVMULCombine
8626 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8627 /// special multiplier accumulator forwarding.
8633 // However, for (A + B) * (A + B),
8640 static SDValue PerformVMULCombine(SDNode *N,
8641 TargetLowering::DAGCombinerInfo &DCI,
8642 const ARMSubtarget *Subtarget) {
8643 if (!Subtarget->hasVMLxForwarding())
8646 SelectionDAG &DAG = DCI.DAG;
8647 SDValue N0 = N->getOperand(0);
8648 SDValue N1 = N->getOperand(1);
8649 unsigned Opcode = N0.getOpcode();
8650 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8651 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8652 Opcode = N1.getOpcode();
8653 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8654 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8662 EVT VT = N->getValueType(0);
8664 SDValue N00 = N0->getOperand(0);
8665 SDValue N01 = N0->getOperand(1);
8666 return DAG.getNode(Opcode, DL, VT,
8667 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8668 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8671 static SDValue PerformMULCombine(SDNode *N,
8672 TargetLowering::DAGCombinerInfo &DCI,
8673 const ARMSubtarget *Subtarget) {
8674 SelectionDAG &DAG = DCI.DAG;
8676 if (Subtarget->isThumb1Only())
8679 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8682 EVT VT = N->getValueType(0);
8683 if (VT.is64BitVector() || VT.is128BitVector())
8684 return PerformVMULCombine(N, DCI, Subtarget);
8688 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8692 int64_t MulAmt = C->getSExtValue();
8693 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8695 ShiftAmt = ShiftAmt & (32 - 1);
8696 SDValue V = N->getOperand(0);
8700 MulAmt >>= ShiftAmt;
8703 if (isPowerOf2_32(MulAmt - 1)) {
8704 // (mul x, 2^N + 1) => (add (shl x, N), x)
8705 Res = DAG.getNode(ISD::ADD, DL, VT,
8707 DAG.getNode(ISD::SHL, DL, VT,
8709 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8711 } else if (isPowerOf2_32(MulAmt + 1)) {
8712 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8713 Res = DAG.getNode(ISD::SUB, DL, VT,
8714 DAG.getNode(ISD::SHL, DL, VT,
8716 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8722 uint64_t MulAmtAbs = -MulAmt;
8723 if (isPowerOf2_32(MulAmtAbs + 1)) {
8724 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8725 Res = DAG.getNode(ISD::SUB, DL, VT,
8727 DAG.getNode(ISD::SHL, DL, VT,
8729 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8731 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8732 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8733 Res = DAG.getNode(ISD::ADD, DL, VT,
8735 DAG.getNode(ISD::SHL, DL, VT,
8737 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8739 Res = DAG.getNode(ISD::SUB, DL, VT,
8740 DAG.getConstant(0, DL, MVT::i32), Res);
8747 Res = DAG.getNode(ISD::SHL, DL, VT,
8748 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8750 // Do not add new nodes to DAG combiner worklist.
8751 DCI.CombineTo(N, Res, false);
8755 static SDValue PerformANDCombine(SDNode *N,
8756 TargetLowering::DAGCombinerInfo &DCI,
8757 const ARMSubtarget *Subtarget) {
8759 // Attempt to use immediate-form VBIC
8760 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8762 EVT VT = N->getValueType(0);
8763 SelectionDAG &DAG = DCI.DAG;
8765 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8768 APInt SplatBits, SplatUndef;
8769 unsigned SplatBitSize;
8772 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8773 if (SplatBitSize <= 64) {
8775 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8776 SplatUndef.getZExtValue(), SplatBitSize,
8777 DAG, dl, VbicVT, VT.is128BitVector(),
8779 if (Val.getNode()) {
8781 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8782 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8783 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8788 if (!Subtarget->isThumb1Only()) {
8789 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8790 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8791 if (Result.getNode())
8798 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8799 static SDValue PerformORCombine(SDNode *N,
8800 TargetLowering::DAGCombinerInfo &DCI,
8801 const ARMSubtarget *Subtarget) {
8802 // Attempt to use immediate-form VORR
8803 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8805 EVT VT = N->getValueType(0);
8806 SelectionDAG &DAG = DCI.DAG;
8808 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8811 APInt SplatBits, SplatUndef;
8812 unsigned SplatBitSize;
8814 if (BVN && Subtarget->hasNEON() &&
8815 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8816 if (SplatBitSize <= 64) {
8818 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8819 SplatUndef.getZExtValue(), SplatBitSize,
8820 DAG, dl, VorrVT, VT.is128BitVector(),
8822 if (Val.getNode()) {
8824 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8825 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8826 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8831 if (!Subtarget->isThumb1Only()) {
8832 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8833 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8834 if (Result.getNode())
8838 // The code below optimizes (or (and X, Y), Z).
8839 // The AND operand needs to have a single user to make these optimizations
8841 SDValue N0 = N->getOperand(0);
8842 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8844 SDValue N1 = N->getOperand(1);
8846 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8847 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8848 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8850 unsigned SplatBitSize;
8853 APInt SplatBits0, SplatBits1;
8854 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8855 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8856 // Ensure that the second operand of both ands are constants
8857 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8858 HasAnyUndefs) && !HasAnyUndefs) {
8859 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8860 HasAnyUndefs) && !HasAnyUndefs) {
8861 // Ensure that the bit width of the constants are the same and that
8862 // the splat arguments are logical inverses as per the pattern we
8863 // are trying to simplify.
8864 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8865 SplatBits0 == ~SplatBits1) {
8866 // Canonicalize the vector type to make instruction selection
8868 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8869 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8873 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8879 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8882 // BFI is only available on V6T2+
8883 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8887 // 1) or (and A, mask), val => ARMbfi A, val, mask
8888 // iff (val & mask) == val
8890 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8891 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8892 // && mask == ~mask2
8893 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8894 // && ~mask == mask2
8895 // (i.e., copy a bitfield value into another bitfield of the same width)
8900 SDValue N00 = N0.getOperand(0);
8902 // The value and the mask need to be constants so we can verify this is
8903 // actually a bitfield set. If the mask is 0xffff, we can do better
8904 // via a movt instruction, so don't use BFI in that case.
8905 SDValue MaskOp = N0.getOperand(1);
8906 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8909 unsigned Mask = MaskC->getZExtValue();
8913 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8914 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8916 unsigned Val = N1C->getZExtValue();
8917 if ((Val & ~Mask) != Val)
8920 if (ARM::isBitFieldInvertedMask(Mask)) {
8921 Val >>= countTrailingZeros(~Mask);
8923 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8924 DAG.getConstant(Val, DL, MVT::i32),
8925 DAG.getConstant(Mask, DL, MVT::i32));
8927 // Do not add new nodes to DAG combiner worklist.
8928 DCI.CombineTo(N, Res, false);
8931 } else if (N1.getOpcode() == ISD::AND) {
8932 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8933 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8936 unsigned Mask2 = N11C->getZExtValue();
8938 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8940 if (ARM::isBitFieldInvertedMask(Mask) &&
8942 // The pack halfword instruction works better for masks that fit it,
8943 // so use that when it's available.
8944 if (Subtarget->hasT2ExtractPack() &&
8945 (Mask == 0xffff || Mask == 0xffff0000))
8948 unsigned amt = countTrailingZeros(Mask2);
8949 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8950 DAG.getConstant(amt, DL, MVT::i32));
8951 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8952 DAG.getConstant(Mask, DL, MVT::i32));
8953 // Do not add new nodes to DAG combiner worklist.
8954 DCI.CombineTo(N, Res, false);
8956 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8958 // The pack halfword instruction works better for masks that fit it,
8959 // so use that when it's available.
8960 if (Subtarget->hasT2ExtractPack() &&
8961 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8964 unsigned lsb = countTrailingZeros(Mask);
8965 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8966 DAG.getConstant(lsb, DL, MVT::i32));
8967 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8968 DAG.getConstant(Mask2, DL, MVT::i32));
8969 // Do not add new nodes to DAG combiner worklist.
8970 DCI.CombineTo(N, Res, false);
8975 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8976 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8977 ARM::isBitFieldInvertedMask(~Mask)) {
8978 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8979 // where lsb(mask) == #shamt and masked bits of B are known zero.
8980 SDValue ShAmt = N00.getOperand(1);
8981 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8982 unsigned LSB = countTrailingZeros(Mask);
8986 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8987 DAG.getConstant(~Mask, DL, MVT::i32));
8989 // Do not add new nodes to DAG combiner worklist.
8990 DCI.CombineTo(N, Res, false);
8996 static SDValue PerformXORCombine(SDNode *N,
8997 TargetLowering::DAGCombinerInfo &DCI,
8998 const ARMSubtarget *Subtarget) {
8999 EVT VT = N->getValueType(0);
9000 SelectionDAG &DAG = DCI.DAG;
9002 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9005 if (!Subtarget->isThumb1Only()) {
9006 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9007 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9008 if (Result.getNode())
9015 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9016 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9017 // their position in "to" (Rd).
9018 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9019 assert(N->getOpcode() == ARMISD::BFI);
9021 SDValue From = N->getOperand(1);
9022 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9023 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9025 // If the Base came from a SHR #C, we can deduce that it is really testing bit
9026 // #C in the base of the SHR.
9027 if (From->getOpcode() == ISD::SRL &&
9028 isa<ConstantSDNode>(From->getOperand(1))) {
9029 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9030 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9031 FromMask <<= Shift.getLimitedValue(31);
9032 From = From->getOperand(0);
9038 // If A and B contain one contiguous set of bits, does A | B == A . B?
9040 // Neither A nor B must be zero.
9041 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9042 unsigned LastActiveBitInA = A.countTrailingZeros();
9043 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9044 return LastActiveBitInA - 1 == FirstActiveBitInB;
9047 static SDValue FindBFIToCombineWith(SDNode *N) {
9048 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9050 APInt ToMask, FromMask;
9051 SDValue From = ParseBFI(N, ToMask, FromMask);
9052 SDValue To = N->getOperand(0);
9054 // Now check for a compatible BFI to merge with. We can pass through BFIs that
9055 // aren't compatible, but not if they set the same bit in their destination as
9056 // we do (or that of any BFI we're going to combine with).
9058 APInt CombinedToMask = ToMask;
9059 while (V.getOpcode() == ARMISD::BFI) {
9060 APInt NewToMask, NewFromMask;
9061 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9062 if (NewFrom != From) {
9063 // This BFI has a different base. Keep going.
9064 CombinedToMask |= NewToMask;
9065 V = V.getOperand(0);
9069 // Do the written bits conflict with any we've seen so far?
9070 if ((NewToMask & CombinedToMask).getBoolValue())
9071 // Conflicting bits - bail out because going further is unsafe.
9074 // Are the new bits contiguous when combined with the old bits?
9075 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9076 BitsProperlyConcatenate(FromMask, NewFromMask))
9078 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9079 BitsProperlyConcatenate(NewFromMask, FromMask))
9082 // We've seen a write to some bits, so track it.
9083 CombinedToMask |= NewToMask;
9085 V = V.getOperand(0);
9091 static SDValue PerformBFICombine(SDNode *N,
9092 TargetLowering::DAGCombinerInfo &DCI) {
9093 SDValue N1 = N->getOperand(1);
9094 if (N1.getOpcode() == ISD::AND) {
9095 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9096 // the bits being cleared by the AND are not demanded by the BFI.
9097 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9100 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9101 unsigned LSB = countTrailingZeros(~InvMask);
9102 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9104 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9105 "undefined behavior");
9106 unsigned Mask = (1u << Width) - 1;
9107 unsigned Mask2 = N11C->getZExtValue();
9108 if ((Mask & (~Mask2)) == 0)
9109 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9110 N->getOperand(0), N1.getOperand(0),
9112 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9113 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9114 // Keep track of any consecutive bits set that all come from the same base
9115 // value. We can combine these together into a single BFI.
9116 SDValue CombineBFI = FindBFIToCombineWith(N);
9117 if (CombineBFI == SDValue())
9120 // We've found a BFI.
9121 APInt ToMask1, FromMask1;
9122 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9124 APInt ToMask2, FromMask2;
9125 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9126 assert(From1 == From2);
9129 // First, unlink CombineBFI.
9130 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9131 // Then create a new BFI, combining the two together.
9132 APInt NewFromMask = FromMask1 | FromMask2;
9133 APInt NewToMask = ToMask1 | ToMask2;
9135 EVT VT = N->getValueType(0);
9138 if (NewFromMask[0] == 0)
9139 From1 = DCI.DAG.getNode(
9140 ISD::SRL, dl, VT, From1,
9141 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9142 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9143 DCI.DAG.getConstant(~NewToMask, dl, VT));
9148 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9149 /// ARMISD::VMOVRRD.
9150 static SDValue PerformVMOVRRDCombine(SDNode *N,
9151 TargetLowering::DAGCombinerInfo &DCI,
9152 const ARMSubtarget *Subtarget) {
9153 // vmovrrd(vmovdrr x, y) -> x,y
9154 SDValue InDouble = N->getOperand(0);
9155 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9156 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9158 // vmovrrd(load f64) -> (load i32), (load i32)
9159 SDNode *InNode = InDouble.getNode();
9160 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9161 InNode->getValueType(0) == MVT::f64 &&
9162 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9163 !cast<LoadSDNode>(InNode)->isVolatile()) {
9164 // TODO: Should this be done for non-FrameIndex operands?
9165 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9167 SelectionDAG &DAG = DCI.DAG;
9169 SDValue BasePtr = LD->getBasePtr();
9170 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9171 LD->getPointerInfo(), LD->isVolatile(),
9172 LD->isNonTemporal(), LD->isInvariant(),
9173 LD->getAlignment());
9175 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9176 DAG.getConstant(4, DL, MVT::i32));
9177 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9178 LD->getPointerInfo(), LD->isVolatile(),
9179 LD->isNonTemporal(), LD->isInvariant(),
9180 std::min(4U, LD->getAlignment() / 2));
9182 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9183 if (DCI.DAG.getDataLayout().isBigEndian())
9184 std::swap (NewLD1, NewLD2);
9185 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9192 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9193 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9194 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9195 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9196 SDValue Op0 = N->getOperand(0);
9197 SDValue Op1 = N->getOperand(1);
9198 if (Op0.getOpcode() == ISD::BITCAST)
9199 Op0 = Op0.getOperand(0);
9200 if (Op1.getOpcode() == ISD::BITCAST)
9201 Op1 = Op1.getOperand(0);
9202 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9203 Op0.getNode() == Op1.getNode() &&
9204 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9205 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9206 N->getValueType(0), Op0.getOperand(0));
9210 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9211 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9212 /// i64 vector to have f64 elements, since the value can then be loaded
9213 /// directly into a VFP register.
9214 static bool hasNormalLoadOperand(SDNode *N) {
9215 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9216 for (unsigned i = 0; i < NumElts; ++i) {
9217 SDNode *Elt = N->getOperand(i).getNode();
9218 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9224 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9225 /// ISD::BUILD_VECTOR.
9226 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9227 TargetLowering::DAGCombinerInfo &DCI,
9228 const ARMSubtarget *Subtarget) {
9229 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9230 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9231 // into a pair of GPRs, which is fine when the value is used as a scalar,
9232 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9233 SelectionDAG &DAG = DCI.DAG;
9234 if (N->getNumOperands() == 2) {
9235 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9240 // Load i64 elements as f64 values so that type legalization does not split
9241 // them up into i32 values.
9242 EVT VT = N->getValueType(0);
9243 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9246 SmallVector<SDValue, 8> Ops;
9247 unsigned NumElts = VT.getVectorNumElements();
9248 for (unsigned i = 0; i < NumElts; ++i) {
9249 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9251 // Make the DAGCombiner fold the bitcast.
9252 DCI.AddToWorklist(V.getNode());
9254 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9255 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9256 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9259 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9261 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9262 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9263 // At that time, we may have inserted bitcasts from integer to float.
9264 // If these bitcasts have survived DAGCombine, change the lowering of this
9265 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9266 // force to use floating point types.
9268 // Make sure we can change the type of the vector.
9269 // This is possible iff:
9270 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9271 // 1.1. Vector is used only once.
9272 // 1.2. Use is a bit convert to an integer type.
9273 // 2. The size of its operands are 32-bits (64-bits are not legal).
9274 EVT VT = N->getValueType(0);
9275 EVT EltVT = VT.getVectorElementType();
9277 // Check 1.1. and 2.
9278 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9281 // By construction, the input type must be float.
9282 assert(EltVT == MVT::f32 && "Unexpected type!");
9285 SDNode *Use = *N->use_begin();
9286 if (Use->getOpcode() != ISD::BITCAST ||
9287 Use->getValueType(0).isFloatingPoint())
9290 // Check profitability.
9291 // Model is, if more than half of the relevant operands are bitcast from
9292 // i32, turn the build_vector into a sequence of insert_vector_elt.
9293 // Relevant operands are everything that is not statically
9294 // (i.e., at compile time) bitcasted.
9295 unsigned NumOfBitCastedElts = 0;
9296 unsigned NumElts = VT.getVectorNumElements();
9297 unsigned NumOfRelevantElts = NumElts;
9298 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9299 SDValue Elt = N->getOperand(Idx);
9300 if (Elt->getOpcode() == ISD::BITCAST) {
9301 // Assume only bit cast to i32 will go away.
9302 if (Elt->getOperand(0).getValueType() == MVT::i32)
9303 ++NumOfBitCastedElts;
9304 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9305 // Constants are statically casted, thus do not count them as
9306 // relevant operands.
9307 --NumOfRelevantElts;
9310 // Check if more than half of the elements require a non-free bitcast.
9311 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9314 SelectionDAG &DAG = DCI.DAG;
9315 // Create the new vector type.
9316 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9317 // Check if the type is legal.
9318 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9319 if (!TLI.isTypeLegal(VecVT))
9323 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9324 // => BITCAST INSERT_VECTOR_ELT
9325 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9327 SDValue Vec = DAG.getUNDEF(VecVT);
9329 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9330 SDValue V = N->getOperand(Idx);
9331 if (V.getOpcode() == ISD::UNDEF)
9333 if (V.getOpcode() == ISD::BITCAST &&
9334 V->getOperand(0).getValueType() == MVT::i32)
9335 // Fold obvious case.
9336 V = V.getOperand(0);
9338 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9339 // Make the DAGCombiner fold the bitcasts.
9340 DCI.AddToWorklist(V.getNode());
9342 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9343 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9345 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9346 // Make the DAGCombiner fold the bitcasts.
9347 DCI.AddToWorklist(Vec.getNode());
9351 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9352 /// ISD::INSERT_VECTOR_ELT.
9353 static SDValue PerformInsertEltCombine(SDNode *N,
9354 TargetLowering::DAGCombinerInfo &DCI) {
9355 // Bitcast an i64 load inserted into a vector to f64.
9356 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9357 EVT VT = N->getValueType(0);
9358 SDNode *Elt = N->getOperand(1).getNode();
9359 if (VT.getVectorElementType() != MVT::i64 ||
9360 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9363 SelectionDAG &DAG = DCI.DAG;
9365 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9366 VT.getVectorNumElements());
9367 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9368 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9369 // Make the DAGCombiner fold the bitcasts.
9370 DCI.AddToWorklist(Vec.getNode());
9371 DCI.AddToWorklist(V.getNode());
9372 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9373 Vec, V, N->getOperand(2));
9374 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9377 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9378 /// ISD::VECTOR_SHUFFLE.
9379 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9380 // The LLVM shufflevector instruction does not require the shuffle mask
9381 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9382 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9383 // operands do not match the mask length, they are extended by concatenating
9384 // them with undef vectors. That is probably the right thing for other
9385 // targets, but for NEON it is better to concatenate two double-register
9386 // size vector operands into a single quad-register size vector. Do that
9387 // transformation here:
9388 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9389 // shuffle(concat(v1, v2), undef)
9390 SDValue Op0 = N->getOperand(0);
9391 SDValue Op1 = N->getOperand(1);
9392 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9393 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9394 Op0.getNumOperands() != 2 ||
9395 Op1.getNumOperands() != 2)
9397 SDValue Concat0Op1 = Op0.getOperand(1);
9398 SDValue Concat1Op1 = Op1.getOperand(1);
9399 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9400 Concat1Op1.getOpcode() != ISD::UNDEF)
9402 // Skip the transformation if any of the types are illegal.
9403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9404 EVT VT = N->getValueType(0);
9405 if (!TLI.isTypeLegal(VT) ||
9406 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9407 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9410 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9411 Op0.getOperand(0), Op1.getOperand(0));
9412 // Translate the shuffle mask.
9413 SmallVector<int, 16> NewMask;
9414 unsigned NumElts = VT.getVectorNumElements();
9415 unsigned HalfElts = NumElts/2;
9416 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9417 for (unsigned n = 0; n < NumElts; ++n) {
9418 int MaskElt = SVN->getMaskElt(n);
9420 if (MaskElt < (int)HalfElts)
9422 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9423 NewElt = HalfElts + MaskElt - NumElts;
9424 NewMask.push_back(NewElt);
9426 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9427 DAG.getUNDEF(VT), NewMask.data());
9430 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9431 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9432 /// base address updates.
9433 /// For generic load/stores, the memory type is assumed to be a vector.
9434 /// The caller is assumed to have checked legality.
9435 static SDValue CombineBaseUpdate(SDNode *N,
9436 TargetLowering::DAGCombinerInfo &DCI) {
9437 SelectionDAG &DAG = DCI.DAG;
9438 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9439 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9440 const bool isStore = N->getOpcode() == ISD::STORE;
9441 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9442 SDValue Addr = N->getOperand(AddrOpIdx);
9443 MemSDNode *MemN = cast<MemSDNode>(N);
9446 // Search for a use of the address operand that is an increment.
9447 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9448 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9450 if (User->getOpcode() != ISD::ADD ||
9451 UI.getUse().getResNo() != Addr.getResNo())
9454 // Check that the add is independent of the load/store. Otherwise, folding
9455 // it would create a cycle.
9456 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9459 // Find the new opcode for the updating load/store.
9460 bool isLoadOp = true;
9461 bool isLaneOp = false;
9462 unsigned NewOpc = 0;
9463 unsigned NumVecs = 0;
9465 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9467 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9468 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9470 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9472 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9474 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9476 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9477 NumVecs = 2; isLaneOp = true; break;
9478 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9479 NumVecs = 3; isLaneOp = true; break;
9480 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9481 NumVecs = 4; isLaneOp = true; break;
9482 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9483 NumVecs = 1; isLoadOp = false; break;
9484 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9485 NumVecs = 2; isLoadOp = false; break;
9486 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9487 NumVecs = 3; isLoadOp = false; break;
9488 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9489 NumVecs = 4; isLoadOp = false; break;
9490 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9491 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9492 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9493 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9494 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9495 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9499 switch (N->getOpcode()) {
9500 default: llvm_unreachable("unexpected opcode for Neon base update");
9501 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9502 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9503 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9504 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9505 NumVecs = 1; isLaneOp = false; break;
9506 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9507 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9511 // Find the size of memory referenced by the load/store.
9514 VecTy = N->getValueType(0);
9515 } else if (isIntrinsic) {
9516 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9518 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9519 VecTy = N->getOperand(1).getValueType();
9522 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9524 NumBytes /= VecTy.getVectorNumElements();
9526 // If the increment is a constant, it must match the memory ref size.
9527 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9528 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9529 uint64_t IncVal = CInc->getZExtValue();
9530 if (IncVal != NumBytes)
9532 } else if (NumBytes >= 3 * 16) {
9533 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9534 // separate instructions that make it harder to use a non-constant update.
9538 // OK, we found an ADD we can fold into the base update.
9539 // Now, create a _UPD node, taking care of not breaking alignment.
9541 EVT AlignedVecTy = VecTy;
9542 unsigned Alignment = MemN->getAlignment();
9544 // If this is a less-than-standard-aligned load/store, change the type to
9545 // match the standard alignment.
9546 // The alignment is overlooked when selecting _UPD variants; and it's
9547 // easier to introduce bitcasts here than fix that.
9548 // There are 3 ways to get to this base-update combine:
9549 // - intrinsics: they are assumed to be properly aligned (to the standard
9550 // alignment of the memory type), so we don't need to do anything.
9551 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9552 // intrinsics, so, likewise, there's nothing to do.
9553 // - generic load/store instructions: the alignment is specified as an
9554 // explicit operand, rather than implicitly as the standard alignment
9555 // of the memory type (like the intrisics). We need to change the
9556 // memory type to match the explicit alignment. That way, we don't
9557 // generate non-standard-aligned ARMISD::VLDx nodes.
9558 if (isa<LSBaseSDNode>(N)) {
9561 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9562 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9563 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9564 assert(!isLaneOp && "Unexpected generic load/store lane.");
9565 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9566 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9568 // Don't set an explicit alignment on regular load/stores that we want
9569 // to transform to VLD/VST 1_UPD nodes.
9570 // This matches the behavior of regular load/stores, which only get an
9571 // explicit alignment if the MMO alignment is larger than the standard
9572 // alignment of the memory type.
9573 // Intrinsics, however, always get an explicit alignment, set to the
9574 // alignment of the MMO.
9578 // Create the new updating load/store node.
9579 // First, create an SDVTList for the new updating node's results.
9581 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9583 for (n = 0; n < NumResultVecs; ++n)
9584 Tys[n] = AlignedVecTy;
9585 Tys[n++] = MVT::i32;
9586 Tys[n] = MVT::Other;
9587 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9589 // Then, gather the new node's operands.
9590 SmallVector<SDValue, 8> Ops;
9591 Ops.push_back(N->getOperand(0)); // incoming chain
9592 Ops.push_back(N->getOperand(AddrOpIdx));
9595 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9596 // Try to match the intrinsic's signature
9597 Ops.push_back(StN->getValue());
9599 // Loads (and of course intrinsics) match the intrinsics' signature,
9600 // so just add all but the alignment operand.
9601 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9602 Ops.push_back(N->getOperand(i));
9605 // For all node types, the alignment operand is always the last one.
9606 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9608 // If this is a non-standard-aligned STORE, the penultimate operand is the
9609 // stored value. Bitcast it to the aligned type.
9610 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9611 SDValue &StVal = Ops[Ops.size()-2];
9612 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9615 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9617 MemN->getMemOperand());
9620 SmallVector<SDValue, 5> NewResults;
9621 for (unsigned i = 0; i < NumResultVecs; ++i)
9622 NewResults.push_back(SDValue(UpdN.getNode(), i));
9624 // If this is an non-standard-aligned LOAD, the first result is the loaded
9625 // value. Bitcast it to the expected result type.
9626 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9627 SDValue &LdVal = NewResults[0];
9628 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9631 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9632 DCI.CombineTo(N, NewResults);
9633 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9640 static SDValue PerformVLDCombine(SDNode *N,
9641 TargetLowering::DAGCombinerInfo &DCI) {
9642 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9645 return CombineBaseUpdate(N, DCI);
9648 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9649 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9650 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9652 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9653 SelectionDAG &DAG = DCI.DAG;
9654 EVT VT = N->getValueType(0);
9655 // vldN-dup instructions only support 64-bit vectors for N > 1.
9656 if (!VT.is64BitVector())
9659 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9660 SDNode *VLD = N->getOperand(0).getNode();
9661 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9663 unsigned NumVecs = 0;
9664 unsigned NewOpc = 0;
9665 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9666 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9668 NewOpc = ARMISD::VLD2DUP;
9669 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9671 NewOpc = ARMISD::VLD3DUP;
9672 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9674 NewOpc = ARMISD::VLD4DUP;
9679 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9680 // numbers match the load.
9681 unsigned VLDLaneNo =
9682 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9683 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9685 // Ignore uses of the chain result.
9686 if (UI.getUse().getResNo() == NumVecs)
9689 if (User->getOpcode() != ARMISD::VDUPLANE ||
9690 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9694 // Create the vldN-dup node.
9697 for (n = 0; n < NumVecs; ++n)
9699 Tys[n] = MVT::Other;
9700 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9701 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9702 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9703 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9704 Ops, VLDMemInt->getMemoryVT(),
9705 VLDMemInt->getMemOperand());
9708 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9710 unsigned ResNo = UI.getUse().getResNo();
9711 // Ignore uses of the chain result.
9712 if (ResNo == NumVecs)
9715 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9718 // Now the vldN-lane intrinsic is dead except for its chain result.
9719 // Update uses of the chain.
9720 std::vector<SDValue> VLDDupResults;
9721 for (unsigned n = 0; n < NumVecs; ++n)
9722 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9723 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9724 DCI.CombineTo(VLD, VLDDupResults);
9729 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9730 /// ARMISD::VDUPLANE.
9731 static SDValue PerformVDUPLANECombine(SDNode *N,
9732 TargetLowering::DAGCombinerInfo &DCI) {
9733 SDValue Op = N->getOperand(0);
9735 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9736 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9737 if (CombineVLDDUP(N, DCI))
9738 return SDValue(N, 0);
9740 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9741 // redundant. Ignore bit_converts for now; element sizes are checked below.
9742 while (Op.getOpcode() == ISD::BITCAST)
9743 Op = Op.getOperand(0);
9744 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9747 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9748 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9749 // The canonical VMOV for a zero vector uses a 32-bit element size.
9750 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9752 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9754 EVT VT = N->getValueType(0);
9755 if (EltSize > VT.getVectorElementType().getSizeInBits())
9758 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9761 static SDValue PerformLOADCombine(SDNode *N,
9762 TargetLowering::DAGCombinerInfo &DCI) {
9763 EVT VT = N->getValueType(0);
9765 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9766 if (ISD::isNormalLoad(N) && VT.isVector() &&
9767 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9768 return CombineBaseUpdate(N, DCI);
9773 /// PerformSTORECombine - Target-specific dag combine xforms for
9775 static SDValue PerformSTORECombine(SDNode *N,
9776 TargetLowering::DAGCombinerInfo &DCI) {
9777 StoreSDNode *St = cast<StoreSDNode>(N);
9778 if (St->isVolatile())
9781 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9782 // pack all of the elements in one place. Next, store to memory in fewer
9784 SDValue StVal = St->getValue();
9785 EVT VT = StVal.getValueType();
9786 if (St->isTruncatingStore() && VT.isVector()) {
9787 SelectionDAG &DAG = DCI.DAG;
9788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9789 EVT StVT = St->getMemoryVT();
9790 unsigned NumElems = VT.getVectorNumElements();
9791 assert(StVT != VT && "Cannot truncate to the same type");
9792 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9793 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9795 // From, To sizes and ElemCount must be pow of two
9796 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9798 // We are going to use the original vector elt for storing.
9799 // Accumulated smaller vector elements must be a multiple of the store size.
9800 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9802 unsigned SizeRatio = FromEltSz / ToEltSz;
9803 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9805 // Create a type on which we perform the shuffle.
9806 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9807 NumElems*SizeRatio);
9808 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9811 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9812 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9813 for (unsigned i = 0; i < NumElems; ++i)
9814 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9815 ? (i + 1) * SizeRatio - 1
9818 // Can't shuffle using an illegal type.
9819 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9821 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9822 DAG.getUNDEF(WideVec.getValueType()),
9824 // At this point all of the data is stored at the bottom of the
9825 // register. We now need to save it to mem.
9827 // Find the largest store unit
9828 MVT StoreType = MVT::i8;
9829 for (MVT Tp : MVT::integer_valuetypes()) {
9830 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9833 // Didn't find a legal store type.
9834 if (!TLI.isTypeLegal(StoreType))
9837 // Bitcast the original vector into a vector of store-size units
9838 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9839 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9840 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9841 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9842 SmallVector<SDValue, 8> Chains;
9843 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9844 TLI.getPointerTy(DAG.getDataLayout()));
9845 SDValue BasePtr = St->getBasePtr();
9847 // Perform one or more big stores into memory.
9848 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9849 for (unsigned I = 0; I < E; I++) {
9850 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9851 StoreType, ShuffWide,
9852 DAG.getIntPtrConstant(I, DL));
9853 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9854 St->getPointerInfo(), St->isVolatile(),
9855 St->isNonTemporal(), St->getAlignment());
9856 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9858 Chains.push_back(Ch);
9860 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9863 if (!ISD::isNormalStore(St))
9866 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9867 // ARM stores of arguments in the same cache line.
9868 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9869 StVal.getNode()->hasOneUse()) {
9870 SelectionDAG &DAG = DCI.DAG;
9871 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9873 SDValue BasePtr = St->getBasePtr();
9874 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9875 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9876 BasePtr, St->getPointerInfo(), St->isVolatile(),
9877 St->isNonTemporal(), St->getAlignment());
9879 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9880 DAG.getConstant(4, DL, MVT::i32));
9881 return DAG.getStore(NewST1.getValue(0), DL,
9882 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9883 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9884 St->isNonTemporal(),
9885 std::min(4U, St->getAlignment() / 2));
9888 if (StVal.getValueType() == MVT::i64 &&
9889 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9891 // Bitcast an i64 store extracted from a vector to f64.
9892 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9893 SelectionDAG &DAG = DCI.DAG;
9895 SDValue IntVec = StVal.getOperand(0);
9896 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9897 IntVec.getValueType().getVectorNumElements());
9898 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9899 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9900 Vec, StVal.getOperand(1));
9902 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9903 // Make the DAGCombiner fold the bitcasts.
9904 DCI.AddToWorklist(Vec.getNode());
9905 DCI.AddToWorklist(ExtElt.getNode());
9906 DCI.AddToWorklist(V.getNode());
9907 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9908 St->getPointerInfo(), St->isVolatile(),
9909 St->isNonTemporal(), St->getAlignment(),
9913 // If this is a legal vector store, try to combine it into a VST1_UPD.
9914 if (ISD::isNormalStore(N) && VT.isVector() &&
9915 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9916 return CombineBaseUpdate(N, DCI);
9921 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9922 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9923 /// when the VMUL has a constant operand that is a power of 2.
9925 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9926 /// vmul.f32 d16, d17, d16
9927 /// vcvt.s32.f32 d16, d16
9929 /// vcvt.s32.f32 d16, d16, #3
9930 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9931 const ARMSubtarget *Subtarget) {
9932 if (!Subtarget->hasNEON())
9935 SDValue Op = N->getOperand(0);
9936 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9939 SDValue ConstVec = Op->getOperand(1);
9940 if (!isa<BuildVectorSDNode>(ConstVec))
9943 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9944 uint32_t FloatBits = FloatTy.getSizeInBits();
9945 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9946 uint32_t IntBits = IntTy.getSizeInBits();
9947 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9948 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9949 // These instructions only exist converting from f32 to i32. We can handle
9950 // smaller integers by generating an extra truncate, but larger ones would
9951 // be lossy. We also can't handle more then 4 lanes, since these intructions
9952 // only support v2i32/v4i32 types.
9956 BitVector UndefElements;
9957 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9958 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9959 if (C == -1 || C == 0 || C > 32)
9963 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9964 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9965 Intrinsic::arm_neon_vcvtfp2fxu;
9966 SDValue FixConv = DAG.getNode(
9967 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9968 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9969 DAG.getConstant(C, dl, MVT::i32));
9971 if (IntBits < FloatBits)
9972 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9977 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9978 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9979 /// when the VDIV has a constant operand that is a power of 2.
9981 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9982 /// vcvt.f32.s32 d16, d16
9983 /// vdiv.f32 d16, d17, d16
9985 /// vcvt.f32.s32 d16, d16, #3
9986 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9987 const ARMSubtarget *Subtarget) {
9988 if (!Subtarget->hasNEON())
9991 SDValue Op = N->getOperand(0);
9992 unsigned OpOpcode = Op.getNode()->getOpcode();
9993 if (!N->getValueType(0).isVector() ||
9994 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9997 SDValue ConstVec = N->getOperand(1);
9998 if (!isa<BuildVectorSDNode>(ConstVec))
10001 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10002 uint32_t FloatBits = FloatTy.getSizeInBits();
10003 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10004 uint32_t IntBits = IntTy.getSizeInBits();
10005 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10006 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10007 // These instructions only exist converting from i32 to f32. We can handle
10008 // smaller integers by generating an extra extend, but larger ones would
10009 // be lossy. We also can't handle more then 4 lanes, since these intructions
10010 // only support v2i32/v4i32 types.
10014 BitVector UndefElements;
10015 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10016 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10017 if (C == -1 || C == 0 || C > 32)
10021 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10022 SDValue ConvInput = Op.getOperand(0);
10023 if (IntBits < FloatBits)
10024 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10025 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10028 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10029 Intrinsic::arm_neon_vcvtfxu2fp;
10030 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10032 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10033 ConvInput, DAG.getConstant(C, dl, MVT::i32));
10036 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10037 /// operand of a vector shift operation, where all the elements of the
10038 /// build_vector must have the same constant integer value.
10039 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10040 // Ignore bit_converts.
10041 while (Op.getOpcode() == ISD::BITCAST)
10042 Op = Op.getOperand(0);
10043 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10044 APInt SplatBits, SplatUndef;
10045 unsigned SplatBitSize;
10047 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10048 HasAnyUndefs, ElementBits) ||
10049 SplatBitSize > ElementBits)
10051 Cnt = SplatBits.getSExtValue();
10055 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10056 /// operand of a vector shift left operation. That value must be in the range:
10057 /// 0 <= Value < ElementBits for a left shift; or
10058 /// 0 <= Value <= ElementBits for a long left shift.
10059 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10060 assert(VT.isVector() && "vector shift count is not a vector type");
10061 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10062 if (! getVShiftImm(Op, ElementBits, Cnt))
10064 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10067 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10068 /// operand of a vector shift right operation. For a shift opcode, the value
10069 /// is positive, but for an intrinsic the value count must be negative. The
10070 /// absolute value must be in the range:
10071 /// 1 <= |Value| <= ElementBits for a right shift; or
10072 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
10073 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10075 assert(VT.isVector() && "vector shift count is not a vector type");
10076 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10077 if (! getVShiftImm(Op, ElementBits, Cnt))
10080 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10081 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10088 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10089 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10090 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10093 // Don't do anything for most intrinsics.
10096 case Intrinsic::arm_neon_vabds:
10097 if (!N->getValueType(0).isInteger())
10099 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
10100 N->getOperand(1), N->getOperand(2));
10101 case Intrinsic::arm_neon_vabdu:
10102 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10103 N->getOperand(1), N->getOperand(2));
10105 // Vector shifts: check for immediate versions and lower them.
10106 // Note: This is done during DAG combining instead of DAG legalizing because
10107 // the build_vectors for 64-bit vector element shift counts are generally
10108 // not legal, and it is hard to see their values after they get legalized to
10109 // loads from a constant pool.
10110 case Intrinsic::arm_neon_vshifts:
10111 case Intrinsic::arm_neon_vshiftu:
10112 case Intrinsic::arm_neon_vrshifts:
10113 case Intrinsic::arm_neon_vrshiftu:
10114 case Intrinsic::arm_neon_vrshiftn:
10115 case Intrinsic::arm_neon_vqshifts:
10116 case Intrinsic::arm_neon_vqshiftu:
10117 case Intrinsic::arm_neon_vqshiftsu:
10118 case Intrinsic::arm_neon_vqshiftns:
10119 case Intrinsic::arm_neon_vqshiftnu:
10120 case Intrinsic::arm_neon_vqshiftnsu:
10121 case Intrinsic::arm_neon_vqrshiftns:
10122 case Intrinsic::arm_neon_vqrshiftnu:
10123 case Intrinsic::arm_neon_vqrshiftnsu: {
10124 EVT VT = N->getOperand(1).getValueType();
10126 unsigned VShiftOpc = 0;
10129 case Intrinsic::arm_neon_vshifts:
10130 case Intrinsic::arm_neon_vshiftu:
10131 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10132 VShiftOpc = ARMISD::VSHL;
10135 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10136 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10137 ARMISD::VSHRs : ARMISD::VSHRu);
10142 case Intrinsic::arm_neon_vrshifts:
10143 case Intrinsic::arm_neon_vrshiftu:
10144 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10148 case Intrinsic::arm_neon_vqshifts:
10149 case Intrinsic::arm_neon_vqshiftu:
10150 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10154 case Intrinsic::arm_neon_vqshiftsu:
10155 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10157 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10159 case Intrinsic::arm_neon_vrshiftn:
10160 case Intrinsic::arm_neon_vqshiftns:
10161 case Intrinsic::arm_neon_vqshiftnu:
10162 case Intrinsic::arm_neon_vqshiftnsu:
10163 case Intrinsic::arm_neon_vqrshiftns:
10164 case Intrinsic::arm_neon_vqrshiftnu:
10165 case Intrinsic::arm_neon_vqrshiftnsu:
10166 // Narrowing shifts require an immediate right shift.
10167 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10169 llvm_unreachable("invalid shift count for narrowing vector shift "
10173 llvm_unreachable("unhandled vector shift");
10177 case Intrinsic::arm_neon_vshifts:
10178 case Intrinsic::arm_neon_vshiftu:
10179 // Opcode already set above.
10181 case Intrinsic::arm_neon_vrshifts:
10182 VShiftOpc = ARMISD::VRSHRs; break;
10183 case Intrinsic::arm_neon_vrshiftu:
10184 VShiftOpc = ARMISD::VRSHRu; break;
10185 case Intrinsic::arm_neon_vrshiftn:
10186 VShiftOpc = ARMISD::VRSHRN; break;
10187 case Intrinsic::arm_neon_vqshifts:
10188 VShiftOpc = ARMISD::VQSHLs; break;
10189 case Intrinsic::arm_neon_vqshiftu:
10190 VShiftOpc = ARMISD::VQSHLu; break;
10191 case Intrinsic::arm_neon_vqshiftsu:
10192 VShiftOpc = ARMISD::VQSHLsu; break;
10193 case Intrinsic::arm_neon_vqshiftns:
10194 VShiftOpc = ARMISD::VQSHRNs; break;
10195 case Intrinsic::arm_neon_vqshiftnu:
10196 VShiftOpc = ARMISD::VQSHRNu; break;
10197 case Intrinsic::arm_neon_vqshiftnsu:
10198 VShiftOpc = ARMISD::VQSHRNsu; break;
10199 case Intrinsic::arm_neon_vqrshiftns:
10200 VShiftOpc = ARMISD::VQRSHRNs; break;
10201 case Intrinsic::arm_neon_vqrshiftnu:
10202 VShiftOpc = ARMISD::VQRSHRNu; break;
10203 case Intrinsic::arm_neon_vqrshiftnsu:
10204 VShiftOpc = ARMISD::VQRSHRNsu; break;
10208 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10209 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10212 case Intrinsic::arm_neon_vshiftins: {
10213 EVT VT = N->getOperand(1).getValueType();
10215 unsigned VShiftOpc = 0;
10217 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10218 VShiftOpc = ARMISD::VSLI;
10219 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10220 VShiftOpc = ARMISD::VSRI;
10222 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10226 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10227 N->getOperand(1), N->getOperand(2),
10228 DAG.getConstant(Cnt, dl, MVT::i32));
10231 case Intrinsic::arm_neon_vqrshifts:
10232 case Intrinsic::arm_neon_vqrshiftu:
10233 // No immediate versions of these to check for.
10240 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10241 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10242 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10243 /// vector element shift counts are generally not legal, and it is hard to see
10244 /// their values after they get legalized to loads from a constant pool.
10245 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10246 const ARMSubtarget *ST) {
10247 EVT VT = N->getValueType(0);
10248 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10249 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10250 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10251 SDValue N1 = N->getOperand(1);
10252 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10253 SDValue N0 = N->getOperand(0);
10254 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10255 DAG.MaskedValueIsZero(N0.getOperand(0),
10256 APInt::getHighBitsSet(32, 16)))
10257 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10261 // Nothing to be done for scalar shifts.
10262 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10263 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10266 assert(ST->hasNEON() && "unexpected vector shift");
10269 switch (N->getOpcode()) {
10270 default: llvm_unreachable("unexpected shift opcode");
10273 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10275 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10276 DAG.getConstant(Cnt, dl, MVT::i32));
10282 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10283 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10284 ARMISD::VSHRs : ARMISD::VSHRu);
10286 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10287 DAG.getConstant(Cnt, dl, MVT::i32));
10293 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10294 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10295 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10296 const ARMSubtarget *ST) {
10297 SDValue N0 = N->getOperand(0);
10299 // Check for sign- and zero-extensions of vector extract operations of 8-
10300 // and 16-bit vector elements. NEON supports these directly. They are
10301 // handled during DAG combining because type legalization will promote them
10302 // to 32-bit types and it is messy to recognize the operations after that.
10303 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10304 SDValue Vec = N0.getOperand(0);
10305 SDValue Lane = N0.getOperand(1);
10306 EVT VT = N->getValueType(0);
10307 EVT EltVT = N0.getValueType();
10308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10310 if (VT == MVT::i32 &&
10311 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10312 TLI.isTypeLegal(Vec.getValueType()) &&
10313 isa<ConstantSDNode>(Lane)) {
10316 switch (N->getOpcode()) {
10317 default: llvm_unreachable("unexpected opcode");
10318 case ISD::SIGN_EXTEND:
10319 Opc = ARMISD::VGETLANEs;
10321 case ISD::ZERO_EXTEND:
10322 case ISD::ANY_EXTEND:
10323 Opc = ARMISD::VGETLANEu;
10326 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10333 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10335 if (Op.getOpcode() == ARMISD::BFI) {
10336 // Conservatively, we can recurse down the first operand
10337 // and just mask out all affected bits.
10338 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10340 // The operand to BFI is already a mask suitable for removing the bits it
10342 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10343 APInt Mask = CI->getAPIntValue();
10348 if (Op.getOpcode() == ARMISD::CMOV) {
10349 APInt KZ2(KnownZero.getBitWidth(), 0);
10350 APInt KO2(KnownOne.getBitWidth(), 0);
10351 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10352 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10358 return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10361 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10362 // If we have a CMOV, OR and AND combination such as:
10367 // * CN is a single bit;
10368 // * All bits covered by CM are known zero in y
10370 // Then we can convert this into a sequence of BFI instructions. This will
10371 // always be a win if CM is a single bit, will always be no worse than the
10372 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10373 // three bits (due to the extra IT instruction).
10375 SDValue Op0 = CMOV->getOperand(0);
10376 SDValue Op1 = CMOV->getOperand(1);
10377 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10378 auto CC = CCNode->getAPIntValue().getLimitedValue();
10379 SDValue CmpZ = CMOV->getOperand(4);
10381 // The compare must be against zero.
10382 if (!isNullConstant(CmpZ->getOperand(1)))
10385 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10386 SDValue And = CmpZ->getOperand(0);
10387 if (And->getOpcode() != ISD::AND)
10389 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10390 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10392 SDValue X = And->getOperand(0);
10394 if (CC == ARMCC::EQ) {
10395 // We're performing an "equal to zero" compare. Swap the operands so we
10396 // canonicalize on a "not equal to zero" compare.
10397 std::swap(Op0, Op1);
10399 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10402 if (Op1->getOpcode() != ISD::OR)
10405 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10408 SDValue Y = Op1->getOperand(0);
10413 // Now, is it profitable to continue?
10414 APInt OrCI = OrC->getAPIntValue();
10415 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10416 if (OrCI.countPopulation() > Heuristic)
10419 // Lastly, can we determine that the bits defined by OrCI
10421 APInt KnownZero, KnownOne;
10422 computeKnownBits(DAG, Y, KnownZero, KnownOne);
10423 if ((OrCI & KnownZero) != OrCI)
10426 // OK, we can do the combine.
10429 EVT VT = X.getValueType();
10430 unsigned BitInX = AndC->getAPIntValue().logBase2();
10433 // We must shift X first.
10434 X = DAG.getNode(ISD::SRL, dl, VT, X,
10435 DAG.getConstant(BitInX, dl, VT));
10438 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10439 BitInY < NumActiveBits; ++BitInY) {
10440 if (OrCI[BitInY] == 0)
10442 APInt Mask(VT.getSizeInBits(), 0);
10443 Mask.setBit(BitInY);
10444 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10445 // Confusingly, the operand is an *inverted* mask.
10446 DAG.getConstant(~Mask, dl, VT));
10452 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10454 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10455 SDValue Cmp = N->getOperand(4);
10456 if (Cmp.getOpcode() != ARMISD::CMPZ)
10457 // Only looking at EQ and NE cases.
10460 EVT VT = N->getValueType(0);
10462 SDValue LHS = Cmp.getOperand(0);
10463 SDValue RHS = Cmp.getOperand(1);
10464 SDValue FalseVal = N->getOperand(0);
10465 SDValue TrueVal = N->getOperand(1);
10466 SDValue ARMcc = N->getOperand(2);
10467 ARMCC::CondCodes CC =
10468 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10470 // BFI is only available on V6T2+.
10471 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10472 SDValue R = PerformCMOVToBFICombine(N, DAG);
10493 /// FIXME: Turn this into a target neutral optimization?
10495 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10496 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10497 N->getOperand(3), Cmp);
10498 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10500 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10501 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10502 N->getOperand(3), NewCmp);
10505 if (Res.getNode()) {
10506 APInt KnownZero, KnownOne;
10507 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10508 // Capture demanded bits information that would be otherwise lost.
10509 if (KnownZero == 0xfffffffe)
10510 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10511 DAG.getValueType(MVT::i1));
10512 else if (KnownZero == 0xffffff00)
10513 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10514 DAG.getValueType(MVT::i8));
10515 else if (KnownZero == 0xffff0000)
10516 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10517 DAG.getValueType(MVT::i16));
10523 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10524 DAGCombinerInfo &DCI) const {
10525 switch (N->getOpcode()) {
10527 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10528 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10529 case ISD::SUB: return PerformSUBCombine(N, DCI);
10530 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10531 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10532 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10533 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10534 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10535 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10536 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10537 case ISD::STORE: return PerformSTORECombine(N, DCI);
10538 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10539 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10540 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10541 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10542 case ISD::FP_TO_SINT:
10543 case ISD::FP_TO_UINT:
10544 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10546 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10547 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10550 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10551 case ISD::SIGN_EXTEND:
10552 case ISD::ZERO_EXTEND:
10553 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10554 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10555 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10556 case ARMISD::VLD2DUP:
10557 case ARMISD::VLD3DUP:
10558 case ARMISD::VLD4DUP:
10559 return PerformVLDCombine(N, DCI);
10560 case ARMISD::BUILD_VECTOR:
10561 return PerformARMBUILD_VECTORCombine(N, DCI);
10562 case ISD::INTRINSIC_VOID:
10563 case ISD::INTRINSIC_W_CHAIN:
10564 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10565 case Intrinsic::arm_neon_vld1:
10566 case Intrinsic::arm_neon_vld2:
10567 case Intrinsic::arm_neon_vld3:
10568 case Intrinsic::arm_neon_vld4:
10569 case Intrinsic::arm_neon_vld2lane:
10570 case Intrinsic::arm_neon_vld3lane:
10571 case Intrinsic::arm_neon_vld4lane:
10572 case Intrinsic::arm_neon_vst1:
10573 case Intrinsic::arm_neon_vst2:
10574 case Intrinsic::arm_neon_vst3:
10575 case Intrinsic::arm_neon_vst4:
10576 case Intrinsic::arm_neon_vst2lane:
10577 case Intrinsic::arm_neon_vst3lane:
10578 case Intrinsic::arm_neon_vst4lane:
10579 return PerformVLDCombine(N, DCI);
10587 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10589 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10592 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10595 bool *Fast) const {
10596 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10597 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10599 switch (VT.getSimpleVT().SimpleTy) {
10605 // Unaligned access can use (for example) LRDB, LRDH, LDR
10606 if (AllowsUnaligned) {
10608 *Fast = Subtarget->hasV7Ops();
10615 // For any little-endian targets with neon, we can support unaligned ld/st
10616 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10617 // A big-endian target may also explicitly support unaligned accesses
10618 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10628 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10629 unsigned AlignCheck) {
10630 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10631 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10634 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10635 unsigned DstAlign, unsigned SrcAlign,
10636 bool IsMemset, bool ZeroMemset,
10638 MachineFunction &MF) const {
10639 const Function *F = MF.getFunction();
10641 // See if we can use NEON instructions for this...
10642 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10643 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10646 (memOpAlign(SrcAlign, DstAlign, 16) ||
10647 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10649 } else if (Size >= 8 &&
10650 (memOpAlign(SrcAlign, DstAlign, 8) ||
10651 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10657 // Lowering to i32/i16 if the size permits.
10660 else if (Size >= 2)
10663 // Let the target-independent logic figure it out.
10667 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10668 if (Val.getOpcode() != ISD::LOAD)
10671 EVT VT1 = Val.getValueType();
10672 if (!VT1.isSimple() || !VT1.isInteger() ||
10673 !VT2.isSimple() || !VT2.isInteger())
10676 switch (VT1.getSimpleVT().SimpleTy) {
10681 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10688 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10689 EVT VT = ExtVal.getValueType();
10691 if (!isTypeLegal(VT))
10694 // Don't create a loadext if we can fold the extension into a wide/long
10696 // If there's more than one user instruction, the loadext is desirable no
10697 // matter what. There can be two uses by the same instruction.
10698 if (ExtVal->use_empty() ||
10699 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10702 SDNode *U = *ExtVal->use_begin();
10703 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10704 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10710 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10711 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10714 if (!isTypeLegal(EVT::getEVT(Ty1)))
10717 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10719 // Assuming the caller doesn't have a zeroext or signext return parameter,
10720 // truncation all the way down to i1 is valid.
10725 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10729 unsigned Scale = 1;
10730 switch (VT.getSimpleVT().SimpleTy) {
10731 default: return false;
10746 if ((V & (Scale - 1)) != 0)
10749 return V == (V & ((1LL << 5) - 1));
10752 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10753 const ARMSubtarget *Subtarget) {
10754 bool isNeg = false;
10760 switch (VT.getSimpleVT().SimpleTy) {
10761 default: return false;
10766 // + imm12 or - imm8
10768 return V == (V & ((1LL << 8) - 1));
10769 return V == (V & ((1LL << 12) - 1));
10772 // Same as ARM mode. FIXME: NEON?
10773 if (!Subtarget->hasVFP2())
10778 return V == (V & ((1LL << 8) - 1));
10782 /// isLegalAddressImmediate - Return true if the integer value can be used
10783 /// as the offset of the target addressing mode for load / store of the
10785 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10786 const ARMSubtarget *Subtarget) {
10790 if (!VT.isSimple())
10793 if (Subtarget->isThumb1Only())
10794 return isLegalT1AddressImmediate(V, VT);
10795 else if (Subtarget->isThumb2())
10796 return isLegalT2AddressImmediate(V, VT, Subtarget);
10801 switch (VT.getSimpleVT().SimpleTy) {
10802 default: return false;
10807 return V == (V & ((1LL << 12) - 1));
10810 return V == (V & ((1LL << 8) - 1));
10813 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10818 return V == (V & ((1LL << 8) - 1));
10822 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10824 int Scale = AM.Scale;
10828 switch (VT.getSimpleVT().SimpleTy) {
10829 default: return false;
10837 Scale = Scale & ~1;
10838 return Scale == 2 || Scale == 4 || Scale == 8;
10841 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10845 // Note, we allow "void" uses (basically, uses that aren't loads or
10846 // stores), because arm allows folding a scale into many arithmetic
10847 // operations. This should be made more precise and revisited later.
10849 // Allow r << imm, but the imm has to be a multiple of two.
10850 if (Scale & 1) return false;
10851 return isPowerOf2_32(Scale);
10855 /// isLegalAddressingMode - Return true if the addressing mode represented
10856 /// by AM is legal for this target, for a load/store of the specified type.
10857 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10858 const AddrMode &AM, Type *Ty,
10859 unsigned AS) const {
10860 EVT VT = getValueType(DL, Ty, true);
10861 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10864 // Can never fold addr of global into load/store.
10868 switch (AM.Scale) {
10869 case 0: // no scale reg, must be "r+i" or "r", or "i".
10872 if (Subtarget->isThumb1Only())
10876 // ARM doesn't support any R+R*scale+imm addr modes.
10880 if (!VT.isSimple())
10883 if (Subtarget->isThumb2())
10884 return isLegalT2ScaledAddressingMode(AM, VT);
10886 int Scale = AM.Scale;
10887 switch (VT.getSimpleVT().SimpleTy) {
10888 default: return false;
10892 if (Scale < 0) Scale = -Scale;
10896 return isPowerOf2_32(Scale & ~1);
10900 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10905 // Note, we allow "void" uses (basically, uses that aren't loads or
10906 // stores), because arm allows folding a scale into many arithmetic
10907 // operations. This should be made more precise and revisited later.
10909 // Allow r << imm, but the imm has to be a multiple of two.
10910 if (Scale & 1) return false;
10911 return isPowerOf2_32(Scale);
10917 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10918 /// icmp immediate, that is the target has icmp instructions which can compare
10919 /// a register against the immediate without having to materialize the
10920 /// immediate into a register.
10921 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10922 // Thumb2 and ARM modes can use cmn for negative immediates.
10923 if (!Subtarget->isThumb())
10924 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10925 if (Subtarget->isThumb2())
10926 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10927 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10928 return Imm >= 0 && Imm <= 255;
10931 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10932 /// *or sub* immediate, that is the target has add or sub instructions which can
10933 /// add a register with the immediate without having to materialize the
10934 /// immediate into a register.
10935 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10936 // Same encoding for add/sub, just flip the sign.
10937 int64_t AbsImm = std::abs(Imm);
10938 if (!Subtarget->isThumb())
10939 return ARM_AM::getSOImmVal(AbsImm) != -1;
10940 if (Subtarget->isThumb2())
10941 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10942 // Thumb1 only has 8-bit unsigned immediate.
10943 return AbsImm >= 0 && AbsImm <= 255;
10946 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10947 bool isSEXTLoad, SDValue &Base,
10948 SDValue &Offset, bool &isInc,
10949 SelectionDAG &DAG) {
10950 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10953 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10954 // AddressingMode 3
10955 Base = Ptr->getOperand(0);
10956 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10957 int RHSC = (int)RHS->getZExtValue();
10958 if (RHSC < 0 && RHSC > -256) {
10959 assert(Ptr->getOpcode() == ISD::ADD);
10961 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10965 isInc = (Ptr->getOpcode() == ISD::ADD);
10966 Offset = Ptr->getOperand(1);
10968 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10969 // AddressingMode 2
10970 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10971 int RHSC = (int)RHS->getZExtValue();
10972 if (RHSC < 0 && RHSC > -0x1000) {
10973 assert(Ptr->getOpcode() == ISD::ADD);
10975 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10976 Base = Ptr->getOperand(0);
10981 if (Ptr->getOpcode() == ISD::ADD) {
10983 ARM_AM::ShiftOpc ShOpcVal=
10984 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10985 if (ShOpcVal != ARM_AM::no_shift) {
10986 Base = Ptr->getOperand(1);
10987 Offset = Ptr->getOperand(0);
10989 Base = Ptr->getOperand(0);
10990 Offset = Ptr->getOperand(1);
10995 isInc = (Ptr->getOpcode() == ISD::ADD);
10996 Base = Ptr->getOperand(0);
10997 Offset = Ptr->getOperand(1);
11001 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11005 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11006 bool isSEXTLoad, SDValue &Base,
11007 SDValue &Offset, bool &isInc,
11008 SelectionDAG &DAG) {
11009 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11012 Base = Ptr->getOperand(0);
11013 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11014 int RHSC = (int)RHS->getZExtValue();
11015 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11016 assert(Ptr->getOpcode() == ISD::ADD);
11018 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11020 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11021 isInc = Ptr->getOpcode() == ISD::ADD;
11022 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11030 /// getPreIndexedAddressParts - returns true by value, base pointer and
11031 /// offset pointer and addressing mode by reference if the node's address
11032 /// can be legally represented as pre-indexed load / store address.
11034 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11036 ISD::MemIndexedMode &AM,
11037 SelectionDAG &DAG) const {
11038 if (Subtarget->isThumb1Only())
11043 bool isSEXTLoad = false;
11044 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11045 Ptr = LD->getBasePtr();
11046 VT = LD->getMemoryVT();
11047 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11048 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11049 Ptr = ST->getBasePtr();
11050 VT = ST->getMemoryVT();
11055 bool isLegal = false;
11056 if (Subtarget->isThumb2())
11057 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11058 Offset, isInc, DAG);
11060 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11061 Offset, isInc, DAG);
11065 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11069 /// getPostIndexedAddressParts - returns true by value, base pointer and
11070 /// offset pointer and addressing mode by reference if this node can be
11071 /// combined with a load / store to form a post-indexed load / store.
11072 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11075 ISD::MemIndexedMode &AM,
11076 SelectionDAG &DAG) const {
11077 if (Subtarget->isThumb1Only())
11082 bool isSEXTLoad = false;
11083 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11084 VT = LD->getMemoryVT();
11085 Ptr = LD->getBasePtr();
11086 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11087 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11088 VT = ST->getMemoryVT();
11089 Ptr = ST->getBasePtr();
11094 bool isLegal = false;
11095 if (Subtarget->isThumb2())
11096 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11099 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11105 // Swap base ptr and offset to catch more post-index load / store when
11106 // it's legal. In Thumb2 mode, offset must be an immediate.
11107 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11108 !Subtarget->isThumb2())
11109 std::swap(Base, Offset);
11111 // Post-indexed load / store update the base pointer.
11116 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11120 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11123 const SelectionDAG &DAG,
11124 unsigned Depth) const {
11125 unsigned BitWidth = KnownOne.getBitWidth();
11126 KnownZero = KnownOne = APInt(BitWidth, 0);
11127 switch (Op.getOpcode()) {
11133 // These nodes' second result is a boolean
11134 if (Op.getResNo() == 0)
11136 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11138 case ARMISD::CMOV: {
11139 // Bits are known zero/one if known on the LHS and RHS.
11140 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11141 if (KnownZero == 0 && KnownOne == 0) return;
11143 APInt KnownZeroRHS, KnownOneRHS;
11144 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11145 KnownZero &= KnownZeroRHS;
11146 KnownOne &= KnownOneRHS;
11149 case ISD::INTRINSIC_W_CHAIN: {
11150 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11151 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11154 case Intrinsic::arm_ldaex:
11155 case Intrinsic::arm_ldrex: {
11156 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11157 unsigned MemBits = VT.getScalarType().getSizeInBits();
11158 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11166 //===----------------------------------------------------------------------===//
11167 // ARM Inline Assembly Support
11168 //===----------------------------------------------------------------------===//
11170 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11171 // Looking for "rev" which is V6+.
11172 if (!Subtarget->hasV6Ops())
11175 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11176 std::string AsmStr = IA->getAsmString();
11177 SmallVector<StringRef, 4> AsmPieces;
11178 SplitString(AsmStr, AsmPieces, ";\n");
11180 switch (AsmPieces.size()) {
11181 default: return false;
11183 AsmStr = AsmPieces[0];
11185 SplitString(AsmStr, AsmPieces, " \t,");
11188 if (AsmPieces.size() == 3 &&
11189 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11190 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11191 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11192 if (Ty && Ty->getBitWidth() == 32)
11193 return IntrinsicLowering::LowerToByteSwap(CI);
11201 /// getConstraintType - Given a constraint letter, return the type of
11202 /// constraint it is for this target.
11203 ARMTargetLowering::ConstraintType
11204 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11205 if (Constraint.size() == 1) {
11206 switch (Constraint[0]) {
11208 case 'l': return C_RegisterClass;
11209 case 'w': return C_RegisterClass;
11210 case 'h': return C_RegisterClass;
11211 case 'x': return C_RegisterClass;
11212 case 't': return C_RegisterClass;
11213 case 'j': return C_Other; // Constant for movw.
11214 // An address with a single base register. Due to the way we
11215 // currently handle addresses it is the same as an 'r' memory constraint.
11216 case 'Q': return C_Memory;
11218 } else if (Constraint.size() == 2) {
11219 switch (Constraint[0]) {
11221 // All 'U+' constraints are addresses.
11222 case 'U': return C_Memory;
11225 return TargetLowering::getConstraintType(Constraint);
11228 /// Examine constraint type and operand type and determine a weight value.
11229 /// This object must already have been set up with the operand type
11230 /// and the current alternative constraint selected.
11231 TargetLowering::ConstraintWeight
11232 ARMTargetLowering::getSingleConstraintMatchWeight(
11233 AsmOperandInfo &info, const char *constraint) const {
11234 ConstraintWeight weight = CW_Invalid;
11235 Value *CallOperandVal = info.CallOperandVal;
11236 // If we don't have a value, we can't do a match,
11237 // but allow it at the lowest weight.
11238 if (!CallOperandVal)
11240 Type *type = CallOperandVal->getType();
11241 // Look at the constraint type.
11242 switch (*constraint) {
11244 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11247 if (type->isIntegerTy()) {
11248 if (Subtarget->isThumb())
11249 weight = CW_SpecificReg;
11251 weight = CW_Register;
11255 if (type->isFloatingPointTy())
11256 weight = CW_Register;
11262 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11263 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11264 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11265 if (Constraint.size() == 1) {
11266 // GCC ARM Constraint Letters
11267 switch (Constraint[0]) {
11268 case 'l': // Low regs or general regs.
11269 if (Subtarget->isThumb())
11270 return RCPair(0U, &ARM::tGPRRegClass);
11271 return RCPair(0U, &ARM::GPRRegClass);
11272 case 'h': // High regs or no regs.
11273 if (Subtarget->isThumb())
11274 return RCPair(0U, &ARM::hGPRRegClass);
11277 if (Subtarget->isThumb1Only())
11278 return RCPair(0U, &ARM::tGPRRegClass);
11279 return RCPair(0U, &ARM::GPRRegClass);
11281 if (VT == MVT::Other)
11283 if (VT == MVT::f32)
11284 return RCPair(0U, &ARM::SPRRegClass);
11285 if (VT.getSizeInBits() == 64)
11286 return RCPair(0U, &ARM::DPRRegClass);
11287 if (VT.getSizeInBits() == 128)
11288 return RCPair(0U, &ARM::QPRRegClass);
11291 if (VT == MVT::Other)
11293 if (VT == MVT::f32)
11294 return RCPair(0U, &ARM::SPR_8RegClass);
11295 if (VT.getSizeInBits() == 64)
11296 return RCPair(0U, &ARM::DPR_8RegClass);
11297 if (VT.getSizeInBits() == 128)
11298 return RCPair(0U, &ARM::QPR_8RegClass);
11301 if (VT == MVT::f32)
11302 return RCPair(0U, &ARM::SPRRegClass);
11306 if (StringRef("{cc}").equals_lower(Constraint))
11307 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11309 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11312 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11313 /// vector. If it is invalid, don't add anything to Ops.
11314 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11315 std::string &Constraint,
11316 std::vector<SDValue>&Ops,
11317 SelectionDAG &DAG) const {
11320 // Currently only support length 1 constraints.
11321 if (Constraint.length() != 1) return;
11323 char ConstraintLetter = Constraint[0];
11324 switch (ConstraintLetter) {
11327 case 'I': case 'J': case 'K': case 'L':
11328 case 'M': case 'N': case 'O':
11329 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11333 int64_t CVal64 = C->getSExtValue();
11334 int CVal = (int) CVal64;
11335 // None of these constraints allow values larger than 32 bits. Check
11336 // that the value fits in an int.
11337 if (CVal != CVal64)
11340 switch (ConstraintLetter) {
11342 // Constant suitable for movw, must be between 0 and
11344 if (Subtarget->hasV6T2Ops())
11345 if (CVal >= 0 && CVal <= 65535)
11349 if (Subtarget->isThumb1Only()) {
11350 // This must be a constant between 0 and 255, for ADD
11352 if (CVal >= 0 && CVal <= 255)
11354 } else if (Subtarget->isThumb2()) {
11355 // A constant that can be used as an immediate value in a
11356 // data-processing instruction.
11357 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11360 // A constant that can be used as an immediate value in a
11361 // data-processing instruction.
11362 if (ARM_AM::getSOImmVal(CVal) != -1)
11368 if (Subtarget->isThumb()) { // FIXME thumb2
11369 // This must be a constant between -255 and -1, for negated ADD
11370 // immediates. This can be used in GCC with an "n" modifier that
11371 // prints the negated value, for use with SUB instructions. It is
11372 // not useful otherwise but is implemented for compatibility.
11373 if (CVal >= -255 && CVal <= -1)
11376 // This must be a constant between -4095 and 4095. It is not clear
11377 // what this constraint is intended for. Implemented for
11378 // compatibility with GCC.
11379 if (CVal >= -4095 && CVal <= 4095)
11385 if (Subtarget->isThumb1Only()) {
11386 // A 32-bit value where only one byte has a nonzero value. Exclude
11387 // zero to match GCC. This constraint is used by GCC internally for
11388 // constants that can be loaded with a move/shift combination.
11389 // It is not useful otherwise but is implemented for compatibility.
11390 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11392 } else if (Subtarget->isThumb2()) {
11393 // A constant whose bitwise inverse can be used as an immediate
11394 // value in a data-processing instruction. This can be used in GCC
11395 // with a "B" modifier that prints the inverted value, for use with
11396 // BIC and MVN instructions. It is not useful otherwise but is
11397 // implemented for compatibility.
11398 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11401 // A constant whose bitwise inverse can be used as an immediate
11402 // value in a data-processing instruction. This can be used in GCC
11403 // with a "B" modifier that prints the inverted value, for use with
11404 // BIC and MVN instructions. It is not useful otherwise but is
11405 // implemented for compatibility.
11406 if (ARM_AM::getSOImmVal(~CVal) != -1)
11412 if (Subtarget->isThumb1Only()) {
11413 // This must be a constant between -7 and 7,
11414 // for 3-operand ADD/SUB immediate instructions.
11415 if (CVal >= -7 && CVal < 7)
11417 } else if (Subtarget->isThumb2()) {
11418 // A constant whose negation can be used as an immediate value in a
11419 // data-processing instruction. This can be used in GCC with an "n"
11420 // modifier that prints the negated value, for use with SUB
11421 // instructions. It is not useful otherwise but is implemented for
11423 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11426 // A constant whose negation can be used as an immediate value in a
11427 // data-processing instruction. This can be used in GCC with an "n"
11428 // modifier that prints the negated value, for use with SUB
11429 // instructions. It is not useful otherwise but is implemented for
11431 if (ARM_AM::getSOImmVal(-CVal) != -1)
11437 if (Subtarget->isThumb()) { // FIXME thumb2
11438 // This must be a multiple of 4 between 0 and 1020, for
11439 // ADD sp + immediate.
11440 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11443 // A power of two or a constant between 0 and 32. This is used in
11444 // GCC for the shift amount on shifted register operands, but it is
11445 // useful in general for any shift amounts.
11446 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11452 if (Subtarget->isThumb()) { // FIXME thumb2
11453 // This must be a constant between 0 and 31, for shift amounts.
11454 if (CVal >= 0 && CVal <= 31)
11460 if (Subtarget->isThumb()) { // FIXME thumb2
11461 // This must be a multiple of 4 between -508 and 508, for
11462 // ADD/SUB sp = sp + immediate.
11463 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11468 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11472 if (Result.getNode()) {
11473 Ops.push_back(Result);
11476 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11479 static RTLIB::Libcall getDivRemLibcall(
11480 const SDNode *N, MVT::SimpleValueType SVT) {
11481 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11482 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11483 "Unhandled Opcode in getDivRemLibcall");
11484 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11485 N->getOpcode() == ISD::SREM;
11488 default: llvm_unreachable("Unexpected request for libcall!");
11489 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11490 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11491 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11492 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11497 static TargetLowering::ArgListTy getDivRemArgList(
11498 const SDNode *N, LLVMContext *Context) {
11499 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11500 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11501 "Unhandled Opcode in getDivRemArgList");
11502 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11503 N->getOpcode() == ISD::SREM;
11504 TargetLowering::ArgListTy Args;
11505 TargetLowering::ArgListEntry Entry;
11506 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11507 EVT ArgVT = N->getOperand(i).getValueType();
11508 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11509 Entry.Node = N->getOperand(i);
11511 Entry.isSExt = isSigned;
11512 Entry.isZExt = !isSigned;
11513 Args.push_back(Entry);
11518 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11519 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11520 "Register-based DivRem lowering only");
11521 unsigned Opcode = Op->getOpcode();
11522 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11523 "Invalid opcode for Div/Rem lowering");
11524 bool isSigned = (Opcode == ISD::SDIVREM);
11525 EVT VT = Op->getValueType(0);
11526 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11528 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11529 VT.getSimpleVT().SimpleTy);
11530 SDValue InChain = DAG.getEntryNode();
11532 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11535 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11536 getPointerTy(DAG.getDataLayout()));
11538 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11541 TargetLowering::CallLoweringInfo CLI(DAG);
11542 CLI.setDebugLoc(dl).setChain(InChain)
11543 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11544 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11546 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11547 return CallInfo.first;
11550 // Lowers REM using divmod helpers
11551 // see RTABI section 4.2/4.3
11552 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11553 // Build return types (div and rem)
11554 std::vector<Type*> RetTyParams;
11555 Type *RetTyElement;
11557 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11558 default: llvm_unreachable("Unexpected request for libcall!");
11559 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11560 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11561 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11562 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11565 RetTyParams.push_back(RetTyElement);
11566 RetTyParams.push_back(RetTyElement);
11567 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11568 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11570 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11572 SDValue InChain = DAG.getEntryNode();
11573 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11574 bool isSigned = N->getOpcode() == ISD::SREM;
11575 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11576 getPointerTy(DAG.getDataLayout()));
11579 CallLoweringInfo CLI(DAG);
11580 CLI.setChain(InChain)
11581 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11582 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11583 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11585 // Return second (rem) result operand (first contains div)
11586 SDNode *ResNode = CallResult.first.getNode();
11587 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11588 return ResNode->getOperand(1);
11592 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11593 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11597 SDValue Chain = Op.getOperand(0);
11598 SDValue Size = Op.getOperand(1);
11600 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11601 DAG.getConstant(2, DL, MVT::i32));
11604 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11605 Flag = Chain.getValue(1);
11607 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11608 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11610 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11611 Chain = NewSP.getValue(1);
11613 SDValue Ops[2] = { NewSP, Chain };
11614 return DAG.getMergeValues(Ops, DL);
11617 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11618 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11619 "Unexpected type for custom-lowering FP_EXTEND");
11622 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11624 SDValue SrcVal = Op.getOperand(0);
11625 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11629 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11630 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11631 Subtarget->isFPOnlySP() &&
11632 "Unexpected type for custom-lowering FP_ROUND");
11635 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11637 SDValue SrcVal = Op.getOperand(0);
11638 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11643 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11644 // The ARM target isn't yet aware of offsets.
11648 bool ARM::isBitFieldInvertedMask(unsigned v) {
11649 if (v == 0xffffffff)
11652 // there can be 1's on either or both "outsides", all the "inside"
11653 // bits must be 0's
11654 return isShiftedMask_32(~v);
11657 /// isFPImmLegal - Returns true if the target can instruction select the
11658 /// specified FP immediate natively. If false, the legalizer will
11659 /// materialize the FP immediate as a load from a constant pool.
11660 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11661 if (!Subtarget->hasVFP3())
11663 if (VT == MVT::f32)
11664 return ARM_AM::getFP32Imm(Imm) != -1;
11665 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11666 return ARM_AM::getFP64Imm(Imm) != -1;
11670 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11671 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11672 /// specified in the intrinsic calls.
11673 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11675 unsigned Intrinsic) const {
11676 switch (Intrinsic) {
11677 case Intrinsic::arm_neon_vld1:
11678 case Intrinsic::arm_neon_vld2:
11679 case Intrinsic::arm_neon_vld3:
11680 case Intrinsic::arm_neon_vld4:
11681 case Intrinsic::arm_neon_vld2lane:
11682 case Intrinsic::arm_neon_vld3lane:
11683 case Intrinsic::arm_neon_vld4lane: {
11684 Info.opc = ISD::INTRINSIC_W_CHAIN;
11685 // Conservatively set memVT to the entire set of vectors loaded.
11686 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11687 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11688 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11689 Info.ptrVal = I.getArgOperand(0);
11691 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11692 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11693 Info.vol = false; // volatile loads with NEON intrinsics not supported
11694 Info.readMem = true;
11695 Info.writeMem = false;
11698 case Intrinsic::arm_neon_vst1:
11699 case Intrinsic::arm_neon_vst2:
11700 case Intrinsic::arm_neon_vst3:
11701 case Intrinsic::arm_neon_vst4:
11702 case Intrinsic::arm_neon_vst2lane:
11703 case Intrinsic::arm_neon_vst3lane:
11704 case Intrinsic::arm_neon_vst4lane: {
11705 Info.opc = ISD::INTRINSIC_VOID;
11706 // Conservatively set memVT to the entire set of vectors stored.
11707 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11708 unsigned NumElts = 0;
11709 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11710 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11711 if (!ArgTy->isVectorTy())
11713 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11715 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11716 Info.ptrVal = I.getArgOperand(0);
11718 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11719 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11720 Info.vol = false; // volatile stores with NEON intrinsics not supported
11721 Info.readMem = false;
11722 Info.writeMem = true;
11725 case Intrinsic::arm_ldaex:
11726 case Intrinsic::arm_ldrex: {
11727 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11728 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11729 Info.opc = ISD::INTRINSIC_W_CHAIN;
11730 Info.memVT = MVT::getVT(PtrTy->getElementType());
11731 Info.ptrVal = I.getArgOperand(0);
11733 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11735 Info.readMem = true;
11736 Info.writeMem = false;
11739 case Intrinsic::arm_stlex:
11740 case Intrinsic::arm_strex: {
11741 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11742 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11743 Info.opc = ISD::INTRINSIC_W_CHAIN;
11744 Info.memVT = MVT::getVT(PtrTy->getElementType());
11745 Info.ptrVal = I.getArgOperand(1);
11747 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11749 Info.readMem = false;
11750 Info.writeMem = true;
11753 case Intrinsic::arm_stlexd:
11754 case Intrinsic::arm_strexd: {
11755 Info.opc = ISD::INTRINSIC_W_CHAIN;
11756 Info.memVT = MVT::i64;
11757 Info.ptrVal = I.getArgOperand(2);
11761 Info.readMem = false;
11762 Info.writeMem = true;
11765 case Intrinsic::arm_ldaexd:
11766 case Intrinsic::arm_ldrexd: {
11767 Info.opc = ISD::INTRINSIC_W_CHAIN;
11768 Info.memVT = MVT::i64;
11769 Info.ptrVal = I.getArgOperand(0);
11773 Info.readMem = true;
11774 Info.writeMem = false;
11784 /// \brief Returns true if it is beneficial to convert a load of a constant
11785 /// to just the constant itself.
11786 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11788 assert(Ty->isIntegerTy());
11790 unsigned Bits = Ty->getPrimitiveSizeInBits();
11791 if (Bits == 0 || Bits > 32)
11796 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11797 ARM_MB::MemBOpt Domain) const {
11798 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11800 // First, if the target has no DMB, see what fallback we can use.
11801 if (!Subtarget->hasDataBarrier()) {
11802 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11803 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11805 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11806 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11807 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11808 Builder.getInt32(0), Builder.getInt32(7),
11809 Builder.getInt32(10), Builder.getInt32(5)};
11810 return Builder.CreateCall(MCR, args);
11812 // Instead of using barriers, atomic accesses on these subtargets use
11814 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11817 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11818 // Only a full system barrier exists in the M-class architectures.
11819 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11820 Constant *CDomain = Builder.getInt32(Domain);
11821 return Builder.CreateCall(DMB, CDomain);
11825 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11826 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11827 AtomicOrdering Ord, bool IsStore,
11828 bool IsLoad) const {
11829 if (!getInsertFencesForAtomic())
11835 llvm_unreachable("Invalid fence: unordered/non-atomic");
11838 return nullptr; // Nothing to do
11839 case SequentiallyConsistent:
11841 return nullptr; // Nothing to do
11844 case AcquireRelease:
11845 if (Subtarget->isSwift())
11846 return makeDMB(Builder, ARM_MB::ISHST);
11847 // FIXME: add a comment with a link to documentation justifying this.
11849 return makeDMB(Builder, ARM_MB::ISH);
11851 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11854 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11855 AtomicOrdering Ord, bool IsStore,
11856 bool IsLoad) const {
11857 if (!getInsertFencesForAtomic())
11863 llvm_unreachable("Invalid fence: unordered/not-atomic");
11866 return nullptr; // Nothing to do
11868 case AcquireRelease:
11869 case SequentiallyConsistent:
11870 return makeDMB(Builder, ARM_MB::ISH);
11872 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11875 // Loads and stores less than 64-bits are already atomic; ones above that
11876 // are doomed anyway, so defer to the default libcall and blame the OS when
11877 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11878 // anything for those.
11879 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11880 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11881 return (Size == 64) && !Subtarget->isMClass();
11884 // Loads and stores less than 64-bits are already atomic; ones above that
11885 // are doomed anyway, so defer to the default libcall and blame the OS when
11886 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11887 // anything for those.
11888 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11889 // guarantee, see DDI0406C ARM architecture reference manual,
11890 // sections A8.8.72-74 LDRD)
11891 TargetLowering::AtomicExpansionKind
11892 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11893 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11894 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11895 : AtomicExpansionKind::None;
11898 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11899 // and up to 64 bits on the non-M profiles
11900 TargetLowering::AtomicExpansionKind
11901 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11902 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11903 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11904 ? AtomicExpansionKind::LLSC
11905 : AtomicExpansionKind::None;
11908 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11909 AtomicCmpXchgInst *AI) const {
11913 // This has so far only been implemented for MachO.
11914 bool ARMTargetLowering::useLoadStackGuardNode() const {
11915 return Subtarget->isTargetMachO();
11918 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11919 unsigned &Cost) const {
11920 // If we do not have NEON, vector types are not natively supported.
11921 if (!Subtarget->hasNEON())
11924 // Floating point values and vector values map to the same register file.
11925 // Therefore, although we could do a store extract of a vector type, this is
11926 // better to leave at float as we have more freedom in the addressing mode for
11928 if (VectorTy->isFPOrFPVectorTy())
11931 // If the index is unknown at compile time, this is very expensive to lower
11932 // and it is not possible to combine the store with the extract.
11933 if (!isa<ConstantInt>(Idx))
11936 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11937 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11938 // We can do a store + vector extract on any vector that fits perfectly in a D
11940 if (BitWidth == 64 || BitWidth == 128) {
11947 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
11948 return Subtarget->hasV6T2Ops();
11951 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
11952 return Subtarget->hasV6T2Ops();
11955 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11956 AtomicOrdering Ord) const {
11957 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11958 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11959 bool IsAcquire = isAtLeastAcquire(Ord);
11961 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11962 // intrinsic must return {i32, i32} and we have to recombine them into a
11963 // single i64 here.
11964 if (ValTy->getPrimitiveSizeInBits() == 64) {
11965 Intrinsic::ID Int =
11966 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11967 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11969 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11970 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11972 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11973 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11974 if (!Subtarget->isLittle())
11975 std::swap (Lo, Hi);
11976 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11977 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11978 return Builder.CreateOr(
11979 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11982 Type *Tys[] = { Addr->getType() };
11983 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11984 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11986 return Builder.CreateTruncOrBitCast(
11987 Builder.CreateCall(Ldrex, Addr),
11988 cast<PointerType>(Addr->getType())->getElementType());
11991 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11992 IRBuilder<> &Builder) const {
11993 if (!Subtarget->hasV7Ops())
11995 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11996 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11999 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12001 AtomicOrdering Ord) const {
12002 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12003 bool IsRelease = isAtLeastRelease(Ord);
12005 // Since the intrinsics must have legal type, the i64 intrinsics take two
12006 // parameters: "i32, i32". We must marshal Val into the appropriate form
12007 // before the call.
12008 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12009 Intrinsic::ID Int =
12010 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12011 Function *Strex = Intrinsic::getDeclaration(M, Int);
12012 Type *Int32Ty = Type::getInt32Ty(M->getContext());
12014 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12015 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12016 if (!Subtarget->isLittle())
12017 std::swap (Lo, Hi);
12018 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12019 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12022 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12023 Type *Tys[] = { Addr->getType() };
12024 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12026 return Builder.CreateCall(
12027 Strex, {Builder.CreateZExtOrBitCast(
12028 Val, Strex->getFunctionType()->getParamType(0)),
12032 /// \brief Lower an interleaved load into a vldN intrinsic.
12034 /// E.g. Lower an interleaved load (Factor = 2):
12035 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12036 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
12037 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
12040 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12041 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12042 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12043 bool ARMTargetLowering::lowerInterleavedLoad(
12044 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12045 ArrayRef<unsigned> Indices, unsigned Factor) const {
12046 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12047 "Invalid interleave factor");
12048 assert(!Shuffles.empty() && "Empty shufflevector input");
12049 assert(Shuffles.size() == Indices.size() &&
12050 "Unmatched number of shufflevectors and indices");
12052 VectorType *VecTy = Shuffles[0]->getType();
12053 Type *EltTy = VecTy->getVectorElementType();
12055 const DataLayout &DL = LI->getModule()->getDataLayout();
12056 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
12057 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12059 // Skip if we do not have NEON and skip illegal vector types and vector types
12060 // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12061 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12064 // A pointer vector can not be the return type of the ldN intrinsics. Need to
12065 // load integer vectors first and then convert to pointer vectors.
12066 if (EltTy->isPointerTy())
12068 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12070 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12071 Intrinsic::arm_neon_vld3,
12072 Intrinsic::arm_neon_vld4};
12074 IRBuilder<> Builder(LI);
12075 SmallVector<Value *, 2> Ops;
12077 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12078 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12079 Ops.push_back(Builder.getInt32(LI->getAlignment()));
12081 Type *Tys[] = { VecTy, Int8Ptr };
12082 Function *VldnFunc =
12083 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12084 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12086 // Replace uses of each shufflevector with the corresponding vector loaded
12088 for (unsigned i = 0; i < Shuffles.size(); i++) {
12089 ShuffleVectorInst *SV = Shuffles[i];
12090 unsigned Index = Indices[i];
12092 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12094 // Convert the integer vector to pointer vector if the element is pointer.
12095 if (EltTy->isPointerTy())
12096 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12098 SV->replaceAllUsesWith(SubVec);
12104 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12106 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12107 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12108 unsigned NumElts) {
12109 SmallVector<Constant *, 16> Mask;
12110 for (unsigned i = 0; i < NumElts; i++)
12111 Mask.push_back(Builder.getInt32(Start + i));
12113 return ConstantVector::get(Mask);
12116 /// \brief Lower an interleaved store into a vstN intrinsic.
12118 /// E.g. Lower an interleaved store (Factor = 3):
12119 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12120 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12121 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12124 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12125 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12126 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12127 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12129 /// Note that the new shufflevectors will be removed and we'll only generate one
12130 /// vst3 instruction in CodeGen.
12131 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12132 ShuffleVectorInst *SVI,
12133 unsigned Factor) const {
12134 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12135 "Invalid interleave factor");
12137 VectorType *VecTy = SVI->getType();
12138 assert(VecTy->getVectorNumElements() % Factor == 0 &&
12139 "Invalid interleaved store");
12141 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12142 Type *EltTy = VecTy->getVectorElementType();
12143 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12145 const DataLayout &DL = SI->getModule()->getDataLayout();
12146 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
12147 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12149 // Skip if we do not have NEON and skip illegal vector types and vector types
12150 // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12151 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12155 Value *Op0 = SVI->getOperand(0);
12156 Value *Op1 = SVI->getOperand(1);
12157 IRBuilder<> Builder(SI);
12159 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12160 // vectors to integer vectors.
12161 if (EltTy->isPointerTy()) {
12162 Type *IntTy = DL.getIntPtrType(EltTy);
12164 // Convert to the corresponding integer vector.
12166 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12167 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12168 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12170 SubVecTy = VectorType::get(IntTy, NumSubElts);
12173 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12174 Intrinsic::arm_neon_vst3,
12175 Intrinsic::arm_neon_vst4};
12176 SmallVector<Value *, 6> Ops;
12178 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12179 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12181 Type *Tys[] = { Int8Ptr, SubVecTy };
12182 Function *VstNFunc = Intrinsic::getDeclaration(
12183 SI->getModule(), StoreInts[Factor - 2], Tys);
12185 // Split the shufflevector operands into sub vectors for the new vstN call.
12186 for (unsigned i = 0; i < Factor; i++)
12187 Ops.push_back(Builder.CreateShuffleVector(
12188 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12190 Ops.push_back(Builder.getInt32(SI->getAlignment()));
12191 Builder.CreateCall(VstNFunc, Ops);
12203 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12204 uint64_t &Members) {
12205 if (auto *ST = dyn_cast<StructType>(Ty)) {
12206 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12207 uint64_t SubMembers = 0;
12208 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12210 Members += SubMembers;
12212 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12213 uint64_t SubMembers = 0;
12214 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12216 Members += SubMembers * AT->getNumElements();
12217 } else if (Ty->isFloatTy()) {
12218 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12222 } else if (Ty->isDoubleTy()) {
12223 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12227 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12234 return VT->getBitWidth() == 64;
12236 return VT->getBitWidth() == 128;
12238 switch (VT->getBitWidth()) {
12251 return (Members > 0 && Members <= 4);
12254 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12255 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12256 /// passing according to AAPCS rules.
12257 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12258 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12259 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12260 CallingConv::ARM_AAPCS_VFP)
12263 HABaseType Base = HA_UNKNOWN;
12264 uint64_t Members = 0;
12265 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12266 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12268 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12269 return IsHA || IsIntArray;
12272 unsigned ARMTargetLowering::getExceptionPointerRegister(
12273 const Constant *PersonalityFn) const {
12274 // Platforms which do not use SjLj EH may return values in these registers
12275 // via the personality function.
12276 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12279 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12280 const Constant *PersonalityFn) const {
12281 // Platforms which do not use SjLj EH may return values in these registers
12282 // via the personality function.
12283 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;