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 "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/MachineValueType.h"
56 #include "llvm/CodeGen/RuntimeLibcalls.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGNodes.h"
59 #include "llvm/CodeGen/ValueTypes.h"
60 #include "llvm/IR/Attributes.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugLoc.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalValue.h"
71 #include "llvm/IR/GlobalVariable.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/Instruction.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/User.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/MC/MCInstrDesc.h"
83 #include "llvm/MC/MCInstrItineraries.h"
84 #include "llvm/MC/MCRegisterInfo.h"
85 #include "llvm/MC/MCSchedule.h"
86 #include "llvm/Support/AtomicOrdering.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CodeGen.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetInstrInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
110 using namespace llvm;
112 #define DEBUG_TYPE "arm-isel"
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
117 STATISTIC(NumConstpoolPromoted,
118 "Number of constants with their storage promoted into constant pools");
121 ARMInterworking("arm-interworking", cl::Hidden,
122 cl::desc("Enable / disable ARM interworking (for debugging only)"),
125 static cl::opt<bool> EnableConstpoolPromotion(
126 "arm-promote-constant", cl::Hidden,
127 cl::desc("Enable / disable promotion of unnamed_addr constants into "
130 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
131 "arm-promote-constant-max-size", cl::Hidden,
132 cl::desc("Maximum size of constant to promote into a constant pool"),
134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
135 "arm-promote-constant-max-total", cl::Hidden,
136 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
139 // The APCS parameter registers.
140 static const MCPhysReg GPRArgRegs[] = {
141 ARM::R0, ARM::R1, ARM::R2, ARM::R3
144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
145 MVT PromotedBitwiseVT) {
146 if (VT != PromotedLdStVT) {
147 setOperationAction(ISD::LOAD, VT, Promote);
148 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
150 setOperationAction(ISD::STORE, VT, Promote);
151 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
154 MVT ElemTy = VT.getVectorElementType();
155 if (ElemTy != MVT::f64)
156 setOperationAction(ISD::SETCC, VT, Custom);
157 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
158 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
159 if (ElemTy == MVT::i32) {
160 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
161 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
162 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
163 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
165 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
166 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
167 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
168 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
170 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
171 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
172 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
173 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
174 setOperationAction(ISD::SELECT, VT, Expand);
175 setOperationAction(ISD::SELECT_CC, VT, Expand);
176 setOperationAction(ISD::VSELECT, VT, Expand);
177 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
178 if (VT.isInteger()) {
179 setOperationAction(ISD::SHL, VT, Custom);
180 setOperationAction(ISD::SRA, VT, Custom);
181 setOperationAction(ISD::SRL, VT, Custom);
184 // Promote all bit-wise operations.
185 if (VT.isInteger() && VT != PromotedBitwiseVT) {
186 setOperationAction(ISD::AND, VT, Promote);
187 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
188 setOperationAction(ISD::OR, VT, Promote);
189 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
190 setOperationAction(ISD::XOR, VT, Promote);
191 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
194 // Neon does not support vector divide/remainder operations.
195 setOperationAction(ISD::SDIV, VT, Expand);
196 setOperationAction(ISD::UDIV, VT, Expand);
197 setOperationAction(ISD::FDIV, VT, Expand);
198 setOperationAction(ISD::SREM, VT, Expand);
199 setOperationAction(ISD::UREM, VT, Expand);
200 setOperationAction(ISD::FREM, VT, Expand);
202 if (!VT.isFloatingPoint() &&
203 VT != MVT::v2i64 && VT != MVT::v1i64)
204 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
205 setOperationAction(Opcode, VT, Legal);
208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
209 addRegisterClass(VT, &ARM::DPRRegClass);
210 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
214 addRegisterClass(VT, &ARM::DPairRegClass);
215 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
219 const ARMSubtarget &STI)
220 : TargetLowering(TM), Subtarget(&STI) {
221 RegInfo = Subtarget->getRegisterInfo();
222 Itins = Subtarget->getInstrItineraryData();
224 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
226 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
227 !Subtarget->isTargetWatchOS()) {
228 const auto &E = Subtarget->getTargetTriple().getEnvironment();
230 bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
231 E == Triple::MuslEABIHF;
232 // Windows is a special case. Technically, we will replace all of the "GNU"
233 // calls with calls to MSVCRT if appropriate and adjust the calling
235 IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
237 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
238 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
239 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
240 : CallingConv::ARM_AAPCS);
243 if (Subtarget->isTargetMachO()) {
244 // Uses VFP for Thumb libfuncs if available.
245 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
246 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
247 static const struct {
248 const RTLIB::Libcall Op;
249 const char * const Name;
250 const ISD::CondCode Cond;
252 // Single-precision floating-point arithmetic.
253 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
254 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
255 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
256 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
258 // Double-precision floating-point arithmetic.
259 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
260 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
261 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
262 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
264 // Single-precision comparisons.
265 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
266 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
267 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
268 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
269 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
270 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
271 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
272 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
274 // Double-precision comparisons.
275 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
276 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
277 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
278 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
279 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
280 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
281 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
282 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
284 // Floating-point to integer conversions.
285 // i64 conversions are done via library routines even when generating VFP
286 // instructions, so use the same ones.
287 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
288 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
289 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
290 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
292 // Conversions between floating types.
293 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
294 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
296 // Integer to floating-point conversions.
297 // i64 conversions are done via library routines even when generating VFP
298 // instructions, so use the same ones.
299 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
300 // e.g., __floatunsidf vs. __floatunssidfvfp.
301 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
302 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
303 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
304 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
307 for (const auto &LC : LibraryCalls) {
308 setLibcallName(LC.Op, LC.Name);
309 if (LC.Cond != ISD::SETCC_INVALID)
310 setCmpLibcallCC(LC.Op, LC.Cond);
314 // Set the correct calling convention for ARMv7k WatchOS. It's just
315 // AAPCS_VFP for functions as simple as libcalls.
316 if (Subtarget->isTargetWatchABI()) {
317 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
318 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
322 // These libcalls are not available in 32-bit.
323 setLibcallName(RTLIB::SHL_I128, nullptr);
324 setLibcallName(RTLIB::SRL_I128, nullptr);
325 setLibcallName(RTLIB::SRA_I128, nullptr);
328 if (Subtarget->isAAPCS_ABI() &&
329 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
330 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
331 static const struct {
332 const RTLIB::Libcall Op;
333 const char * const Name;
334 const CallingConv::ID CC;
335 const ISD::CondCode Cond;
337 // Double-precision floating-point arithmetic helper functions
338 // RTABI chapter 4.1.2, Table 2
339 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 // Double-precision floating-point comparison helper functions
345 // RTABI chapter 4.1.2, Table 3
346 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
347 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
348 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
349 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
350 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
351 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
352 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
353 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
355 // Single-precision floating-point arithmetic helper functions
356 // RTABI chapter 4.1.2, Table 4
357 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
362 // Single-precision floating-point comparison helper functions
363 // RTABI chapter 4.1.2, Table 5
364 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
365 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
366 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
367 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
368 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
369 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
370 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
371 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
373 // Floating-point to integer conversions.
374 // RTABI chapter 4.1.2, Table 6
375 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384 // Conversions between floating types.
385 // RTABI chapter 4.1.2, Table 7
386 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390 // Integer to floating-point conversions.
391 // RTABI chapter 4.1.2, Table 8
392 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401 // Long long helper functions
402 // RTABI chapter 4.2, Table 9
403 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408 // Integer division functions
409 // RTABI chapter 4.3.1
410 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
420 for (const auto &LC : LibraryCalls) {
421 setLibcallName(LC.Op, LC.Name);
422 setLibcallCallingConv(LC.Op, LC.CC);
423 if (LC.Cond != ISD::SETCC_INVALID)
424 setCmpLibcallCC(LC.Op, LC.Cond);
427 // EABI dependent RTLIB
428 if (TM.Options.EABIVersion == EABI::EABI4 ||
429 TM.Options.EABIVersion == EABI::EABI5) {
430 static const struct {
431 const RTLIB::Libcall Op;
432 const char *const Name;
433 const CallingConv::ID CC;
434 const ISD::CondCode Cond;
435 } MemOpsLibraryCalls[] = {
437 // RTABI chapter 4.3.4
438 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
443 for (const auto &LC : MemOpsLibraryCalls) {
444 setLibcallName(LC.Op, LC.Name);
445 setLibcallCallingConv(LC.Op, LC.CC);
446 if (LC.Cond != ISD::SETCC_INVALID)
447 setCmpLibcallCC(LC.Op, LC.Cond);
452 if (Subtarget->isTargetWindows()) {
453 static const struct {
454 const RTLIB::Libcall Op;
455 const char * const Name;
456 const CallingConv::ID CC;
458 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
459 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
460 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
461 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
462 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
463 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
464 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
465 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
468 for (const auto &LC : LibraryCalls) {
469 setLibcallName(LC.Op, LC.Name);
470 setLibcallCallingConv(LC.Op, LC.CC);
474 // Use divmod compiler-rt calls for iOS 5.0 and later.
475 if (Subtarget->isTargetWatchOS() ||
476 (Subtarget->isTargetIOS() &&
477 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
478 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
479 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
482 // The half <-> float conversion functions are always soft-float on
483 // non-watchos platforms, but are needed for some targets which use a
484 // hard-float calling convention by default.
485 if (!Subtarget->isTargetWatchABI()) {
486 if (Subtarget->isAAPCS_ABI()) {
487 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
488 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
489 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
491 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
492 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
493 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
497 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
498 // a __gnu_ prefix (which is the default).
499 if (Subtarget->isTargetAEABI()) {
500 static const struct {
501 const RTLIB::Libcall Op;
502 const char * const Name;
503 const CallingConv::ID CC;
505 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
506 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
507 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
510 for (const auto &LC : LibraryCalls) {
511 setLibcallName(LC.Op, LC.Name);
512 setLibcallCallingConv(LC.Op, LC.CC);
516 if (Subtarget->isThumb1Only())
517 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
519 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
521 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
522 !Subtarget->isThumb1Only()) {
523 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
524 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
527 for (MVT VT : MVT::vector_valuetypes()) {
528 for (MVT InnerVT : MVT::vector_valuetypes()) {
529 setTruncStoreAction(VT, InnerVT, Expand);
530 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
531 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
532 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
535 setOperationAction(ISD::MULHS, VT, Expand);
536 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
537 setOperationAction(ISD::MULHU, VT, Expand);
538 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
540 setOperationAction(ISD::BSWAP, VT, Expand);
543 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
544 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
546 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
547 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
549 if (Subtarget->hasNEON()) {
550 addDRTypeForNEON(MVT::v2f32);
551 addDRTypeForNEON(MVT::v8i8);
552 addDRTypeForNEON(MVT::v4i16);
553 addDRTypeForNEON(MVT::v2i32);
554 addDRTypeForNEON(MVT::v1i64);
556 addQRTypeForNEON(MVT::v4f32);
557 addQRTypeForNEON(MVT::v2f64);
558 addQRTypeForNEON(MVT::v16i8);
559 addQRTypeForNEON(MVT::v8i16);
560 addQRTypeForNEON(MVT::v4i32);
561 addQRTypeForNEON(MVT::v2i64);
563 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
564 // neither Neon nor VFP support any arithmetic operations on it.
565 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
566 // supported for v4f32.
567 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
568 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
569 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
570 // FIXME: Code duplication: FDIV and FREM are expanded always, see
571 // ARMTargetLowering::addTypeForNEON method for details.
572 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
573 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
574 // FIXME: Create unittest.
575 // In another words, find a way when "copysign" appears in DAG with vector
577 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
578 // FIXME: Code duplication: SETCC has custom operation action, see
579 // ARMTargetLowering::addTypeForNEON method for details.
580 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
581 // FIXME: Create unittest for FNEG and for FABS.
582 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
583 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
584 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
585 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
586 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
587 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
588 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
589 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
590 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
591 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
592 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
593 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
594 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
595 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
596 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
597 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
598 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
599 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
600 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
602 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
603 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
604 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
605 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
606 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
607 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
608 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
609 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
610 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
611 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
612 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
613 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
614 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
615 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
616 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
618 // Mark v2f32 intrinsics.
619 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
620 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
621 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
622 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
623 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
624 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
625 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
626 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
627 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
628 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
629 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
630 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
631 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
632 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
633 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
635 // Neon does not support some operations on v1i64 and v2i64 types.
636 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
637 // Custom handling for some quad-vector types to detect VMULL.
638 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
639 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
640 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
641 // Custom handling for some vector types to avoid expensive expansions
642 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
643 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
644 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
645 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
646 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
647 // a destination type that is wider than the source, and nor does
648 // it have a FP_TO_[SU]INT instruction with a narrower destination than
650 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
651 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
652 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
653 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
655 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
656 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
658 // NEON does not have single instruction CTPOP for vectors with element
659 // types wider than 8-bits. However, custom lowering can leverage the
660 // v8i8/v16i8 vcnt instruction.
661 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
662 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
663 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
664 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
665 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand);
666 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand);
668 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
669 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
671 // NEON does not have single instruction CTTZ for vectors.
672 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
673 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
674 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
675 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
677 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
678 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
679 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
680 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
688 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
692 // NEON only has FMA instructions as of VFP4.
693 if (!Subtarget->hasVFP4()) {
694 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
695 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
698 setTargetDAGCombine(ISD::INTRINSIC_VOID);
699 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
700 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
701 setTargetDAGCombine(ISD::SHL);
702 setTargetDAGCombine(ISD::SRL);
703 setTargetDAGCombine(ISD::SRA);
704 setTargetDAGCombine(ISD::SIGN_EXTEND);
705 setTargetDAGCombine(ISD::ZERO_EXTEND);
706 setTargetDAGCombine(ISD::ANY_EXTEND);
707 setTargetDAGCombine(ISD::BUILD_VECTOR);
708 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
709 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
710 setTargetDAGCombine(ISD::STORE);
711 setTargetDAGCombine(ISD::FP_TO_SINT);
712 setTargetDAGCombine(ISD::FP_TO_UINT);
713 setTargetDAGCombine(ISD::FDIV);
714 setTargetDAGCombine(ISD::LOAD);
716 // It is legal to extload from v4i8 to v4i16 or v4i32.
717 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
719 for (MVT VT : MVT::integer_vector_valuetypes()) {
720 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
721 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
722 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
727 if (Subtarget->isFPOnlySP()) {
728 // When targeting a floating-point unit with only single-precision
729 // operations, f64 is legal for the few double-precision instructions which
730 // are present However, no double-precision operations other than moves,
731 // loads and stores are provided by the hardware.
732 setOperationAction(ISD::FADD, MVT::f64, Expand);
733 setOperationAction(ISD::FSUB, MVT::f64, Expand);
734 setOperationAction(ISD::FMUL, MVT::f64, Expand);
735 setOperationAction(ISD::FMA, MVT::f64, Expand);
736 setOperationAction(ISD::FDIV, MVT::f64, Expand);
737 setOperationAction(ISD::FREM, MVT::f64, Expand);
738 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
739 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
740 setOperationAction(ISD::FNEG, MVT::f64, Expand);
741 setOperationAction(ISD::FABS, MVT::f64, Expand);
742 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
743 setOperationAction(ISD::FSIN, MVT::f64, Expand);
744 setOperationAction(ISD::FCOS, MVT::f64, Expand);
745 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
746 setOperationAction(ISD::FPOW, MVT::f64, Expand);
747 setOperationAction(ISD::FLOG, MVT::f64, Expand);
748 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
749 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
750 setOperationAction(ISD::FEXP, MVT::f64, Expand);
751 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
752 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
753 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
754 setOperationAction(ISD::FRINT, MVT::f64, Expand);
755 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
756 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
757 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
758 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
759 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
760 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
761 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
762 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
763 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
764 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
767 computeRegisterProperties(Subtarget->getRegisterInfo());
769 // ARM does not have floating-point extending loads.
770 for (MVT VT : MVT::fp_valuetypes()) {
771 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
772 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
775 // ... or truncating stores
776 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
777 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
778 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
780 // ARM does not have i1 sign extending load.
781 for (MVT VT : MVT::integer_valuetypes())
782 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
784 // ARM supports all 4 flavors of integer indexed load / store.
785 if (!Subtarget->isThumb1Only()) {
786 for (unsigned im = (unsigned)ISD::PRE_INC;
787 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
788 setIndexedLoadAction(im, MVT::i1, Legal);
789 setIndexedLoadAction(im, MVT::i8, Legal);
790 setIndexedLoadAction(im, MVT::i16, Legal);
791 setIndexedLoadAction(im, MVT::i32, Legal);
792 setIndexedStoreAction(im, MVT::i1, Legal);
793 setIndexedStoreAction(im, MVT::i8, Legal);
794 setIndexedStoreAction(im, MVT::i16, Legal);
795 setIndexedStoreAction(im, MVT::i32, Legal);
798 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
799 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
800 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
803 setOperationAction(ISD::SADDO, MVT::i32, Custom);
804 setOperationAction(ISD::UADDO, MVT::i32, Custom);
805 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
806 setOperationAction(ISD::USUBO, MVT::i32, Custom);
808 // i64 operation support.
809 setOperationAction(ISD::MUL, MVT::i64, Expand);
810 setOperationAction(ISD::MULHU, MVT::i32, Expand);
811 if (Subtarget->isThumb1Only()) {
812 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
813 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
815 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
816 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
817 setOperationAction(ISD::MULHS, MVT::i32, Expand);
819 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
820 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
821 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
822 setOperationAction(ISD::SRL, MVT::i64, Custom);
823 setOperationAction(ISD::SRA, MVT::i64, Custom);
825 setOperationAction(ISD::ADDC, MVT::i32, Custom);
826 setOperationAction(ISD::ADDE, MVT::i32, Custom);
827 setOperationAction(ISD::SUBC, MVT::i32, Custom);
828 setOperationAction(ISD::SUBE, MVT::i32, Custom);
830 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
831 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
833 // ARM does not have ROTL.
834 setOperationAction(ISD::ROTL, MVT::i32, Expand);
835 for (MVT VT : MVT::vector_valuetypes()) {
836 setOperationAction(ISD::ROTL, VT, Expand);
837 setOperationAction(ISD::ROTR, VT, Expand);
839 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
840 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
841 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
842 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
844 // @llvm.readcyclecounter requires the Performance Monitors extension.
845 // Default to the 0 expansion on unsupported platforms.
846 // FIXME: Technically there are older ARM CPUs that have
847 // implementation-specific ways of obtaining this information.
848 if (Subtarget->hasPerfMon())
849 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
851 // Only ARMv6 has BSWAP.
852 if (!Subtarget->hasV6Ops())
853 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
855 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
856 : Subtarget->hasDivideInARMMode();
858 // These are expanded into libcalls if the cpu doesn't have HW divider.
859 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
860 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
863 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
864 setOperationAction(ISD::SDIV, MVT::i32, Custom);
865 setOperationAction(ISD::UDIV, MVT::i32, Custom);
867 setOperationAction(ISD::SDIV, MVT::i64, Custom);
868 setOperationAction(ISD::UDIV, MVT::i64, Custom);
871 setOperationAction(ISD::SREM, MVT::i32, Expand);
872 setOperationAction(ISD::UREM, MVT::i32, Expand);
874 // Register based DivRem for AEABI (RTABI 4.2)
875 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
876 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
877 Subtarget->isTargetWindows()) {
878 setOperationAction(ISD::SREM, MVT::i64, Custom);
879 setOperationAction(ISD::UREM, MVT::i64, Custom);
880 HasStandaloneRem = false;
882 if (Subtarget->isTargetWindows()) {
884 const RTLIB::Libcall Op;
885 const char * const Name;
886 const CallingConv::ID CC;
888 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
889 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
890 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
891 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
893 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
894 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
895 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
896 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
899 for (const auto &LC : LibraryCalls) {
900 setLibcallName(LC.Op, LC.Name);
901 setLibcallCallingConv(LC.Op, LC.CC);
905 const RTLIB::Libcall Op;
906 const char * const Name;
907 const CallingConv::ID CC;
909 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
910 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
911 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
912 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
914 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
915 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
916 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
917 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
920 for (const auto &LC : LibraryCalls) {
921 setLibcallName(LC.Op, LC.Name);
922 setLibcallCallingConv(LC.Op, LC.CC);
926 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
927 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
928 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
929 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
931 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
932 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
935 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
936 for (auto &VT : {MVT::f32, MVT::f64})
937 setOperationAction(ISD::FPOWI, VT, Custom);
939 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
940 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
941 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
942 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
944 setOperationAction(ISD::TRAP, MVT::Other, Legal);
946 // Use the default implementation.
947 setOperationAction(ISD::VASTART, MVT::Other, Custom);
948 setOperationAction(ISD::VAARG, MVT::Other, Expand);
949 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
950 setOperationAction(ISD::VAEND, MVT::Other, Expand);
951 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
952 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
954 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
957 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
959 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
960 // the default expansion.
961 InsertFencesForAtomic = false;
962 if (Subtarget->hasAnyDataBarrier() &&
963 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
964 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
965 // to ldrex/strex loops already.
966 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
967 if (!Subtarget->isThumb() || !Subtarget->isMClass())
968 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
970 // On v8, we have particularly efficient implementations of atomic fences
971 // if they can be combined with nearby atomic loads and stores.
972 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
973 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
974 InsertFencesForAtomic = true;
977 // If there's anything we can use as a barrier, go through custom lowering
979 // If target has DMB in thumb, Fences can be inserted.
980 if (Subtarget->hasDataBarrier())
981 InsertFencesForAtomic = true;
983 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
984 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
986 // Set them all for expansion, which will force libcalls.
987 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
988 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
989 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
990 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
991 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
992 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
993 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
994 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
995 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
996 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
997 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
998 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
999 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1000 // Unordered/Monotonic case.
1001 if (!InsertFencesForAtomic) {
1002 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1003 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1007 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1009 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1010 if (!Subtarget->hasV6Ops()) {
1011 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1014 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1016 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1017 !Subtarget->isThumb1Only()) {
1018 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1019 // iff target supports vfp2.
1020 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1021 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1024 // We want to custom lower some of our intrinsics.
1025 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1026 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1027 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1028 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1029 if (Subtarget->useSjLjEH())
1030 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1032 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1033 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1034 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1035 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1036 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1037 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1038 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1039 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1040 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1042 // Thumb-1 cannot currently select ARMISD::SUBE.
1043 if (!Subtarget->isThumb1Only())
1044 setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1046 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1047 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1048 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1049 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1050 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1052 // We don't support sin/cos/fmod/copysign/pow
1053 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1054 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1055 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1056 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1057 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1058 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1059 setOperationAction(ISD::FREM, MVT::f64, Expand);
1060 setOperationAction(ISD::FREM, MVT::f32, Expand);
1061 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1062 !Subtarget->isThumb1Only()) {
1063 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1064 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1066 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1067 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1069 if (!Subtarget->hasVFP4()) {
1070 setOperationAction(ISD::FMA, MVT::f64, Expand);
1071 setOperationAction(ISD::FMA, MVT::f32, Expand);
1074 // Various VFP goodness
1075 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1076 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1077 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1078 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1079 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1082 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1083 if (!Subtarget->hasFP16()) {
1084 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1085 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1089 // Combine sin / cos into one node or libcall if possible.
1090 if (Subtarget->hasSinCos()) {
1091 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1092 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1093 if (Subtarget->isTargetWatchABI()) {
1094 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1095 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1097 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1098 // For iOS, we don't want to the normal expansion of a libcall to
1099 // sincos. We want to issue a libcall to __sincos_stret.
1100 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1101 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1105 // FP-ARMv8 implements a lot of rounding-like FP operations.
1106 if (Subtarget->hasFPARMv8()) {
1107 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1108 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1109 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1110 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1111 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1112 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1113 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1114 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1115 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1116 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1117 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1118 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1120 if (!Subtarget->isFPOnlySP()) {
1121 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1122 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1123 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1124 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1125 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1126 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1127 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1128 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1132 if (Subtarget->hasNEON()) {
1133 // vmin and vmax aren't available in a scalar form, so we use
1134 // a NEON instruction with an undef lane instead.
1135 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1136 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1137 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1138 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1139 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1140 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1143 // We have target-specific dag combine patterns for the following nodes:
1144 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1145 setTargetDAGCombine(ISD::ADD);
1146 setTargetDAGCombine(ISD::SUB);
1147 setTargetDAGCombine(ISD::MUL);
1148 setTargetDAGCombine(ISD::AND);
1149 setTargetDAGCombine(ISD::OR);
1150 setTargetDAGCombine(ISD::XOR);
1152 if (Subtarget->hasV6Ops())
1153 setTargetDAGCombine(ISD::SRL);
1155 setStackPointerRegisterToSaveRestore(ARM::SP);
1157 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1158 !Subtarget->hasVFP2())
1159 setSchedulingPreference(Sched::RegPressure);
1161 setSchedulingPreference(Sched::Hybrid);
1163 //// temporary - rewrite interface to use type
1164 MaxStoresPerMemset = 8;
1165 MaxStoresPerMemsetOptSize = 4;
1166 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1167 MaxStoresPerMemcpyOptSize = 2;
1168 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1169 MaxStoresPerMemmoveOptSize = 2;
1171 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1172 // are at least 4 bytes aligned.
1173 setMinStackArgumentAlignment(4);
1175 // Prefer likely predicted branches to selects on out-of-order cores.
1176 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1178 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1181 bool ARMTargetLowering::useSoftFloat() const {
1182 return Subtarget->useSoftFloat();
1185 // FIXME: It might make sense to define the representative register class as the
1186 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1187 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1188 // SPR's representative would be DPR_VFP2. This should work well if register
1189 // pressure tracking were modified such that a register use would increment the
1190 // pressure of the register class's representative and all of it's super
1191 // classes' representatives transitively. We have not implemented this because
1192 // of the difficulty prior to coalescing of modeling operand register classes
1193 // due to the common occurrence of cross class copies and subregister insertions
1195 std::pair<const TargetRegisterClass *, uint8_t>
1196 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1198 const TargetRegisterClass *RRC = nullptr;
1200 switch (VT.SimpleTy) {
1202 return TargetLowering::findRepresentativeClass(TRI, VT);
1203 // Use DPR as representative register class for all floating point
1204 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1205 // the cost is 1 for both f32 and f64.
1206 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1207 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1208 RRC = &ARM::DPRRegClass;
1209 // When NEON is used for SP, only half of the register file is available
1210 // because operations that define both SP and DP results will be constrained
1211 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1212 // coalescing by double-counting the SP regs. See the FIXME above.
1213 if (Subtarget->useNEONForSinglePrecisionFP())
1216 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1217 case MVT::v4f32: case MVT::v2f64:
1218 RRC = &ARM::DPRRegClass;
1222 RRC = &ARM::DPRRegClass;
1226 RRC = &ARM::DPRRegClass;
1230 return std::make_pair(RRC, Cost);
1233 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1234 switch ((ARMISD::NodeType)Opcode) {
1235 case ARMISD::FIRST_NUMBER: break;
1236 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1237 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1238 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1239 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1240 case ARMISD::CALL: return "ARMISD::CALL";
1241 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1242 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1243 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1244 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1245 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1246 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1247 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1248 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1249 case ARMISD::CMP: return "ARMISD::CMP";
1250 case ARMISD::CMN: return "ARMISD::CMN";
1251 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1252 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1253 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1254 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1255 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1257 case ARMISD::CMOV: return "ARMISD::CMOV";
1259 case ARMISD::SSAT: return "ARMISD::SSAT";
1261 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1262 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1263 case ARMISD::RRX: return "ARMISD::RRX";
1265 case ARMISD::ADDC: return "ARMISD::ADDC";
1266 case ARMISD::ADDE: return "ARMISD::ADDE";
1267 case ARMISD::SUBC: return "ARMISD::SUBC";
1268 case ARMISD::SUBE: return "ARMISD::SUBE";
1270 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1271 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1273 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1274 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1275 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1277 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1279 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1281 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1283 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1285 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1287 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1288 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1290 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1291 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1292 case ARMISD::VCGE: return "ARMISD::VCGE";
1293 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1294 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1295 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1296 case ARMISD::VCGT: return "ARMISD::VCGT";
1297 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1298 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1299 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1300 case ARMISD::VTST: return "ARMISD::VTST";
1302 case ARMISD::VSHL: return "ARMISD::VSHL";
1303 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1304 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1305 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1306 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1307 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1308 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1309 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1310 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1311 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1312 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1313 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1314 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1315 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1316 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1317 case ARMISD::VSLI: return "ARMISD::VSLI";
1318 case ARMISD::VSRI: return "ARMISD::VSRI";
1319 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1320 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1321 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1322 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1323 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1324 case ARMISD::VDUP: return "ARMISD::VDUP";
1325 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1326 case ARMISD::VEXT: return "ARMISD::VEXT";
1327 case ARMISD::VREV64: return "ARMISD::VREV64";
1328 case ARMISD::VREV32: return "ARMISD::VREV32";
1329 case ARMISD::VREV16: return "ARMISD::VREV16";
1330 case ARMISD::VZIP: return "ARMISD::VZIP";
1331 case ARMISD::VUZP: return "ARMISD::VUZP";
1332 case ARMISD::VTRN: return "ARMISD::VTRN";
1333 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1334 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1335 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1336 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1337 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1338 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1339 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1340 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1341 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1342 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1343 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1344 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1345 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1346 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1347 case ARMISD::BFI: return "ARMISD::BFI";
1348 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1349 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1350 case ARMISD::VBSL: return "ARMISD::VBSL";
1351 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1352 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1353 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1354 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1355 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1356 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1357 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1358 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1359 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1360 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1361 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1362 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1363 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1364 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1365 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1366 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1367 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1368 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1369 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1370 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1371 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1372 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1373 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1378 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1381 return getPointerTy(DL);
1382 return VT.changeVectorElementTypeToInteger();
1385 /// getRegClassFor - Return the register class that should be used for the
1386 /// specified value type.
1387 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1388 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1389 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1390 // load / store 4 to 8 consecutive D registers.
1391 if (Subtarget->hasNEON()) {
1392 if (VT == MVT::v4i64)
1393 return &ARM::QQPRRegClass;
1394 if (VT == MVT::v8i64)
1395 return &ARM::QQQQPRRegClass;
1397 return TargetLowering::getRegClassFor(VT);
1400 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1401 // source/dest is aligned and the copy size is large enough. We therefore want
1402 // to align such objects passed to memory intrinsics.
1403 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1404 unsigned &PrefAlign) const {
1405 if (!isa<MemIntrinsic>(CI))
1408 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1409 // cycle faster than 4-byte aligned LDM.
1410 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1414 // Create a fast isel object.
1416 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1417 const TargetLibraryInfo *libInfo) const {
1418 return ARM::createFastISel(funcInfo, libInfo);
1421 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1422 unsigned NumVals = N->getNumValues();
1424 return Sched::RegPressure;
1426 for (unsigned i = 0; i != NumVals; ++i) {
1427 EVT VT = N->getValueType(i);
1428 if (VT == MVT::Glue || VT == MVT::Other)
1430 if (VT.isFloatingPoint() || VT.isVector())
1434 if (!N->isMachineOpcode())
1435 return Sched::RegPressure;
1437 // Load are scheduled for latency even if there instruction itinerary
1438 // is not available.
1439 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1440 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1442 if (MCID.getNumDefs() == 0)
1443 return Sched::RegPressure;
1444 if (!Itins->isEmpty() &&
1445 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1448 return Sched::RegPressure;
1451 //===----------------------------------------------------------------------===//
1453 //===----------------------------------------------------------------------===//
1455 static bool isSRL16(const SDValue &Op) {
1456 if (Op.getOpcode() != ISD::SRL)
1458 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1459 return Const->getZExtValue() == 16;
1463 static bool isSRA16(const SDValue &Op) {
1464 if (Op.getOpcode() != ISD::SRA)
1466 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1467 return Const->getZExtValue() == 16;
1471 static bool isSHL16(const SDValue &Op) {
1472 if (Op.getOpcode() != ISD::SHL)
1474 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1475 return Const->getZExtValue() == 16;
1479 // Check for a signed 16-bit value. We special case SRA because it makes it
1480 // more simple when also looking for SRAs that aren't sign extending a
1481 // smaller value. Without the check, we'd need to take extra care with
1482 // checking order for some operations.
1483 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1485 return isSHL16(Op.getOperand(0));
1486 return DAG.ComputeNumSignBits(Op) == 17;
1489 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1490 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1492 default: llvm_unreachable("Unknown condition code!");
1493 case ISD::SETNE: return ARMCC::NE;
1494 case ISD::SETEQ: return ARMCC::EQ;
1495 case ISD::SETGT: return ARMCC::GT;
1496 case ISD::SETGE: return ARMCC::GE;
1497 case ISD::SETLT: return ARMCC::LT;
1498 case ISD::SETLE: return ARMCC::LE;
1499 case ISD::SETUGT: return ARMCC::HI;
1500 case ISD::SETUGE: return ARMCC::HS;
1501 case ISD::SETULT: return ARMCC::LO;
1502 case ISD::SETULE: return ARMCC::LS;
1506 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1507 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1508 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1509 CondCode2 = ARMCC::AL;
1510 InvalidOnQNaN = true;
1512 default: llvm_unreachable("Unknown FP condition!");
1515 CondCode = ARMCC::EQ;
1516 InvalidOnQNaN = false;
1519 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1521 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1522 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1523 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1525 CondCode = ARMCC::MI;
1526 CondCode2 = ARMCC::GT;
1527 InvalidOnQNaN = false;
1529 case ISD::SETO: CondCode = ARMCC::VC; break;
1530 case ISD::SETUO: CondCode = ARMCC::VS; break;
1532 CondCode = ARMCC::EQ;
1533 CondCode2 = ARMCC::VS;
1534 InvalidOnQNaN = false;
1536 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1537 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1539 case ISD::SETULT: CondCode = ARMCC::LT; break;
1541 case ISD::SETULE: CondCode = ARMCC::LE; break;
1544 CondCode = ARMCC::NE;
1545 InvalidOnQNaN = false;
1550 //===----------------------------------------------------------------------===//
1551 // Calling Convention Implementation
1552 //===----------------------------------------------------------------------===//
1554 #include "ARMGenCallingConv.inc"
1556 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1557 /// account presence of floating point hardware and calling convention
1558 /// limitations, such as support for variadic functions.
1560 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1561 bool isVarArg) const {
1564 llvm_unreachable("Unsupported calling convention");
1565 case CallingConv::ARM_AAPCS:
1566 case CallingConv::ARM_APCS:
1567 case CallingConv::GHC:
1569 case CallingConv::PreserveMost:
1570 return CallingConv::PreserveMost;
1571 case CallingConv::ARM_AAPCS_VFP:
1572 case CallingConv::Swift:
1573 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1574 case CallingConv::C:
1575 if (!Subtarget->isAAPCS_ABI())
1576 return CallingConv::ARM_APCS;
1577 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1578 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1580 return CallingConv::ARM_AAPCS_VFP;
1582 return CallingConv::ARM_AAPCS;
1583 case CallingConv::Fast:
1584 case CallingConv::CXX_FAST_TLS:
1585 if (!Subtarget->isAAPCS_ABI()) {
1586 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1587 return CallingConv::Fast;
1588 return CallingConv::ARM_APCS;
1589 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1590 return CallingConv::ARM_AAPCS_VFP;
1592 return CallingConv::ARM_AAPCS;
1596 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1597 bool isVarArg) const {
1598 return CCAssignFnForNode(CC, false, isVarArg);
1601 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1602 bool isVarArg) const {
1603 return CCAssignFnForNode(CC, true, isVarArg);
1606 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1607 /// CallingConvention.
1608 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1610 bool isVarArg) const {
1611 switch (getEffectiveCallingConv(CC, isVarArg)) {
1613 llvm_unreachable("Unsupported calling convention");
1614 case CallingConv::ARM_APCS:
1615 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1616 case CallingConv::ARM_AAPCS:
1617 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1618 case CallingConv::ARM_AAPCS_VFP:
1619 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1620 case CallingConv::Fast:
1621 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1622 case CallingConv::GHC:
1623 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1624 case CallingConv::PreserveMost:
1625 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1629 /// LowerCallResult - Lower the result values of a call into the
1630 /// appropriate copies out of appropriate physical registers.
1631 SDValue ARMTargetLowering::LowerCallResult(
1632 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1633 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1634 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1635 SDValue ThisVal) const {
1637 // Assign locations to each value returned by this call.
1638 SmallVector<CCValAssign, 16> RVLocs;
1639 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1641 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1643 // Copy all of the result registers out of their specified physreg.
1644 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1645 CCValAssign VA = RVLocs[i];
1647 // Pass 'this' value directly from the argument to return value, to avoid
1648 // reg unit interference
1649 if (i == 0 && isThisReturn) {
1650 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1651 "unexpected return calling convention register assignment");
1652 InVals.push_back(ThisVal);
1657 if (VA.needsCustom()) {
1658 // Handle f64 or half of a v2f64.
1659 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1661 Chain = Lo.getValue(1);
1662 InFlag = Lo.getValue(2);
1663 VA = RVLocs[++i]; // skip ahead to next loc
1664 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1666 Chain = Hi.getValue(1);
1667 InFlag = Hi.getValue(2);
1668 if (!Subtarget->isLittle())
1670 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1672 if (VA.getLocVT() == MVT::v2f64) {
1673 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1674 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1675 DAG.getConstant(0, dl, MVT::i32));
1677 VA = RVLocs[++i]; // skip ahead to next loc
1678 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1679 Chain = Lo.getValue(1);
1680 InFlag = Lo.getValue(2);
1681 VA = RVLocs[++i]; // skip ahead to next loc
1682 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1683 Chain = Hi.getValue(1);
1684 InFlag = Hi.getValue(2);
1685 if (!Subtarget->isLittle())
1687 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1688 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1689 DAG.getConstant(1, dl, MVT::i32));
1692 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1694 Chain = Val.getValue(1);
1695 InFlag = Val.getValue(2);
1698 switch (VA.getLocInfo()) {
1699 default: llvm_unreachable("Unknown loc info!");
1700 case CCValAssign::Full: break;
1701 case CCValAssign::BCvt:
1702 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1706 InVals.push_back(Val);
1712 /// LowerMemOpCallTo - Store the argument to the stack.
1713 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1714 SDValue Arg, const SDLoc &dl,
1716 const CCValAssign &VA,
1717 ISD::ArgFlagsTy Flags) const {
1718 unsigned LocMemOffset = VA.getLocMemOffset();
1719 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1720 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1722 return DAG.getStore(
1723 Chain, dl, Arg, PtrOff,
1724 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1727 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1728 SDValue Chain, SDValue &Arg,
1729 RegsToPassVector &RegsToPass,
1730 CCValAssign &VA, CCValAssign &NextVA,
1732 SmallVectorImpl<SDValue> &MemOpChains,
1733 ISD::ArgFlagsTy Flags) const {
1735 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1736 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1737 unsigned id = Subtarget->isLittle() ? 0 : 1;
1738 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1740 if (NextVA.isRegLoc())
1741 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1743 assert(NextVA.isMemLoc());
1744 if (!StackPtr.getNode())
1745 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1746 getPointerTy(DAG.getDataLayout()));
1748 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1754 /// LowerCall - Lowering a call into a callseq_start <-
1755 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1758 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1759 SmallVectorImpl<SDValue> &InVals) const {
1760 SelectionDAG &DAG = CLI.DAG;
1762 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1763 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1764 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1765 SDValue Chain = CLI.Chain;
1766 SDValue Callee = CLI.Callee;
1767 bool &isTailCall = CLI.IsTailCall;
1768 CallingConv::ID CallConv = CLI.CallConv;
1769 bool doesNotRet = CLI.DoesNotReturn;
1770 bool isVarArg = CLI.IsVarArg;
1772 MachineFunction &MF = DAG.getMachineFunction();
1773 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1774 bool isThisReturn = false;
1775 bool isSibCall = false;
1776 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1778 // Disable tail calls if they're not supported.
1779 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1783 // Check if it's really possible to do a tail call.
1784 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1785 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1786 Outs, OutVals, Ins, DAG);
1787 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1788 report_fatal_error("failed to perform tail call elimination on a call "
1789 "site marked musttail");
1790 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1791 // detected sibcalls.
1798 // Analyze operands of the call, assigning locations to each operand.
1799 SmallVector<CCValAssign, 16> ArgLocs;
1800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1802 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1804 // Get a count of how many bytes are to be pushed on the stack.
1805 unsigned NumBytes = CCInfo.getNextStackOffset();
1807 // For tail calls, memory operands are available in our caller's stack.
1811 // Adjust the stack pointer for the new arguments...
1812 // These operations are automatically eliminated by the prolog/epilog pass
1814 Chain = DAG.getCALLSEQ_START(Chain,
1815 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1818 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1820 RegsToPassVector RegsToPass;
1821 SmallVector<SDValue, 8> MemOpChains;
1823 // Walk the register/memloc assignments, inserting copies/loads. In the case
1824 // of tail call optimization, arguments are handled later.
1825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1827 ++i, ++realArgIdx) {
1828 CCValAssign &VA = ArgLocs[i];
1829 SDValue Arg = OutVals[realArgIdx];
1830 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831 bool isByVal = Flags.isByVal();
1833 // Promote the value if needed.
1834 switch (VA.getLocInfo()) {
1835 default: llvm_unreachable("Unknown loc info!");
1836 case CCValAssign::Full: break;
1837 case CCValAssign::SExt:
1838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1840 case CCValAssign::ZExt:
1841 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1843 case CCValAssign::AExt:
1844 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1846 case CCValAssign::BCvt:
1847 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1851 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1852 if (VA.needsCustom()) {
1853 if (VA.getLocVT() == MVT::v2f64) {
1854 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1855 DAG.getConstant(0, dl, MVT::i32));
1856 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1857 DAG.getConstant(1, dl, MVT::i32));
1859 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1860 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1862 VA = ArgLocs[++i]; // skip ahead to next loc
1863 if (VA.isRegLoc()) {
1864 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1865 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1867 assert(VA.isMemLoc());
1869 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1870 dl, DAG, VA, Flags));
1873 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1874 StackPtr, MemOpChains, Flags);
1876 } else if (VA.isRegLoc()) {
1877 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1878 Outs[0].VT == MVT::i32) {
1879 assert(VA.getLocVT() == MVT::i32 &&
1880 "unexpected calling convention register assignment");
1881 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1882 "unexpected use of 'returned'");
1883 isThisReturn = true;
1885 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1886 } else if (isByVal) {
1887 assert(VA.isMemLoc());
1888 unsigned offset = 0;
1890 // True if this byval aggregate will be split between registers
1892 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1893 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1895 if (CurByValIdx < ByValArgsCount) {
1897 unsigned RegBegin, RegEnd;
1898 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1901 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1903 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1904 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1905 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1906 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1907 MachinePointerInfo(),
1908 DAG.InferPtrAlignment(AddArg));
1909 MemOpChains.push_back(Load.getValue(1));
1910 RegsToPass.push_back(std::make_pair(j, Load));
1913 // If parameter size outsides register area, "offset" value
1914 // helps us to calculate stack slot for remained part properly.
1915 offset = RegEnd - RegBegin;
1917 CCInfo.nextInRegsParam();
1920 if (Flags.getByValSize() > 4*offset) {
1921 auto PtrVT = getPointerTy(DAG.getDataLayout());
1922 unsigned LocMemOffset = VA.getLocMemOffset();
1923 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1924 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1925 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1926 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1927 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1929 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1932 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1933 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1934 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1937 } else if (!isSibCall) {
1938 assert(VA.isMemLoc());
1940 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1941 dl, DAG, VA, Flags));
1945 if (!MemOpChains.empty())
1946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1948 // Build a sequence of copy-to-reg nodes chained together with token chain
1949 // and flag operands which copy the outgoing args into the appropriate regs.
1951 // Tail call byval lowering might overwrite argument registers so in case of
1952 // tail call optimization the copies to registers are lowered later.
1954 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1955 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1956 RegsToPass[i].second, InFlag);
1957 InFlag = Chain.getValue(1);
1960 // For tail calls lower the arguments to the 'real' stack slot.
1962 // Force all the incoming stack arguments to be loaded from the stack
1963 // before any new outgoing arguments are stored to the stack, because the
1964 // outgoing stack slots may alias the incoming argument stack slots, and
1965 // the alias isn't otherwise explicit. This is slightly more conservative
1966 // than necessary, because it means that each store effectively depends
1967 // on every argument instead of just those arguments it would clobber.
1969 // Do not flag preceding copytoreg stuff together with the following stuff.
1971 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1972 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1973 RegsToPass[i].second, InFlag);
1974 InFlag = Chain.getValue(1);
1979 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1980 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1981 // node so that legalize doesn't hack it.
1982 bool isDirect = false;
1984 const TargetMachine &TM = getTargetMachine();
1985 const Module *Mod = MF.getFunction()->getParent();
1986 const GlobalValue *GV = nullptr;
1987 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1988 GV = G->getGlobal();
1990 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1992 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1993 bool isLocalARMFunc = false;
1994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1995 auto PtrVt = getPointerTy(DAG.getDataLayout());
1997 if (Subtarget->genLongCalls()) {
1998 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1999 "long-calls codegen is not position independent!");
2000 // Handle a global address or an external symbol. If it's not one of
2001 // those, the target's already in a register, so we don't need to do
2003 if (isa<GlobalAddressSDNode>(Callee)) {
2004 // Create a constant pool entry for the callee address
2005 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2006 ARMConstantPoolValue *CPV =
2007 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2009 // Get the address of the callee into a register
2010 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2011 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2012 Callee = DAG.getLoad(
2013 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2014 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2015 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2016 const char *Sym = S->getSymbol();
2018 // Create a constant pool entry for the callee address
2019 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2020 ARMConstantPoolValue *CPV =
2021 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2022 ARMPCLabelIndex, 0);
2023 // Get the address of the callee into a register
2024 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2025 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2026 Callee = DAG.getLoad(
2027 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2028 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2030 } else if (isa<GlobalAddressSDNode>(Callee)) {
2031 // If we're optimizing for minimum size and the function is called three or
2032 // more times in this block, we can improve codesize by calling indirectly
2033 // as BLXr has a 16-bit encoding.
2034 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2035 auto *BB = CLI.CS->getParent();
2036 bool PreferIndirect =
2037 Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2038 count_if(GV->users(), [&BB](const User *U) {
2039 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2042 if (!PreferIndirect) {
2044 bool isDef = GV->isStrongDefinitionForLinker();
2046 // ARM call to a local ARM function is predicable.
2047 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2048 // tBX takes a register source operand.
2049 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2050 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2051 Callee = DAG.getNode(
2052 ARMISD::WrapperPIC, dl, PtrVt,
2053 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2054 Callee = DAG.getLoad(
2055 PtrVt, dl, DAG.getEntryNode(), Callee,
2056 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2057 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2058 MachineMemOperand::MOInvariant);
2059 } else if (Subtarget->isTargetCOFF()) {
2060 assert(Subtarget->isTargetWindows() &&
2061 "Windows is the only supported COFF target");
2062 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2063 ? ARMII::MO_DLLIMPORT
2064 : ARMII::MO_NO_FLAG;
2065 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2067 if (GV->hasDLLImportStorageClass())
2069 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2070 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2071 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2073 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2076 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2078 // tBX takes a register source operand.
2079 const char *Sym = S->getSymbol();
2080 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2081 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2082 ARMConstantPoolValue *CPV =
2083 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2084 ARMPCLabelIndex, 4);
2085 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2086 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2087 Callee = DAG.getLoad(
2088 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2089 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2090 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2091 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2093 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2097 // FIXME: handle tail calls differently.
2099 if (Subtarget->isThumb()) {
2100 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2101 CallOpc = ARMISD::CALL_NOLINK;
2103 CallOpc = ARMISD::CALL;
2105 if (!isDirect && !Subtarget->hasV5TOps())
2106 CallOpc = ARMISD::CALL_NOLINK;
2107 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2108 // Emit regular call when code size is the priority
2109 !MF.getFunction()->optForMinSize())
2110 // "mov lr, pc; b _foo" to avoid confusing the RSP
2111 CallOpc = ARMISD::CALL_NOLINK;
2113 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2116 std::vector<SDValue> Ops;
2117 Ops.push_back(Chain);
2118 Ops.push_back(Callee);
2120 // Add argument registers to the end of the list so that they are known live
2122 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2123 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2124 RegsToPass[i].second.getValueType()));
2126 // Add a register mask operand representing the call-preserved registers.
2128 const uint32_t *Mask;
2129 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2131 // For 'this' returns, use the R0-preserving mask if applicable
2132 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2134 // Set isThisReturn to false if the calling convention is not one that
2135 // allows 'returned' to be modeled in this way, so LowerCallResult does
2136 // not try to pass 'this' straight through
2137 isThisReturn = false;
2138 Mask = ARI->getCallPreservedMask(MF, CallConv);
2141 Mask = ARI->getCallPreservedMask(MF, CallConv);
2143 assert(Mask && "Missing call preserved mask for calling convention");
2144 Ops.push_back(DAG.getRegisterMask(Mask));
2147 if (InFlag.getNode())
2148 Ops.push_back(InFlag);
2150 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2152 MF.getFrameInfo().setHasTailCall();
2153 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2156 // Returns a chain and a flag for retval copy to use.
2157 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2158 InFlag = Chain.getValue(1);
2160 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2161 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2163 InFlag = Chain.getValue(1);
2165 // Handle result values, copying them out of physregs into vregs that we
2167 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2168 InVals, isThisReturn,
2169 isThisReturn ? OutVals[0] : SDValue());
2172 /// HandleByVal - Every parameter *after* a byval parameter is passed
2173 /// on the stack. Remember the next parameter register to allocate,
2174 /// and then confiscate the rest of the parameter registers to insure
2176 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2177 unsigned Align) const {
2178 // Byval (as with any stack) slots are always at least 4 byte aligned.
2179 Align = std::max(Align, 4U);
2181 unsigned Reg = State->AllocateReg(GPRArgRegs);
2185 unsigned AlignInRegs = Align / 4;
2186 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2187 for (unsigned i = 0; i < Waste; ++i)
2188 Reg = State->AllocateReg(GPRArgRegs);
2193 unsigned Excess = 4 * (ARM::R4 - Reg);
2195 // Special case when NSAA != SP and parameter size greater than size of
2196 // all remained GPR regs. In that case we can't split parameter, we must
2197 // send it to stack. We also must set NCRN to R4, so waste all
2198 // remained registers.
2199 const unsigned NSAAOffset = State->getNextStackOffset();
2200 if (NSAAOffset != 0 && Size > Excess) {
2201 while (State->AllocateReg(GPRArgRegs))
2206 // First register for byval parameter is the first register that wasn't
2207 // allocated before this method call, so it would be "reg".
2208 // If parameter is small enough to be saved in range [reg, r4), then
2209 // the end (first after last) register would be reg + param-size-in-regs,
2210 // else parameter would be splitted between registers and stack,
2211 // end register would be r4 in this case.
2212 unsigned ByValRegBegin = Reg;
2213 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2214 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2215 // Note, first register is allocated in the beginning of function already,
2216 // allocate remained amount of registers we need.
2217 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2218 State->AllocateReg(GPRArgRegs);
2219 // A byval parameter that is split between registers and memory needs its
2220 // size truncated here.
2221 // In the case where the entire structure fits in registers, we set the
2222 // size in memory to zero.
2223 Size = std::max<int>(Size - Excess, 0);
2226 /// MatchingStackOffset - Return true if the given stack call argument is
2227 /// already available in the same position (relatively) of the caller's
2228 /// incoming argument stack.
2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2231 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2232 const TargetInstrInfo *TII) {
2233 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2234 int FI = std::numeric_limits<int>::max();
2235 if (Arg.getOpcode() == ISD::CopyFromReg) {
2236 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2237 if (!TargetRegisterInfo::isVirtualRegister(VR))
2239 MachineInstr *Def = MRI->getVRegDef(VR);
2242 if (!Flags.isByVal()) {
2243 if (!TII->isLoadFromStackSlot(*Def, FI))
2248 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2249 if (Flags.isByVal())
2250 // ByVal argument is passed in as a pointer but it's now being
2251 // dereferenced. e.g.
2252 // define @foo(%struct.X* %A) {
2253 // tail call @bar(%struct.X* byval %A)
2256 SDValue Ptr = Ld->getBasePtr();
2257 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2260 FI = FINode->getIndex();
2264 assert(FI != std::numeric_limits<int>::max());
2265 if (!MFI.isFixedObjectIndex(FI))
2267 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2270 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2271 /// for tail call optimization. Targets which want to do tail call
2272 /// optimization should implement this function.
2274 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2275 CallingConv::ID CalleeCC,
2277 bool isCalleeStructRet,
2278 bool isCallerStructRet,
2279 const SmallVectorImpl<ISD::OutputArg> &Outs,
2280 const SmallVectorImpl<SDValue> &OutVals,
2281 const SmallVectorImpl<ISD::InputArg> &Ins,
2282 SelectionDAG& DAG) const {
2283 MachineFunction &MF = DAG.getMachineFunction();
2284 const Function *CallerF = MF.getFunction();
2285 CallingConv::ID CallerCC = CallerF->getCallingConv();
2287 assert(Subtarget->supportsTailCall());
2289 // Look for obvious safe cases to perform tail call optimization that do not
2290 // require ABI changes. This is what gcc calls sibcall.
2292 // Exception-handling functions need a special set of instructions to indicate
2293 // a return to the hardware. Tail-calling another function would probably
2295 if (CallerF->hasFnAttribute("interrupt"))
2298 // Also avoid sibcall optimization if either caller or callee uses struct
2299 // return semantics.
2300 if (isCalleeStructRet || isCallerStructRet)
2303 // Externally-defined functions with weak linkage should not be
2304 // tail-called on ARM when the OS does not support dynamic
2305 // pre-emption of symbols, as the AAELF spec requires normal calls
2306 // to undefined weak functions to be replaced with a NOP or jump to the
2307 // next instruction. The behaviour of branch instructions in this
2308 // situation (as used for tail calls) is implementation-defined, so we
2309 // cannot rely on the linker replacing the tail call with a return.
2310 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2311 const GlobalValue *GV = G->getGlobal();
2312 const Triple &TT = getTargetMachine().getTargetTriple();
2313 if (GV->hasExternalWeakLinkage() &&
2314 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2318 // Check that the call results are passed in the same way.
2319 LLVMContext &C = *DAG.getContext();
2320 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2321 CCAssignFnForReturn(CalleeCC, isVarArg),
2322 CCAssignFnForReturn(CallerCC, isVarArg)))
2324 // The callee has to preserve all registers the caller needs to preserve.
2325 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2326 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2327 if (CalleeCC != CallerCC) {
2328 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2329 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2333 // If Caller's vararg or byval argument has been split between registers and
2334 // stack, do not perform tail call, since part of the argument is in caller's
2336 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2337 if (AFI_Caller->getArgRegsSaveSize())
2340 // If the callee takes no arguments then go on to check the results of the
2342 if (!Outs.empty()) {
2343 // Check if stack adjustment is needed. For now, do not do this if any
2344 // argument is passed on the stack.
2345 SmallVector<CCValAssign, 16> ArgLocs;
2346 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2347 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2348 if (CCInfo.getNextStackOffset()) {
2349 // Check if the arguments are already laid out in the right way as
2350 // the caller's fixed stack objects.
2351 MachineFrameInfo &MFI = MF.getFrameInfo();
2352 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2353 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2354 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2356 ++i, ++realArgIdx) {
2357 CCValAssign &VA = ArgLocs[i];
2358 EVT RegVT = VA.getLocVT();
2359 SDValue Arg = OutVals[realArgIdx];
2360 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2361 if (VA.getLocInfo() == CCValAssign::Indirect)
2363 if (VA.needsCustom()) {
2364 // f64 and vector types are split into multiple registers or
2365 // register/stack-slot combinations. The types will not match
2366 // the registers; give up on memory f64 refs until we figure
2367 // out what to do about this.
2370 if (!ArgLocs[++i].isRegLoc())
2372 if (RegVT == MVT::v2f64) {
2373 if (!ArgLocs[++i].isRegLoc())
2375 if (!ArgLocs[++i].isRegLoc())
2378 } else if (!VA.isRegLoc()) {
2379 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2386 const MachineRegisterInfo &MRI = MF.getRegInfo();
2387 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2395 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2396 MachineFunction &MF, bool isVarArg,
2397 const SmallVectorImpl<ISD::OutputArg> &Outs,
2398 LLVMContext &Context) const {
2399 SmallVector<CCValAssign, 16> RVLocs;
2400 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2401 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2405 const SDLoc &DL, SelectionDAG &DAG) {
2406 const MachineFunction &MF = DAG.getMachineFunction();
2407 const Function *F = MF.getFunction();
2409 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2411 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2412 // version of the "preferred return address". These offsets affect the return
2413 // instruction if this is a return from PL1 without hypervisor extensions.
2414 // IRQ/FIQ: +4 "subs pc, lr, #4"
2415 // SWI: 0 "subs pc, lr, #0"
2416 // ABORT: +4 "subs pc, lr, #4"
2417 // UNDEF: +4/+2 "subs pc, lr, #0"
2418 // UNDEF varies depending on where the exception came from ARM or Thumb
2419 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2422 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2425 else if (IntKind == "SWI" || IntKind == "UNDEF")
2428 report_fatal_error("Unsupported interrupt attribute. If present, value "
2429 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2431 RetOps.insert(RetOps.begin() + 1,
2432 DAG.getConstant(LROffset, DL, MVT::i32, false));
2434 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2440 const SmallVectorImpl<ISD::OutputArg> &Outs,
2441 const SmallVectorImpl<SDValue> &OutVals,
2442 const SDLoc &dl, SelectionDAG &DAG) const {
2444 // CCValAssign - represent the assignment of the return value to a location.
2445 SmallVector<CCValAssign, 16> RVLocs;
2447 // CCState - Info about the registers and stack slots.
2448 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2451 // Analyze outgoing return values.
2452 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2455 SmallVector<SDValue, 4> RetOps;
2456 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2457 bool isLittleEndian = Subtarget->isLittle();
2459 MachineFunction &MF = DAG.getMachineFunction();
2460 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2461 AFI->setReturnRegsCount(RVLocs.size());
2463 // Copy the result values into the output registers.
2464 for (unsigned i = 0, realRVLocIdx = 0;
2466 ++i, ++realRVLocIdx) {
2467 CCValAssign &VA = RVLocs[i];
2468 assert(VA.isRegLoc() && "Can only return in registers!");
2470 SDValue Arg = OutVals[realRVLocIdx];
2472 switch (VA.getLocInfo()) {
2473 default: llvm_unreachable("Unknown loc info!");
2474 case CCValAssign::Full: break;
2475 case CCValAssign::BCvt:
2476 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2480 if (VA.needsCustom()) {
2481 if (VA.getLocVT() == MVT::v2f64) {
2482 // Extract the first half and return it in two registers.
2483 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2484 DAG.getConstant(0, dl, MVT::i32));
2485 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2486 DAG.getVTList(MVT::i32, MVT::i32), Half);
2488 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2489 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2491 Flag = Chain.getValue(1);
2492 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2493 VA = RVLocs[++i]; // skip ahead to next loc
2494 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2497 Flag = Chain.getValue(1);
2498 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2499 VA = RVLocs[++i]; // skip ahead to next loc
2501 // Extract the 2nd half and fall through to handle it as an f64 value.
2502 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2503 DAG.getConstant(1, dl, MVT::i32));
2505 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2507 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2508 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2509 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2510 fmrrd.getValue(isLittleEndian ? 0 : 1),
2512 Flag = Chain.getValue(1);
2513 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2514 VA = RVLocs[++i]; // skip ahead to next loc
2515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516 fmrrd.getValue(isLittleEndian ? 1 : 0),
2519 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2521 // Guarantee that all emitted copies are
2522 // stuck together, avoiding something bad.
2523 Flag = Chain.getValue(1);
2524 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2526 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2527 const MCPhysReg *I =
2528 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2531 if (ARM::GPRRegClass.contains(*I))
2532 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2533 else if (ARM::DPRRegClass.contains(*I))
2534 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2536 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2540 // Update chain and glue.
2543 RetOps.push_back(Flag);
2545 // CPUs which aren't M-class use a special sequence to return from
2546 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2547 // though we use "subs pc, lr, #N").
2549 // M-class CPUs actually use a normal return sequence with a special
2550 // (hardware-provided) value in LR, so the normal code path works.
2551 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2552 !Subtarget->isMClass()) {
2553 if (Subtarget->isThumb1Only())
2554 report_fatal_error("interrupt attribute is not supported in Thumb1");
2555 return LowerInterruptReturn(RetOps, dl, DAG);
2558 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2561 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2562 if (N->getNumValues() != 1)
2564 if (!N->hasNUsesOfValue(1, 0))
2567 SDValue TCChain = Chain;
2568 SDNode *Copy = *N->use_begin();
2569 if (Copy->getOpcode() == ISD::CopyToReg) {
2570 // If the copy has a glue operand, we conservatively assume it isn't safe to
2571 // perform a tail call.
2572 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2574 TCChain = Copy->getOperand(0);
2575 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2576 SDNode *VMov = Copy;
2577 // f64 returned in a pair of GPRs.
2578 SmallPtrSet<SDNode*, 2> Copies;
2579 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2581 if (UI->getOpcode() != ISD::CopyToReg)
2585 if (Copies.size() > 2)
2588 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2590 SDValue UseChain = UI->getOperand(0);
2591 if (Copies.count(UseChain.getNode()))
2595 // We are at the top of this chain.
2596 // If the copy has a glue operand, we conservatively assume it
2597 // isn't safe to perform a tail call.
2598 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2604 } else if (Copy->getOpcode() == ISD::BITCAST) {
2605 // f32 returned in a single GPR.
2606 if (!Copy->hasOneUse())
2608 Copy = *Copy->use_begin();
2609 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2611 // If the copy has a glue operand, we conservatively assume it isn't safe to
2612 // perform a tail call.
2613 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2615 TCChain = Copy->getOperand(0);
2620 bool HasRet = false;
2621 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2623 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2624 UI->getOpcode() != ARMISD::INTRET_FLAG)
2636 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2637 if (!Subtarget->supportsTailCall())
2641 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2642 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2648 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2649 // and pass the lower and high parts through.
2650 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2652 SDValue WriteValue = Op->getOperand(2);
2654 // This function is only supposed to be called for i64 type argument.
2655 assert(WriteValue.getValueType() == MVT::i64
2656 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2658 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2659 DAG.getConstant(0, DL, MVT::i32));
2660 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2661 DAG.getConstant(1, DL, MVT::i32));
2662 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2663 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2666 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2667 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2668 // one of the above mentioned nodes. It has to be wrapped because otherwise
2669 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2670 // be used to form addressing mode. These wrapped nodes will be selected
2672 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2673 EVT PtrVT = Op.getValueType();
2674 // FIXME there is no actual debug info here
2676 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2678 if (CP->isMachineConstantPoolEntry())
2679 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2680 CP->getAlignment());
2682 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2683 CP->getAlignment());
2684 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2687 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2688 return MachineJumpTableInfo::EK_Inline;
2691 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2692 SelectionDAG &DAG) const {
2693 MachineFunction &MF = DAG.getMachineFunction();
2694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2695 unsigned ARMPCLabelIndex = 0;
2697 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2698 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2700 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2701 if (!IsPositionIndependent) {
2702 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2704 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2705 ARMPCLabelIndex = AFI->createPICLabelUId();
2706 ARMConstantPoolValue *CPV =
2707 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2708 ARMCP::CPBlockAddress, PCAdj);
2709 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2711 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2712 SDValue Result = DAG.getLoad(
2713 PtrVT, DL, DAG.getEntryNode(), CPAddr,
2714 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2715 if (!IsPositionIndependent)
2717 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2718 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2721 /// \brief Convert a TLS address reference into the correct sequence of loads
2722 /// and calls to compute the variable's address for Darwin, and return an
2723 /// SDValue containing the final node.
2725 /// Darwin only has one TLS scheme which must be capable of dealing with the
2726 /// fully general situation, in the worst case. This means:
2727 /// + "extern __thread" declaration.
2728 /// + Defined in a possibly unknown dynamic library.
2730 /// The general system is that each __thread variable has a [3 x i32] descriptor
2731 /// which contains information used by the runtime to calculate the address. The
2732 /// only part of this the compiler needs to know about is the first word, which
2733 /// contains a function pointer that must be called with the address of the
2734 /// entire descriptor in "r0".
2736 /// Since this descriptor may be in a different unit, in general access must
2737 /// proceed along the usual ARM rules. A common sequence to produce is:
2739 /// movw rT1, :lower16:_var$non_lazy_ptr
2740 /// movt rT1, :upper16:_var$non_lazy_ptr
2744 /// [...address now in r0...]
2746 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2747 SelectionDAG &DAG) const {
2748 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2751 // First step is to get the address of the actua global symbol. This is where
2752 // the TLS descriptor lives.
2753 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2755 // The first entry in the descriptor is a function pointer that we must call
2756 // to obtain the address of the variable.
2757 SDValue Chain = DAG.getEntryNode();
2758 SDValue FuncTLVGet = DAG.getLoad(
2759 MVT::i32, DL, Chain, DescAddr,
2760 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2761 /* Alignment = */ 4,
2762 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2763 MachineMemOperand::MOInvariant);
2764 Chain = FuncTLVGet.getValue(1);
2766 MachineFunction &F = DAG.getMachineFunction();
2767 MachineFrameInfo &MFI = F.getFrameInfo();
2768 MFI.setAdjustsStack(true);
2770 // TLS calls preserve all registers except those that absolutely must be
2771 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2774 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2775 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2776 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2778 // Finally, we can make the call. This is just a degenerate version of a
2779 // normal AArch64 call node: r0 takes the address of the descriptor, and
2780 // returns the address of the variable in this thread.
2781 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2783 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2784 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2785 DAG.getRegisterMask(Mask), Chain.getValue(1));
2786 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2790 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2791 SelectionDAG &DAG) const {
2792 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2794 SDValue Chain = DAG.getEntryNode();
2795 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2798 // Load the current TEB (thread environment block)
2799 SDValue Ops[] = {Chain,
2800 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2801 DAG.getConstant(15, DL, MVT::i32),
2802 DAG.getConstant(0, DL, MVT::i32),
2803 DAG.getConstant(13, DL, MVT::i32),
2804 DAG.getConstant(0, DL, MVT::i32),
2805 DAG.getConstant(2, DL, MVT::i32)};
2806 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2807 DAG.getVTList(MVT::i32, MVT::Other), Ops);
2809 SDValue TEB = CurrentTEB.getValue(0);
2810 Chain = CurrentTEB.getValue(1);
2812 // Load the ThreadLocalStoragePointer from the TEB
2813 // A pointer to the TLS array is located at offset 0x2c from the TEB.
2815 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2816 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2818 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2819 // offset into the TLSArray.
2821 // Load the TLS index from the C runtime
2823 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2824 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2825 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2827 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2828 DAG.getConstant(2, DL, MVT::i32));
2829 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2830 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2831 MachinePointerInfo());
2833 // Get the offset of the start of the .tls section (section base)
2834 const auto *GA = cast<GlobalAddressSDNode>(Op);
2835 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2836 SDValue Offset = DAG.getLoad(
2837 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2838 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2841 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2846 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2847 SelectionDAG &DAG) const {
2849 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2850 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2851 MachineFunction &MF = DAG.getMachineFunction();
2852 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2853 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2854 ARMConstantPoolValue *CPV =
2855 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2856 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2857 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2858 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2859 Argument = DAG.getLoad(
2860 PtrVT, dl, DAG.getEntryNode(), Argument,
2861 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2862 SDValue Chain = Argument.getValue(1);
2864 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2865 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2867 // call __tls_get_addr.
2870 Entry.Node = Argument;
2871 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2872 Args.push_back(Entry);
2874 // FIXME: is there useful debug info available here?
2875 TargetLowering::CallLoweringInfo CLI(DAG);
2876 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2877 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2878 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2880 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2881 return CallResult.first;
2884 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2885 // "local exec" model.
2887 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2889 TLSModel::Model model) const {
2890 const GlobalValue *GV = GA->getGlobal();
2893 SDValue Chain = DAG.getEntryNode();
2894 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2895 // Get the Thread Pointer
2896 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2898 if (model == TLSModel::InitialExec) {
2899 MachineFunction &MF = DAG.getMachineFunction();
2900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2902 // Initial exec model.
2903 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2904 ARMConstantPoolValue *CPV =
2905 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2906 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2908 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2909 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2910 Offset = DAG.getLoad(
2911 PtrVT, dl, Chain, Offset,
2912 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2913 Chain = Offset.getValue(1);
2915 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2916 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2918 Offset = DAG.getLoad(
2919 PtrVT, dl, Chain, Offset,
2920 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2923 assert(model == TLSModel::LocalExec);
2924 ARMConstantPoolValue *CPV =
2925 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2926 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2927 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2928 Offset = DAG.getLoad(
2929 PtrVT, dl, Chain, Offset,
2930 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2933 // The address of the thread local variable is the add of the thread
2934 // pointer with the offset of the variable.
2935 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2939 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2940 if (Subtarget->isTargetDarwin())
2941 return LowerGlobalTLSAddressDarwin(Op, DAG);
2943 if (Subtarget->isTargetWindows())
2944 return LowerGlobalTLSAddressWindows(Op, DAG);
2946 // TODO: implement the "local dynamic" model
2947 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2948 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2949 if (DAG.getTarget().Options.EmulatedTLS)
2950 return LowerToTLSEmulatedModel(GA, DAG);
2952 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2955 case TLSModel::GeneralDynamic:
2956 case TLSModel::LocalDynamic:
2957 return LowerToTLSGeneralDynamicModel(GA, DAG);
2958 case TLSModel::InitialExec:
2959 case TLSModel::LocalExec:
2960 return LowerToTLSExecModels(GA, DAG, model);
2962 llvm_unreachable("bogus TLS model");
2965 /// Return true if all users of V are within function F, looking through
2967 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2968 SmallVector<const User*,4> Worklist;
2969 for (auto *U : V->users())
2970 Worklist.push_back(U);
2971 while (!Worklist.empty()) {
2972 auto *U = Worklist.pop_back_val();
2973 if (isa<ConstantExpr>(U)) {
2974 for (auto *UU : U->users())
2975 Worklist.push_back(UU);
2979 auto *I = dyn_cast<Instruction>(U);
2980 if (!I || I->getParent()->getParent() != F)
2986 /// Return true if all users of V are within some (any) function, looking through
2987 /// ConstantExprs. In other words, are there any global constant users?
2988 static bool allUsersAreInFunctions(const Value *V) {
2989 SmallVector<const User*,4> Worklist;
2990 for (auto *U : V->users())
2991 Worklist.push_back(U);
2992 while (!Worklist.empty()) {
2993 auto *U = Worklist.pop_back_val();
2994 if (isa<ConstantExpr>(U)) {
2995 for (auto *UU : U->users())
2996 Worklist.push_back(UU);
3000 if (!isa<Instruction>(U))
3006 // Return true if T is an integer, float or an array/vector of either.
3007 static bool isSimpleType(Type *T) {
3008 if (T->isIntegerTy() || T->isFloatingPointTy())
3010 Type *SubT = nullptr;
3012 SubT = T->getArrayElementType();
3013 else if (T->isVectorTy())
3014 SubT = T->getVectorElementType();
3017 return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3020 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3021 EVT PtrVT, const SDLoc &dl) {
3022 // If we're creating a pool entry for a constant global with unnamed address,
3023 // and the global is small enough, we can emit it inline into the constant pool
3024 // to save ourselves an indirection.
3026 // This is a win if the constant is only used in one function (so it doesn't
3027 // need to be duplicated) or duplicating the constant wouldn't increase code
3028 // size (implying the constant is no larger than 4 bytes).
3029 const Function *F = DAG.getMachineFunction().getFunction();
3031 // We rely on this decision to inline being idemopotent and unrelated to the
3032 // use-site. We know that if we inline a variable at one use site, we'll
3033 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3034 // doesn't know about this optimization, so bail out if it's enabled else
3035 // we could decide to inline here (and thus never emit the GV) but require
3036 // the GV from fast-isel generated code.
3037 if (!EnableConstpoolPromotion ||
3038 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3041 auto *GVar = dyn_cast<GlobalVariable>(GV);
3042 if (!GVar || !GVar->hasInitializer() ||
3043 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3044 !GVar->hasLocalLinkage())
3047 // Ensure that we don't try and inline any type that contains pointers. If
3048 // we inline a value that contains relocations, we move the relocations from
3049 // .data to .text which is not ideal.
3050 auto *Init = GVar->getInitializer();
3051 if (!isSimpleType(Init->getType()))
3054 // The constant islands pass can only really deal with alignment requests
3055 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3056 // any type wanting greater alignment requirements than 4 bytes. We also
3057 // can only promote constants that are multiples of 4 bytes in size or
3058 // are paddable to a multiple of 4. Currently we only try and pad constants
3059 // that are strings for simplicity.
3060 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3061 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3062 unsigned Align = GVar->getAlignment();
3063 unsigned RequiredPadding = 4 - (Size % 4);
3064 bool PaddingPossible =
3065 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3066 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3070 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3071 MachineFunction &MF = DAG.getMachineFunction();
3072 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3074 // We can't bloat the constant pool too much, else the ConstantIslands pass
3075 // may fail to converge. If we haven't promoted this global yet (it may have
3076 // multiple uses), and promoting it would increase the constant pool size (Sz
3077 // > 4), ensure we have space to do so up to MaxTotal.
3078 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3079 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3080 ConstpoolPromotionMaxTotal)
3083 // This is only valid if all users are in a single function OR it has users
3084 // in multiple functions but it no larger than a pointer. We also check if
3085 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3087 if (!allUsersAreInFunction(GVar, F) &&
3088 !(Size <= 4 && allUsersAreInFunctions(GVar)))
3091 // We're going to inline this global. Pad it out if needed.
3092 if (RequiredPadding != 4) {
3093 StringRef S = CDAInit->getAsString();
3095 SmallVector<uint8_t,16> V(S.size());
3096 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3097 while (RequiredPadding--)
3099 Init = ConstantDataArray::get(*DAG.getContext(), V);
3102 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3104 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3105 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3106 AFI->markGlobalAsPromotedToConstantPool(GVar);
3107 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3110 ++NumConstpoolPromoted;
3111 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3114 static bool isReadOnly(const GlobalValue *GV) {
3115 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3116 GV = GA->getBaseObject();
3117 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3121 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3122 SelectionDAG &DAG) const {
3123 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3125 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3126 const TargetMachine &TM = getTargetMachine();
3127 bool IsRO = isReadOnly(GV);
3129 // promoteToConstantPool only if not generating XO text section
3130 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3131 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3134 if (isPositionIndependent()) {
3135 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3137 MachineFunction &MF = DAG.getMachineFunction();
3138 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3139 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3140 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3142 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3143 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3144 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3145 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3146 /*AddCurrentAddress=*/UseGOT_PREL);
3147 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3148 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3149 SDValue Result = DAG.getLoad(
3150 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3151 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3152 SDValue Chain = Result.getValue(1);
3153 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3154 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3157 DAG.getLoad(PtrVT, dl, Chain, Result,
3158 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3160 } else if (Subtarget->isROPI() && IsRO) {
3162 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3163 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3165 } else if (Subtarget->isRWPI() && !IsRO) {
3168 if (Subtarget->useMovt(DAG.getMachineFunction())) {
3170 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3171 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3172 } else { // use literal pool for address constant
3173 ARMConstantPoolValue *CPV =
3174 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3175 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3176 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3177 RelAddr = DAG.getLoad(
3178 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3179 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3181 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3182 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3186 // If we have T2 ops, we can materialize the address directly via movt/movw
3187 // pair. This is always cheaper.
3188 if (Subtarget->useMovt(DAG.getMachineFunction())) {
3190 // FIXME: Once remat is capable of dealing with instructions with register
3191 // operands, expand this into two nodes.
3192 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3193 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3195 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3196 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3198 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3199 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3203 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3204 SelectionDAG &DAG) const {
3205 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3206 "ROPI/RWPI not currently supported for Darwin");
3207 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3209 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3211 if (Subtarget->useMovt(DAG.getMachineFunction()))
3214 // FIXME: Once remat is capable of dealing with instructions with register
3215 // operands, expand this into multiple nodes
3217 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3219 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3220 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3222 if (Subtarget->isGVIndirectSymbol(GV))
3223 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3224 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3228 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3229 SelectionDAG &DAG) const {
3230 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3231 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3232 "Windows on ARM expects to use movw/movt");
3233 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3234 "ROPI/RWPI not currently supported for Windows");
3236 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3237 const ARMII::TOF TargetFlags =
3238 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3239 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3245 // FIXME: Once remat is capable of dealing with instructions with register
3246 // operands, expand this into two nodes.
3247 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3248 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3250 if (GV->hasDLLImportStorageClass())
3251 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3252 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3257 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3259 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3260 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3261 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3262 Op.getOperand(1), Val);
3266 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3268 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3269 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3272 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3273 SelectionDAG &DAG) const {
3275 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3280 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3281 const ARMSubtarget *Subtarget) const {
3282 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3285 default: return SDValue(); // Don't custom lower most intrinsics.
3286 case Intrinsic::thread_pointer: {
3287 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3288 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3290 case Intrinsic::eh_sjlj_lsda: {
3291 MachineFunction &MF = DAG.getMachineFunction();
3292 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3293 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3294 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3296 bool IsPositionIndependent = isPositionIndependent();
3297 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3298 ARMConstantPoolValue *CPV =
3299 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3300 ARMCP::CPLSDA, PCAdj);
3301 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3302 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3303 SDValue Result = DAG.getLoad(
3304 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3305 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3307 if (IsPositionIndependent) {
3308 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3309 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3313 case Intrinsic::arm_neon_vmulls:
3314 case Intrinsic::arm_neon_vmullu: {
3315 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3316 ? ARMISD::VMULLs : ARMISD::VMULLu;
3317 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3318 Op.getOperand(1), Op.getOperand(2));
3320 case Intrinsic::arm_neon_vminnm:
3321 case Intrinsic::arm_neon_vmaxnm: {
3322 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3323 ? ISD::FMINNUM : ISD::FMAXNUM;
3324 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3325 Op.getOperand(1), Op.getOperand(2));
3327 case Intrinsic::arm_neon_vminu:
3328 case Intrinsic::arm_neon_vmaxu: {
3329 if (Op.getValueType().isFloatingPoint())
3331 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3332 ? ISD::UMIN : ISD::UMAX;
3333 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3334 Op.getOperand(1), Op.getOperand(2));
3336 case Intrinsic::arm_neon_vmins:
3337 case Intrinsic::arm_neon_vmaxs: {
3338 // v{min,max}s is overloaded between signed integers and floats.
3339 if (!Op.getValueType().isFloatingPoint()) {
3340 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3341 ? ISD::SMIN : ISD::SMAX;
3342 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3343 Op.getOperand(1), Op.getOperand(2));
3345 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3346 ? ISD::FMINNAN : ISD::FMAXNAN;
3347 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3348 Op.getOperand(1), Op.getOperand(2));
3350 case Intrinsic::arm_neon_vtbl1:
3351 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3352 Op.getOperand(1), Op.getOperand(2));
3353 case Intrinsic::arm_neon_vtbl2:
3354 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3355 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3359 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3360 const ARMSubtarget *Subtarget) {
3362 ConstantSDNode *ScopeN = cast<ConstantSDNode>(Op.getOperand(2));
3363 auto Scope = static_cast<SynchronizationScope>(ScopeN->getZExtValue());
3364 if (Scope == SynchronizationScope::SingleThread)
3367 if (!Subtarget->hasDataBarrier()) {
3368 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3369 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3371 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3372 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3373 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3374 DAG.getConstant(0, dl, MVT::i32));
3377 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3378 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3379 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3380 if (Subtarget->isMClass()) {
3381 // Only a full system barrier exists in the M-class architectures.
3382 Domain = ARM_MB::SY;
3383 } else if (Subtarget->preferISHSTBarriers() &&
3384 Ord == AtomicOrdering::Release) {
3385 // Swift happens to implement ISHST barriers in a way that's compatible with
3386 // Release semantics but weaker than ISH so we'd be fools not to use
3387 // it. Beware: other processors probably don't!
3388 Domain = ARM_MB::ISHST;
3391 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3392 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3393 DAG.getConstant(Domain, dl, MVT::i32));
3396 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3397 const ARMSubtarget *Subtarget) {
3398 // ARM pre v5TE and Thumb1 does not have preload instructions.
3399 if (!(Subtarget->isThumb2() ||
3400 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3401 // Just preserve the chain.
3402 return Op.getOperand(0);
3405 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3407 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3408 // ARMv7 with MP extension has PLDW.
3409 return Op.getOperand(0);
3411 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3412 if (Subtarget->isThumb()) {
3414 isRead = ~isRead & 1;
3415 isData = ~isData & 1;
3418 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3419 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3420 DAG.getConstant(isData, dl, MVT::i32));
3423 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3424 MachineFunction &MF = DAG.getMachineFunction();
3425 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3427 // vastart just stores the address of the VarArgsFrameIndex slot into the
3428 // memory location argument.
3430 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3431 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3432 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3433 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3434 MachinePointerInfo(SV));
3437 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3438 CCValAssign &NextVA,
3441 const SDLoc &dl) const {
3442 MachineFunction &MF = DAG.getMachineFunction();
3443 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3445 const TargetRegisterClass *RC;
3446 if (AFI->isThumb1OnlyFunction())
3447 RC = &ARM::tGPRRegClass;
3449 RC = &ARM::GPRRegClass;
3451 // Transform the arguments stored in physical registers into virtual ones.
3452 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3453 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3456 if (NextVA.isMemLoc()) {
3457 MachineFrameInfo &MFI = MF.getFrameInfo();
3458 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3460 // Create load node to retrieve arguments from the stack.
3461 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3462 ArgValue2 = DAG.getLoad(
3463 MVT::i32, dl, Root, FIN,
3464 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3466 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3467 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3469 if (!Subtarget->isLittle())
3470 std::swap (ArgValue, ArgValue2);
3471 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3474 // The remaining GPRs hold either the beginning of variable-argument
3475 // data, or the beginning of an aggregate passed by value (usually
3476 // byval). Either way, we allocate stack slots adjacent to the data
3477 // provided by our caller, and store the unallocated registers there.
3478 // If this is a variadic function, the va_list pointer will begin with
3479 // these values; otherwise, this reassembles a (byval) structure that
3480 // was split between registers and memory.
3481 // Return: The frame index registers were stored into.
3482 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3483 const SDLoc &dl, SDValue &Chain,
3484 const Value *OrigArg,
3485 unsigned InRegsParamRecordIdx,
3486 int ArgOffset, unsigned ArgSize) const {
3487 // Currently, two use-cases possible:
3488 // Case #1. Non-var-args function, and we meet first byval parameter.
3489 // Setup first unallocated register as first byval register;
3490 // eat all remained registers
3491 // (these two actions are performed by HandleByVal method).
3492 // Then, here, we initialize stack frame with
3493 // "store-reg" instructions.
3494 // Case #2. Var-args function, that doesn't contain byval parameters.
3495 // The same: eat all remained unallocated registers,
3496 // initialize stack frame.
3498 MachineFunction &MF = DAG.getMachineFunction();
3499 MachineFrameInfo &MFI = MF.getFrameInfo();
3500 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3501 unsigned RBegin, REnd;
3502 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3503 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3505 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3506 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3511 ArgOffset = -4 * (ARM::R4 - RBegin);
3513 auto PtrVT = getPointerTy(DAG.getDataLayout());
3514 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3515 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3517 SmallVector<SDValue, 4> MemOps;
3518 const TargetRegisterClass *RC =
3519 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3521 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3522 unsigned VReg = MF.addLiveIn(Reg, RC);
3523 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3524 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3525 MachinePointerInfo(OrigArg, 4 * i));
3526 MemOps.push_back(Store);
3527 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3530 if (!MemOps.empty())
3531 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3535 // Setup stack frame, the va_list pointer will start from.
3536 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3537 const SDLoc &dl, SDValue &Chain,
3539 unsigned TotalArgRegsSaveSize,
3540 bool ForceMutable) const {
3541 MachineFunction &MF = DAG.getMachineFunction();
3542 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3544 // Try to store any remaining integer argument regs
3545 // to their spots on the stack so that they may be loaded by dereferencing
3546 // the result of va_next.
3547 // If there is no regs to be stored, just point address after last
3548 // argument passed via stack.
3549 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3550 CCInfo.getInRegsParamsCount(),
3551 CCInfo.getNextStackOffset(), 4);
3552 AFI->setVarArgsFrameIndex(FrameIndex);
3555 SDValue ARMTargetLowering::LowerFormalArguments(
3556 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3557 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3558 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3559 MachineFunction &MF = DAG.getMachineFunction();
3560 MachineFrameInfo &MFI = MF.getFrameInfo();
3562 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3564 // Assign locations to all of the incoming arguments.
3565 SmallVector<CCValAssign, 16> ArgLocs;
3566 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3568 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3570 SmallVector<SDValue, 16> ArgValues;
3572 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3573 unsigned CurArgIdx = 0;
3575 // Initially ArgRegsSaveSize is zero.
3576 // Then we increase this value each time we meet byval parameter.
3577 // We also increase this value in case of varargs function.
3578 AFI->setArgRegsSaveSize(0);
3580 // Calculate the amount of stack space that we need to allocate to store
3581 // byval and variadic arguments that are passed in registers.
3582 // We need to know this before we allocate the first byval or variadic
3583 // argument, as they will be allocated a stack slot below the CFA (Canonical
3584 // Frame Address, the stack pointer at entry to the function).
3585 unsigned ArgRegBegin = ARM::R4;
3586 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3587 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3590 CCValAssign &VA = ArgLocs[i];
3591 unsigned Index = VA.getValNo();
3592 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3593 if (!Flags.isByVal())
3596 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3597 unsigned RBegin, REnd;
3598 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3599 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3601 CCInfo.nextInRegsParam();
3603 CCInfo.rewindByValRegsInfo();
3605 int lastInsIndex = -1;
3606 if (isVarArg && MFI.hasVAStart()) {
3607 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3608 if (RegIdx != array_lengthof(GPRArgRegs))
3609 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3612 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3613 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3614 auto PtrVT = getPointerTy(DAG.getDataLayout());
3616 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3617 CCValAssign &VA = ArgLocs[i];
3618 if (Ins[VA.getValNo()].isOrigArg()) {
3619 std::advance(CurOrigArg,
3620 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3621 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3623 // Arguments stored in registers.
3624 if (VA.isRegLoc()) {
3625 EVT RegVT = VA.getLocVT();
3627 if (VA.needsCustom()) {
3628 // f64 and vector types are split up into multiple registers or
3629 // combinations of registers and stack slots.
3630 if (VA.getLocVT() == MVT::v2f64) {
3631 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3633 VA = ArgLocs[++i]; // skip ahead to next loc
3635 if (VA.isMemLoc()) {
3636 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3637 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3638 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3639 MachinePointerInfo::getFixedStack(
3640 DAG.getMachineFunction(), FI));
3642 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3645 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3646 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3647 ArgValue, ArgValue1,
3648 DAG.getIntPtrConstant(0, dl));
3649 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3650 ArgValue, ArgValue2,
3651 DAG.getIntPtrConstant(1, dl));
3653 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3656 const TargetRegisterClass *RC;
3658 if (RegVT == MVT::f32)
3659 RC = &ARM::SPRRegClass;
3660 else if (RegVT == MVT::f64)
3661 RC = &ARM::DPRRegClass;
3662 else if (RegVT == MVT::v2f64)
3663 RC = &ARM::QPRRegClass;
3664 else if (RegVT == MVT::i32)
3665 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3666 : &ARM::GPRRegClass;
3668 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3670 // Transform the arguments in physical registers into virtual ones.
3671 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3672 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3675 // If this is an 8 or 16-bit value, it is really passed promoted
3676 // to 32 bits. Insert an assert[sz]ext to capture this, then
3677 // truncate to the right size.
3678 switch (VA.getLocInfo()) {
3679 default: llvm_unreachable("Unknown loc info!");
3680 case CCValAssign::Full: break;
3681 case CCValAssign::BCvt:
3682 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3684 case CCValAssign::SExt:
3685 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3686 DAG.getValueType(VA.getValVT()));
3687 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3689 case CCValAssign::ZExt:
3690 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3691 DAG.getValueType(VA.getValVT()));
3692 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3696 InVals.push_back(ArgValue);
3698 } else { // VA.isRegLoc()
3700 assert(VA.isMemLoc());
3701 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3703 int index = VA.getValNo();
3705 // Some Ins[] entries become multiple ArgLoc[] entries.
3706 // Process them only once.
3707 if (index != lastInsIndex)
3709 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3710 // FIXME: For now, all byval parameter objects are marked mutable.
3711 // This can be changed with more analysis.
3712 // In case of tail call optimization mark all arguments mutable.
3713 // Since they could be overwritten by lowering of arguments in case of
3715 if (Flags.isByVal()) {
3716 assert(Ins[index].isOrigArg() &&
3717 "Byval arguments cannot be implicit");
3718 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3720 int FrameIndex = StoreByValRegs(
3721 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3722 VA.getLocMemOffset(), Flags.getByValSize());
3723 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3724 CCInfo.nextInRegsParam();
3726 unsigned FIOffset = VA.getLocMemOffset();
3727 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3730 // Create load nodes to retrieve arguments from the stack.
3731 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3732 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3733 MachinePointerInfo::getFixedStack(
3734 DAG.getMachineFunction(), FI)));
3736 lastInsIndex = index;
3742 if (isVarArg && MFI.hasVAStart())
3743 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3744 CCInfo.getNextStackOffset(),
3745 TotalArgRegsSaveSize);
3747 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3752 /// isFloatingPointZero - Return true if this is +0.0.
3753 static bool isFloatingPointZero(SDValue Op) {
3754 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3755 return CFP->getValueAPF().isPosZero();
3756 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3757 // Maybe this has already been legalized into the constant pool?
3758 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3759 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3760 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3761 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3762 return CFP->getValueAPF().isPosZero();
3764 } else if (Op->getOpcode() == ISD::BITCAST &&
3765 Op->getValueType(0) == MVT::f64) {
3766 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3767 // created by LowerConstantFP().
3768 SDValue BitcastOp = Op->getOperand(0);
3769 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3770 isNullConstant(BitcastOp->getOperand(0)))
3776 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3777 /// the given operands.
3778 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3779 SDValue &ARMcc, SelectionDAG &DAG,
3780 const SDLoc &dl) const {
3781 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3782 unsigned C = RHSC->getZExtValue();
3783 if (!isLegalICmpImmediate(C)) {
3784 // Constant does not fit, try adjusting it by one?
3789 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3790 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3791 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3796 if (C != 0 && isLegalICmpImmediate(C-1)) {
3797 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3798 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3803 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3804 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3805 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3810 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3811 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3812 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3819 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3820 ARMISD::NodeType CompareType;
3823 CompareType = ARMISD::CMP;
3828 CompareType = ARMISD::CMPZ;
3831 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3832 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3835 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3836 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3837 SelectionDAG &DAG, const SDLoc &dl,
3838 bool InvalidOnQNaN) const {
3839 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3841 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3842 if (!isFloatingPointZero(RHS))
3843 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3845 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3846 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3849 /// duplicateCmp - Glue values can have only one use, so this function
3850 /// duplicates a comparison node.
3852 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3853 unsigned Opc = Cmp.getOpcode();
3855 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3856 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3858 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3859 Cmp = Cmp.getOperand(0);
3860 Opc = Cmp.getOpcode();
3861 if (Opc == ARMISD::CMPFP)
3862 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3863 Cmp.getOperand(1), Cmp.getOperand(2));
3865 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3866 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3869 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3872 std::pair<SDValue, SDValue>
3873 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3874 SDValue &ARMcc) const {
3875 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3877 SDValue Value, OverflowCmp;
3878 SDValue LHS = Op.getOperand(0);
3879 SDValue RHS = Op.getOperand(1);
3882 // FIXME: We are currently always generating CMPs because we don't support
3883 // generating CMN through the backend. This is not as good as the natural
3884 // CMP case because it causes a register dependency and cannot be folded
3887 switch (Op.getOpcode()) {
3889 llvm_unreachable("Unknown overflow instruction!");
3891 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3892 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3893 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3896 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3897 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3898 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3901 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3902 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3903 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3906 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3907 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3908 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3912 return std::make_pair(Value, OverflowCmp);
3916 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3917 // Let legalize expand this if it isn't a legal type yet.
3918 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3921 SDValue Value, OverflowCmp;
3923 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3924 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3926 // We use 0 and 1 as false and true values.
3927 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3928 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3929 EVT VT = Op.getValueType();
3931 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3932 ARMcc, CCR, OverflowCmp);
3934 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3935 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3938 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3939 SDValue Cond = Op.getOperand(0);
3940 SDValue SelectTrue = Op.getOperand(1);
3941 SDValue SelectFalse = Op.getOperand(2);
3943 unsigned Opc = Cond.getOpcode();
3945 if (Cond.getResNo() == 1 &&
3946 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3947 Opc == ISD::USUBO)) {
3948 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3951 SDValue Value, OverflowCmp;
3953 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3954 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3955 EVT VT = Op.getValueType();
3957 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3963 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3964 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3966 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3967 const ConstantSDNode *CMOVTrue =
3968 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3969 const ConstantSDNode *CMOVFalse =
3970 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3972 if (CMOVTrue && CMOVFalse) {
3973 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3974 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3978 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3980 False = SelectFalse;
3981 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3986 if (True.getNode() && False.getNode()) {
3987 EVT VT = Op.getValueType();
3988 SDValue ARMcc = Cond.getOperand(2);
3989 SDValue CCR = Cond.getOperand(3);
3990 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3991 assert(True.getValueType() == VT);
3992 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3997 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3998 // undefined bits before doing a full-word comparison with zero.
3999 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4000 DAG.getConstant(1, dl, Cond.getValueType()));
4002 return DAG.getSelectCC(dl, Cond,
4003 DAG.getConstant(0, dl, Cond.getValueType()),
4004 SelectTrue, SelectFalse, ISD::SETNE);
4007 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4008 bool &swpCmpOps, bool &swpVselOps) {
4009 // Start by selecting the GE condition code for opcodes that return true for
4011 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4013 CondCode = ARMCC::GE;
4015 // and GT for opcodes that return false for 'equality'.
4016 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4018 CondCode = ARMCC::GT;
4020 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4021 // to swap the compare operands.
4022 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4026 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4027 // If we have an unordered opcode, we need to swap the operands to the VSEL
4028 // instruction (effectively negating the condition).
4030 // This also has the effect of swapping which one of 'less' or 'greater'
4031 // returns true, so we also swap the compare operands. It also switches
4032 // whether we return true for 'equality', so we compensate by picking the
4033 // opposite condition code to our original choice.
4034 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4035 CC == ISD::SETUGT) {
4036 swpCmpOps = !swpCmpOps;
4037 swpVselOps = !swpVselOps;
4038 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4041 // 'ordered' is 'anything but unordered', so use the VS condition code and
4042 // swap the VSEL operands.
4043 if (CC == ISD::SETO) {
4044 CondCode = ARMCC::VS;
4048 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4049 // code and swap the VSEL operands.
4050 if (CC == ISD::SETUNE) {
4051 CondCode = ARMCC::EQ;
4056 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4057 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4058 SDValue Cmp, SelectionDAG &DAG) const {
4059 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4060 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4061 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4062 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4063 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4065 SDValue TrueLow = TrueVal.getValue(0);
4066 SDValue TrueHigh = TrueVal.getValue(1);
4067 SDValue FalseLow = FalseVal.getValue(0);
4068 SDValue FalseHigh = FalseVal.getValue(1);
4070 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4072 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4073 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4075 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4077 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4082 static bool isGTorGE(ISD::CondCode CC) {
4083 return CC == ISD::SETGT || CC == ISD::SETGE;
4086 static bool isLTorLE(ISD::CondCode CC) {
4087 return CC == ISD::SETLT || CC == ISD::SETLE;
4090 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4091 // All of these conditions (and their <= and >= counterparts) will do:
4096 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4097 const SDValue TrueVal, const SDValue FalseVal,
4098 const ISD::CondCode CC, const SDValue K) {
4099 return (isGTorGE(CC) &&
4100 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4102 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4105 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4106 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4107 const SDValue TrueVal, const SDValue FalseVal,
4108 const ISD::CondCode CC, const SDValue K) {
4109 return (isGTorGE(CC) &&
4110 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4112 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4115 // Check if two chained conditionals could be converted into SSAT.
4117 // SSAT can replace a set of two conditional selectors that bound a number to an
4118 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4120 // x < -k ? -k : (x > k ? k : x)
4121 // x < -k ? -k : (x < k ? x : k)
4122 // x > -k ? (x > k ? k : x) : -k
4123 // x < k ? (x < -k ? -k : x) : k
4126 // It returns true if the conversion can be done, false otherwise.
4127 // Additionally, the variable is returned in parameter V and the constant in K.
4128 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4130 SDValue LHS1 = Op.getOperand(0);
4131 SDValue RHS1 = Op.getOperand(1);
4132 SDValue TrueVal1 = Op.getOperand(2);
4133 SDValue FalseVal1 = Op.getOperand(3);
4134 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4136 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4137 if (Op2.getOpcode() != ISD::SELECT_CC)
4140 SDValue LHS2 = Op2.getOperand(0);
4141 SDValue RHS2 = Op2.getOperand(1);
4142 SDValue TrueVal2 = Op2.getOperand(2);
4143 SDValue FalseVal2 = Op2.getOperand(3);
4144 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4146 // Find out which are the constants and which are the variables
4147 // in each conditional
4148 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4151 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4154 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4155 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4156 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4157 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4159 // We must detect cases where the original operations worked with 16- or
4160 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4161 // must work with sign-extended values but the select operations return
4162 // the original non-extended value.
4163 SDValue V2TmpReg = V2Tmp;
4164 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4165 V2TmpReg = V2Tmp->getOperand(0);
4167 // Check that the registers and the constants have the correct values
4168 // in both conditionals
4169 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4173 // Figure out which conditional is saturating the lower/upper bound.
4174 const SDValue *LowerCheckOp =
4175 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4177 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4180 const SDValue *UpperCheckOp =
4181 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4183 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4187 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4190 // Check that the constant in the lower-bound check is
4191 // the opposite of the constant in the upper-bound check
4192 // in 1's complement.
4193 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4194 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4195 int64_t PosVal = std::max(Val1, Val2);
4197 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4198 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4199 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4202 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4209 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4210 EVT VT = Op.getValueType();
4213 // Try to convert two saturating conditional selects into a single SSAT
4215 uint64_t SatConstant;
4216 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4217 isSaturatingConditional(Op, SatValue, SatConstant))
4218 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4219 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4221 SDValue LHS = Op.getOperand(0);
4222 SDValue RHS = Op.getOperand(1);
4223 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4224 SDValue TrueVal = Op.getOperand(2);
4225 SDValue FalseVal = Op.getOperand(3);
4227 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4228 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4231 // If softenSetCCOperands only returned one value, we should compare it to
4233 if (!RHS.getNode()) {
4234 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4239 if (LHS.getValueType() == MVT::i32) {
4240 // Try to generate VSEL on ARMv8.
4241 // The VSEL instruction can't use all the usual ARM condition
4242 // codes: it only has two bits to select the condition code, so it's
4243 // constrained to use only GE, GT, VS and EQ.
4245 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4246 // swap the operands of the previous compare instruction (effectively
4247 // inverting the compare condition, swapping 'less' and 'greater') and
4248 // sometimes need to swap the operands to the VSEL (which inverts the
4249 // condition in the sense of firing whenever the previous condition didn't)
4250 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4251 TrueVal.getValueType() == MVT::f64)) {
4252 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4253 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4254 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4255 CC = ISD::getSetCCInverse(CC, true);
4256 std::swap(TrueVal, FalseVal);
4261 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4262 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4263 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4266 ARMCC::CondCodes CondCode, CondCode2;
4268 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4270 // Try to generate VMAXNM/VMINNM on ARMv8.
4271 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4272 TrueVal.getValueType() == MVT::f64)) {
4273 bool swpCmpOps = false;
4274 bool swpVselOps = false;
4275 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4277 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4278 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4280 std::swap(LHS, RHS);
4282 std::swap(TrueVal, FalseVal);
4286 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4287 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4289 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4290 if (CondCode2 != ARMCC::AL) {
4291 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4292 // FIXME: Needs another CMP because flag can have but one use.
4293 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4294 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4299 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4300 /// to morph to an integer compare sequence.
4301 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4302 const ARMSubtarget *Subtarget) {
4303 SDNode *N = Op.getNode();
4304 if (!N->hasOneUse())
4305 // Otherwise it requires moving the value from fp to integer registers.
4307 if (!N->getNumValues())
4309 EVT VT = Op.getValueType();
4310 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4311 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4312 // vmrs are very slow, e.g. cortex-a8.
4315 if (isFloatingPointZero(Op)) {
4319 return ISD::isNormalLoad(N);
4322 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4323 if (isFloatingPointZero(Op))
4324 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4326 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4327 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4328 Ld->getPointerInfo(), Ld->getAlignment(),
4329 Ld->getMemOperand()->getFlags());
4331 llvm_unreachable("Unknown VFP cmp argument!");
4334 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4335 SDValue &RetVal1, SDValue &RetVal2) {
4338 if (isFloatingPointZero(Op)) {
4339 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4340 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4344 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4345 SDValue Ptr = Ld->getBasePtr();
4347 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4348 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4350 EVT PtrType = Ptr.getValueType();
4351 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4352 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4353 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4354 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4355 Ld->getPointerInfo().getWithOffset(4), NewAlign,
4356 Ld->getMemOperand()->getFlags());
4360 llvm_unreachable("Unknown VFP cmp argument!");
4363 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4364 /// f32 and even f64 comparisons to integer ones.
4366 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4367 SDValue Chain = Op.getOperand(0);
4368 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4369 SDValue LHS = Op.getOperand(2);
4370 SDValue RHS = Op.getOperand(3);
4371 SDValue Dest = Op.getOperand(4);
4374 bool LHSSeenZero = false;
4375 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4376 bool RHSSeenZero = false;
4377 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4378 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4379 // If unsafe fp math optimization is enabled and there are no other uses of
4380 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4381 // to an integer comparison.
4382 if (CC == ISD::SETOEQ)
4384 else if (CC == ISD::SETUNE)
4387 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4389 if (LHS.getValueType() == MVT::f32) {
4390 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4391 bitcastf32Toi32(LHS, DAG), Mask);
4392 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4393 bitcastf32Toi32(RHS, DAG), Mask);
4394 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4395 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4396 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4397 Chain, Dest, ARMcc, CCR, Cmp);
4402 expandf64Toi32(LHS, DAG, LHS1, LHS2);
4403 expandf64Toi32(RHS, DAG, RHS1, RHS2);
4404 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4405 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4406 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4407 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4408 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4409 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4410 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4416 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4417 SDValue Chain = Op.getOperand(0);
4418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4419 SDValue LHS = Op.getOperand(2);
4420 SDValue RHS = Op.getOperand(3);
4421 SDValue Dest = Op.getOperand(4);
4424 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4425 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4428 // If softenSetCCOperands only returned one value, we should compare it to
4430 if (!RHS.getNode()) {
4431 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4436 if (LHS.getValueType() == MVT::i32) {
4438 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4439 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4440 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4441 Chain, Dest, ARMcc, CCR, Cmp);
4444 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4446 if (getTargetMachine().Options.UnsafeFPMath &&
4447 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4448 CC == ISD::SETNE || CC == ISD::SETUNE)) {
4449 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4453 ARMCC::CondCodes CondCode, CondCode2;
4455 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4457 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4458 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4459 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4460 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4461 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4462 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4463 if (CondCode2 != ARMCC::AL) {
4464 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4465 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4466 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4471 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4472 SDValue Chain = Op.getOperand(0);
4473 SDValue Table = Op.getOperand(1);
4474 SDValue Index = Op.getOperand(2);
4477 EVT PTy = getPointerTy(DAG.getDataLayout());
4478 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4479 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4480 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4481 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4482 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4483 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4484 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4485 // which does another jump to the destination. This also makes it easier
4486 // to translate it to TBB / TBH later (Thumb2 only).
4487 // FIXME: This might not work if the function is extremely large.
4488 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4489 Addr, Op.getOperand(2), JTI);
4491 if (isPositionIndependent() || Subtarget->isROPI()) {
4493 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4494 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4495 Chain = Addr.getValue(1);
4496 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4497 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4500 DAG.getLoad(PTy, dl, Chain, Addr,
4501 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4502 Chain = Addr.getValue(1);
4503 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4507 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4508 EVT VT = Op.getValueType();
4511 if (Op.getValueType().getVectorElementType() == MVT::i32) {
4512 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4514 return DAG.UnrollVectorOp(Op.getNode());
4517 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4518 "Invalid type for custom lowering!");
4519 if (VT != MVT::v4i16)
4520 return DAG.UnrollVectorOp(Op.getNode());
4522 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4523 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4526 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4527 EVT VT = Op.getValueType();
4529 return LowerVectorFP_TO_INT(Op, DAG);
4530 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4532 if (Op.getOpcode() == ISD::FP_TO_SINT)
4533 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4536 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4538 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4539 /*isSigned*/ false, SDLoc(Op)).first;
4545 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4546 EVT VT = Op.getValueType();
4549 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4550 if (VT.getVectorElementType() == MVT::f32)
4552 return DAG.UnrollVectorOp(Op.getNode());
4555 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4556 "Invalid type for custom lowering!");
4557 if (VT != MVT::v4f32)
4558 return DAG.UnrollVectorOp(Op.getNode());
4562 switch (Op.getOpcode()) {
4563 default: llvm_unreachable("Invalid opcode!");
4564 case ISD::SINT_TO_FP:
4565 CastOpc = ISD::SIGN_EXTEND;
4566 Opc = ISD::SINT_TO_FP;
4568 case ISD::UINT_TO_FP:
4569 CastOpc = ISD::ZERO_EXTEND;
4570 Opc = ISD::UINT_TO_FP;
4574 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4575 return DAG.getNode(Opc, dl, VT, Op);
4578 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4579 EVT VT = Op.getValueType();
4581 return LowerVectorINT_TO_FP(Op, DAG);
4582 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4584 if (Op.getOpcode() == ISD::SINT_TO_FP)
4585 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4588 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4590 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4591 /*isSigned*/ false, SDLoc(Op)).first;
4597 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4598 // Implement fcopysign with a fabs and a conditional fneg.
4599 SDValue Tmp0 = Op.getOperand(0);
4600 SDValue Tmp1 = Op.getOperand(1);
4602 EVT VT = Op.getValueType();
4603 EVT SrcVT = Tmp1.getValueType();
4604 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4605 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4606 bool UseNEON = !InGPR && Subtarget->hasNEON();
4609 // Use VBSL to copy the sign bit.
4610 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4611 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4612 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4613 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4615 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4616 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4617 DAG.getConstant(32, dl, MVT::i32));
4618 else /*if (VT == MVT::f32)*/
4619 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4620 if (SrcVT == MVT::f32) {
4621 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4623 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4624 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4625 DAG.getConstant(32, dl, MVT::i32));
4626 } else if (VT == MVT::f32)
4627 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4628 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4629 DAG.getConstant(32, dl, MVT::i32));
4630 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4631 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4633 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4635 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4636 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4637 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4639 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4640 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4641 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4642 if (VT == MVT::f32) {
4643 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4644 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4645 DAG.getConstant(0, dl, MVT::i32));
4647 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4653 // Bitcast operand 1 to i32.
4654 if (SrcVT == MVT::f64)
4655 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4657 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4659 // Or in the signbit with integer operations.
4660 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4661 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4662 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4663 if (VT == MVT::f32) {
4664 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4665 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4666 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4667 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4670 // f64: Or the high part with signbit and then combine two parts.
4671 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4673 SDValue Lo = Tmp0.getValue(0);
4674 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4675 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4676 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4679 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4680 MachineFunction &MF = DAG.getMachineFunction();
4681 MachineFrameInfo &MFI = MF.getFrameInfo();
4682 MFI.setReturnAddressIsTaken(true);
4684 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4687 EVT VT = Op.getValueType();
4689 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4691 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4692 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4693 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4694 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4695 MachinePointerInfo());
4698 // Return LR, which contains the return address. Mark it an implicit live-in.
4699 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4700 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4703 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4704 const ARMBaseRegisterInfo &ARI =
4705 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4706 MachineFunction &MF = DAG.getMachineFunction();
4707 MachineFrameInfo &MFI = MF.getFrameInfo();
4708 MFI.setFrameAddressIsTaken(true);
4710 EVT VT = Op.getValueType();
4711 SDLoc dl(Op); // FIXME probably not meaningful
4712 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4713 unsigned FrameReg = ARI.getFrameRegister(MF);
4714 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4716 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4717 MachinePointerInfo());
4721 // FIXME? Maybe this could be a TableGen attribute on some registers and
4722 // this table could be generated automatically from RegInfo.
4723 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4724 SelectionDAG &DAG) const {
4725 unsigned Reg = StringSwitch<unsigned>(RegName)
4726 .Case("sp", ARM::SP)
4730 report_fatal_error(Twine("Invalid register name \""
4731 + StringRef(RegName) + "\"."));
4734 // Result is 64 bit value so split into two 32 bit values and return as a
4736 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4737 SelectionDAG &DAG) {
4740 // This function is only supposed to be called for i64 type destination.
4741 assert(N->getValueType(0) == MVT::i64
4742 && "ExpandREAD_REGISTER called for non-i64 type result.");
4744 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4745 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4749 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4751 Results.push_back(Read.getOperand(0));
4754 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4755 /// When \p DstVT, the destination type of \p BC, is on the vector
4756 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4757 /// it might be possible to combine them, such that everything stays on the
4758 /// vector register bank.
4759 /// \p return The node that would replace \p BT, if the combine
4761 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4762 SelectionDAG &DAG) {
4763 SDValue Op = BC->getOperand(0);
4764 EVT DstVT = BC->getValueType(0);
4766 // The only vector instruction that can produce a scalar (remember,
4767 // since the bitcast was about to be turned into VMOVDRR, the source
4768 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4769 // Moreover, we can do this combine only if there is one use.
4770 // Finally, if the destination type is not a vector, there is not
4771 // much point on forcing everything on the vector bank.
4772 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4776 // If the index is not constant, we will introduce an additional
4777 // multiply that will stick.
4778 // Give up in that case.
4779 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4782 unsigned DstNumElt = DstVT.getVectorNumElements();
4784 // Compute the new index.
4785 const APInt &APIntIndex = Index->getAPIntValue();
4786 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4787 NewIndex *= APIntIndex;
4788 // Check if the new constant index fits into i32.
4789 if (NewIndex.getBitWidth() > 32)
4792 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4793 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4795 SDValue ExtractSrc = Op.getOperand(0);
4796 EVT VecVT = EVT::getVectorVT(
4797 *DAG.getContext(), DstVT.getScalarType(),
4798 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4799 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4800 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4801 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4804 /// ExpandBITCAST - If the target supports VFP, this function is called to
4805 /// expand a bit convert where either the source or destination type is i64 to
4806 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4807 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4808 /// vectors), since the legalizer won't know what to do with that.
4809 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4810 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4812 SDValue Op = N->getOperand(0);
4814 // This function is only supposed to be called for i64 types, either as the
4815 // source or destination of the bit convert.
4816 EVT SrcVT = Op.getValueType();
4817 EVT DstVT = N->getValueType(0);
4818 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4819 "ExpandBITCAST called for non-i64 type");
4821 // Turn i64->f64 into VMOVDRR.
4822 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4823 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4824 // if we can combine the bitcast with its source.
4825 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4828 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4829 DAG.getConstant(0, dl, MVT::i32));
4830 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4831 DAG.getConstant(1, dl, MVT::i32));
4832 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4833 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4836 // Turn f64->i64 into VMOVRRD.
4837 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4839 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4840 SrcVT.getVectorNumElements() > 1)
4841 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4842 DAG.getVTList(MVT::i32, MVT::i32),
4843 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4845 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4846 DAG.getVTList(MVT::i32, MVT::i32), Op);
4847 // Merge the pieces into a single i64 value.
4848 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4854 /// getZeroVector - Returns a vector of specified type with all zero elements.
4855 /// Zero vectors are used to represent vector negation and in those cases
4856 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4857 /// not support i64 elements, so sometimes the zero vectors will need to be
4858 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4860 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4861 assert(VT.isVector() && "Expected a vector type");
4862 // The canonical modified immediate encoding of a zero vector is....0!
4863 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4864 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4865 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4866 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4869 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4870 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4871 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4872 SelectionDAG &DAG) const {
4873 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4874 EVT VT = Op.getValueType();
4875 unsigned VTBits = VT.getSizeInBits();
4877 SDValue ShOpLo = Op.getOperand(0);
4878 SDValue ShOpHi = Op.getOperand(1);
4879 SDValue ShAmt = Op.getOperand(2);
4881 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4882 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4884 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4886 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4887 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4888 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4889 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4890 DAG.getConstant(VTBits, dl, MVT::i32));
4891 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4892 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4893 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4894 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4895 ISD::SETGE, ARMcc, DAG, dl);
4896 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4900 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4901 SDValue HiBigShift = Opc == ISD::SRA
4902 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4903 DAG.getConstant(VTBits - 1, dl, VT))
4904 : DAG.getConstant(0, dl, VT);
4905 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4906 ISD::SETGE, ARMcc, DAG, dl);
4907 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4910 SDValue Ops[2] = { Lo, Hi };
4911 return DAG.getMergeValues(Ops, dl);
4914 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4915 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4916 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4917 SelectionDAG &DAG) const {
4918 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4919 EVT VT = Op.getValueType();
4920 unsigned VTBits = VT.getSizeInBits();
4922 SDValue ShOpLo = Op.getOperand(0);
4923 SDValue ShOpHi = Op.getOperand(1);
4924 SDValue ShAmt = Op.getOperand(2);
4926 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4928 assert(Op.getOpcode() == ISD::SHL_PARTS);
4929 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4930 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4931 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4932 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4933 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4935 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4936 DAG.getConstant(VTBits, dl, MVT::i32));
4937 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4938 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4939 ISD::SETGE, ARMcc, DAG, dl);
4940 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4943 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4944 ISD::SETGE, ARMcc, DAG, dl);
4945 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4946 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
4947 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
4949 SDValue Ops[2] = { Lo, Hi };
4950 return DAG.getMergeValues(Ops, dl);
4953 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4954 SelectionDAG &DAG) const {
4955 // The rounding mode is in bits 23:22 of the FPSCR.
4956 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4957 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4958 // so that the shift + and get folded into a bitfield extract.
4960 SDValue Ops[] = { DAG.getEntryNode(),
4961 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
4963 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
4964 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4965 DAG.getConstant(1U << 22, dl, MVT::i32));
4966 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4967 DAG.getConstant(22, dl, MVT::i32));
4968 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4969 DAG.getConstant(3, dl, MVT::i32));
4972 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4973 const ARMSubtarget *ST) {
4975 EVT VT = N->getValueType(0);
4976 if (VT.isVector()) {
4977 assert(ST->hasNEON());
4979 // Compute the least significant set bit: LSB = X & -X
4980 SDValue X = N->getOperand(0);
4981 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4982 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4984 EVT ElemTy = VT.getVectorElementType();
4986 if (ElemTy == MVT::i8) {
4987 // Compute with: cttz(x) = ctpop(lsb - 1)
4988 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4989 DAG.getTargetConstant(1, dl, ElemTy));
4990 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4991 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4994 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4995 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4996 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4997 unsigned NumBits = ElemTy.getSizeInBits();
4998 SDValue WidthMinus1 =
4999 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5000 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5001 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5002 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5005 // Compute with: cttz(x) = ctpop(lsb - 1)
5007 // Since we can only compute the number of bits in a byte with vcnt.8, we
5008 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5013 if (ElemTy == MVT::i64) {
5014 // Load constant 0xffff'ffff'ffff'ffff to register.
5015 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5016 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5017 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5019 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5020 DAG.getTargetConstant(1, dl, ElemTy));
5021 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5024 // Count #bits with vcnt.8.
5025 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5026 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5027 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5029 // Gather the #bits with vpaddl (pairwise add.)
5030 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5031 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5032 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5034 if (ElemTy == MVT::i16)
5037 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5038 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5039 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5041 if (ElemTy == MVT::i32)
5044 assert(ElemTy == MVT::i64);
5045 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5046 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5051 if (!ST->hasV6T2Ops())
5054 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5055 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5058 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5059 /// for each 16-bit element from operand, repeated. The basic idea is to
5060 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5062 /// Trace for v4i16:
5063 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
5064 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5065 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5066 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5067 /// [b0 b1 b2 b3 b4 b5 b6 b7]
5068 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
5069 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5070 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
5071 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5072 EVT VT = N->getValueType(0);
5075 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5076 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5077 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5078 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5079 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5080 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5083 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5084 /// bit-count for each 16-bit element from the operand. We need slightly
5085 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5086 /// 64/128-bit registers.
5088 /// Trace for v4i16:
5089 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
5090 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5091 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
5092 /// v4i16:Extracted = [k0 k1 k2 k3 ]
5093 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5094 EVT VT = N->getValueType(0);
5097 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5098 if (VT.is64BitVector()) {
5099 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5100 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5101 DAG.getIntPtrConstant(0, DL));
5103 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5104 BitCounts, DAG.getIntPtrConstant(0, DL));
5105 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5109 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5110 /// bit-count for each 32-bit element from the operand. The idea here is
5111 /// to split the vector into 16-bit elements, leverage the 16-bit count
5112 /// routine, and then combine the results.
5114 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5115 /// input = [v0 v1 ] (vi: 32-bit elements)
5116 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5117 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5118 /// vrev: N0 = [k1 k0 k3 k2 ]
5120 /// N1 =+[k1 k0 k3 k2 ]
5122 /// N2 =+[k1 k3 k0 k2 ]
5124 /// Extended =+[k1 k3 k0 k2 ]
5126 /// Extracted=+[k1 k3 ]
5128 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5129 EVT VT = N->getValueType(0);
5132 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5134 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5135 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5136 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5137 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5138 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5140 if (VT.is64BitVector()) {
5141 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5142 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5143 DAG.getIntPtrConstant(0, DL));
5145 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5146 DAG.getIntPtrConstant(0, DL));
5147 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5151 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5152 const ARMSubtarget *ST) {
5153 EVT VT = N->getValueType(0);
5155 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5156 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5157 VT == MVT::v4i16 || VT == MVT::v8i16) &&
5158 "Unexpected type for custom ctpop lowering");
5160 if (VT.getVectorElementType() == MVT::i32)
5161 return lowerCTPOP32BitElements(N, DAG);
5163 return lowerCTPOP16BitElements(N, DAG);
5166 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5167 const ARMSubtarget *ST) {
5168 EVT VT = N->getValueType(0);
5174 // Lower vector shifts on NEON to use VSHL.
5175 assert(ST->hasNEON() && "unexpected vector shift");
5177 // Left shifts translate directly to the vshiftu intrinsic.
5178 if (N->getOpcode() == ISD::SHL)
5179 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5180 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5182 N->getOperand(0), N->getOperand(1));
5184 assert((N->getOpcode() == ISD::SRA ||
5185 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5187 // NEON uses the same intrinsics for both left and right shifts. For
5188 // right shifts, the shift amounts are negative, so negate the vector of
5190 EVT ShiftVT = N->getOperand(1).getValueType();
5191 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5192 getZeroVector(ShiftVT, DAG, dl),
5194 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5195 Intrinsic::arm_neon_vshifts :
5196 Intrinsic::arm_neon_vshiftu);
5197 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5198 DAG.getConstant(vshiftInt, dl, MVT::i32),
5199 N->getOperand(0), NegatedCount);
5202 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5203 const ARMSubtarget *ST) {
5204 EVT VT = N->getValueType(0);
5207 // We can get here for a node like i32 = ISD::SHL i32, i64
5211 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5212 "Unknown shift to lower!");
5214 // We only lower SRA, SRL of 1 here, all others use generic lowering.
5215 if (!isOneConstant(N->getOperand(1)))
5218 // If we are in thumb mode, we don't have RRX.
5219 if (ST->isThumb1Only()) return SDValue();
5221 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
5222 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5223 DAG.getConstant(0, dl, MVT::i32));
5224 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5225 DAG.getConstant(1, dl, MVT::i32));
5227 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5228 // captures the result into a carry flag.
5229 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5230 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5232 // The low part is an ARMISD::RRX operand, which shifts the carry in.
5233 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5235 // Merge the pieces into a single i64 value.
5236 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5239 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5240 SDValue TmpOp0, TmpOp1;
5241 bool Invert = false;
5245 SDValue Op0 = Op.getOperand(0);
5246 SDValue Op1 = Op.getOperand(1);
5247 SDValue CC = Op.getOperand(2);
5248 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5249 EVT VT = Op.getValueType();
5250 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5253 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5254 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5255 // Special-case integer 64-bit equality comparisons. They aren't legal,
5256 // but they can be lowered with a few vector instructions.
5257 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5258 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5259 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5260 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5261 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5262 DAG.getCondCode(ISD::SETEQ));
5263 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5264 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5265 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5266 if (SetCCOpcode == ISD::SETNE)
5267 Merged = DAG.getNOT(dl, Merged, CmpVT);
5268 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5272 if (CmpVT.getVectorElementType() == MVT::i64)
5273 // 64-bit comparisons are not legal in general.
5276 if (Op1.getValueType().isFloatingPoint()) {
5277 switch (SetCCOpcode) {
5278 default: llvm_unreachable("Illegal FP comparison");
5280 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH;
5282 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5284 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5286 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5288 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5290 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5291 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5292 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5293 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5294 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5295 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5297 // Expand this to (OLT | OGT).
5301 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5302 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5308 // Expand this to (OLT | OGE).
5312 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5313 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5317 // Integer comparisons.
5318 switch (SetCCOpcode) {
5319 default: llvm_unreachable("Illegal integer comparison");
5320 case ISD::SETNE: Invert = true;
5321 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5322 case ISD::SETLT: Swap = true;
5323 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5324 case ISD::SETLE: Swap = true;
5325 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5326 case ISD::SETULT: Swap = true;
5327 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5328 case ISD::SETULE: Swap = true;
5329 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5332 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5333 if (Opc == ARMISD::VCEQ) {
5336 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5338 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5341 // Ignore bitconvert.
5342 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5343 AndOp = AndOp.getOperand(0);
5345 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5347 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5348 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5355 std::swap(Op0, Op1);
5357 // If one of the operands is a constant vector zero, attempt to fold the
5358 // comparison to a specialized compare-against-zero form.
5360 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5362 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5363 if (Opc == ARMISD::VCGE)
5364 Opc = ARMISD::VCLEZ;
5365 else if (Opc == ARMISD::VCGT)
5366 Opc = ARMISD::VCLTZ;
5371 if (SingleOp.getNode()) {
5374 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5376 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5378 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5380 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5382 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5384 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5387 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5390 Result = DAG.getSExtOrTrunc(Result, dl, VT);
5393 Result = DAG.getNOT(dl, Result, VT);
5398 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5399 SDValue LHS = Op.getOperand(0);
5400 SDValue RHS = Op.getOperand(1);
5401 SDValue Carry = Op.getOperand(2);
5402 SDValue Cond = Op.getOperand(3);
5405 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5407 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5408 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5409 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5411 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5412 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5413 SDValue ARMcc = DAG.getConstant(
5414 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5415 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5416 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5417 Cmp.getValue(1), SDValue());
5418 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5419 CCR, Chain.getValue(1));
5422 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5423 /// valid vector constant for a NEON instruction with a "modified immediate"
5424 /// operand (e.g., VMOV). If so, return the encoded value.
5425 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5426 unsigned SplatBitSize, SelectionDAG &DAG,
5427 const SDLoc &dl, EVT &VT, bool is128Bits,
5428 NEONModImmType type) {
5429 unsigned OpCmode, Imm;
5431 // SplatBitSize is set to the smallest size that splats the vector, so a
5432 // zero vector will always have SplatBitSize == 8. However, NEON modified
5433 // immediate instructions others than VMOV do not support the 8-bit encoding
5434 // of a zero vector, and the default encoding of zero is supposed to be the
5439 switch (SplatBitSize) {
5441 if (type != VMOVModImm)
5443 // Any 1-byte value is OK. Op=0, Cmode=1110.
5444 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5447 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5451 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5452 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5453 if ((SplatBits & ~0xff) == 0) {
5454 // Value = 0x00nn: Op=x, Cmode=100x.
5459 if ((SplatBits & ~0xff00) == 0) {
5460 // Value = 0xnn00: Op=x, Cmode=101x.
5462 Imm = SplatBits >> 8;
5468 // NEON's 32-bit VMOV supports splat values where:
5469 // * only one byte is nonzero, or
5470 // * the least significant byte is 0xff and the second byte is nonzero, or
5471 // * the least significant 2 bytes are 0xff and the third is nonzero.
5472 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5473 if ((SplatBits & ~0xff) == 0) {
5474 // Value = 0x000000nn: Op=x, Cmode=000x.
5479 if ((SplatBits & ~0xff00) == 0) {
5480 // Value = 0x0000nn00: Op=x, Cmode=001x.
5482 Imm = SplatBits >> 8;
5485 if ((SplatBits & ~0xff0000) == 0) {
5486 // Value = 0x00nn0000: Op=x, Cmode=010x.
5488 Imm = SplatBits >> 16;
5491 if ((SplatBits & ~0xff000000) == 0) {
5492 // Value = 0xnn000000: Op=x, Cmode=011x.
5494 Imm = SplatBits >> 24;
5498 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5499 if (type == OtherModImm) return SDValue();
5501 if ((SplatBits & ~0xffff) == 0 &&
5502 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5503 // Value = 0x0000nnff: Op=x, Cmode=1100.
5505 Imm = SplatBits >> 8;
5509 if ((SplatBits & ~0xffffff) == 0 &&
5510 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5511 // Value = 0x00nnffff: Op=x, Cmode=1101.
5513 Imm = SplatBits >> 16;
5517 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5518 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5519 // VMOV.I32. A (very) minor optimization would be to replicate the value
5520 // and fall through here to test for a valid 64-bit splat. But, then the
5521 // caller would also need to check and handle the change in size.
5525 if (type != VMOVModImm)
5527 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5528 uint64_t BitMask = 0xff;
5530 unsigned ImmMask = 1;
5532 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5533 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5536 } else if ((SplatBits & BitMask) != 0) {
5543 if (DAG.getDataLayout().isBigEndian())
5544 // swap higher and lower 32 bit word
5545 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5547 // Op=1, Cmode=1110.
5549 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5554 llvm_unreachable("unexpected size for isNEONModifiedImm");
5557 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5558 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5561 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5562 const ARMSubtarget *ST) const {
5563 bool IsDouble = Op.getValueType() == MVT::f64;
5564 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5565 const APFloat &FPVal = CFP->getValueAPF();
5567 // Prevent floating-point constants from using literal loads
5568 // when execute-only is enabled.
5569 if (ST->genExecuteOnly()) {
5570 APInt INTVal = FPVal.bitcastToAPInt();
5573 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5574 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5575 if (!ST->isLittle())
5577 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5579 return DAG.getConstant(INTVal, DL, MVT::i32);
5586 // Use the default (constant pool) lowering for double constants when we have
5588 if (IsDouble && Subtarget->isFPOnlySP())
5591 // Try splatting with a VMOV.f32...
5592 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5595 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5596 // We have code in place to select a valid ConstantFP already, no need to
5601 // It's a float and we are trying to use NEON operations where
5602 // possible. Lower it to a splat followed by an extract.
5604 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5605 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5607 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5608 DAG.getConstant(0, DL, MVT::i32));
5611 // The rest of our options are NEON only, make sure that's allowed before
5613 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5617 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5619 // It wouldn't really be worth bothering for doubles except for one very
5620 // important value, which does happen to match: 0.0. So make sure we don't do
5622 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5625 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5626 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5627 VMovVT, false, VMOVModImm);
5628 if (NewVal != SDValue()) {
5630 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5633 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5635 // It's a float: cast and extract a vector element.
5636 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5639 DAG.getConstant(0, DL, MVT::i32));
5642 // Finally, try a VMVN.i32
5643 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5645 if (NewVal != SDValue()) {
5647 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5650 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5652 // It's a float: cast and extract a vector element.
5653 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5655 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5656 DAG.getConstant(0, DL, MVT::i32));
5662 // check if an VEXT instruction can handle the shuffle mask when the
5663 // vector sources of the shuffle are the same.
5664 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5665 unsigned NumElts = VT.getVectorNumElements();
5667 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5673 // If this is a VEXT shuffle, the immediate value is the index of the first
5674 // element. The other shuffle indices must be the successive elements after
5676 unsigned ExpectedElt = Imm;
5677 for (unsigned i = 1; i < NumElts; ++i) {
5678 // Increment the expected index. If it wraps around, just follow it
5679 // back to index zero and keep going.
5681 if (ExpectedElt == NumElts)
5684 if (M[i] < 0) continue; // ignore UNDEF indices
5685 if (ExpectedElt != static_cast<unsigned>(M[i]))
5692 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5693 bool &ReverseVEXT, unsigned &Imm) {
5694 unsigned NumElts = VT.getVectorNumElements();
5695 ReverseVEXT = false;
5697 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5703 // If this is a VEXT shuffle, the immediate value is the index of the first
5704 // element. The other shuffle indices must be the successive elements after
5706 unsigned ExpectedElt = Imm;
5707 for (unsigned i = 1; i < NumElts; ++i) {
5708 // Increment the expected index. If it wraps around, it may still be
5709 // a VEXT but the source vectors must be swapped.
5711 if (ExpectedElt == NumElts * 2) {
5716 if (M[i] < 0) continue; // ignore UNDEF indices
5717 if (ExpectedElt != static_cast<unsigned>(M[i]))
5721 // Adjust the index value if the source operands will be swapped.
5728 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5729 /// instruction with the specified blocksize. (The order of the elements
5730 /// within each block of the vector is reversed.)
5731 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5732 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5733 "Only possible block sizes for VREV are: 16, 32, 64");
5735 unsigned EltSz = VT.getScalarSizeInBits();
5739 unsigned NumElts = VT.getVectorNumElements();
5740 unsigned BlockElts = M[0] + 1;
5741 // If the first shuffle index is UNDEF, be optimistic.
5743 BlockElts = BlockSize / EltSz;
5745 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5748 for (unsigned i = 0; i < NumElts; ++i) {
5749 if (M[i] < 0) continue; // ignore UNDEF indices
5750 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5757 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5758 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5759 // range, then 0 is placed into the resulting vector. So pretty much any mask
5760 // of 8 elements can work here.
5761 return VT == MVT::v8i8 && M.size() == 8;
5764 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5765 // checking that pairs of elements in the shuffle mask represent the same index
5766 // in each vector, incrementing the expected index by 2 at each step.
5767 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5768 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5770 // WhichResult gives the offset for each element in the mask based on which
5771 // of the two results it belongs to.
5773 // The transpose can be represented either as:
5774 // result1 = shufflevector v1, v2, result1_shuffle_mask
5775 // result2 = shufflevector v1, v2, result2_shuffle_mask
5776 // where v1/v2 and the shuffle masks have the same number of elements
5777 // (here WhichResult (see below) indicates which result is being checked)
5780 // results = shufflevector v1, v2, shuffle_mask
5781 // where both results are returned in one vector and the shuffle mask has twice
5782 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5783 // want to check the low half and high half of the shuffle mask as if it were
5785 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5786 unsigned EltSz = VT.getScalarSizeInBits();
5790 unsigned NumElts = VT.getVectorNumElements();
5791 if (M.size() != NumElts && M.size() != NumElts*2)
5794 // If the mask is twice as long as the input vector then we need to check the
5795 // upper and lower parts of the mask with a matching value for WhichResult
5796 // FIXME: A mask with only even values will be rejected in case the first
5797 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5798 // M[0] is used to determine WhichResult
5799 for (unsigned i = 0; i < M.size(); i += NumElts) {
5800 if (M.size() == NumElts * 2)
5801 WhichResult = i / NumElts;
5803 WhichResult = M[i] == 0 ? 0 : 1;
5804 for (unsigned j = 0; j < NumElts; j += 2) {
5805 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5806 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5811 if (M.size() == NumElts*2)
5817 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5818 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5819 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5820 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5821 unsigned EltSz = VT.getScalarSizeInBits();
5825 unsigned NumElts = VT.getVectorNumElements();
5826 if (M.size() != NumElts && M.size() != NumElts*2)
5829 for (unsigned i = 0; i < M.size(); i += NumElts) {
5830 if (M.size() == NumElts * 2)
5831 WhichResult = i / NumElts;
5833 WhichResult = M[i] == 0 ? 0 : 1;
5834 for (unsigned j = 0; j < NumElts; j += 2) {
5835 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5836 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5841 if (M.size() == NumElts*2)
5847 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5848 // that the mask elements are either all even and in steps of size 2 or all odd
5849 // and in steps of size 2.
5850 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5851 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5853 // Requires similar checks to that of isVTRNMask with
5854 // respect the how results are returned.
5855 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5856 unsigned EltSz = VT.getScalarSizeInBits();
5860 unsigned NumElts = VT.getVectorNumElements();
5861 if (M.size() != NumElts && M.size() != NumElts*2)
5864 for (unsigned i = 0; i < M.size(); i += NumElts) {
5865 WhichResult = M[i] == 0 ? 0 : 1;
5866 for (unsigned j = 0; j < NumElts; ++j) {
5867 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5872 if (M.size() == NumElts*2)
5875 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5876 if (VT.is64BitVector() && EltSz == 32)
5882 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5883 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5884 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5885 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5886 unsigned EltSz = VT.getScalarSizeInBits();
5890 unsigned NumElts = VT.getVectorNumElements();
5891 if (M.size() != NumElts && M.size() != NumElts*2)
5894 unsigned Half = NumElts / 2;
5895 for (unsigned i = 0; i < M.size(); i += NumElts) {
5896 WhichResult = M[i] == 0 ? 0 : 1;
5897 for (unsigned j = 0; j < NumElts; j += Half) {
5898 unsigned Idx = WhichResult;
5899 for (unsigned k = 0; k < Half; ++k) {
5900 int MIdx = M[i + j + k];
5901 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5908 if (M.size() == NumElts*2)
5911 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5912 if (VT.is64BitVector() && EltSz == 32)
5918 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5919 // that pairs of elements of the shufflemask represent the same index in each
5920 // vector incrementing sequentially through the vectors.
5921 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5922 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5924 // Requires similar checks to that of isVTRNMask with respect the how results
5926 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5927 unsigned EltSz = VT.getScalarSizeInBits();
5931 unsigned NumElts = VT.getVectorNumElements();
5932 if (M.size() != NumElts && M.size() != NumElts*2)
5935 for (unsigned i = 0; i < M.size(); i += NumElts) {
5936 WhichResult = M[i] == 0 ? 0 : 1;
5937 unsigned Idx = WhichResult * NumElts / 2;
5938 for (unsigned j = 0; j < NumElts; j += 2) {
5939 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5940 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5946 if (M.size() == NumElts*2)
5949 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5950 if (VT.is64BitVector() && EltSz == 32)
5956 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5957 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5958 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5959 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5960 unsigned EltSz = VT.getScalarSizeInBits();
5964 unsigned NumElts = VT.getVectorNumElements();
5965 if (M.size() != NumElts && M.size() != NumElts*2)
5968 for (unsigned i = 0; i < M.size(); i += NumElts) {
5969 WhichResult = M[i] == 0 ? 0 : 1;
5970 unsigned Idx = WhichResult * NumElts / 2;
5971 for (unsigned j = 0; j < NumElts; j += 2) {
5972 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5973 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5979 if (M.size() == NumElts*2)
5982 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5983 if (VT.is64BitVector() && EltSz == 32)
5989 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5990 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5991 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5992 unsigned &WhichResult,
5995 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5996 return ARMISD::VTRN;
5997 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5998 return ARMISD::VUZP;
5999 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6000 return ARMISD::VZIP;
6003 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6004 return ARMISD::VTRN;
6005 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6006 return ARMISD::VUZP;
6007 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6008 return ARMISD::VZIP;
6013 /// \return true if this is a reverse operation on an vector.
6014 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6015 unsigned NumElts = VT.getVectorNumElements();
6016 // Make sure the mask has the right size.
6017 if (NumElts != M.size())
6020 // Look for <15, ..., 3, -1, 1, 0>.
6021 for (unsigned i = 0; i != NumElts; ++i)
6022 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6028 // If N is an integer constant that can be moved into a register in one
6029 // instruction, return an SDValue of such a constant (will become a MOV
6030 // instruction). Otherwise return null.
6031 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6032 const ARMSubtarget *ST, const SDLoc &dl) {
6034 if (!isa<ConstantSDNode>(N))
6036 Val = cast<ConstantSDNode>(N)->getZExtValue();
6038 if (ST->isThumb1Only()) {
6039 if (Val <= 255 || ~Val <= 255)
6040 return DAG.getConstant(Val, dl, MVT::i32);
6042 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6043 return DAG.getConstant(Val, dl, MVT::i32);
6048 // If this is a case we can't handle, return null and let the default
6049 // expansion code take care of it.
6050 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6051 const ARMSubtarget *ST) const {
6052 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6054 EVT VT = Op.getValueType();
6056 APInt SplatBits, SplatUndef;
6057 unsigned SplatBitSize;
6059 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6060 if (SplatUndef.isAllOnesValue())
6061 return DAG.getUNDEF(VT);
6063 if (SplatBitSize <= 64) {
6064 // Check if an immediate VMOV works.
6066 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6067 SplatUndef.getZExtValue(), SplatBitSize,
6068 DAG, dl, VmovVT, VT.is128BitVector(),
6070 if (Val.getNode()) {
6071 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6072 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6075 // Try an immediate VMVN.
6076 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6077 Val = isNEONModifiedImm(NegatedImm,
6078 SplatUndef.getZExtValue(), SplatBitSize,
6079 DAG, dl, VmovVT, VT.is128BitVector(),
6081 if (Val.getNode()) {
6082 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6083 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6086 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6087 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6088 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6090 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6091 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6097 // Scan through the operands to see if only one value is used.
6099 // As an optimisation, even if more than one value is used it may be more
6100 // profitable to splat with one value then change some lanes.
6102 // Heuristically we decide to do this if the vector has a "dominant" value,
6103 // defined as splatted to more than half of the lanes.
6104 unsigned NumElts = VT.getVectorNumElements();
6105 bool isOnlyLowElement = true;
6106 bool usesOnlyOneValue = true;
6107 bool hasDominantValue = false;
6108 bool isConstant = true;
6110 // Map of the number of times a particular SDValue appears in the
6112 DenseMap<SDValue, unsigned> ValueCounts;
6114 for (unsigned i = 0; i < NumElts; ++i) {
6115 SDValue V = Op.getOperand(i);
6119 isOnlyLowElement = false;
6120 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6123 ValueCounts.insert(std::make_pair(V, 0));
6124 unsigned &Count = ValueCounts[V];
6126 // Is this value dominant? (takes up more than half of the lanes)
6127 if (++Count > (NumElts / 2)) {
6128 hasDominantValue = true;
6132 if (ValueCounts.size() != 1)
6133 usesOnlyOneValue = false;
6134 if (!Value.getNode() && !ValueCounts.empty())
6135 Value = ValueCounts.begin()->first;
6137 if (ValueCounts.empty())
6138 return DAG.getUNDEF(VT);
6140 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6141 // Keep going if we are hitting this case.
6142 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6143 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6145 unsigned EltSize = VT.getScalarSizeInBits();
6147 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
6148 // i32 and try again.
6149 if (hasDominantValue && EltSize <= 32) {
6153 // If we are VDUPing a value that comes directly from a vector, that will
6154 // cause an unnecessary move to and from a GPR, where instead we could
6155 // just use VDUPLANE. We can only do this if the lane being extracted
6156 // is at a constant index, as the VDUP from lane instructions only have
6157 // constant-index forms.
6158 ConstantSDNode *constIndex;
6159 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6160 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6161 // We need to create a new undef vector to use for the VDUPLANE if the
6162 // size of the vector from which we get the value is different than the
6163 // size of the vector that we need to create. We will insert the element
6164 // such that the register coalescer will remove unnecessary copies.
6165 if (VT != Value->getOperand(0).getValueType()) {
6166 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6167 VT.getVectorNumElements();
6168 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6169 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6170 Value, DAG.getConstant(index, dl, MVT::i32)),
6171 DAG.getConstant(index, dl, MVT::i32));
6173 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6174 Value->getOperand(0), Value->getOperand(1));
6176 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6178 if (!usesOnlyOneValue) {
6179 // The dominant value was splatted as 'N', but we now have to insert
6180 // all differing elements.
6181 for (unsigned I = 0; I < NumElts; ++I) {
6182 if (Op.getOperand(I) == Value)
6184 SmallVector<SDValue, 3> Ops;
6186 Ops.push_back(Op.getOperand(I));
6187 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6188 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6193 if (VT.getVectorElementType().isFloatingPoint()) {
6194 SmallVector<SDValue, 8> Ops;
6195 for (unsigned i = 0; i < NumElts; ++i)
6196 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6198 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6199 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6200 Val = LowerBUILD_VECTOR(Val, DAG, ST);
6202 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6204 if (usesOnlyOneValue) {
6205 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6206 if (isConstant && Val.getNode())
6207 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6211 // If all elements are constants and the case above didn't get hit, fall back
6212 // to the default expansion, which will generate a load from the constant
6217 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6219 SDValue shuffle = ReconstructShuffle(Op, DAG);
6220 if (shuffle != SDValue())
6224 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6225 // If we haven't found an efficient lowering, try splitting a 128-bit vector
6226 // into two 64-bit vectors; we might discover a better way to lower it.
6227 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6228 EVT ExtVT = VT.getVectorElementType();
6229 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6231 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6232 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6233 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6234 SDValue Upper = DAG.getBuildVector(
6235 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6236 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6237 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6239 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6242 // Vectors with 32- or 64-bit elements can be built by directly assigning
6243 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
6244 // will be legalized.
6245 if (EltSize >= 32) {
6246 // Do the expansion with floating-point types, since that is what the VFP
6247 // registers are defined to use, and since i64 is not legal.
6248 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6249 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6250 SmallVector<SDValue, 8> Ops;
6251 for (unsigned i = 0; i < NumElts; ++i)
6252 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6253 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6254 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6257 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6258 // know the default expansion would otherwise fall back on something even
6259 // worse. For a vector with one or two non-undef values, that's
6260 // scalar_to_vector for the elements followed by a shuffle (provided the
6261 // shuffle is valid for the target) and materialization element by element
6262 // on the stack followed by a load for everything else.
6263 if (!isConstant && !usesOnlyOneValue) {
6264 SDValue Vec = DAG.getUNDEF(VT);
6265 for (unsigned i = 0 ; i < NumElts; ++i) {
6266 SDValue V = Op.getOperand(i);
6269 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6270 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6278 // Gather data to see if the operation can be modelled as a
6279 // shuffle in combination with VEXTs.
6280 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6281 SelectionDAG &DAG) const {
6282 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6284 EVT VT = Op.getValueType();
6285 unsigned NumElts = VT.getVectorNumElements();
6287 struct ShuffleSourceInfo {
6289 unsigned MinElt = std::numeric_limits<unsigned>::max();
6290 unsigned MaxElt = 0;
6292 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6293 // be compatible with the shuffle we intend to construct. As a result
6294 // ShuffleVec will be some sliding window into the original Vec.
6297 // Code should guarantee that element i in Vec starts at element "WindowBase
6298 // + i * WindowScale in ShuffleVec".
6300 int WindowScale = 1;
6302 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6304 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6307 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6309 SmallVector<ShuffleSourceInfo, 2> Sources;
6310 for (unsigned i = 0; i < NumElts; ++i) {
6311 SDValue V = Op.getOperand(i);
6314 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6315 // A shuffle can only come from building a vector from various
6316 // elements of other vectors.
6318 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6319 // Furthermore, shuffles require a constant mask, whereas extractelts
6320 // accept variable indices.
6324 // Add this element source to the list if it's not already there.
6325 SDValue SourceVec = V.getOperand(0);
6326 auto Source = llvm::find(Sources, SourceVec);
6327 if (Source == Sources.end())
6328 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6330 // Update the minimum and maximum lane number seen.
6331 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6332 Source->MinElt = std::min(Source->MinElt, EltNo);
6333 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6336 // Currently only do something sane when at most two source vectors
6338 if (Sources.size() > 2)
6341 // Find out the smallest element size among result and two sources, and use
6342 // it as element size to build the shuffle_vector.
6343 EVT SmallestEltTy = VT.getVectorElementType();
6344 for (auto &Source : Sources) {
6345 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6346 if (SrcEltTy.bitsLT(SmallestEltTy))
6347 SmallestEltTy = SrcEltTy;
6349 unsigned ResMultiplier =
6350 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6351 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6352 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6354 // If the source vector is too wide or too narrow, we may nevertheless be able
6355 // to construct a compatible shuffle either by concatenating it with UNDEF or
6356 // extracting a suitable range of elements.
6357 for (auto &Src : Sources) {
6358 EVT SrcVT = Src.ShuffleVec.getValueType();
6360 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6363 // This stage of the search produces a source with the same element type as
6364 // the original, but with a total width matching the BUILD_VECTOR output.
6365 EVT EltVT = SrcVT.getVectorElementType();
6366 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6367 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6369 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6370 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6372 // We can pad out the smaller vector for free, so if it's part of a
6375 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6376 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6380 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6383 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6384 // Span too large for a VEXT to cope
6388 if (Src.MinElt >= NumSrcElts) {
6389 // The extraction can just take the second half
6391 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6392 DAG.getConstant(NumSrcElts, dl, MVT::i32));
6393 Src.WindowBase = -NumSrcElts;
6394 } else if (Src.MaxElt < NumSrcElts) {
6395 // The extraction can just take the first half
6397 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6398 DAG.getConstant(0, dl, MVT::i32));
6400 // An actual VEXT is needed
6402 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6403 DAG.getConstant(0, dl, MVT::i32));
6405 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6406 DAG.getConstant(NumSrcElts, dl, MVT::i32));
6408 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6410 DAG.getConstant(Src.MinElt, dl, MVT::i32));
6411 Src.WindowBase = -Src.MinElt;
6415 // Another possible incompatibility occurs from the vector element types. We
6416 // can fix this by bitcasting the source vectors to the same type we intend
6418 for (auto &Src : Sources) {
6419 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6420 if (SrcEltTy == SmallestEltTy)
6422 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6423 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6424 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6425 Src.WindowBase *= Src.WindowScale;
6428 // Final sanity check before we try to actually produce a shuffle.
6430 for (auto Src : Sources)
6431 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6434 // The stars all align, our next step is to produce the mask for the shuffle.
6435 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6436 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6437 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6438 SDValue Entry = Op.getOperand(i);
6439 if (Entry.isUndef())
6442 auto Src = llvm::find(Sources, Entry.getOperand(0));
6443 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6445 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6446 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6448 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6449 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6450 VT.getScalarSizeInBits());
6451 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6453 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6454 // starting at the appropriate offset.
6455 int *LaneMask = &Mask[i * ResMultiplier];
6457 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6458 ExtractBase += NumElts * (Src - Sources.begin());
6459 for (int j = 0; j < LanesDefined; ++j)
6460 LaneMask[j] = ExtractBase + j;
6463 // Final check before we try to produce nonsense...
6464 if (!isShuffleMaskLegal(Mask, ShuffleVT))
6467 // We can't handle more than two sources. This should have already
6468 // been checked before this point.
6469 assert(Sources.size() <= 2 && "Too many sources!");
6471 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6472 for (unsigned i = 0; i < Sources.size(); ++i)
6473 ShuffleOps[i] = Sources[i].ShuffleVec;
6475 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6476 ShuffleOps[1], Mask);
6477 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6480 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6481 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6482 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6483 /// are assumed to be legal.
6485 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6487 if (VT.getVectorNumElements() == 4 &&
6488 (VT.is128BitVector() || VT.is64BitVector())) {
6489 unsigned PFIndexes[4];
6490 for (unsigned i = 0; i != 4; ++i) {
6494 PFIndexes[i] = M[i];
6497 // Compute the index in the perfect shuffle table.
6498 unsigned PFTableIndex =
6499 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6500 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6501 unsigned Cost = (PFEntry >> 30);
6507 bool ReverseVEXT, isV_UNDEF;
6508 unsigned Imm, WhichResult;
6510 unsigned EltSize = VT.getScalarSizeInBits();
6511 return (EltSize >= 32 ||
6512 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6513 isVREVMask(M, VT, 64) ||
6514 isVREVMask(M, VT, 32) ||
6515 isVREVMask(M, VT, 16) ||
6516 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6517 isVTBLMask(M, VT) ||
6518 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6519 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6522 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6523 /// the specified operations to build the shuffle.
6524 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6525 SDValue RHS, SelectionDAG &DAG,
6527 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6528 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6529 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6532 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6541 OP_VUZPL, // VUZP, left result
6542 OP_VUZPR, // VUZP, right result
6543 OP_VZIPL, // VZIP, left result
6544 OP_VZIPR, // VZIP, right result
6545 OP_VTRNL, // VTRN, left result
6546 OP_VTRNR // VTRN, right result
6549 if (OpNum == OP_COPY) {
6550 if (LHSID == (1*9+2)*9+3) return LHS;
6551 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6555 SDValue OpLHS, OpRHS;
6556 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6557 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6558 EVT VT = OpLHS.getValueType();
6561 default: llvm_unreachable("Unknown shuffle opcode!");
6563 // VREV divides the vector in half and swaps within the half.
6564 if (VT.getVectorElementType() == MVT::i32 ||
6565 VT.getVectorElementType() == MVT::f32)
6566 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6567 // vrev <4 x i16> -> VREV32
6568 if (VT.getVectorElementType() == MVT::i16)
6569 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6570 // vrev <4 x i8> -> VREV16
6571 assert(VT.getVectorElementType() == MVT::i8);
6572 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6577 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6578 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6582 return DAG.getNode(ARMISD::VEXT, dl, VT,
6584 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6587 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6588 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6591 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6592 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6595 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6596 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6600 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6601 ArrayRef<int> ShuffleMask,
6602 SelectionDAG &DAG) {
6603 // Check to see if we can use the VTBL instruction.
6604 SDValue V1 = Op.getOperand(0);
6605 SDValue V2 = Op.getOperand(1);
6608 SmallVector<SDValue, 8> VTBLMask;
6609 for (ArrayRef<int>::iterator
6610 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6611 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6613 if (V2.getNode()->isUndef())
6614 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6615 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6617 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6618 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6621 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6622 SelectionDAG &DAG) {
6624 SDValue OpLHS = Op.getOperand(0);
6625 EVT VT = OpLHS.getValueType();
6627 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6628 "Expect an v8i16/v16i8 type");
6629 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6630 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6631 // extract the first 8 bytes into the top double word and the last 8 bytes
6632 // into the bottom double word. The v8i16 case is similar.
6633 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6634 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6635 DAG.getConstant(ExtractNum, DL, MVT::i32));
6638 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6639 SDValue V1 = Op.getOperand(0);
6640 SDValue V2 = Op.getOperand(1);
6642 EVT VT = Op.getValueType();
6643 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6645 // Convert shuffles that are directly supported on NEON to target-specific
6646 // DAG nodes, instead of keeping them as shuffles and matching them again
6647 // during code selection. This is more efficient and avoids the possibility
6648 // of inconsistencies between legalization and selection.
6649 // FIXME: floating-point vectors should be canonicalized to integer vectors
6650 // of the same time so that they get CSEd properly.
6651 ArrayRef<int> ShuffleMask = SVN->getMask();
6653 unsigned EltSize = VT.getScalarSizeInBits();
6654 if (EltSize <= 32) {
6655 if (SVN->isSplat()) {
6656 int Lane = SVN->getSplatIndex();
6657 // If this is undef splat, generate it via "just" vdup, if possible.
6658 if (Lane == -1) Lane = 0;
6660 // Test if V1 is a SCALAR_TO_VECTOR.
6661 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6662 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6664 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6665 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6667 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6668 !isa<ConstantSDNode>(V1.getOperand(0))) {
6669 bool IsScalarToVector = true;
6670 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6671 if (!V1.getOperand(i).isUndef()) {
6672 IsScalarToVector = false;
6675 if (IsScalarToVector)
6676 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6678 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6679 DAG.getConstant(Lane, dl, MVT::i32));
6684 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6687 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6688 DAG.getConstant(Imm, dl, MVT::i32));
6691 if (isVREVMask(ShuffleMask, VT, 64))
6692 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6693 if (isVREVMask(ShuffleMask, VT, 32))
6694 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6695 if (isVREVMask(ShuffleMask, VT, 16))
6696 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6698 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6699 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6700 DAG.getConstant(Imm, dl, MVT::i32));
6703 // Check for Neon shuffles that modify both input vectors in place.
6704 // If both results are used, i.e., if there are two shuffles with the same
6705 // source operands and with masks corresponding to both results of one of
6706 // these operations, DAG memoization will ensure that a single node is
6707 // used for both shuffles.
6708 unsigned WhichResult;
6710 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6711 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6714 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6715 .getValue(WhichResult);
6718 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6719 // shuffles that produce a result larger than their operands with:
6720 // shuffle(concat(v1, undef), concat(v2, undef))
6722 // shuffle(concat(v1, v2), undef)
6723 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6725 // This is useful in the general case, but there are special cases where
6726 // native shuffles produce larger results: the two-result ops.
6728 // Look through the concat when lowering them:
6729 // shuffle(concat(v1, v2), undef)
6731 // concat(VZIP(v1, v2):0, :1)
6733 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6734 SDValue SubV1 = V1->getOperand(0);
6735 SDValue SubV2 = V1->getOperand(1);
6736 EVT SubVT = SubV1.getValueType();
6738 // We expect these to have been canonicalized to -1.
6739 assert(llvm::all_of(ShuffleMask, [&](int i) {
6740 return i < (int)VT.getVectorNumElements();
6741 }) && "Unexpected shuffle index into UNDEF operand!");
6743 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6744 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6747 assert((WhichResult == 0) &&
6748 "In-place shuffle of concat can only have one result!");
6749 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6751 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6757 // If the shuffle is not directly supported and it has 4 elements, use
6758 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6759 unsigned NumElts = VT.getVectorNumElements();
6761 unsigned PFIndexes[4];
6762 for (unsigned i = 0; i != 4; ++i) {
6763 if (ShuffleMask[i] < 0)
6766 PFIndexes[i] = ShuffleMask[i];
6769 // Compute the index in the perfect shuffle table.
6770 unsigned PFTableIndex =
6771 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6772 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6773 unsigned Cost = (PFEntry >> 30);
6776 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6779 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6780 if (EltSize >= 32) {
6781 // Do the expansion with floating-point types, since that is what the VFP
6782 // registers are defined to use, and since i64 is not legal.
6783 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6784 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6785 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6786 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6787 SmallVector<SDValue, 8> Ops;
6788 for (unsigned i = 0; i < NumElts; ++i) {
6789 if (ShuffleMask[i] < 0)
6790 Ops.push_back(DAG.getUNDEF(EltVT));
6792 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6793 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6794 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6797 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6798 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6801 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6802 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6804 if (VT == MVT::v8i8)
6805 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6811 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6812 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6813 SDValue Lane = Op.getOperand(2);
6814 if (!isa<ConstantSDNode>(Lane))
6820 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6821 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6822 SDValue Lane = Op.getOperand(1);
6823 if (!isa<ConstantSDNode>(Lane))
6826 SDValue Vec = Op.getOperand(0);
6827 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6829 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6835 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6836 // The only time a CONCAT_VECTORS operation can have legal types is when
6837 // two 64-bit vectors are concatenated to a 128-bit vector.
6838 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6839 "unexpected CONCAT_VECTORS");
6841 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6842 SDValue Op0 = Op.getOperand(0);
6843 SDValue Op1 = Op.getOperand(1);
6845 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6846 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6847 DAG.getIntPtrConstant(0, dl));
6849 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6850 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6851 DAG.getIntPtrConstant(1, dl));
6852 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6855 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6856 /// element has been zero/sign-extended, depending on the isSigned parameter,
6857 /// from an integer type half its size.
6858 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6860 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6861 EVT VT = N->getValueType(0);
6862 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6863 SDNode *BVN = N->getOperand(0).getNode();
6864 if (BVN->getValueType(0) != MVT::v4i32 ||
6865 BVN->getOpcode() != ISD::BUILD_VECTOR)
6867 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6868 unsigned HiElt = 1 - LoElt;
6869 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6870 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6871 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6872 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6873 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6876 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6877 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6880 if (Hi0->isNullValue() && Hi1->isNullValue())
6886 if (N->getOpcode() != ISD::BUILD_VECTOR)
6889 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6890 SDNode *Elt = N->getOperand(i).getNode();
6891 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6892 unsigned EltSize = VT.getScalarSizeInBits();
6893 unsigned HalfSize = EltSize / 2;
6895 if (!isIntN(HalfSize, C->getSExtValue()))
6898 if (!isUIntN(HalfSize, C->getZExtValue()))
6909 /// isSignExtended - Check if a node is a vector value that is sign-extended
6910 /// or a constant BUILD_VECTOR with sign-extended elements.
6911 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6912 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6914 if (isExtendedBUILD_VECTOR(N, DAG, true))
6919 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6920 /// or a constant BUILD_VECTOR with zero-extended elements.
6921 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6922 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6924 if (isExtendedBUILD_VECTOR(N, DAG, false))
6929 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6930 if (OrigVT.getSizeInBits() >= 64)
6933 assert(OrigVT.isSimple() && "Expecting a simple value type");
6935 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6936 switch (OrigSimpleTy) {
6937 default: llvm_unreachable("Unexpected Vector Type");
6946 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6947 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6948 /// We insert the required extension here to get the vector to fill a D register.
6949 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6952 unsigned ExtOpcode) {
6953 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6954 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6955 // 64-bits we need to insert a new extension so that it will be 64-bits.
6956 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6957 if (OrigTy.getSizeInBits() >= 64)
6960 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6961 EVT NewVT = getExtensionTo64Bits(OrigTy);
6963 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6966 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6967 /// does not do any sign/zero extension. If the original vector is less
6968 /// than 64 bits, an appropriate extension will be added after the load to
6969 /// reach a total size of 64 bits. We have to add the extension separately
6970 /// because ARM does not have a sign/zero extending load for vectors.
6971 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6972 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6974 // The load already has the right type.
6975 if (ExtendedTy == LD->getMemoryVT())
6976 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6977 LD->getBasePtr(), LD->getPointerInfo(),
6978 LD->getAlignment(), LD->getMemOperand()->getFlags());
6980 // We need to create a zextload/sextload. We cannot just create a load
6981 // followed by a zext/zext node because LowerMUL is also run during normal
6982 // operation legalization where we can't create illegal types.
6983 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6984 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6985 LD->getMemoryVT(), LD->getAlignment(),
6986 LD->getMemOperand()->getFlags());
6989 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6990 /// extending load, or BUILD_VECTOR with extended elements, return the
6991 /// unextended value. The unextended vector should be 64 bits so that it can
6992 /// be used as an operand to a VMULL instruction. If the original vector size
6993 /// before extension is less than 64 bits we add a an extension to resize
6994 /// the vector to 64 bits.
6995 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6996 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6997 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6998 N->getOperand(0)->getValueType(0),
7002 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7003 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7004 "Expected extending load");
7006 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7007 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7008 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7010 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7011 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7016 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
7017 // have been legalized as a BITCAST from v4i32.
7018 if (N->getOpcode() == ISD::BITCAST) {
7019 SDNode *BVN = N->getOperand(0).getNode();
7020 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7021 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7022 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7023 return DAG.getBuildVector(
7024 MVT::v2i32, SDLoc(N),
7025 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7027 // Construct a new BUILD_VECTOR with elements truncated to half the size.
7028 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7029 EVT VT = N->getValueType(0);
7030 unsigned EltSize = VT.getScalarSizeInBits() / 2;
7031 unsigned NumElts = VT.getVectorNumElements();
7032 MVT TruncVT = MVT::getIntegerVT(EltSize);
7033 SmallVector<SDValue, 8> Ops;
7035 for (unsigned i = 0; i != NumElts; ++i) {
7036 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7037 const APInt &CInt = C->getAPIntValue();
7038 // Element types smaller than 32 bits are not legal, so use i32 elements.
7039 // The values are implicitly truncated so sext vs. zext doesn't matter.
7040 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7042 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7045 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7046 unsigned Opcode = N->getOpcode();
7047 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7048 SDNode *N0 = N->getOperand(0).getNode();
7049 SDNode *N1 = N->getOperand(1).getNode();
7050 return N0->hasOneUse() && N1->hasOneUse() &&
7051 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7056 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7057 unsigned Opcode = N->getOpcode();
7058 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7059 SDNode *N0 = N->getOperand(0).getNode();
7060 SDNode *N1 = N->getOperand(1).getNode();
7061 return N0->hasOneUse() && N1->hasOneUse() &&
7062 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7067 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7068 // Multiplications are only custom-lowered for 128-bit vectors so that
7069 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
7070 EVT VT = Op.getValueType();
7071 assert(VT.is128BitVector() && VT.isInteger() &&
7072 "unexpected type for custom-lowering ISD::MUL");
7073 SDNode *N0 = Op.getOperand(0).getNode();
7074 SDNode *N1 = Op.getOperand(1).getNode();
7075 unsigned NewOpc = 0;
7077 bool isN0SExt = isSignExtended(N0, DAG);
7078 bool isN1SExt = isSignExtended(N1, DAG);
7079 if (isN0SExt && isN1SExt)
7080 NewOpc = ARMISD::VMULLs;
7082 bool isN0ZExt = isZeroExtended(N0, DAG);
7083 bool isN1ZExt = isZeroExtended(N1, DAG);
7084 if (isN0ZExt && isN1ZExt)
7085 NewOpc = ARMISD::VMULLu;
7086 else if (isN1SExt || isN1ZExt) {
7087 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7088 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7089 if (isN1SExt && isAddSubSExt(N0, DAG)) {
7090 NewOpc = ARMISD::VMULLs;
7092 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7093 NewOpc = ARMISD::VMULLu;
7095 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7097 NewOpc = ARMISD::VMULLu;
7103 if (VT == MVT::v2i64)
7104 // Fall through to expand this. It is not legal.
7107 // Other vector multiplications are legal.
7112 // Legalize to a VMULL instruction.
7115 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7117 Op0 = SkipExtensionForVMULL(N0, DAG);
7118 assert(Op0.getValueType().is64BitVector() &&
7119 Op1.getValueType().is64BitVector() &&
7120 "unexpected types for extended operands to VMULL");
7121 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7124 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7125 // isel lowering to take advantage of no-stall back to back vmul + vmla.
7132 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7133 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7134 EVT Op1VT = Op1.getValueType();
7135 return DAG.getNode(N0->getOpcode(), DL, VT,
7136 DAG.getNode(NewOpc, DL, VT,
7137 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7138 DAG.getNode(NewOpc, DL, VT,
7139 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7142 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7143 SelectionDAG &DAG) {
7144 // TODO: Should this propagate fast-math-flags?
7147 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7148 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7149 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7150 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7151 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7152 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7153 // Get reciprocal estimate.
7154 // float4 recip = vrecpeq_f32(yf);
7155 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7156 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7158 // Because char has a smaller range than uchar, we can actually get away
7159 // without any newton steps. This requires that we use a weird bias
7160 // of 0xb000, however (again, this has been exhaustively tested).
7161 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7162 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7163 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7164 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7165 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7166 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7167 // Convert back to short.
7168 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7169 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7173 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7174 SelectionDAG &DAG) {
7175 // TODO: Should this propagate fast-math-flags?
7178 // Convert to float.
7179 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7180 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7181 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7182 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7183 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7184 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7186 // Use reciprocal estimate and one refinement step.
7187 // float4 recip = vrecpeq_f32(yf);
7188 // recip *= vrecpsq_f32(yf, recip);
7189 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7190 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7192 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7193 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7195 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7196 // Because short has a smaller range than ushort, we can actually get away
7197 // with only a single newton step. This requires that we use a weird bias
7198 // of 89, however (again, this has been exhaustively tested).
7199 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7200 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7201 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7202 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7203 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7204 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7205 // Convert back to integer and return.
7206 // return vmovn_s32(vcvt_s32_f32(result));
7207 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7208 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7212 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7213 EVT VT = Op.getValueType();
7214 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7215 "unexpected type for custom-lowering ISD::SDIV");
7218 SDValue N0 = Op.getOperand(0);
7219 SDValue N1 = Op.getOperand(1);
7222 if (VT == MVT::v8i8) {
7223 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7224 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7226 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7227 DAG.getIntPtrConstant(4, dl));
7228 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7229 DAG.getIntPtrConstant(4, dl));
7230 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7231 DAG.getIntPtrConstant(0, dl));
7232 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7233 DAG.getIntPtrConstant(0, dl));
7235 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7236 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7238 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7239 N0 = LowerCONCAT_VECTORS(N0, DAG);
7241 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7244 return LowerSDIV_v4i16(N0, N1, dl, DAG);
7247 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7248 // TODO: Should this propagate fast-math-flags?
7249 EVT VT = Op.getValueType();
7250 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7251 "unexpected type for custom-lowering ISD::UDIV");
7254 SDValue N0 = Op.getOperand(0);
7255 SDValue N1 = Op.getOperand(1);
7258 if (VT == MVT::v8i8) {
7259 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7260 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7262 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7263 DAG.getIntPtrConstant(4, dl));
7264 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7265 DAG.getIntPtrConstant(4, dl));
7266 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7267 DAG.getIntPtrConstant(0, dl));
7268 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7269 DAG.getIntPtrConstant(0, dl));
7271 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7272 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7274 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7275 N0 = LowerCONCAT_VECTORS(N0, DAG);
7277 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7278 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7284 // v4i16 sdiv ... Convert to float.
7285 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7286 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7287 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7288 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7289 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7290 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7292 // Use reciprocal estimate and two refinement steps.
7293 // float4 recip = vrecpeq_f32(yf);
7294 // recip *= vrecpsq_f32(yf, recip);
7295 // recip *= vrecpsq_f32(yf, recip);
7296 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7297 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7299 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7300 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7302 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7303 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7304 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7306 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7307 // Simply multiplying by the reciprocal estimate can leave us a few ulps
7308 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7309 // and that it will never cause us to return an answer too large).
7310 // float4 result = as_float4(as_int4(xf*recip) + 2);
7311 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7312 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7313 N1 = DAG.getConstant(2, dl, MVT::v4i32);
7314 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7315 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7316 // Convert back to integer and return.
7317 // return vmovn_u32(vcvt_s32_f32(result));
7318 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7319 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7323 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7324 EVT VT = Op.getNode()->getValueType(0);
7325 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7328 bool ExtraOp = false;
7329 switch (Op.getOpcode()) {
7330 default: llvm_unreachable("Invalid code");
7331 case ISD::ADDC: Opc = ARMISD::ADDC; break;
7332 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7333 case ISD::SUBC: Opc = ARMISD::SUBC; break;
7334 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7338 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7340 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7341 Op.getOperand(1), Op.getOperand(2));
7344 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7345 assert(Subtarget->isTargetDarwin());
7347 // For iOS, we want to call an alternative entry point: __sincos_stret,
7348 // return values are passed via sret.
7350 SDValue Arg = Op.getOperand(0);
7351 EVT ArgVT = Arg.getValueType();
7352 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7353 auto PtrVT = getPointerTy(DAG.getDataLayout());
7355 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7358 // Pair of floats / doubles used to pass the result.
7359 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7360 auto &DL = DAG.getDataLayout();
7363 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7365 if (ShouldUseSRet) {
7366 // Create stack object for sret.
7367 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7368 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7369 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7370 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7374 Entry.Ty = RetTy->getPointerTo();
7375 Entry.IsSExt = false;
7376 Entry.IsZExt = false;
7377 Entry.IsSRet = true;
7378 Args.push_back(Entry);
7379 RetTy = Type::getVoidTy(*DAG.getContext());
7385 Entry.IsSExt = false;
7386 Entry.IsZExt = false;
7387 Args.push_back(Entry);
7389 const char *LibcallName =
7390 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7392 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7393 CallingConv::ID CC = getLibcallCallingConv(LC);
7394 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7396 TargetLowering::CallLoweringInfo CLI(DAG);
7398 .setChain(DAG.getEntryNode())
7399 .setCallee(CC, RetTy, Callee, std::move(Args))
7400 .setDiscardResult(ShouldUseSRet);
7401 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7404 return CallResult.first;
7407 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7409 // Address of cos field.
7410 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7411 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7413 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7415 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7416 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7417 LoadSin.getValue(0), LoadCos.getValue(0));
7420 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7422 SDValue &Chain) const {
7423 EVT VT = Op.getValueType();
7424 assert((VT == MVT::i32 || VT == MVT::i64) &&
7425 "unexpected type for custom lowering DIV");
7428 const auto &DL = DAG.getDataLayout();
7429 const auto &TLI = DAG.getTargetLoweringInfo();
7431 const char *Name = nullptr;
7433 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7435 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7437 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7439 ARMTargetLowering::ArgListTy Args;
7441 for (auto AI : {1, 0}) {
7443 Arg.Node = Op.getOperand(AI);
7444 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7445 Args.push_back(Arg);
7448 CallLoweringInfo CLI(DAG);
7451 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7452 ES, std::move(Args));
7454 return LowerCallTo(CLI).first;
7457 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7458 bool Signed) const {
7459 assert(Op.getValueType() == MVT::i32 &&
7460 "unexpected type for custom lowering DIV");
7463 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7464 DAG.getEntryNode(), Op.getOperand(1));
7466 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7469 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7471 SDValue Op = N->getOperand(1);
7472 if (N->getValueType(0) == MVT::i32)
7473 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7474 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7475 DAG.getConstant(0, DL, MVT::i32));
7476 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7477 DAG.getConstant(1, DL, MVT::i32));
7478 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7479 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7482 void ARMTargetLowering::ExpandDIV_Windows(
7483 SDValue Op, SelectionDAG &DAG, bool Signed,
7484 SmallVectorImpl<SDValue> &Results) const {
7485 const auto &DL = DAG.getDataLayout();
7486 const auto &TLI = DAG.getTargetLoweringInfo();
7488 assert(Op.getValueType() == MVT::i64 &&
7489 "unexpected type for custom lowering DIV");
7492 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7494 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7496 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7497 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7498 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7499 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7501 Results.push_back(Lower);
7502 Results.push_back(Upper);
7505 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7506 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7507 // Acquire/Release load/store is not legal for targets without a dmb or
7508 // equivalent available.
7511 // Monotonic load/store is legal for all targets.
7515 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7516 SmallVectorImpl<SDValue> &Results,
7518 const ARMSubtarget *Subtarget) {
7520 // Under Power Management extensions, the cycle-count is:
7521 // mrc p15, #0, <Rt>, c9, c13, #0
7522 SDValue Ops[] = { N->getOperand(0), // Chain
7523 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7524 DAG.getConstant(15, DL, MVT::i32),
7525 DAG.getConstant(0, DL, MVT::i32),
7526 DAG.getConstant(9, DL, MVT::i32),
7527 DAG.getConstant(13, DL, MVT::i32),
7528 DAG.getConstant(0, DL, MVT::i32)
7531 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7532 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7533 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7534 DAG.getConstant(0, DL, MVT::i32)));
7535 Results.push_back(Cycles32.getValue(1));
7538 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7539 SDLoc dl(V.getNode());
7540 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7541 SDValue VHi = DAG.getAnyExtOrTrunc(
7542 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7545 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7546 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7547 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7548 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7550 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7553 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7554 SmallVectorImpl<SDValue> & Results,
7555 SelectionDAG &DAG) {
7556 assert(N->getValueType(0) == MVT::i64 &&
7557 "AtomicCmpSwap on types less than 64 should be legal");
7558 SDValue Ops[] = {N->getOperand(1),
7559 createGPRPairNode(DAG, N->getOperand(2)),
7560 createGPRPairNode(DAG, N->getOperand(3)),
7562 SDNode *CmpSwap = DAG.getMachineNode(
7563 ARM::CMP_SWAP_64, SDLoc(N),
7564 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7566 MachineFunction &MF = DAG.getMachineFunction();
7567 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7568 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7569 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7571 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7572 SDValue(CmpSwap, 0)));
7573 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7574 SDValue(CmpSwap, 0)));
7575 Results.push_back(SDValue(CmpSwap, 2));
7578 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7579 SelectionDAG &DAG) {
7580 const auto &TLI = DAG.getTargetLoweringInfo();
7582 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7583 "Custom lowering is MSVCRT specific!");
7586 SDValue Val = Op.getOperand(0);
7587 MVT Ty = Val->getSimpleValueType(0);
7588 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7589 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7590 TLI.getPointerTy(DAG.getDataLayout()));
7592 TargetLowering::ArgListTy Args;
7593 TargetLowering::ArgListEntry Entry;
7596 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7597 Entry.IsZExt = true;
7598 Args.push_back(Entry);
7600 Entry.Node = Exponent;
7601 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7602 Entry.IsZExt = true;
7603 Args.push_back(Entry);
7605 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7607 // In the in-chain to the call is the entry node If we are emitting a
7608 // tailcall, the chain will be mutated if the node has a non-entry input
7610 SDValue InChain = DAG.getEntryNode();
7611 SDValue TCChain = InChain;
7613 const auto *F = DAG.getMachineFunction().getFunction();
7614 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7615 F->getReturnType() == LCRTy;
7619 TargetLowering::CallLoweringInfo CLI(DAG);
7622 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7624 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7626 // Return the chain (the DAG root) if it is a tail call
7627 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7630 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7631 switch (Op.getOpcode()) {
7632 default: llvm_unreachable("Don't know how to custom lower this!");
7633 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7634 case ISD::ConstantPool:
7635 if (Subtarget->genExecuteOnly())
7636 llvm_unreachable("execute-only should not generate constant pools");
7637 return LowerConstantPool(Op, DAG);
7638 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7639 case ISD::GlobalAddress:
7640 switch (Subtarget->getTargetTriple().getObjectFormat()) {
7641 default: llvm_unreachable("unknown object format");
7643 return LowerGlobalAddressWindows(Op, DAG);
7645 return LowerGlobalAddressELF(Op, DAG);
7647 return LowerGlobalAddressDarwin(Op, DAG);
7649 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7650 case ISD::SELECT: return LowerSELECT(Op, DAG);
7651 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7652 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
7653 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
7654 case ISD::VASTART: return LowerVASTART(Op, DAG);
7655 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7656 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
7657 case ISD::SINT_TO_FP:
7658 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7659 case ISD::FP_TO_SINT:
7660 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
7661 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7662 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7663 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7664 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7665 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7666 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7667 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7669 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
7672 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
7673 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
7674 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
7675 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
7676 case ISD::SRL_PARTS:
7677 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
7679 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7680 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7681 case ISD::SETCC: return LowerVSETCC(Op, DAG);
7682 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
7683 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
7684 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7685 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7686 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7687 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7688 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7689 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7690 case ISD::MUL: return LowerMUL(Op, DAG);
7692 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7693 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7694 return LowerSDIV(Op, DAG);
7696 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7697 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7698 return LowerUDIV(Op, DAG);
7702 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7707 return LowerXALUO(Op, DAG);
7708 case ISD::ATOMIC_LOAD:
7709 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
7710 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
7712 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
7713 case ISD::DYNAMIC_STACKALLOC:
7714 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7715 return LowerDYNAMIC_STACKALLOC(Op, DAG);
7716 llvm_unreachable("Don't know how to custom lower this!");
7717 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7718 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7719 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7720 case ARMISD::WIN__DBZCHK: return SDValue();
7724 /// ReplaceNodeResults - Replace the results of node with an illegal result
7725 /// type with new values built out of custom code.
7726 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7727 SmallVectorImpl<SDValue> &Results,
7728 SelectionDAG &DAG) const {
7730 switch (N->getOpcode()) {
7732 llvm_unreachable("Don't know how to custom expand this!");
7733 case ISD::READ_REGISTER:
7734 ExpandREAD_REGISTER(N, Results, DAG);
7737 Res = ExpandBITCAST(N, DAG);
7741 Res = Expand64BitShift(N, DAG, Subtarget);
7745 Res = LowerREM(N, DAG);
7749 Res = LowerDivRem(SDValue(N, 0), DAG);
7750 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7751 Results.push_back(Res.getValue(0));
7752 Results.push_back(Res.getValue(1));
7754 case ISD::READCYCLECOUNTER:
7755 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7759 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7760 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7762 case ISD::ATOMIC_CMP_SWAP:
7763 ReplaceCMP_SWAP_64Results(N, Results, DAG);
7767 Results.push_back(Res);
7770 //===----------------------------------------------------------------------===//
7771 // ARM Scheduler Hooks
7772 //===----------------------------------------------------------------------===//
7774 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7775 /// registers the function context.
7776 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7777 MachineBasicBlock *MBB,
7778 MachineBasicBlock *DispatchBB,
7780 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7781 "ROPI/RWPI not currently supported with SjLj");
7782 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7783 DebugLoc dl = MI.getDebugLoc();
7784 MachineFunction *MF = MBB->getParent();
7785 MachineRegisterInfo *MRI = &MF->getRegInfo();
7786 MachineConstantPool *MCP = MF->getConstantPool();
7787 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7788 const Function *F = MF->getFunction();
7790 bool isThumb = Subtarget->isThumb();
7791 bool isThumb2 = Subtarget->isThumb2();
7793 unsigned PCLabelId = AFI->createPICLabelUId();
7794 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7795 ARMConstantPoolValue *CPV =
7796 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7797 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7799 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7800 : &ARM::GPRRegClass;
7802 // Grab constant pool and fixed stack memory operands.
7803 MachineMemOperand *CPMMO =
7804 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7805 MachineMemOperand::MOLoad, 4, 4);
7807 MachineMemOperand *FIMMOSt =
7808 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7809 MachineMemOperand::MOStore, 4, 4);
7811 // Load the address of the dispatch MBB into the jump buffer.
7813 // Incoming value: jbuf
7814 // ldr.n r5, LCPI1_1
7817 // str r5, [$jbuf, #+4] ; &jbuf[1]
7818 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7819 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7820 .addConstantPoolIndex(CPI)
7821 .addMemOperand(CPMMO)
7822 .add(predOps(ARMCC::AL));
7823 // Set the low bit because of thumb mode.
7824 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7825 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7826 .addReg(NewVReg1, RegState::Kill)
7828 .add(predOps(ARMCC::AL))
7830 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7831 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7832 .addReg(NewVReg2, RegState::Kill)
7834 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7835 .addReg(NewVReg3, RegState::Kill)
7837 .addImm(36) // &jbuf[1] :: pc
7838 .addMemOperand(FIMMOSt)
7839 .add(predOps(ARMCC::AL));
7840 } else if (isThumb) {
7841 // Incoming value: jbuf
7842 // ldr.n r1, LCPI1_4
7846 // add r2, $jbuf, #+4 ; &jbuf[1]
7848 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7849 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7850 .addConstantPoolIndex(CPI)
7851 .addMemOperand(CPMMO)
7852 .add(predOps(ARMCC::AL));
7853 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7854 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7855 .addReg(NewVReg1, RegState::Kill)
7857 // Set the low bit because of thumb mode.
7858 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7859 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7860 .addReg(ARM::CPSR, RegState::Define)
7862 .add(predOps(ARMCC::AL));
7863 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7864 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7865 .addReg(ARM::CPSR, RegState::Define)
7866 .addReg(NewVReg2, RegState::Kill)
7867 .addReg(NewVReg3, RegState::Kill)
7868 .add(predOps(ARMCC::AL));
7869 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7870 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7872 .addImm(36); // &jbuf[1] :: pc
7873 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7874 .addReg(NewVReg4, RegState::Kill)
7875 .addReg(NewVReg5, RegState::Kill)
7877 .addMemOperand(FIMMOSt)
7878 .add(predOps(ARMCC::AL));
7880 // Incoming value: jbuf
7883 // str r1, [$jbuf, #+4] ; &jbuf[1]
7884 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7885 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7886 .addConstantPoolIndex(CPI)
7888 .addMemOperand(CPMMO)
7889 .add(predOps(ARMCC::AL));
7890 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7891 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7892 .addReg(NewVReg1, RegState::Kill)
7894 .add(predOps(ARMCC::AL));
7895 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7896 .addReg(NewVReg2, RegState::Kill)
7898 .addImm(36) // &jbuf[1] :: pc
7899 .addMemOperand(FIMMOSt)
7900 .add(predOps(ARMCC::AL));
7904 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7905 MachineBasicBlock *MBB) const {
7906 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7907 DebugLoc dl = MI.getDebugLoc();
7908 MachineFunction *MF = MBB->getParent();
7909 MachineRegisterInfo *MRI = &MF->getRegInfo();
7910 MachineFrameInfo &MFI = MF->getFrameInfo();
7911 int FI = MFI.getFunctionContextIndex();
7913 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7914 : &ARM::GPRnopcRegClass;
7916 // Get a mapping of the call site numbers to all of the landing pads they're
7918 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
7919 unsigned MaxCSNum = 0;
7920 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7922 if (!BB->isEHPad()) continue;
7924 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7926 for (MachineBasicBlock::iterator
7927 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7928 if (!II->isEHLabel()) continue;
7930 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7931 if (!MF->hasCallSiteLandingPad(Sym)) continue;
7933 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
7934 for (SmallVectorImpl<unsigned>::iterator
7935 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7936 CSI != CSE; ++CSI) {
7937 CallSiteNumToLPad[*CSI].push_back(&*BB);
7938 MaxCSNum = std::max(MaxCSNum, *CSI);
7944 // Get an ordered list of the machine basic blocks for the jump table.
7945 std::vector<MachineBasicBlock*> LPadList;
7946 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7947 LPadList.reserve(CallSiteNumToLPad.size());
7948 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7949 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7950 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7951 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7952 LPadList.push_back(*II);
7953 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7957 assert(!LPadList.empty() &&
7958 "No landing pad destinations for the dispatch jump table!");
7960 // Create the jump table and associated information.
7961 MachineJumpTableInfo *JTI =
7962 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7963 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7965 // Create the MBBs for the dispatch code.
7967 // Shove the dispatch's address into the return slot in the function context.
7968 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7969 DispatchBB->setIsEHPad();
7971 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7972 unsigned trap_opcode;
7973 if (Subtarget->isThumb())
7974 trap_opcode = ARM::tTRAP;
7976 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7978 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7979 DispatchBB->addSuccessor(TrapBB);
7981 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7982 DispatchBB->addSuccessor(DispContBB);
7985 MF->insert(MF->end(), DispatchBB);
7986 MF->insert(MF->end(), DispContBB);
7987 MF->insert(MF->end(), TrapBB);
7989 // Insert code into the entry block that creates and registers the function
7991 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7993 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7994 MachinePointerInfo::getFixedStack(*MF, FI),
7995 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7997 MachineInstrBuilder MIB;
7998 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8000 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8001 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8003 // Add a register mask with no preserved registers. This results in all
8004 // registers being marked as clobbered. This can't work if the dispatch block
8005 // is in a Thumb1 function and is linked with ARM code which uses the FP
8006 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8007 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8009 bool IsPositionIndependent = isPositionIndependent();
8010 unsigned NumLPads = LPadList.size();
8011 if (Subtarget->isThumb2()) {
8012 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8013 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8016 .addMemOperand(FIMMOLd)
8017 .add(predOps(ARMCC::AL));
8019 if (NumLPads < 256) {
8020 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8022 .addImm(LPadList.size())
8023 .add(predOps(ARMCC::AL));
8025 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8026 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8027 .addImm(NumLPads & 0xFFFF)
8028 .add(predOps(ARMCC::AL));
8030 unsigned VReg2 = VReg1;
8031 if ((NumLPads & 0xFFFF0000) != 0) {
8032 VReg2 = MRI->createVirtualRegister(TRC);
8033 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8035 .addImm(NumLPads >> 16)
8036 .add(predOps(ARMCC::AL));
8039 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8042 .add(predOps(ARMCC::AL));
8045 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8050 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8051 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8052 .addJumpTableIndex(MJTI)
8053 .add(predOps(ARMCC::AL));
8055 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8056 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8057 .addReg(NewVReg3, RegState::Kill)
8059 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8060 .add(predOps(ARMCC::AL))
8063 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8064 .addReg(NewVReg4, RegState::Kill)
8066 .addJumpTableIndex(MJTI);
8067 } else if (Subtarget->isThumb()) {
8068 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8069 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8072 .addMemOperand(FIMMOLd)
8073 .add(predOps(ARMCC::AL));
8075 if (NumLPads < 256) {
8076 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8079 .add(predOps(ARMCC::AL));
8081 MachineConstantPool *ConstantPool = MF->getConstantPool();
8082 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8083 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8085 // MachineConstantPool wants an explicit alignment.
8086 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8088 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8089 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8091 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8092 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8093 .addReg(VReg1, RegState::Define)
8094 .addConstantPoolIndex(Idx)
8095 .add(predOps(ARMCC::AL));
8096 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8099 .add(predOps(ARMCC::AL));
8102 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8107 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8108 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8109 .addReg(ARM::CPSR, RegState::Define)
8112 .add(predOps(ARMCC::AL));
8114 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8115 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8116 .addJumpTableIndex(MJTI)
8117 .add(predOps(ARMCC::AL));
8119 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8120 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8121 .addReg(ARM::CPSR, RegState::Define)
8122 .addReg(NewVReg2, RegState::Kill)
8124 .add(predOps(ARMCC::AL));
8126 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8127 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8129 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8130 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8131 .addReg(NewVReg4, RegState::Kill)
8133 .addMemOperand(JTMMOLd)
8134 .add(predOps(ARMCC::AL));
8136 unsigned NewVReg6 = NewVReg5;
8137 if (IsPositionIndependent) {
8138 NewVReg6 = MRI->createVirtualRegister(TRC);
8139 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8140 .addReg(ARM::CPSR, RegState::Define)
8141 .addReg(NewVReg5, RegState::Kill)
8143 .add(predOps(ARMCC::AL));
8146 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8147 .addReg(NewVReg6, RegState::Kill)
8148 .addJumpTableIndex(MJTI);
8150 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8151 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8154 .addMemOperand(FIMMOLd)
8155 .add(predOps(ARMCC::AL));
8157 if (NumLPads < 256) {
8158 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8161 .add(predOps(ARMCC::AL));
8162 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8163 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8164 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8165 .addImm(NumLPads & 0xFFFF)
8166 .add(predOps(ARMCC::AL));
8168 unsigned VReg2 = VReg1;
8169 if ((NumLPads & 0xFFFF0000) != 0) {
8170 VReg2 = MRI->createVirtualRegister(TRC);
8171 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8173 .addImm(NumLPads >> 16)
8174 .add(predOps(ARMCC::AL));
8177 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8180 .add(predOps(ARMCC::AL));
8182 MachineConstantPool *ConstantPool = MF->getConstantPool();
8183 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8184 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8186 // MachineConstantPool wants an explicit alignment.
8187 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8189 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8190 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8192 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8193 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8194 .addReg(VReg1, RegState::Define)
8195 .addConstantPoolIndex(Idx)
8197 .add(predOps(ARMCC::AL));
8198 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8200 .addReg(VReg1, RegState::Kill)
8201 .add(predOps(ARMCC::AL));
8204 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8209 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8210 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8212 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8213 .add(predOps(ARMCC::AL))
8215 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8216 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8217 .addJumpTableIndex(MJTI)
8218 .add(predOps(ARMCC::AL));
8220 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8221 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8222 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8223 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8224 .addReg(NewVReg3, RegState::Kill)
8227 .addMemOperand(JTMMOLd)
8228 .add(predOps(ARMCC::AL));
8230 if (IsPositionIndependent) {
8231 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8232 .addReg(NewVReg5, RegState::Kill)
8234 .addJumpTableIndex(MJTI);
8236 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8237 .addReg(NewVReg5, RegState::Kill)
8238 .addJumpTableIndex(MJTI);
8242 // Add the jump table entries as successors to the MBB.
8243 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8244 for (std::vector<MachineBasicBlock*>::iterator
8245 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8246 MachineBasicBlock *CurMBB = *I;
8247 if (SeenMBBs.insert(CurMBB).second)
8248 DispContBB->addSuccessor(CurMBB);
8251 // N.B. the order the invoke BBs are processed in doesn't matter here.
8252 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8253 SmallVector<MachineBasicBlock*, 64> MBBLPads;
8254 for (MachineBasicBlock *BB : InvokeBBs) {
8256 // Remove the landing pad successor from the invoke block and replace it
8257 // with the new dispatch block.
8258 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8260 while (!Successors.empty()) {
8261 MachineBasicBlock *SMBB = Successors.pop_back_val();
8262 if (SMBB->isEHPad()) {
8263 BB->removeSuccessor(SMBB);
8264 MBBLPads.push_back(SMBB);
8268 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8269 BB->normalizeSuccProbs();
8271 // Find the invoke call and mark all of the callee-saved registers as
8272 // 'implicit defined' so that they're spilled. This prevents code from
8273 // moving instructions to before the EH block, where they will never be
8275 for (MachineBasicBlock::reverse_iterator
8276 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8277 if (!II->isCall()) continue;
8279 DenseMap<unsigned, bool> DefRegs;
8280 for (MachineInstr::mop_iterator
8281 OI = II->operands_begin(), OE = II->operands_end();
8283 if (!OI->isReg()) continue;
8284 DefRegs[OI->getReg()] = true;
8287 MachineInstrBuilder MIB(*MF, &*II);
8289 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8290 unsigned Reg = SavedRegs[i];
8291 if (Subtarget->isThumb2() &&
8292 !ARM::tGPRRegClass.contains(Reg) &&
8293 !ARM::hGPRRegClass.contains(Reg))
8295 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8297 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8300 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8307 // Mark all former landing pads as non-landing pads. The dispatch is the only
8309 for (SmallVectorImpl<MachineBasicBlock*>::iterator
8310 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8311 (*I)->setIsEHPad(false);
8313 // The instruction is gone now.
8314 MI.eraseFromParent();
8318 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8319 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8320 E = MBB->succ_end(); I != E; ++I)
8323 llvm_unreachable("Expecting a BB with two successors!");
8326 /// Return the load opcode for a given load size. If load size >= 8,
8327 /// neon opcode will be returned.
8328 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8330 return LdSize == 16 ? ARM::VLD1q32wb_fixed
8331 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8333 return LdSize == 4 ? ARM::tLDRi
8334 : LdSize == 2 ? ARM::tLDRHi
8335 : LdSize == 1 ? ARM::tLDRBi : 0;
8337 return LdSize == 4 ? ARM::t2LDR_POST
8338 : LdSize == 2 ? ARM::t2LDRH_POST
8339 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8340 return LdSize == 4 ? ARM::LDR_POST_IMM
8341 : LdSize == 2 ? ARM::LDRH_POST
8342 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8345 /// Return the store opcode for a given store size. If store size >= 8,
8346 /// neon opcode will be returned.
8347 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8349 return StSize == 16 ? ARM::VST1q32wb_fixed
8350 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8352 return StSize == 4 ? ARM::tSTRi
8353 : StSize == 2 ? ARM::tSTRHi
8354 : StSize == 1 ? ARM::tSTRBi : 0;
8356 return StSize == 4 ? ARM::t2STR_POST
8357 : StSize == 2 ? ARM::t2STRH_POST
8358 : StSize == 1 ? ARM::t2STRB_POST : 0;
8359 return StSize == 4 ? ARM::STR_POST_IMM
8360 : StSize == 2 ? ARM::STRH_POST
8361 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8364 /// Emit a post-increment load operation with given size. The instructions
8365 /// will be added to BB at Pos.
8366 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8367 const TargetInstrInfo *TII, const DebugLoc &dl,
8368 unsigned LdSize, unsigned Data, unsigned AddrIn,
8369 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8370 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8371 assert(LdOpc != 0 && "Should have a load opcode");
8373 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8374 .addReg(AddrOut, RegState::Define)
8377 .add(predOps(ARMCC::AL));
8378 } else if (IsThumb1) {
8379 // load + update AddrIn
8380 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8383 .add(predOps(ARMCC::AL));
8384 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8385 .add(t1CondCodeOp())
8388 .add(predOps(ARMCC::AL));
8389 } else if (IsThumb2) {
8390 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8391 .addReg(AddrOut, RegState::Define)
8394 .add(predOps(ARMCC::AL));
8396 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8397 .addReg(AddrOut, RegState::Define)
8401 .add(predOps(ARMCC::AL));
8405 /// Emit a post-increment store operation with given size. The instructions
8406 /// will be added to BB at Pos.
8407 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8408 const TargetInstrInfo *TII, const DebugLoc &dl,
8409 unsigned StSize, unsigned Data, unsigned AddrIn,
8410 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8411 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8412 assert(StOpc != 0 && "Should have a store opcode");
8414 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8418 .add(predOps(ARMCC::AL));
8419 } else if (IsThumb1) {
8420 // store + update AddrIn
8421 BuildMI(*BB, Pos, dl, TII->get(StOpc))
8425 .add(predOps(ARMCC::AL));
8426 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8427 .add(t1CondCodeOp())
8430 .add(predOps(ARMCC::AL));
8431 } else if (IsThumb2) {
8432 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8436 .add(predOps(ARMCC::AL));
8438 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8443 .add(predOps(ARMCC::AL));
8448 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8449 MachineBasicBlock *BB) const {
8450 // This pseudo instruction has 3 operands: dst, src, size
8451 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8452 // Otherwise, we will generate unrolled scalar copies.
8453 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8454 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8455 MachineFunction::iterator It = ++BB->getIterator();
8457 unsigned dest = MI.getOperand(0).getReg();
8458 unsigned src = MI.getOperand(1).getReg();
8459 unsigned SizeVal = MI.getOperand(2).getImm();
8460 unsigned Align = MI.getOperand(3).getImm();
8461 DebugLoc dl = MI.getDebugLoc();
8463 MachineFunction *MF = BB->getParent();
8464 MachineRegisterInfo &MRI = MF->getRegInfo();
8465 unsigned UnitSize = 0;
8466 const TargetRegisterClass *TRC = nullptr;
8467 const TargetRegisterClass *VecTRC = nullptr;
8469 bool IsThumb1 = Subtarget->isThumb1Only();
8470 bool IsThumb2 = Subtarget->isThumb2();
8471 bool IsThumb = Subtarget->isThumb();
8475 } else if (Align & 2) {
8478 // Check whether we can use NEON instructions.
8479 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8480 Subtarget->hasNEON()) {
8481 if ((Align % 16 == 0) && SizeVal >= 16)
8483 else if ((Align % 8 == 0) && SizeVal >= 8)
8486 // Can't use NEON instructions.
8491 // Select the correct opcode and register class for unit size load/store
8492 bool IsNeon = UnitSize >= 8;
8493 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8495 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8496 : UnitSize == 8 ? &ARM::DPRRegClass
8499 unsigned BytesLeft = SizeVal % UnitSize;
8500 unsigned LoopSize = SizeVal - BytesLeft;
8502 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8503 // Use LDR and STR to copy.
8504 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8505 // [destOut] = STR_POST(scratch, destIn, UnitSize)
8506 unsigned srcIn = src;
8507 unsigned destIn = dest;
8508 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8509 unsigned srcOut = MRI.createVirtualRegister(TRC);
8510 unsigned destOut = MRI.createVirtualRegister(TRC);
8511 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8512 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8513 IsThumb1, IsThumb2);
8514 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8515 IsThumb1, IsThumb2);
8520 // Handle the leftover bytes with LDRB and STRB.
8521 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8522 // [destOut] = STRB_POST(scratch, destIn, 1)
8523 for (unsigned i = 0; i < BytesLeft; i++) {
8524 unsigned srcOut = MRI.createVirtualRegister(TRC);
8525 unsigned destOut = MRI.createVirtualRegister(TRC);
8526 unsigned scratch = MRI.createVirtualRegister(TRC);
8527 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8528 IsThumb1, IsThumb2);
8529 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8530 IsThumb1, IsThumb2);
8534 MI.eraseFromParent(); // The instruction is gone now.
8538 // Expand the pseudo op to a loop.
8541 // movw varEnd, # --> with thumb2
8543 // ldrcp varEnd, idx --> without thumb2
8544 // fallthrough --> loopMBB
8546 // PHI varPhi, varEnd, varLoop
8547 // PHI srcPhi, src, srcLoop
8548 // PHI destPhi, dst, destLoop
8549 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8550 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8551 // subs varLoop, varPhi, #UnitSize
8553 // fallthrough --> exitMBB
8555 // epilogue to handle left-over bytes
8556 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8557 // [destOut] = STRB_POST(scratch, destLoop, 1)
8558 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8559 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8560 MF->insert(It, loopMBB);
8561 MF->insert(It, exitMBB);
8563 // Transfer the remainder of BB and its successor edges to exitMBB.
8564 exitMBB->splice(exitMBB->begin(), BB,
8565 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8566 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8568 // Load an immediate to varEnd.
8569 unsigned varEnd = MRI.createVirtualRegister(TRC);
8570 if (Subtarget->useMovt(*MF)) {
8571 unsigned Vtmp = varEnd;
8572 if ((LoopSize & 0xFFFF0000) != 0)
8573 Vtmp = MRI.createVirtualRegister(TRC);
8574 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8575 .addImm(LoopSize & 0xFFFF)
8576 .add(predOps(ARMCC::AL));
8578 if ((LoopSize & 0xFFFF0000) != 0)
8579 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8581 .addImm(LoopSize >> 16)
8582 .add(predOps(ARMCC::AL));
8584 MachineConstantPool *ConstantPool = MF->getConstantPool();
8585 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8586 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8588 // MachineConstantPool wants an explicit alignment.
8589 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8591 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8592 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8595 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8596 .addReg(varEnd, RegState::Define)
8597 .addConstantPoolIndex(Idx)
8598 .add(predOps(ARMCC::AL));
8600 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8601 .addReg(varEnd, RegState::Define)
8602 .addConstantPoolIndex(Idx)
8604 .add(predOps(ARMCC::AL));
8606 BB->addSuccessor(loopMBB);
8608 // Generate the loop body:
8609 // varPhi = PHI(varLoop, varEnd)
8610 // srcPhi = PHI(srcLoop, src)
8611 // destPhi = PHI(destLoop, dst)
8612 MachineBasicBlock *entryBB = BB;
8614 unsigned varLoop = MRI.createVirtualRegister(TRC);
8615 unsigned varPhi = MRI.createVirtualRegister(TRC);
8616 unsigned srcLoop = MRI.createVirtualRegister(TRC);
8617 unsigned srcPhi = MRI.createVirtualRegister(TRC);
8618 unsigned destLoop = MRI.createVirtualRegister(TRC);
8619 unsigned destPhi = MRI.createVirtualRegister(TRC);
8621 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8622 .addReg(varLoop).addMBB(loopMBB)
8623 .addReg(varEnd).addMBB(entryBB);
8624 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8625 .addReg(srcLoop).addMBB(loopMBB)
8626 .addReg(src).addMBB(entryBB);
8627 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8628 .addReg(destLoop).addMBB(loopMBB)
8629 .addReg(dest).addMBB(entryBB);
8631 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8632 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8633 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8634 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8635 IsThumb1, IsThumb2);
8636 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8637 IsThumb1, IsThumb2);
8639 // Decrement loop variable by UnitSize.
8641 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8642 .add(t1CondCodeOp())
8645 .add(predOps(ARMCC::AL));
8647 MachineInstrBuilder MIB =
8648 BuildMI(*BB, BB->end(), dl,
8649 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8652 .add(predOps(ARMCC::AL))
8654 MIB->getOperand(5).setReg(ARM::CPSR);
8655 MIB->getOperand(5).setIsDef(true);
8657 BuildMI(*BB, BB->end(), dl,
8658 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8659 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8661 // loopMBB can loop back to loopMBB or fall through to exitMBB.
8662 BB->addSuccessor(loopMBB);
8663 BB->addSuccessor(exitMBB);
8665 // Add epilogue to handle BytesLeft.
8667 auto StartOfExit = exitMBB->begin();
8669 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8670 // [destOut] = STRB_POST(scratch, destLoop, 1)
8671 unsigned srcIn = srcLoop;
8672 unsigned destIn = destLoop;
8673 for (unsigned i = 0; i < BytesLeft; i++) {
8674 unsigned srcOut = MRI.createVirtualRegister(TRC);
8675 unsigned destOut = MRI.createVirtualRegister(TRC);
8676 unsigned scratch = MRI.createVirtualRegister(TRC);
8677 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8678 IsThumb1, IsThumb2);
8679 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8680 IsThumb1, IsThumb2);
8685 MI.eraseFromParent(); // The instruction is gone now.
8690 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8691 MachineBasicBlock *MBB) const {
8692 const TargetMachine &TM = getTargetMachine();
8693 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8694 DebugLoc DL = MI.getDebugLoc();
8696 assert(Subtarget->isTargetWindows() &&
8697 "__chkstk is only supported on Windows");
8698 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8700 // __chkstk takes the number of words to allocate on the stack in R4, and
8701 // returns the stack adjustment in number of bytes in R4. This will not
8702 // clober any other registers (other than the obvious lr).
8704 // Although, technically, IP should be considered a register which may be
8705 // clobbered, the call itself will not touch it. Windows on ARM is a pure
8706 // thumb-2 environment, so there is no interworking required. As a result, we
8707 // do not expect a veneer to be emitted by the linker, clobbering IP.
8709 // Each module receives its own copy of __chkstk, so no import thunk is
8710 // required, again, ensuring that IP is not clobbered.
8712 // Finally, although some linkers may theoretically provide a trampoline for
8713 // out of range calls (which is quite common due to a 32M range limitation of
8714 // branches for Thumb), we can generate the long-call version via
8715 // -mcmodel=large, alleviating the need for the trampoline which may clobber
8718 switch (TM.getCodeModel()) {
8719 case CodeModel::Small:
8720 case CodeModel::Medium:
8721 case CodeModel::Default:
8722 case CodeModel::Kernel:
8723 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8724 .add(predOps(ARMCC::AL))
8725 .addExternalSymbol("__chkstk")
8726 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8727 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8729 RegState::Implicit | RegState::Define | RegState::Dead);
8731 case CodeModel::Large:
8732 case CodeModel::JITDefault: {
8733 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8734 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8736 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8737 .addExternalSymbol("__chkstk");
8738 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8739 .add(predOps(ARMCC::AL))
8740 .addReg(Reg, RegState::Kill)
8741 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8742 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8744 RegState::Implicit | RegState::Define | RegState::Dead);
8749 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8750 .addReg(ARM::SP, RegState::Kill)
8751 .addReg(ARM::R4, RegState::Kill)
8752 .setMIFlags(MachineInstr::FrameSetup)
8753 .add(predOps(ARMCC::AL))
8756 MI.eraseFromParent();
8761 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8762 MachineBasicBlock *MBB) const {
8763 DebugLoc DL = MI.getDebugLoc();
8764 MachineFunction *MF = MBB->getParent();
8765 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8767 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8768 MF->insert(++MBB->getIterator(), ContBB);
8769 ContBB->splice(ContBB->begin(), MBB,
8770 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8771 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8772 MBB->addSuccessor(ContBB);
8774 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8775 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8776 MF->push_back(TrapBB);
8777 MBB->addSuccessor(TrapBB);
8779 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8780 .addReg(MI.getOperand(0).getReg())
8782 .add(predOps(ARMCC::AL));
8783 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8788 MI.eraseFromParent();
8793 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8794 MachineBasicBlock *BB) const {
8795 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8796 DebugLoc dl = MI.getDebugLoc();
8797 bool isThumb2 = Subtarget->isThumb2();
8798 switch (MI.getOpcode()) {
8801 llvm_unreachable("Unexpected instr type to insert");
8804 // Thumb1 post-indexed loads are really just single-register LDMs.
8805 case ARM::tLDR_postidx: {
8806 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8807 .add(MI.getOperand(1)) // Rn_wb
8808 .add(MI.getOperand(2)) // Rn
8809 .add(MI.getOperand(3)) // PredImm
8810 .add(MI.getOperand(4)) // PredReg
8811 .add(MI.getOperand(0)); // Rt
8812 MI.eraseFromParent();
8816 // The Thumb2 pre-indexed stores have the same MI operands, they just
8817 // define them differently in the .td files from the isel patterns, so
8818 // they need pseudos.
8819 case ARM::t2STR_preidx:
8820 MI.setDesc(TII->get(ARM::t2STR_PRE));
8822 case ARM::t2STRB_preidx:
8823 MI.setDesc(TII->get(ARM::t2STRB_PRE));
8825 case ARM::t2STRH_preidx:
8826 MI.setDesc(TII->get(ARM::t2STRH_PRE));
8829 case ARM::STRi_preidx:
8830 case ARM::STRBi_preidx: {
8831 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8832 : ARM::STRB_PRE_IMM;
8833 // Decode the offset.
8834 unsigned Offset = MI.getOperand(4).getImm();
8835 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8836 Offset = ARM_AM::getAM2Offset(Offset);
8840 MachineMemOperand *MMO = *MI.memoperands_begin();
8841 BuildMI(*BB, MI, dl, TII->get(NewOpc))
8842 .add(MI.getOperand(0)) // Rn_wb
8843 .add(MI.getOperand(1)) // Rt
8844 .add(MI.getOperand(2)) // Rn
8845 .addImm(Offset) // offset (skip GPR==zero_reg)
8846 .add(MI.getOperand(5)) // pred
8847 .add(MI.getOperand(6))
8848 .addMemOperand(MMO);
8849 MI.eraseFromParent();
8852 case ARM::STRr_preidx:
8853 case ARM::STRBr_preidx:
8854 case ARM::STRH_preidx: {
8856 switch (MI.getOpcode()) {
8857 default: llvm_unreachable("unexpected opcode!");
8858 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8859 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8860 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8862 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8863 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8864 MIB.add(MI.getOperand(i));
8865 MI.eraseFromParent();
8869 case ARM::tMOVCCr_pseudo: {
8870 // To "insert" a SELECT_CC instruction, we actually have to insert the
8871 // diamond control-flow pattern. The incoming instruction knows the
8872 // destination vreg to set, the condition code register to branch on, the
8873 // true/false values to select between, and a branch opcode to use.
8874 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8875 MachineFunction::iterator It = ++BB->getIterator();
8880 // cmpTY ccX, r1, r2
8882 // fallthrough --> copy0MBB
8883 MachineBasicBlock *thisMBB = BB;
8884 MachineFunction *F = BB->getParent();
8885 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8886 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8887 F->insert(It, copy0MBB);
8888 F->insert(It, sinkMBB);
8890 // Transfer the remainder of BB and its successor edges to sinkMBB.
8891 sinkMBB->splice(sinkMBB->begin(), BB,
8892 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8893 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8895 BB->addSuccessor(copy0MBB);
8896 BB->addSuccessor(sinkMBB);
8898 BuildMI(BB, dl, TII->get(ARM::tBcc))
8900 .addImm(MI.getOperand(3).getImm())
8901 .addReg(MI.getOperand(4).getReg());
8904 // %FalseValue = ...
8905 // # fallthrough to sinkMBB
8908 // Update machine-CFG edges
8909 BB->addSuccessor(sinkMBB);
8912 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8915 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8916 .addReg(MI.getOperand(1).getReg())
8918 .addReg(MI.getOperand(2).getReg())
8921 MI.eraseFromParent(); // The pseudo instruction is gone now.
8926 case ARM::BCCZi64: {
8927 // If there is an unconditional branch to the other successor, remove it.
8928 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8930 // Compare both parts that make up the double comparison separately for
8932 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8934 unsigned LHS1 = MI.getOperand(1).getReg();
8935 unsigned LHS2 = MI.getOperand(2).getReg();
8937 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8940 .add(predOps(ARMCC::AL));
8941 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8942 .addReg(LHS2).addImm(0)
8943 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8945 unsigned RHS1 = MI.getOperand(3).getReg();
8946 unsigned RHS2 = MI.getOperand(4).getReg();
8947 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8950 .add(predOps(ARMCC::AL));
8951 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8952 .addReg(LHS2).addReg(RHS2)
8953 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8956 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8957 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8958 if (MI.getOperand(0).getImm() == ARMCC::NE)
8959 std::swap(destMBB, exitMBB);
8961 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8962 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8964 BuildMI(BB, dl, TII->get(ARM::t2B))
8966 .add(predOps(ARMCC::AL));
8968 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8970 MI.eraseFromParent(); // The pseudo instruction is gone now.
8974 case ARM::Int_eh_sjlj_setjmp:
8975 case ARM::Int_eh_sjlj_setjmp_nofp:
8976 case ARM::tInt_eh_sjlj_setjmp:
8977 case ARM::t2Int_eh_sjlj_setjmp:
8978 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8981 case ARM::Int_eh_sjlj_setup_dispatch:
8982 EmitSjLjDispatchBlock(MI, BB);
8987 // To insert an ABS instruction, we have to insert the
8988 // diamond control-flow pattern. The incoming instruction knows the
8989 // source vreg to test against 0, the destination vreg to set,
8990 // the condition code register to branch on, the
8991 // true/false values to select between, and a branch opcode to use.
8996 // BCC (branch to SinkBB if V0 >= 0)
8997 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8998 // SinkBB: V1 = PHI(V2, V3)
8999 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9000 MachineFunction::iterator BBI = ++BB->getIterator();
9001 MachineFunction *Fn = BB->getParent();
9002 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9003 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9004 Fn->insert(BBI, RSBBB);
9005 Fn->insert(BBI, SinkBB);
9007 unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9008 unsigned int ABSDstReg = MI.getOperand(0).getReg();
9009 bool ABSSrcKIll = MI.getOperand(1).isKill();
9010 bool isThumb2 = Subtarget->isThumb2();
9011 MachineRegisterInfo &MRI = Fn->getRegInfo();
9012 // In Thumb mode S must not be specified if source register is the SP or
9013 // PC and if destination register is the SP, so restrict register class
9014 unsigned NewRsbDstReg =
9015 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9017 // Transfer the remainder of BB and its successor edges to sinkMBB.
9018 SinkBB->splice(SinkBB->begin(), BB,
9019 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9020 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9022 BB->addSuccessor(RSBBB);
9023 BB->addSuccessor(SinkBB);
9025 // fall through to SinkMBB
9026 RSBBB->addSuccessor(SinkBB);
9028 // insert a cmp at the end of BB
9029 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9032 .add(predOps(ARMCC::AL));
9034 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9036 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9037 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9039 // insert rsbri in RSBBB
9040 // Note: BCC and rsbri will be converted into predicated rsbmi
9041 // by if-conversion pass
9042 BuildMI(*RSBBB, RSBBB->begin(), dl,
9043 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9044 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9046 .add(predOps(ARMCC::AL))
9049 // insert PHI in SinkBB,
9050 // reuse ABSDstReg to not change uses of ABS instruction
9051 BuildMI(*SinkBB, SinkBB->begin(), dl,
9052 TII->get(ARM::PHI), ABSDstReg)
9053 .addReg(NewRsbDstReg).addMBB(RSBBB)
9054 .addReg(ABSSrcReg).addMBB(BB);
9056 // remove ABS instruction
9057 MI.eraseFromParent();
9059 // return last added BB
9062 case ARM::COPY_STRUCT_BYVAL_I32:
9064 return EmitStructByval(MI, BB);
9065 case ARM::WIN__CHKSTK:
9066 return EmitLowered__chkstk(MI, BB);
9067 case ARM::WIN__DBZCHK:
9068 return EmitLowered__dbzchk(MI, BB);
9072 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9073 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9074 /// instead of as a custom inserter because we need the use list from the SDNode.
9075 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9076 MachineInstr &MI, const SDNode *Node) {
9077 bool isThumb1 = Subtarget->isThumb1Only();
9079 DebugLoc DL = MI.getDebugLoc();
9080 MachineFunction *MF = MI.getParent()->getParent();
9081 MachineRegisterInfo &MRI = MF->getRegInfo();
9082 MachineInstrBuilder MIB(*MF, MI);
9084 // If the new dst/src is unused mark it as dead.
9085 if (!Node->hasAnyUseOfValue(0)) {
9086 MI.getOperand(0).setIsDead(true);
9088 if (!Node->hasAnyUseOfValue(1)) {
9089 MI.getOperand(1).setIsDead(true);
9092 // The MEMCPY both defines and kills the scratch registers.
9093 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9094 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9095 : &ARM::GPRRegClass);
9096 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9100 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9101 SDNode *Node) const {
9102 if (MI.getOpcode() == ARM::MEMCPY) {
9103 attachMEMCPYScratchRegs(Subtarget, MI, Node);
9107 const MCInstrDesc *MCID = &MI.getDesc();
9108 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9109 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9110 // operand is still set to noreg. If needed, set the optional operand's
9111 // register to CPSR, and remove the redundant implicit def.
9113 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9115 // Rename pseudo opcodes.
9116 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9119 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9120 MCID = &TII->get(NewOpc);
9122 assert(MCID->getNumOperands() ==
9123 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9124 && "converted opcode should be the same except for cc_out"
9125 " (and, on Thumb1, pred)");
9129 // Add the optional cc_out operand
9130 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9132 // On Thumb1, move all input operands to the end, then add the predicate
9133 if (Subtarget->isThumb1Only()) {
9134 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9135 MI.addOperand(MI.getOperand(1));
9136 MI.RemoveOperand(1);
9140 for (unsigned i = MI.getNumOperands(); i--;) {
9141 const MachineOperand& op = MI.getOperand(i);
9142 if (op.isReg() && op.isUse()) {
9143 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9145 MI.tieOperands(DefIdx, i);
9149 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9150 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9153 ccOutIdx = MCID->getNumOperands() - 1;
9155 ccOutIdx = MCID->getNumOperands() - 1;
9157 // Any ARM instruction that sets the 's' bit should specify an optional
9158 // "cc_out" operand in the last operand position.
9159 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9160 assert(!NewOpc && "Optional cc_out operand required");
9163 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9164 // since we already have an optional CPSR def.
9165 bool definesCPSR = false;
9166 bool deadCPSR = false;
9167 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9169 const MachineOperand &MO = MI.getOperand(i);
9170 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9174 MI.RemoveOperand(i);
9179 assert(!NewOpc && "Optional cc_out operand required");
9182 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9184 assert(!MI.getOperand(ccOutIdx).getReg() &&
9185 "expect uninitialized optional cc_out operand");
9186 // Thumb1 instructions must have the S bit even if the CPSR is dead.
9187 if (!Subtarget->isThumb1Only())
9191 // If this instruction was defined with an optional CPSR def and its dag node
9192 // had a live implicit CPSR def, then activate the optional CPSR def.
9193 MachineOperand &MO = MI.getOperand(ccOutIdx);
9194 MO.setReg(ARM::CPSR);
9198 //===----------------------------------------------------------------------===//
9199 // ARM Optimization Hooks
9200 //===----------------------------------------------------------------------===//
9202 // Helper function that checks if N is a null or all ones constant.
9203 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9204 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9207 // Return true if N is conditionally 0 or all ones.
9208 // Detects these expressions where cc is an i1 value:
9210 // (select cc 0, y) [AllOnes=0]
9211 // (select cc y, 0) [AllOnes=0]
9212 // (zext cc) [AllOnes=0]
9213 // (sext cc) [AllOnes=0/1]
9214 // (select cc -1, y) [AllOnes=1]
9215 // (select cc y, -1) [AllOnes=1]
9217 // Invert is set when N is the null/all ones constant when CC is false.
9218 // OtherOp is set to the alternative value of N.
9219 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9220 SDValue &CC, bool &Invert,
9222 SelectionDAG &DAG) {
9223 switch (N->getOpcode()) {
9224 default: return false;
9226 CC = N->getOperand(0);
9227 SDValue N1 = N->getOperand(1);
9228 SDValue N2 = N->getOperand(2);
9229 if (isZeroOrAllOnes(N1, AllOnes)) {
9234 if (isZeroOrAllOnes(N2, AllOnes)) {
9241 case ISD::ZERO_EXTEND:
9242 // (zext cc) can never be the all ones value.
9246 case ISD::SIGN_EXTEND: {
9248 EVT VT = N->getValueType(0);
9249 CC = N->getOperand(0);
9250 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9254 // When looking for an AllOnes constant, N is an sext, and the 'other'
9256 OtherOp = DAG.getConstant(0, dl, VT);
9257 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9258 // When looking for a 0 constant, N can be zext or sext.
9259 OtherOp = DAG.getConstant(1, dl, VT);
9261 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9268 // Combine a constant select operand into its use:
9270 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9271 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9272 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
9273 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9274 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9276 // The transform is rejected if the select doesn't have a constant operand that
9277 // is null, or all ones when AllOnes is set.
9279 // Also recognize sext/zext from i1:
9281 // (add (zext cc), x) -> (select cc (add x, 1), x)
9282 // (add (sext cc), x) -> (select cc (add x, -1), x)
9284 // These transformations eventually create predicated instructions.
9286 // @param N The node to transform.
9287 // @param Slct The N operand that is a select.
9288 // @param OtherOp The other N operand (x above).
9289 // @param DCI Context.
9290 // @param AllOnes Require the select constant to be all ones instead of null.
9291 // @returns The new node, or SDValue() on failure.
9293 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9294 TargetLowering::DAGCombinerInfo &DCI,
9295 bool AllOnes = false) {
9296 SelectionDAG &DAG = DCI.DAG;
9297 EVT VT = N->getValueType(0);
9298 SDValue NonConstantVal;
9301 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9302 NonConstantVal, DAG))
9305 // Slct is now know to be the desired identity constant when CC is true.
9306 SDValue TrueVal = OtherOp;
9307 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9308 OtherOp, NonConstantVal);
9309 // Unless SwapSelectOps says CC should be false.
9311 std::swap(TrueVal, FalseVal);
9313 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9314 CCOp, TrueVal, FalseVal);
9317 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9319 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9320 TargetLowering::DAGCombinerInfo &DCI) {
9321 SDValue N0 = N->getOperand(0);
9322 SDValue N1 = N->getOperand(1);
9323 if (N0.getNode()->hasOneUse())
9324 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9326 if (N1.getNode()->hasOneUse())
9327 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9332 static bool IsVUZPShuffleNode(SDNode *N) {
9333 // VUZP shuffle node.
9334 if (N->getOpcode() == ARMISD::VUZP)
9337 // "VUZP" on i32 is an alias for VTRN.
9338 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9344 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9345 TargetLowering::DAGCombinerInfo &DCI,
9346 const ARMSubtarget *Subtarget) {
9347 // Look for ADD(VUZP.0, VUZP.1).
9348 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9352 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9353 if (!N->getValueType(0).is64BitVector())
9357 SelectionDAG &DAG = DCI.DAG;
9358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9360 SDNode *Unzip = N0.getNode();
9361 EVT VT = N->getValueType(0);
9363 SmallVector<SDValue, 8> Ops;
9364 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9365 TLI.getPointerTy(DAG.getDataLayout())));
9366 Ops.push_back(Unzip->getOperand(0));
9367 Ops.push_back(Unzip->getOperand(1));
9369 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9372 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9373 TargetLowering::DAGCombinerInfo &DCI,
9374 const ARMSubtarget *Subtarget) {
9375 // Check for two extended operands.
9376 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9377 N1.getOpcode() == ISD::SIGN_EXTEND) &&
9378 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9379 N1.getOpcode() == ISD::ZERO_EXTEND))
9382 SDValue N00 = N0.getOperand(0);
9383 SDValue N10 = N1.getOperand(0);
9385 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9386 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9390 // We only recognize Q register paddl here; this can't be reached until
9391 // after type legalization.
9392 if (!N00.getValueType().is64BitVector() ||
9393 !N0.getValueType().is128BitVector())
9397 SelectionDAG &DAG = DCI.DAG;
9398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9400 EVT VT = N->getValueType(0);
9402 SmallVector<SDValue, 8> Ops;
9403 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9405 if (N0.getOpcode() == ISD::SIGN_EXTEND)
9406 Opcode = Intrinsic::arm_neon_vpaddls;
9408 Opcode = Intrinsic::arm_neon_vpaddlu;
9409 Ops.push_back(DAG.getConstant(Opcode, dl,
9410 TLI.getPointerTy(DAG.getDataLayout())));
9411 EVT ElemTy = N00.getValueType().getVectorElementType();
9412 unsigned NumElts = VT.getVectorNumElements();
9413 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9414 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9415 N00.getOperand(0), N00.getOperand(1));
9416 Ops.push_back(Concat);
9418 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9421 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9422 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9423 // much easier to match.
9425 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9426 TargetLowering::DAGCombinerInfo &DCI,
9427 const ARMSubtarget *Subtarget) {
9428 // Only perform optimization if after legalize, and if NEON is available. We
9429 // also expected both operands to be BUILD_VECTORs.
9430 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9431 || N0.getOpcode() != ISD::BUILD_VECTOR
9432 || N1.getOpcode() != ISD::BUILD_VECTOR)
9435 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9436 EVT VT = N->getValueType(0);
9437 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9440 // Check that the vector operands are of the right form.
9441 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9442 // operands, where N is the size of the formed vector.
9443 // Each EXTRACT_VECTOR should have the same input vector and odd or even
9444 // index such that we have a pair wise add pattern.
9446 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9447 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9449 SDValue Vec = N0->getOperand(0)->getOperand(0);
9450 SDNode *V = Vec.getNode();
9451 unsigned nextIndex = 0;
9453 // For each operands to the ADD which are BUILD_VECTORs,
9454 // check to see if each of their operands are an EXTRACT_VECTOR with
9455 // the same vector and appropriate index.
9456 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9457 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9458 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9460 SDValue ExtVec0 = N0->getOperand(i);
9461 SDValue ExtVec1 = N1->getOperand(i);
9463 // First operand is the vector, verify its the same.
9464 if (V != ExtVec0->getOperand(0).getNode() ||
9465 V != ExtVec1->getOperand(0).getNode())
9468 // Second is the constant, verify its correct.
9469 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9470 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9472 // For the constant, we want to see all the even or all the odd.
9473 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9474 || C1->getZExtValue() != nextIndex+1)
9483 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9484 // we're using the entire input vector, otherwise there's a size/legality
9485 // mismatch somewhere.
9486 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9487 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9490 // Create VPADDL node.
9491 SelectionDAG &DAG = DCI.DAG;
9492 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9496 // Build operand list.
9497 SmallVector<SDValue, 8> Ops;
9498 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9499 TLI.getPointerTy(DAG.getDataLayout())));
9501 // Input is the vector.
9504 // Get widened type and narrowed type.
9506 unsigned numElem = VT.getVectorNumElements();
9508 EVT inputLaneType = Vec.getValueType().getVectorElementType();
9509 switch (inputLaneType.getSimpleVT().SimpleTy) {
9510 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9511 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9512 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9514 llvm_unreachable("Invalid vector element type for padd optimization.");
9517 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9518 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9519 return DAG.getNode(ExtOp, dl, VT, tmp);
9522 static SDValue findMUL_LOHI(SDValue V) {
9523 if (V->getOpcode() == ISD::UMUL_LOHI ||
9524 V->getOpcode() == ISD::SMUL_LOHI)
9529 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9530 TargetLowering::DAGCombinerInfo &DCI,
9531 const ARMSubtarget *Subtarget) {
9533 if (Subtarget->isThumb()) {
9534 if (!Subtarget->hasDSP())
9536 } else if (!Subtarget->hasV5TEOps())
9539 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9540 // accumulates the product into a 64-bit value. The 16-bit values will
9541 // be sign extended somehow or SRA'd into 32-bit values
9542 // (addc (adde (mul 16bit, 16bit), lo), hi)
9543 SDValue Mul = AddcNode->getOperand(0);
9544 SDValue Lo = AddcNode->getOperand(1);
9545 if (Mul.getOpcode() != ISD::MUL) {
9546 Lo = AddcNode->getOperand(0);
9547 Mul = AddcNode->getOperand(1);
9548 if (Mul.getOpcode() != ISD::MUL)
9552 SDValue SRA = AddeNode->getOperand(0);
9553 SDValue Hi = AddeNode->getOperand(1);
9554 if (SRA.getOpcode() != ISD::SRA) {
9555 SRA = AddeNode->getOperand(1);
9556 Hi = AddeNode->getOperand(0);
9557 if (SRA.getOpcode() != ISD::SRA)
9560 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9561 if (Const->getZExtValue() != 31)
9566 if (SRA.getOperand(0) != Mul)
9569 SelectionDAG &DAG = DCI.DAG;
9571 unsigned Opcode = 0;
9575 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9576 Opcode = ARMISD::SMLALBB;
9577 Op0 = Mul.getOperand(0);
9578 Op1 = Mul.getOperand(1);
9579 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9580 Opcode = ARMISD::SMLALBT;
9581 Op0 = Mul.getOperand(0);
9582 Op1 = Mul.getOperand(1).getOperand(0);
9583 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9584 Opcode = ARMISD::SMLALTB;
9585 Op0 = Mul.getOperand(0).getOperand(0);
9586 Op1 = Mul.getOperand(1);
9587 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9588 Opcode = ARMISD::SMLALTT;
9589 Op0 = Mul->getOperand(0).getOperand(0);
9590 Op1 = Mul->getOperand(1).getOperand(0);
9596 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9598 // Replace the ADDs' nodes uses by the MLA node's values.
9599 SDValue HiMLALResult(SMLAL.getNode(), 1);
9600 SDValue LoMLALResult(SMLAL.getNode(), 0);
9602 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9603 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9605 // Return original node to notify the driver to stop replacing.
9606 SDValue resNode(AddcNode, 0);
9610 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9611 TargetLowering::DAGCombinerInfo &DCI,
9612 const ARMSubtarget *Subtarget) {
9613 // Look for multiply add opportunities.
9614 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9615 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9616 // a glue link from the first add to the second add.
9617 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9618 // a S/UMLAL instruction.
9621 // / \ [no multiline comment]
9627 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9629 assert(AddeNode->getNumOperands() == 3 &&
9630 AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9631 "ADDE node has the wrong inputs");
9633 // Check that we have a glued ADDC node.
9634 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9635 if (AddcNode->getOpcode() != ARMISD::ADDC)
9638 SDValue AddcOp0 = AddcNode->getOperand(0);
9639 SDValue AddcOp1 = AddcNode->getOperand(1);
9641 // Check if the two operands are from the same mul_lohi node.
9642 if (AddcOp0.getNode() == AddcOp1.getNode())
9645 assert(AddcNode->getNumValues() == 2 &&
9646 AddcNode->getValueType(0) == MVT::i32 &&
9647 "Expect ADDC with two result values. First: i32");
9649 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9650 // maybe a SMLAL which multiplies two 16-bit values.
9651 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9652 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9653 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9654 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9655 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9657 // Check for the triangle shape.
9658 SDValue AddeOp0 = AddeNode->getOperand(0);
9659 SDValue AddeOp1 = AddeNode->getOperand(1);
9661 // Make sure that the ADDE operands are not coming from the same node.
9662 if (AddeOp0.getNode() == AddeOp1.getNode())
9665 // Find the MUL_LOHI node walking up ADDE's operands.
9666 bool IsLeftOperandMUL = false;
9667 SDValue MULOp = findMUL_LOHI(AddeOp0);
9668 if (MULOp == SDValue())
9669 MULOp = findMUL_LOHI(AddeOp1);
9671 IsLeftOperandMUL = true;
9672 if (MULOp == SDValue())
9675 // Figure out the right opcode.
9676 unsigned Opc = MULOp->getOpcode();
9677 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9679 // Figure out the high and low input values to the MLAL node.
9680 SDValue* HiAdd = nullptr;
9681 SDValue* LoMul = nullptr;
9682 SDValue* LowAdd = nullptr;
9684 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9685 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9688 if (IsLeftOperandMUL)
9694 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9695 // whose low result is fed to the ADDC we are checking.
9697 if (AddcOp0 == MULOp.getValue(0)) {
9701 if (AddcOp1 == MULOp.getValue(0)) {
9709 // Create the merged node.
9710 SelectionDAG &DAG = DCI.DAG;
9712 // Build operand list.
9713 SmallVector<SDValue, 8> Ops;
9714 Ops.push_back(LoMul->getOperand(0));
9715 Ops.push_back(LoMul->getOperand(1));
9716 Ops.push_back(*LowAdd);
9717 Ops.push_back(*HiAdd);
9719 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
9720 DAG.getVTList(MVT::i32, MVT::i32), Ops);
9722 // Replace the ADDs' nodes uses by the MLA node's values.
9723 SDValue HiMLALResult(MLALNode.getNode(), 1);
9724 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9726 SDValue LoMLALResult(MLALNode.getNode(), 0);
9727 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9729 // Return original node to notify the driver to stop replacing.
9730 return SDValue(AddeNode, 0);
9733 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9734 TargetLowering::DAGCombinerInfo &DCI,
9735 const ARMSubtarget *Subtarget) {
9736 // UMAAL is similar to UMLAL except that it adds two unsigned values.
9737 // While trying to combine for the other MLAL nodes, first search for the
9738 // chance to use UMAAL. Check if Addc uses a node which has already
9739 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9740 // as the addend, and it's handled in PerformUMLALCombine.
9742 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9743 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9745 // Check that we have a glued ADDC node.
9746 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9747 if (AddcNode->getOpcode() != ARMISD::ADDC)
9750 // Find the converted UMAAL or quit if it doesn't exist.
9751 SDNode *UmlalNode = nullptr;
9753 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9754 UmlalNode = AddcNode->getOperand(0).getNode();
9755 AddHi = AddcNode->getOperand(1);
9756 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9757 UmlalNode = AddcNode->getOperand(1).getNode();
9758 AddHi = AddcNode->getOperand(0);
9760 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9763 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9764 // the ADDC as well as Zero.
9765 if (!isNullConstant(UmlalNode->getOperand(3)))
9768 if ((isNullConstant(AddeNode->getOperand(0)) &&
9769 AddeNode->getOperand(1).getNode() == UmlalNode) ||
9770 (AddeNode->getOperand(0).getNode() == UmlalNode &&
9771 isNullConstant(AddeNode->getOperand(1)))) {
9773 SelectionDAG &DAG = DCI.DAG;
9774 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9775 UmlalNode->getOperand(2), AddHi };
9776 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9777 DAG.getVTList(MVT::i32, MVT::i32), Ops);
9779 // Replace the ADDs' nodes uses by the UMAAL node's values.
9780 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9781 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9783 // Return original node to notify the driver to stop replacing.
9784 return SDValue(AddeNode, 0);
9789 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9790 const ARMSubtarget *Subtarget) {
9791 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9794 // Check that we have a pair of ADDC and ADDE as operands.
9795 // Both addends of the ADDE must be zero.
9796 SDNode* AddcNode = N->getOperand(2).getNode();
9797 SDNode* AddeNode = N->getOperand(3).getNode();
9798 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9799 (AddeNode->getOpcode() == ARMISD::ADDE) &&
9800 isNullConstant(AddeNode->getOperand(0)) &&
9801 isNullConstant(AddeNode->getOperand(1)) &&
9802 (AddeNode->getOperand(2).getNode() == AddcNode))
9803 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9804 DAG.getVTList(MVT::i32, MVT::i32),
9805 {N->getOperand(0), N->getOperand(1),
9806 AddcNode->getOperand(0), AddcNode->getOperand(1)});
9811 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG,
9812 const ARMSubtarget *Subtarget) {
9813 if (Subtarget->isThumb1Only()) {
9814 SDValue RHS = N->getOperand(1);
9815 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9816 int32_t imm = C->getSExtValue();
9817 if (imm < 0 && imm > INT_MIN) {
9819 RHS = DAG.getConstant(-imm, DL, MVT::i32);
9820 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
9822 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
9829 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
9830 const ARMSubtarget *Subtarget) {
9831 if (Subtarget->isThumb1Only()) {
9832 SDValue RHS = N->getOperand(1);
9833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9834 int64_t imm = C->getSExtValue();
9838 // The with-carry-in form matches bitwise not instead of the negation.
9839 // Effectively, the inverse interpretation of the carry flag already
9840 // accounts for part of the negation.
9841 RHS = DAG.getConstant(~imm, DL, MVT::i32);
9843 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
9845 return DAG.getNode(Opcode, DL, N->getVTList(),
9846 N->getOperand(0), RHS, N->getOperand(2));
9853 /// PerformADDECombine - Target-specific dag combine transform from
9854 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
9855 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9856 static SDValue PerformADDECombine(SDNode *N,
9857 TargetLowering::DAGCombinerInfo &DCI,
9858 const ARMSubtarget *Subtarget) {
9859 // Only ARM and Thumb2 support UMLAL/SMLAL.
9860 if (Subtarget->isThumb1Only())
9861 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
9863 // Only perform the checks after legalize when the pattern is available.
9864 if (DCI.isBeforeLegalize()) return SDValue();
9866 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9869 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9870 /// operands N0 and N1. This is a helper for PerformADDCombine that is
9871 /// called with the default operands, and if that fails, with commuted
9873 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9874 TargetLowering::DAGCombinerInfo &DCI,
9875 const ARMSubtarget *Subtarget){
9876 // Attempt to create vpadd for this add.
9877 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
9880 // Attempt to create vpaddl for this add.
9881 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
9883 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
9887 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9888 if (N0.getNode()->hasOneUse())
9889 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9894 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9896 static SDValue PerformADDCombine(SDNode *N,
9897 TargetLowering::DAGCombinerInfo &DCI,
9898 const ARMSubtarget *Subtarget) {
9899 SDValue N0 = N->getOperand(0);
9900 SDValue N1 = N->getOperand(1);
9902 // First try with the default operand order.
9903 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9906 // If that didn't work, try again with the operands commuted.
9907 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9910 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9912 static SDValue PerformSUBCombine(SDNode *N,
9913 TargetLowering::DAGCombinerInfo &DCI) {
9914 SDValue N0 = N->getOperand(0);
9915 SDValue N1 = N->getOperand(1);
9917 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9918 if (N1.getNode()->hasOneUse())
9919 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9925 /// PerformVMULCombine
9926 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9927 /// special multiplier accumulator forwarding.
9933 // However, for (A + B) * (A + B),
9940 static SDValue PerformVMULCombine(SDNode *N,
9941 TargetLowering::DAGCombinerInfo &DCI,
9942 const ARMSubtarget *Subtarget) {
9943 if (!Subtarget->hasVMLxForwarding())
9946 SelectionDAG &DAG = DCI.DAG;
9947 SDValue N0 = N->getOperand(0);
9948 SDValue N1 = N->getOperand(1);
9949 unsigned Opcode = N0.getOpcode();
9950 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9951 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9952 Opcode = N1.getOpcode();
9953 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9954 Opcode != ISD::FADD && Opcode != ISD::FSUB)
9962 EVT VT = N->getValueType(0);
9964 SDValue N00 = N0->getOperand(0);
9965 SDValue N01 = N0->getOperand(1);
9966 return DAG.getNode(Opcode, DL, VT,
9967 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9968 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9971 static SDValue PerformMULCombine(SDNode *N,
9972 TargetLowering::DAGCombinerInfo &DCI,
9973 const ARMSubtarget *Subtarget) {
9974 SelectionDAG &DAG = DCI.DAG;
9976 if (Subtarget->isThumb1Only())
9979 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9982 EVT VT = N->getValueType(0);
9983 if (VT.is64BitVector() || VT.is128BitVector())
9984 return PerformVMULCombine(N, DCI, Subtarget);
9988 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9992 int64_t MulAmt = C->getSExtValue();
9993 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9995 ShiftAmt = ShiftAmt & (32 - 1);
9996 SDValue V = N->getOperand(0);
10000 MulAmt >>= ShiftAmt;
10003 if (isPowerOf2_32(MulAmt - 1)) {
10004 // (mul x, 2^N + 1) => (add (shl x, N), x)
10005 Res = DAG.getNode(ISD::ADD, DL, VT,
10007 DAG.getNode(ISD::SHL, DL, VT,
10009 DAG.getConstant(Log2_32(MulAmt - 1), DL,
10011 } else if (isPowerOf2_32(MulAmt + 1)) {
10012 // (mul x, 2^N - 1) => (sub (shl x, N), x)
10013 Res = DAG.getNode(ISD::SUB, DL, VT,
10014 DAG.getNode(ISD::SHL, DL, VT,
10016 DAG.getConstant(Log2_32(MulAmt + 1), DL,
10022 uint64_t MulAmtAbs = -MulAmt;
10023 if (isPowerOf2_32(MulAmtAbs + 1)) {
10024 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10025 Res = DAG.getNode(ISD::SUB, DL, VT,
10027 DAG.getNode(ISD::SHL, DL, VT,
10029 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10031 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10032 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10033 Res = DAG.getNode(ISD::ADD, DL, VT,
10035 DAG.getNode(ISD::SHL, DL, VT,
10037 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10039 Res = DAG.getNode(ISD::SUB, DL, VT,
10040 DAG.getConstant(0, DL, MVT::i32), Res);
10047 Res = DAG.getNode(ISD::SHL, DL, VT,
10048 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10050 // Do not add new nodes to DAG combiner worklist.
10051 DCI.CombineTo(N, Res, false);
10055 static SDValue PerformANDCombine(SDNode *N,
10056 TargetLowering::DAGCombinerInfo &DCI,
10057 const ARMSubtarget *Subtarget) {
10058 // Attempt to use immediate-form VBIC
10059 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10061 EVT VT = N->getValueType(0);
10062 SelectionDAG &DAG = DCI.DAG;
10064 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10067 APInt SplatBits, SplatUndef;
10068 unsigned SplatBitSize;
10071 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10072 if (SplatBitSize <= 64) {
10074 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10075 SplatUndef.getZExtValue(), SplatBitSize,
10076 DAG, dl, VbicVT, VT.is128BitVector(),
10078 if (Val.getNode()) {
10080 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10081 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10082 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10087 if (!Subtarget->isThumb1Only()) {
10088 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10089 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10096 // Try combining OR nodes to SMULWB, SMULWT.
10097 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10098 TargetLowering::DAGCombinerInfo &DCI,
10099 const ARMSubtarget *Subtarget) {
10100 if (!Subtarget->hasV6Ops() ||
10101 (Subtarget->isThumb() &&
10102 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10105 SDValue SRL = OR->getOperand(0);
10106 SDValue SHL = OR->getOperand(1);
10108 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10109 SRL = OR->getOperand(1);
10110 SHL = OR->getOperand(0);
10112 if (!isSRL16(SRL) || !isSHL16(SHL))
10115 // The first operands to the shifts need to be the two results from the
10116 // same smul_lohi node.
10117 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10118 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10121 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10122 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10123 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10127 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10128 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10129 // For SMUWB the 16-bit value will signed extended somehow.
10130 // For SMULWT only the SRA is required.
10131 // Check both sides of SMUL_LOHI
10132 SDValue OpS16 = SMULLOHI->getOperand(0);
10133 SDValue OpS32 = SMULLOHI->getOperand(1);
10135 SelectionDAG &DAG = DCI.DAG;
10136 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10138 OpS32 = SMULLOHI->getOperand(0);
10142 unsigned Opcode = 0;
10143 if (isS16(OpS16, DAG))
10144 Opcode = ARMISD::SMULWB;
10145 else if (isSRA16(OpS16)) {
10146 Opcode = ARMISD::SMULWT;
10147 OpS16 = OpS16->getOperand(0);
10152 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10153 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10154 return SDValue(OR, 0);
10157 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10158 static SDValue PerformORCombine(SDNode *N,
10159 TargetLowering::DAGCombinerInfo &DCI,
10160 const ARMSubtarget *Subtarget) {
10161 // Attempt to use immediate-form VORR
10162 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10164 EVT VT = N->getValueType(0);
10165 SelectionDAG &DAG = DCI.DAG;
10167 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10170 APInt SplatBits, SplatUndef;
10171 unsigned SplatBitSize;
10173 if (BVN && Subtarget->hasNEON() &&
10174 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10175 if (SplatBitSize <= 64) {
10177 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10178 SplatUndef.getZExtValue(), SplatBitSize,
10179 DAG, dl, VorrVT, VT.is128BitVector(),
10181 if (Val.getNode()) {
10183 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10184 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10185 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10190 if (!Subtarget->isThumb1Only()) {
10191 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10192 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10194 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10198 // The code below optimizes (or (and X, Y), Z).
10199 // The AND operand needs to have a single user to make these optimizations
10201 SDValue N0 = N->getOperand(0);
10202 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10204 SDValue N1 = N->getOperand(1);
10206 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10207 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10208 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10210 unsigned SplatBitSize;
10213 APInt SplatBits0, SplatBits1;
10214 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10215 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10216 // Ensure that the second operand of both ands are constants
10217 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10218 HasAnyUndefs) && !HasAnyUndefs) {
10219 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10220 HasAnyUndefs) && !HasAnyUndefs) {
10221 // Ensure that the bit width of the constants are the same and that
10222 // the splat arguments are logical inverses as per the pattern we
10223 // are trying to simplify.
10224 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10225 SplatBits0 == ~SplatBits1) {
10226 // Canonicalize the vector type to make instruction selection
10228 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10229 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10232 N1->getOperand(0));
10233 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10239 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10242 // BFI is only available on V6T2+
10243 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10247 // 1) or (and A, mask), val => ARMbfi A, val, mask
10248 // iff (val & mask) == val
10250 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10251 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10252 // && mask == ~mask2
10253 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10254 // && ~mask == mask2
10255 // (i.e., copy a bitfield value into another bitfield of the same width)
10257 if (VT != MVT::i32)
10260 SDValue N00 = N0.getOperand(0);
10262 // The value and the mask need to be constants so we can verify this is
10263 // actually a bitfield set. If the mask is 0xffff, we can do better
10264 // via a movt instruction, so don't use BFI in that case.
10265 SDValue MaskOp = N0.getOperand(1);
10266 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10269 unsigned Mask = MaskC->getZExtValue();
10270 if (Mask == 0xffff)
10273 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10274 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10276 unsigned Val = N1C->getZExtValue();
10277 if ((Val & ~Mask) != Val)
10280 if (ARM::isBitFieldInvertedMask(Mask)) {
10281 Val >>= countTrailingZeros(~Mask);
10283 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10284 DAG.getConstant(Val, DL, MVT::i32),
10285 DAG.getConstant(Mask, DL, MVT::i32));
10287 // Do not add new nodes to DAG combiner worklist.
10288 DCI.CombineTo(N, Res, false);
10291 } else if (N1.getOpcode() == ISD::AND) {
10292 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10293 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10296 unsigned Mask2 = N11C->getZExtValue();
10298 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10300 if (ARM::isBitFieldInvertedMask(Mask) &&
10301 (Mask == ~Mask2)) {
10302 // The pack halfword instruction works better for masks that fit it,
10303 // so use that when it's available.
10304 if (Subtarget->hasDSP() &&
10305 (Mask == 0xffff || Mask == 0xffff0000))
10308 unsigned amt = countTrailingZeros(Mask2);
10309 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10310 DAG.getConstant(amt, DL, MVT::i32));
10311 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10312 DAG.getConstant(Mask, DL, MVT::i32));
10313 // Do not add new nodes to DAG combiner worklist.
10314 DCI.CombineTo(N, Res, false);
10316 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10317 (~Mask == Mask2)) {
10318 // The pack halfword instruction works better for masks that fit it,
10319 // so use that when it's available.
10320 if (Subtarget->hasDSP() &&
10321 (Mask2 == 0xffff || Mask2 == 0xffff0000))
10324 unsigned lsb = countTrailingZeros(Mask);
10325 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10326 DAG.getConstant(lsb, DL, MVT::i32));
10327 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10328 DAG.getConstant(Mask2, DL, MVT::i32));
10329 // Do not add new nodes to DAG combiner worklist.
10330 DCI.CombineTo(N, Res, false);
10335 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10336 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10337 ARM::isBitFieldInvertedMask(~Mask)) {
10338 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10339 // where lsb(mask) == #shamt and masked bits of B are known zero.
10340 SDValue ShAmt = N00.getOperand(1);
10341 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10342 unsigned LSB = countTrailingZeros(Mask);
10346 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10347 DAG.getConstant(~Mask, DL, MVT::i32));
10349 // Do not add new nodes to DAG combiner worklist.
10350 DCI.CombineTo(N, Res, false);
10356 static SDValue PerformXORCombine(SDNode *N,
10357 TargetLowering::DAGCombinerInfo &DCI,
10358 const ARMSubtarget *Subtarget) {
10359 EVT VT = N->getValueType(0);
10360 SelectionDAG &DAG = DCI.DAG;
10362 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10365 if (!Subtarget->isThumb1Only()) {
10366 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10367 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10374 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10375 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10376 // their position in "to" (Rd).
10377 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10378 assert(N->getOpcode() == ARMISD::BFI);
10380 SDValue From = N->getOperand(1);
10381 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10382 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10384 // If the Base came from a SHR #C, we can deduce that it is really testing bit
10385 // #C in the base of the SHR.
10386 if (From->getOpcode() == ISD::SRL &&
10387 isa<ConstantSDNode>(From->getOperand(1))) {
10388 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10389 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10390 FromMask <<= Shift.getLimitedValue(31);
10391 From = From->getOperand(0);
10397 // If A and B contain one contiguous set of bits, does A | B == A . B?
10399 // Neither A nor B must be zero.
10400 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10401 unsigned LastActiveBitInA = A.countTrailingZeros();
10402 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10403 return LastActiveBitInA - 1 == FirstActiveBitInB;
10406 static SDValue FindBFIToCombineWith(SDNode *N) {
10407 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10409 APInt ToMask, FromMask;
10410 SDValue From = ParseBFI(N, ToMask, FromMask);
10411 SDValue To = N->getOperand(0);
10413 // Now check for a compatible BFI to merge with. We can pass through BFIs that
10414 // aren't compatible, but not if they set the same bit in their destination as
10415 // we do (or that of any BFI we're going to combine with).
10417 APInt CombinedToMask = ToMask;
10418 while (V.getOpcode() == ARMISD::BFI) {
10419 APInt NewToMask, NewFromMask;
10420 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10421 if (NewFrom != From) {
10422 // This BFI has a different base. Keep going.
10423 CombinedToMask |= NewToMask;
10424 V = V.getOperand(0);
10428 // Do the written bits conflict with any we've seen so far?
10429 if ((NewToMask & CombinedToMask).getBoolValue())
10430 // Conflicting bits - bail out because going further is unsafe.
10433 // Are the new bits contiguous when combined with the old bits?
10434 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10435 BitsProperlyConcatenate(FromMask, NewFromMask))
10437 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10438 BitsProperlyConcatenate(NewFromMask, FromMask))
10441 // We've seen a write to some bits, so track it.
10442 CombinedToMask |= NewToMask;
10444 V = V.getOperand(0);
10450 static SDValue PerformBFICombine(SDNode *N,
10451 TargetLowering::DAGCombinerInfo &DCI) {
10452 SDValue N1 = N->getOperand(1);
10453 if (N1.getOpcode() == ISD::AND) {
10454 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10455 // the bits being cleared by the AND are not demanded by the BFI.
10456 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10459 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10460 unsigned LSB = countTrailingZeros(~InvMask);
10461 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10463 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10464 "undefined behavior");
10465 unsigned Mask = (1u << Width) - 1;
10466 unsigned Mask2 = N11C->getZExtValue();
10467 if ((Mask & (~Mask2)) == 0)
10468 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10469 N->getOperand(0), N1.getOperand(0),
10471 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10472 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10473 // Keep track of any consecutive bits set that all come from the same base
10474 // value. We can combine these together into a single BFI.
10475 SDValue CombineBFI = FindBFIToCombineWith(N);
10476 if (CombineBFI == SDValue())
10479 // We've found a BFI.
10480 APInt ToMask1, FromMask1;
10481 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10483 APInt ToMask2, FromMask2;
10484 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10485 assert(From1 == From2);
10488 // First, unlink CombineBFI.
10489 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10490 // Then create a new BFI, combining the two together.
10491 APInt NewFromMask = FromMask1 | FromMask2;
10492 APInt NewToMask = ToMask1 | ToMask2;
10494 EVT VT = N->getValueType(0);
10497 if (NewFromMask[0] == 0)
10498 From1 = DCI.DAG.getNode(
10499 ISD::SRL, dl, VT, From1,
10500 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10501 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10502 DCI.DAG.getConstant(~NewToMask, dl, VT));
10507 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10508 /// ARMISD::VMOVRRD.
10509 static SDValue PerformVMOVRRDCombine(SDNode *N,
10510 TargetLowering::DAGCombinerInfo &DCI,
10511 const ARMSubtarget *Subtarget) {
10512 // vmovrrd(vmovdrr x, y) -> x,y
10513 SDValue InDouble = N->getOperand(0);
10514 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10515 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10517 // vmovrrd(load f64) -> (load i32), (load i32)
10518 SDNode *InNode = InDouble.getNode();
10519 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10520 InNode->getValueType(0) == MVT::f64 &&
10521 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10522 !cast<LoadSDNode>(InNode)->isVolatile()) {
10523 // TODO: Should this be done for non-FrameIndex operands?
10524 LoadSDNode *LD = cast<LoadSDNode>(InNode);
10526 SelectionDAG &DAG = DCI.DAG;
10528 SDValue BasePtr = LD->getBasePtr();
10530 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10531 LD->getAlignment(), LD->getMemOperand()->getFlags());
10533 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10534 DAG.getConstant(4, DL, MVT::i32));
10535 SDValue NewLD2 = DAG.getLoad(
10536 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10537 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10539 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10540 if (DCI.DAG.getDataLayout().isBigEndian())
10541 std::swap (NewLD1, NewLD2);
10542 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10549 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10550 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
10551 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10552 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10553 SDValue Op0 = N->getOperand(0);
10554 SDValue Op1 = N->getOperand(1);
10555 if (Op0.getOpcode() == ISD::BITCAST)
10556 Op0 = Op0.getOperand(0);
10557 if (Op1.getOpcode() == ISD::BITCAST)
10558 Op1 = Op1.getOperand(0);
10559 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10560 Op0.getNode() == Op1.getNode() &&
10561 Op0.getResNo() == 0 && Op1.getResNo() == 1)
10562 return DAG.getNode(ISD::BITCAST, SDLoc(N),
10563 N->getValueType(0), Op0.getOperand(0));
10567 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10568 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
10569 /// i64 vector to have f64 elements, since the value can then be loaded
10570 /// directly into a VFP register.
10571 static bool hasNormalLoadOperand(SDNode *N) {
10572 unsigned NumElts = N->getValueType(0).getVectorNumElements();
10573 for (unsigned i = 0; i < NumElts; ++i) {
10574 SDNode *Elt = N->getOperand(i).getNode();
10575 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10581 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10582 /// ISD::BUILD_VECTOR.
10583 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10584 TargetLowering::DAGCombinerInfo &DCI,
10585 const ARMSubtarget *Subtarget) {
10586 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10587 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
10588 // into a pair of GPRs, which is fine when the value is used as a scalar,
10589 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10590 SelectionDAG &DAG = DCI.DAG;
10591 if (N->getNumOperands() == 2)
10592 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10595 // Load i64 elements as f64 values so that type legalization does not split
10596 // them up into i32 values.
10597 EVT VT = N->getValueType(0);
10598 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10601 SmallVector<SDValue, 8> Ops;
10602 unsigned NumElts = VT.getVectorNumElements();
10603 for (unsigned i = 0; i < NumElts; ++i) {
10604 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10606 // Make the DAGCombiner fold the bitcast.
10607 DCI.AddToWorklist(V.getNode());
10609 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10610 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10611 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10614 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10616 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10617 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10618 // At that time, we may have inserted bitcasts from integer to float.
10619 // If these bitcasts have survived DAGCombine, change the lowering of this
10620 // BUILD_VECTOR in something more vector friendly, i.e., that does not
10621 // force to use floating point types.
10623 // Make sure we can change the type of the vector.
10624 // This is possible iff:
10625 // 1. The vector is only used in a bitcast to a integer type. I.e.,
10626 // 1.1. Vector is used only once.
10627 // 1.2. Use is a bit convert to an integer type.
10628 // 2. The size of its operands are 32-bits (64-bits are not legal).
10629 EVT VT = N->getValueType(0);
10630 EVT EltVT = VT.getVectorElementType();
10632 // Check 1.1. and 2.
10633 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10636 // By construction, the input type must be float.
10637 assert(EltVT == MVT::f32 && "Unexpected type!");
10640 SDNode *Use = *N->use_begin();
10641 if (Use->getOpcode() != ISD::BITCAST ||
10642 Use->getValueType(0).isFloatingPoint())
10645 // Check profitability.
10646 // Model is, if more than half of the relevant operands are bitcast from
10647 // i32, turn the build_vector into a sequence of insert_vector_elt.
10648 // Relevant operands are everything that is not statically
10649 // (i.e., at compile time) bitcasted.
10650 unsigned NumOfBitCastedElts = 0;
10651 unsigned NumElts = VT.getVectorNumElements();
10652 unsigned NumOfRelevantElts = NumElts;
10653 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10654 SDValue Elt = N->getOperand(Idx);
10655 if (Elt->getOpcode() == ISD::BITCAST) {
10656 // Assume only bit cast to i32 will go away.
10657 if (Elt->getOperand(0).getValueType() == MVT::i32)
10658 ++NumOfBitCastedElts;
10659 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10660 // Constants are statically casted, thus do not count them as
10661 // relevant operands.
10662 --NumOfRelevantElts;
10665 // Check if more than half of the elements require a non-free bitcast.
10666 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10669 SelectionDAG &DAG = DCI.DAG;
10670 // Create the new vector type.
10671 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10672 // Check if the type is legal.
10673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10674 if (!TLI.isTypeLegal(VecVT))
10678 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10679 // => BITCAST INSERT_VECTOR_ELT
10680 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10681 // (BITCAST EN), N.
10682 SDValue Vec = DAG.getUNDEF(VecVT);
10684 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10685 SDValue V = N->getOperand(Idx);
10688 if (V.getOpcode() == ISD::BITCAST &&
10689 V->getOperand(0).getValueType() == MVT::i32)
10690 // Fold obvious case.
10691 V = V.getOperand(0);
10693 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10694 // Make the DAGCombiner fold the bitcasts.
10695 DCI.AddToWorklist(V.getNode());
10697 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10698 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10700 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10701 // Make the DAGCombiner fold the bitcasts.
10702 DCI.AddToWorklist(Vec.getNode());
10706 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10707 /// ISD::INSERT_VECTOR_ELT.
10708 static SDValue PerformInsertEltCombine(SDNode *N,
10709 TargetLowering::DAGCombinerInfo &DCI) {
10710 // Bitcast an i64 load inserted into a vector to f64.
10711 // Otherwise, the i64 value will be legalized to a pair of i32 values.
10712 EVT VT = N->getValueType(0);
10713 SDNode *Elt = N->getOperand(1).getNode();
10714 if (VT.getVectorElementType() != MVT::i64 ||
10715 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10718 SelectionDAG &DAG = DCI.DAG;
10720 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10721 VT.getVectorNumElements());
10722 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10723 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10724 // Make the DAGCombiner fold the bitcasts.
10725 DCI.AddToWorklist(Vec.getNode());
10726 DCI.AddToWorklist(V.getNode());
10727 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10728 Vec, V, N->getOperand(2));
10729 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10732 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10733 /// ISD::VECTOR_SHUFFLE.
10734 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10735 // The LLVM shufflevector instruction does not require the shuffle mask
10736 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10737 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
10738 // operands do not match the mask length, they are extended by concatenating
10739 // them with undef vectors. That is probably the right thing for other
10740 // targets, but for NEON it is better to concatenate two double-register
10741 // size vector operands into a single quad-register size vector. Do that
10742 // transformation here:
10743 // shuffle(concat(v1, undef), concat(v2, undef)) ->
10744 // shuffle(concat(v1, v2), undef)
10745 SDValue Op0 = N->getOperand(0);
10746 SDValue Op1 = N->getOperand(1);
10747 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10748 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10749 Op0.getNumOperands() != 2 ||
10750 Op1.getNumOperands() != 2)
10752 SDValue Concat0Op1 = Op0.getOperand(1);
10753 SDValue Concat1Op1 = Op1.getOperand(1);
10754 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10756 // Skip the transformation if any of the types are illegal.
10757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10758 EVT VT = N->getValueType(0);
10759 if (!TLI.isTypeLegal(VT) ||
10760 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10761 !TLI.isTypeLegal(Concat1Op1.getValueType()))
10764 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10765 Op0.getOperand(0), Op1.getOperand(0));
10766 // Translate the shuffle mask.
10767 SmallVector<int, 16> NewMask;
10768 unsigned NumElts = VT.getVectorNumElements();
10769 unsigned HalfElts = NumElts/2;
10770 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10771 for (unsigned n = 0; n < NumElts; ++n) {
10772 int MaskElt = SVN->getMaskElt(n);
10774 if (MaskElt < (int)HalfElts)
10776 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10777 NewElt = HalfElts + MaskElt - NumElts;
10778 NewMask.push_back(NewElt);
10780 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10781 DAG.getUNDEF(VT), NewMask);
10784 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10785 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10786 /// base address updates.
10787 /// For generic load/stores, the memory type is assumed to be a vector.
10788 /// The caller is assumed to have checked legality.
10789 static SDValue CombineBaseUpdate(SDNode *N,
10790 TargetLowering::DAGCombinerInfo &DCI) {
10791 SelectionDAG &DAG = DCI.DAG;
10792 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10793 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10794 const bool isStore = N->getOpcode() == ISD::STORE;
10795 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10796 SDValue Addr = N->getOperand(AddrOpIdx);
10797 MemSDNode *MemN = cast<MemSDNode>(N);
10800 // Search for a use of the address operand that is an increment.
10801 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10802 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10803 SDNode *User = *UI;
10804 if (User->getOpcode() != ISD::ADD ||
10805 UI.getUse().getResNo() != Addr.getResNo())
10808 // Check that the add is independent of the load/store. Otherwise, folding
10809 // it would create a cycle.
10810 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10813 // Find the new opcode for the updating load/store.
10814 bool isLoadOp = true;
10815 bool isLaneOp = false;
10816 unsigned NewOpc = 0;
10817 unsigned NumVecs = 0;
10819 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10821 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10822 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
10823 NumVecs = 1; break;
10824 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
10825 NumVecs = 2; break;
10826 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
10827 NumVecs = 3; break;
10828 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
10829 NumVecs = 4; break;
10830 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10831 NumVecs = 2; isLaneOp = true; break;
10832 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10833 NumVecs = 3; isLaneOp = true; break;
10834 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10835 NumVecs = 4; isLaneOp = true; break;
10836 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
10837 NumVecs = 1; isLoadOp = false; break;
10838 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
10839 NumVecs = 2; isLoadOp = false; break;
10840 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
10841 NumVecs = 3; isLoadOp = false; break;
10842 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
10843 NumVecs = 4; isLoadOp = false; break;
10844 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10845 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10846 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10847 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10848 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10849 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10853 switch (N->getOpcode()) {
10854 default: llvm_unreachable("unexpected opcode for Neon base update");
10855 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
10856 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10857 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10858 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10859 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
10860 NumVecs = 1; isLaneOp = false; break;
10861 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
10862 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10866 // Find the size of memory referenced by the load/store.
10869 VecTy = N->getValueType(0);
10870 } else if (isIntrinsic) {
10871 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10873 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10874 VecTy = N->getOperand(1).getValueType();
10877 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10879 NumBytes /= VecTy.getVectorNumElements();
10881 // If the increment is a constant, it must match the memory ref size.
10882 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10883 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
10884 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
10885 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10886 // separate instructions that make it harder to use a non-constant update.
10890 // OK, we found an ADD we can fold into the base update.
10891 // Now, create a _UPD node, taking care of not breaking alignment.
10893 EVT AlignedVecTy = VecTy;
10894 unsigned Alignment = MemN->getAlignment();
10896 // If this is a less-than-standard-aligned load/store, change the type to
10897 // match the standard alignment.
10898 // The alignment is overlooked when selecting _UPD variants; and it's
10899 // easier to introduce bitcasts here than fix that.
10900 // There are 3 ways to get to this base-update combine:
10901 // - intrinsics: they are assumed to be properly aligned (to the standard
10902 // alignment of the memory type), so we don't need to do anything.
10903 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10904 // intrinsics, so, likewise, there's nothing to do.
10905 // - generic load/store instructions: the alignment is specified as an
10906 // explicit operand, rather than implicitly as the standard alignment
10907 // of the memory type (like the intrisics). We need to change the
10908 // memory type to match the explicit alignment. That way, we don't
10909 // generate non-standard-aligned ARMISD::VLDx nodes.
10910 if (isa<LSBaseSDNode>(N)) {
10911 if (Alignment == 0)
10913 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10914 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10915 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10916 assert(!isLaneOp && "Unexpected generic load/store lane.");
10917 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10918 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10920 // Don't set an explicit alignment on regular load/stores that we want
10921 // to transform to VLD/VST 1_UPD nodes.
10922 // This matches the behavior of regular load/stores, which only get an
10923 // explicit alignment if the MMO alignment is larger than the standard
10924 // alignment of the memory type.
10925 // Intrinsics, however, always get an explicit alignment, set to the
10926 // alignment of the MMO.
10930 // Create the new updating load/store node.
10931 // First, create an SDVTList for the new updating node's results.
10933 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10935 for (n = 0; n < NumResultVecs; ++n)
10936 Tys[n] = AlignedVecTy;
10937 Tys[n++] = MVT::i32;
10938 Tys[n] = MVT::Other;
10939 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10941 // Then, gather the new node's operands.
10942 SmallVector<SDValue, 8> Ops;
10943 Ops.push_back(N->getOperand(0)); // incoming chain
10944 Ops.push_back(N->getOperand(AddrOpIdx));
10945 Ops.push_back(Inc);
10947 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10948 // Try to match the intrinsic's signature
10949 Ops.push_back(StN->getValue());
10951 // Loads (and of course intrinsics) match the intrinsics' signature,
10952 // so just add all but the alignment operand.
10953 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10954 Ops.push_back(N->getOperand(i));
10957 // For all node types, the alignment operand is always the last one.
10958 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10960 // If this is a non-standard-aligned STORE, the penultimate operand is the
10961 // stored value. Bitcast it to the aligned type.
10962 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10963 SDValue &StVal = Ops[Ops.size()-2];
10964 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10967 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
10968 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
10969 MemN->getMemOperand());
10971 // Update the uses.
10972 SmallVector<SDValue, 5> NewResults;
10973 for (unsigned i = 0; i < NumResultVecs; ++i)
10974 NewResults.push_back(SDValue(UpdN.getNode(), i));
10976 // If this is an non-standard-aligned LOAD, the first result is the loaded
10977 // value. Bitcast it to the expected result type.
10978 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10979 SDValue &LdVal = NewResults[0];
10980 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10983 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10984 DCI.CombineTo(N, NewResults);
10985 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10992 static SDValue PerformVLDCombine(SDNode *N,
10993 TargetLowering::DAGCombinerInfo &DCI) {
10994 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10997 return CombineBaseUpdate(N, DCI);
11000 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11001 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11002 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
11004 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11005 SelectionDAG &DAG = DCI.DAG;
11006 EVT VT = N->getValueType(0);
11007 // vldN-dup instructions only support 64-bit vectors for N > 1.
11008 if (!VT.is64BitVector())
11011 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11012 SDNode *VLD = N->getOperand(0).getNode();
11013 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11015 unsigned NumVecs = 0;
11016 unsigned NewOpc = 0;
11017 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11018 if (IntNo == Intrinsic::arm_neon_vld2lane) {
11020 NewOpc = ARMISD::VLD2DUP;
11021 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11023 NewOpc = ARMISD::VLD3DUP;
11024 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11026 NewOpc = ARMISD::VLD4DUP;
11031 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11032 // numbers match the load.
11033 unsigned VLDLaneNo =
11034 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11035 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11037 // Ignore uses of the chain result.
11038 if (UI.getUse().getResNo() == NumVecs)
11040 SDNode *User = *UI;
11041 if (User->getOpcode() != ARMISD::VDUPLANE ||
11042 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11046 // Create the vldN-dup node.
11049 for (n = 0; n < NumVecs; ++n)
11051 Tys[n] = MVT::Other;
11052 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11053 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11054 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11055 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11056 Ops, VLDMemInt->getMemoryVT(),
11057 VLDMemInt->getMemOperand());
11059 // Update the uses.
11060 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11062 unsigned ResNo = UI.getUse().getResNo();
11063 // Ignore uses of the chain result.
11064 if (ResNo == NumVecs)
11066 SDNode *User = *UI;
11067 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11070 // Now the vldN-lane intrinsic is dead except for its chain result.
11071 // Update uses of the chain.
11072 std::vector<SDValue> VLDDupResults;
11073 for (unsigned n = 0; n < NumVecs; ++n)
11074 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11075 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11076 DCI.CombineTo(VLD, VLDDupResults);
11081 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11082 /// ARMISD::VDUPLANE.
11083 static SDValue PerformVDUPLANECombine(SDNode *N,
11084 TargetLowering::DAGCombinerInfo &DCI) {
11085 SDValue Op = N->getOperand(0);
11087 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11088 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11089 if (CombineVLDDUP(N, DCI))
11090 return SDValue(N, 0);
11092 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11093 // redundant. Ignore bit_converts for now; element sizes are checked below.
11094 while (Op.getOpcode() == ISD::BITCAST)
11095 Op = Op.getOperand(0);
11096 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11099 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11100 unsigned EltSize = Op.getScalarValueSizeInBits();
11101 // The canonical VMOV for a zero vector uses a 32-bit element size.
11102 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11104 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11106 EVT VT = N->getValueType(0);
11107 if (EltSize > VT.getScalarSizeInBits())
11110 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11113 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11114 static SDValue PerformVDUPCombine(SDNode *N,
11115 TargetLowering::DAGCombinerInfo &DCI) {
11116 SelectionDAG &DAG = DCI.DAG;
11117 SDValue Op = N->getOperand(0);
11119 // Match VDUP(LOAD) -> VLD1DUP.
11120 // We match this pattern here rather than waiting for isel because the
11121 // transform is only legal for unindexed loads.
11122 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11123 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11124 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11125 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11126 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11127 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11128 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11129 Ops, LD->getMemoryVT(),
11130 LD->getMemOperand());
11131 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11138 static SDValue PerformLOADCombine(SDNode *N,
11139 TargetLowering::DAGCombinerInfo &DCI) {
11140 EVT VT = N->getValueType(0);
11142 // If this is a legal vector load, try to combine it into a VLD1_UPD.
11143 if (ISD::isNormalLoad(N) && VT.isVector() &&
11144 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11145 return CombineBaseUpdate(N, DCI);
11150 /// PerformSTORECombine - Target-specific dag combine xforms for
11152 static SDValue PerformSTORECombine(SDNode *N,
11153 TargetLowering::DAGCombinerInfo &DCI) {
11154 StoreSDNode *St = cast<StoreSDNode>(N);
11155 if (St->isVolatile())
11158 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
11159 // pack all of the elements in one place. Next, store to memory in fewer
11161 SDValue StVal = St->getValue();
11162 EVT VT = StVal.getValueType();
11163 if (St->isTruncatingStore() && VT.isVector()) {
11164 SelectionDAG &DAG = DCI.DAG;
11165 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11166 EVT StVT = St->getMemoryVT();
11167 unsigned NumElems = VT.getVectorNumElements();
11168 assert(StVT != VT && "Cannot truncate to the same type");
11169 unsigned FromEltSz = VT.getScalarSizeInBits();
11170 unsigned ToEltSz = StVT.getScalarSizeInBits();
11172 // From, To sizes and ElemCount must be pow of two
11173 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11175 // We are going to use the original vector elt for storing.
11176 // Accumulated smaller vector elements must be a multiple of the store size.
11177 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11179 unsigned SizeRatio = FromEltSz / ToEltSz;
11180 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11182 // Create a type on which we perform the shuffle.
11183 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11184 NumElems*SizeRatio);
11185 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11188 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11189 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11190 for (unsigned i = 0; i < NumElems; ++i)
11191 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11192 ? (i + 1) * SizeRatio - 1
11195 // Can't shuffle using an illegal type.
11196 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11198 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11199 DAG.getUNDEF(WideVec.getValueType()),
11201 // At this point all of the data is stored at the bottom of the
11202 // register. We now need to save it to mem.
11204 // Find the largest store unit
11205 MVT StoreType = MVT::i8;
11206 for (MVT Tp : MVT::integer_valuetypes()) {
11207 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11210 // Didn't find a legal store type.
11211 if (!TLI.isTypeLegal(StoreType))
11214 // Bitcast the original vector into a vector of store-size units
11215 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11216 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11217 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11218 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11219 SmallVector<SDValue, 8> Chains;
11220 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11221 TLI.getPointerTy(DAG.getDataLayout()));
11222 SDValue BasePtr = St->getBasePtr();
11224 // Perform one or more big stores into memory.
11225 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11226 for (unsigned I = 0; I < E; I++) {
11227 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11228 StoreType, ShuffWide,
11229 DAG.getIntPtrConstant(I, DL));
11230 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11231 St->getPointerInfo(), St->getAlignment(),
11232 St->getMemOperand()->getFlags());
11233 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11235 Chains.push_back(Ch);
11237 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11240 if (!ISD::isNormalStore(St))
11243 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11244 // ARM stores of arguments in the same cache line.
11245 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11246 StVal.getNode()->hasOneUse()) {
11247 SelectionDAG &DAG = DCI.DAG;
11248 bool isBigEndian = DAG.getDataLayout().isBigEndian();
11250 SDValue BasePtr = St->getBasePtr();
11251 SDValue NewST1 = DAG.getStore(
11252 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11253 BasePtr, St->getPointerInfo(), St->getAlignment(),
11254 St->getMemOperand()->getFlags());
11256 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11257 DAG.getConstant(4, DL, MVT::i32));
11258 return DAG.getStore(NewST1.getValue(0), DL,
11259 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11260 OffsetPtr, St->getPointerInfo(),
11261 std::min(4U, St->getAlignment() / 2),
11262 St->getMemOperand()->getFlags());
11265 if (StVal.getValueType() == MVT::i64 &&
11266 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11268 // Bitcast an i64 store extracted from a vector to f64.
11269 // Otherwise, the i64 value will be legalized to a pair of i32 values.
11270 SelectionDAG &DAG = DCI.DAG;
11272 SDValue IntVec = StVal.getOperand(0);
11273 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11274 IntVec.getValueType().getVectorNumElements());
11275 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11276 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11277 Vec, StVal.getOperand(1));
11279 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11280 // Make the DAGCombiner fold the bitcasts.
11281 DCI.AddToWorklist(Vec.getNode());
11282 DCI.AddToWorklist(ExtElt.getNode());
11283 DCI.AddToWorklist(V.getNode());
11284 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11285 St->getPointerInfo(), St->getAlignment(),
11286 St->getMemOperand()->getFlags(), St->getAAInfo());
11289 // If this is a legal vector store, try to combine it into a VST1_UPD.
11290 if (ISD::isNormalStore(N) && VT.isVector() &&
11291 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11292 return CombineBaseUpdate(N, DCI);
11297 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11298 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11299 /// when the VMUL has a constant operand that is a power of 2.
11301 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11302 /// vmul.f32 d16, d17, d16
11303 /// vcvt.s32.f32 d16, d16
11305 /// vcvt.s32.f32 d16, d16, #3
11306 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11307 const ARMSubtarget *Subtarget) {
11308 if (!Subtarget->hasNEON())
11311 SDValue Op = N->getOperand(0);
11312 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11313 Op.getOpcode() != ISD::FMUL)
11316 SDValue ConstVec = Op->getOperand(1);
11317 if (!isa<BuildVectorSDNode>(ConstVec))
11320 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11321 uint32_t FloatBits = FloatTy.getSizeInBits();
11322 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11323 uint32_t IntBits = IntTy.getSizeInBits();
11324 unsigned NumLanes = Op.getValueType().getVectorNumElements();
11325 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11326 // These instructions only exist converting from f32 to i32. We can handle
11327 // smaller integers by generating an extra truncate, but larger ones would
11328 // be lossy. We also can't handle more then 4 lanes, since these intructions
11329 // only support v2i32/v4i32 types.
11333 BitVector UndefElements;
11334 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11335 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11336 if (C == -1 || C == 0 || C > 32)
11340 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11341 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11342 Intrinsic::arm_neon_vcvtfp2fxu;
11343 SDValue FixConv = DAG.getNode(
11344 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11345 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11346 DAG.getConstant(C, dl, MVT::i32));
11348 if (IntBits < FloatBits)
11349 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11354 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11355 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11356 /// when the VDIV has a constant operand that is a power of 2.
11358 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11359 /// vcvt.f32.s32 d16, d16
11360 /// vdiv.f32 d16, d17, d16
11362 /// vcvt.f32.s32 d16, d16, #3
11363 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11364 const ARMSubtarget *Subtarget) {
11365 if (!Subtarget->hasNEON())
11368 SDValue Op = N->getOperand(0);
11369 unsigned OpOpcode = Op.getNode()->getOpcode();
11370 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11371 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11374 SDValue ConstVec = N->getOperand(1);
11375 if (!isa<BuildVectorSDNode>(ConstVec))
11378 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11379 uint32_t FloatBits = FloatTy.getSizeInBits();
11380 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11381 uint32_t IntBits = IntTy.getSizeInBits();
11382 unsigned NumLanes = Op.getValueType().getVectorNumElements();
11383 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11384 // These instructions only exist converting from i32 to f32. We can handle
11385 // smaller integers by generating an extra extend, but larger ones would
11386 // be lossy. We also can't handle more then 4 lanes, since these intructions
11387 // only support v2i32/v4i32 types.
11391 BitVector UndefElements;
11392 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11393 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11394 if (C == -1 || C == 0 || C > 32)
11398 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11399 SDValue ConvInput = Op.getOperand(0);
11400 if (IntBits < FloatBits)
11401 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11402 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11405 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11406 Intrinsic::arm_neon_vcvtfxu2fp;
11407 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11409 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11410 ConvInput, DAG.getConstant(C, dl, MVT::i32));
11413 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11414 /// operand of a vector shift operation, where all the elements of the
11415 /// build_vector must have the same constant integer value.
11416 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11417 // Ignore bit_converts.
11418 while (Op.getOpcode() == ISD::BITCAST)
11419 Op = Op.getOperand(0);
11420 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11421 APInt SplatBits, SplatUndef;
11422 unsigned SplatBitSize;
11424 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11425 HasAnyUndefs, ElementBits) ||
11426 SplatBitSize > ElementBits)
11428 Cnt = SplatBits.getSExtValue();
11432 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11433 /// operand of a vector shift left operation. That value must be in the range:
11434 /// 0 <= Value < ElementBits for a left shift; or
11435 /// 0 <= Value <= ElementBits for a long left shift.
11436 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11437 assert(VT.isVector() && "vector shift count is not a vector type");
11438 int64_t ElementBits = VT.getScalarSizeInBits();
11439 if (! getVShiftImm(Op, ElementBits, Cnt))
11441 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11444 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11445 /// operand of a vector shift right operation. For a shift opcode, the value
11446 /// is positive, but for an intrinsic the value count must be negative. The
11447 /// absolute value must be in the range:
11448 /// 1 <= |Value| <= ElementBits for a right shift; or
11449 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
11450 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11452 assert(VT.isVector() && "vector shift count is not a vector type");
11453 int64_t ElementBits = VT.getScalarSizeInBits();
11454 if (! getVShiftImm(Op, ElementBits, Cnt))
11457 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11458 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11465 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11466 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11467 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11470 // Don't do anything for most intrinsics.
11473 // Vector shifts: check for immediate versions and lower them.
11474 // Note: This is done during DAG combining instead of DAG legalizing because
11475 // the build_vectors for 64-bit vector element shift counts are generally
11476 // not legal, and it is hard to see their values after they get legalized to
11477 // loads from a constant pool.
11478 case Intrinsic::arm_neon_vshifts:
11479 case Intrinsic::arm_neon_vshiftu:
11480 case Intrinsic::arm_neon_vrshifts:
11481 case Intrinsic::arm_neon_vrshiftu:
11482 case Intrinsic::arm_neon_vrshiftn:
11483 case Intrinsic::arm_neon_vqshifts:
11484 case Intrinsic::arm_neon_vqshiftu:
11485 case Intrinsic::arm_neon_vqshiftsu:
11486 case Intrinsic::arm_neon_vqshiftns:
11487 case Intrinsic::arm_neon_vqshiftnu:
11488 case Intrinsic::arm_neon_vqshiftnsu:
11489 case Intrinsic::arm_neon_vqrshiftns:
11490 case Intrinsic::arm_neon_vqrshiftnu:
11491 case Intrinsic::arm_neon_vqrshiftnsu: {
11492 EVT VT = N->getOperand(1).getValueType();
11494 unsigned VShiftOpc = 0;
11497 case Intrinsic::arm_neon_vshifts:
11498 case Intrinsic::arm_neon_vshiftu:
11499 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11500 VShiftOpc = ARMISD::VSHL;
11503 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11504 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11505 ARMISD::VSHRs : ARMISD::VSHRu);
11510 case Intrinsic::arm_neon_vrshifts:
11511 case Intrinsic::arm_neon_vrshiftu:
11512 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11516 case Intrinsic::arm_neon_vqshifts:
11517 case Intrinsic::arm_neon_vqshiftu:
11518 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11522 case Intrinsic::arm_neon_vqshiftsu:
11523 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11525 llvm_unreachable("invalid shift count for vqshlu intrinsic");
11527 case Intrinsic::arm_neon_vrshiftn:
11528 case Intrinsic::arm_neon_vqshiftns:
11529 case Intrinsic::arm_neon_vqshiftnu:
11530 case Intrinsic::arm_neon_vqshiftnsu:
11531 case Intrinsic::arm_neon_vqrshiftns:
11532 case Intrinsic::arm_neon_vqrshiftnu:
11533 case Intrinsic::arm_neon_vqrshiftnsu:
11534 // Narrowing shifts require an immediate right shift.
11535 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11537 llvm_unreachable("invalid shift count for narrowing vector shift "
11541 llvm_unreachable("unhandled vector shift");
11545 case Intrinsic::arm_neon_vshifts:
11546 case Intrinsic::arm_neon_vshiftu:
11547 // Opcode already set above.
11549 case Intrinsic::arm_neon_vrshifts:
11550 VShiftOpc = ARMISD::VRSHRs; break;
11551 case Intrinsic::arm_neon_vrshiftu:
11552 VShiftOpc = ARMISD::VRSHRu; break;
11553 case Intrinsic::arm_neon_vrshiftn:
11554 VShiftOpc = ARMISD::VRSHRN; break;
11555 case Intrinsic::arm_neon_vqshifts:
11556 VShiftOpc = ARMISD::VQSHLs; break;
11557 case Intrinsic::arm_neon_vqshiftu:
11558 VShiftOpc = ARMISD::VQSHLu; break;
11559 case Intrinsic::arm_neon_vqshiftsu:
11560 VShiftOpc = ARMISD::VQSHLsu; break;
11561 case Intrinsic::arm_neon_vqshiftns:
11562 VShiftOpc = ARMISD::VQSHRNs; break;
11563 case Intrinsic::arm_neon_vqshiftnu:
11564 VShiftOpc = ARMISD::VQSHRNu; break;
11565 case Intrinsic::arm_neon_vqshiftnsu:
11566 VShiftOpc = ARMISD::VQSHRNsu; break;
11567 case Intrinsic::arm_neon_vqrshiftns:
11568 VShiftOpc = ARMISD::VQRSHRNs; break;
11569 case Intrinsic::arm_neon_vqrshiftnu:
11570 VShiftOpc = ARMISD::VQRSHRNu; break;
11571 case Intrinsic::arm_neon_vqrshiftnsu:
11572 VShiftOpc = ARMISD::VQRSHRNsu; break;
11576 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11577 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11580 case Intrinsic::arm_neon_vshiftins: {
11581 EVT VT = N->getOperand(1).getValueType();
11583 unsigned VShiftOpc = 0;
11585 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11586 VShiftOpc = ARMISD::VSLI;
11587 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11588 VShiftOpc = ARMISD::VSRI;
11590 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11594 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11595 N->getOperand(1), N->getOperand(2),
11596 DAG.getConstant(Cnt, dl, MVT::i32));
11599 case Intrinsic::arm_neon_vqrshifts:
11600 case Intrinsic::arm_neon_vqrshiftu:
11601 // No immediate versions of these to check for.
11608 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11609 /// lowers them. As with the vector shift intrinsics, this is done during DAG
11610 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11611 /// vector element shift counts are generally not legal, and it is hard to see
11612 /// their values after they get legalized to loads from a constant pool.
11613 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11614 const ARMSubtarget *ST) {
11615 EVT VT = N->getValueType(0);
11616 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11617 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11618 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11619 SDValue N1 = N->getOperand(1);
11620 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11621 SDValue N0 = N->getOperand(0);
11622 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11623 DAG.MaskedValueIsZero(N0.getOperand(0),
11624 APInt::getHighBitsSet(32, 16)))
11625 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11629 // Nothing to be done for scalar shifts.
11630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11631 if (!VT.isVector() || !TLI.isTypeLegal(VT))
11634 assert(ST->hasNEON() && "unexpected vector shift");
11637 switch (N->getOpcode()) {
11638 default: llvm_unreachable("unexpected shift opcode");
11641 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11643 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11644 DAG.getConstant(Cnt, dl, MVT::i32));
11650 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11651 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11652 ARMISD::VSHRs : ARMISD::VSHRu);
11654 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11655 DAG.getConstant(Cnt, dl, MVT::i32));
11661 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11662 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11663 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11664 const ARMSubtarget *ST) {
11665 SDValue N0 = N->getOperand(0);
11667 // Check for sign- and zero-extensions of vector extract operations of 8-
11668 // and 16-bit vector elements. NEON supports these directly. They are
11669 // handled during DAG combining because type legalization will promote them
11670 // to 32-bit types and it is messy to recognize the operations after that.
11671 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11672 SDValue Vec = N0.getOperand(0);
11673 SDValue Lane = N0.getOperand(1);
11674 EVT VT = N->getValueType(0);
11675 EVT EltVT = N0.getValueType();
11676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11678 if (VT == MVT::i32 &&
11679 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11680 TLI.isTypeLegal(Vec.getValueType()) &&
11681 isa<ConstantSDNode>(Lane)) {
11684 switch (N->getOpcode()) {
11685 default: llvm_unreachable("unexpected opcode");
11686 case ISD::SIGN_EXTEND:
11687 Opc = ARMISD::VGETLANEs;
11689 case ISD::ZERO_EXTEND:
11690 case ISD::ANY_EXTEND:
11691 Opc = ARMISD::VGETLANEu;
11694 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11701 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11702 // If we have a CMOV, OR and AND combination such as:
11707 // * CN is a single bit;
11708 // * All bits covered by CM are known zero in y
11710 // Then we can convert this into a sequence of BFI instructions. This will
11711 // always be a win if CM is a single bit, will always be no worse than the
11712 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11713 // three bits (due to the extra IT instruction).
11715 SDValue Op0 = CMOV->getOperand(0);
11716 SDValue Op1 = CMOV->getOperand(1);
11717 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11718 auto CC = CCNode->getAPIntValue().getLimitedValue();
11719 SDValue CmpZ = CMOV->getOperand(4);
11721 // The compare must be against zero.
11722 if (!isNullConstant(CmpZ->getOperand(1)))
11725 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11726 SDValue And = CmpZ->getOperand(0);
11727 if (And->getOpcode() != ISD::AND)
11729 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11730 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11732 SDValue X = And->getOperand(0);
11734 if (CC == ARMCC::EQ) {
11735 // We're performing an "equal to zero" compare. Swap the operands so we
11736 // canonicalize on a "not equal to zero" compare.
11737 std::swap(Op0, Op1);
11739 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11742 if (Op1->getOpcode() != ISD::OR)
11745 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11748 SDValue Y = Op1->getOperand(0);
11753 // Now, is it profitable to continue?
11754 APInt OrCI = OrC->getAPIntValue();
11755 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11756 if (OrCI.countPopulation() > Heuristic)
11759 // Lastly, can we determine that the bits defined by OrCI
11761 APInt KnownZero, KnownOne;
11762 DAG.computeKnownBits(Y, KnownZero, KnownOne);
11763 if ((OrCI & KnownZero) != OrCI)
11766 // OK, we can do the combine.
11769 EVT VT = X.getValueType();
11770 unsigned BitInX = AndC->getAPIntValue().logBase2();
11773 // We must shift X first.
11774 X = DAG.getNode(ISD::SRL, dl, VT, X,
11775 DAG.getConstant(BitInX, dl, VT));
11778 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11779 BitInY < NumActiveBits; ++BitInY) {
11780 if (OrCI[BitInY] == 0)
11782 APInt Mask(VT.getSizeInBits(), 0);
11783 Mask.setBit(BitInY);
11784 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11785 // Confusingly, the operand is an *inverted* mask.
11786 DAG.getConstant(~Mask, dl, VT));
11792 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11794 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11795 SDValue Cmp = N->getOperand(4);
11796 if (Cmp.getOpcode() != ARMISD::CMPZ)
11797 // Only looking at NE cases.
11800 EVT VT = N->getValueType(0);
11802 SDValue LHS = Cmp.getOperand(0);
11803 SDValue RHS = Cmp.getOperand(1);
11804 SDValue Chain = N->getOperand(0);
11805 SDValue BB = N->getOperand(1);
11806 SDValue ARMcc = N->getOperand(2);
11807 ARMCC::CondCodes CC =
11808 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11810 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11811 // -> (brcond Chain BB CC CPSR Cmp)
11812 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11813 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11814 LHS->getOperand(0)->hasOneUse()) {
11815 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11816 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11817 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11818 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11819 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11820 (LHS01C && LHS01C->getZExtValue() == 1) &&
11821 (LHS1C && LHS1C->getZExtValue() == 1) &&
11822 (RHSC && RHSC->getZExtValue() == 0)) {
11823 return DAG.getNode(
11824 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11825 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11832 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11834 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11835 SDValue Cmp = N->getOperand(4);
11836 if (Cmp.getOpcode() != ARMISD::CMPZ)
11837 // Only looking at EQ and NE cases.
11840 EVT VT = N->getValueType(0);
11842 SDValue LHS = Cmp.getOperand(0);
11843 SDValue RHS = Cmp.getOperand(1);
11844 SDValue FalseVal = N->getOperand(0);
11845 SDValue TrueVal = N->getOperand(1);
11846 SDValue ARMcc = N->getOperand(2);
11847 ARMCC::CondCodes CC =
11848 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11850 // BFI is only available on V6T2+.
11851 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11852 SDValue R = PerformCMOVToBFICombine(N, DAG);
11873 /// FIXME: Turn this into a target neutral optimization?
11875 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11876 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11877 N->getOperand(3), Cmp);
11878 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11880 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11881 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11882 N->getOperand(3), NewCmp);
11885 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11886 // -> (cmov F T CC CPSR Cmp)
11887 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11888 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11889 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11890 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11891 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11892 (LHS1C && LHS1C->getZExtValue() == 1) &&
11893 (RHSC && RHSC->getZExtValue() == 0)) {
11894 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11895 LHS->getOperand(2), LHS->getOperand(3),
11896 LHS->getOperand(4));
11900 if (Res.getNode()) {
11901 APInt KnownZero, KnownOne;
11902 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11903 // Capture demanded bits information that would be otherwise lost.
11904 if (KnownZero == 0xfffffffe)
11905 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11906 DAG.getValueType(MVT::i1));
11907 else if (KnownZero == 0xffffff00)
11908 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11909 DAG.getValueType(MVT::i8));
11910 else if (KnownZero == 0xffff0000)
11911 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11912 DAG.getValueType(MVT::i16));
11918 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11919 DAGCombinerInfo &DCI) const {
11920 switch (N->getOpcode()) {
11922 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
11923 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
11924 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
11925 case ISD::SUB: return PerformSUBCombine(N, DCI);
11926 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
11927 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
11928 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
11929 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
11931 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI.DAG, Subtarget);
11932 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
11933 case ARMISD::BFI: return PerformBFICombine(N, DCI);
11934 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11935 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11936 case ISD::STORE: return PerformSTORECombine(N, DCI);
11937 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11938 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11939 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11940 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11941 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
11942 case ISD::FP_TO_SINT:
11943 case ISD::FP_TO_UINT:
11944 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11946 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11947 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11950 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
11951 case ISD::SIGN_EXTEND:
11952 case ISD::ZERO_EXTEND:
11953 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11954 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11955 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11956 case ISD::LOAD: return PerformLOADCombine(N, DCI);
11957 case ARMISD::VLD1DUP:
11958 case ARMISD::VLD2DUP:
11959 case ARMISD::VLD3DUP:
11960 case ARMISD::VLD4DUP:
11961 return PerformVLDCombine(N, DCI);
11962 case ARMISD::BUILD_VECTOR:
11963 return PerformARMBUILD_VECTORCombine(N, DCI);
11964 case ARMISD::SMULWB: {
11965 unsigned BitWidth = N->getValueType(0).getSizeInBits();
11966 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
11967 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
11971 case ARMISD::SMULWT: {
11972 unsigned BitWidth = N->getValueType(0).getSizeInBits();
11973 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
11974 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
11978 case ARMISD::SMLALBB: {
11979 unsigned BitWidth = N->getValueType(0).getSizeInBits();
11980 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
11981 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
11982 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
11986 case ARMISD::SMLALBT: {
11987 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
11988 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
11989 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
11990 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
11991 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
11992 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
11996 case ARMISD::SMLALTB: {
11997 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
11998 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
11999 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12000 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12001 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12002 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12006 case ARMISD::SMLALTT: {
12007 unsigned BitWidth = N->getValueType(0).getSizeInBits();
12008 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12009 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12010 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12014 case ISD::INTRINSIC_VOID:
12015 case ISD::INTRINSIC_W_CHAIN:
12016 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12017 case Intrinsic::arm_neon_vld1:
12018 case Intrinsic::arm_neon_vld2:
12019 case Intrinsic::arm_neon_vld3:
12020 case Intrinsic::arm_neon_vld4:
12021 case Intrinsic::arm_neon_vld2lane:
12022 case Intrinsic::arm_neon_vld3lane:
12023 case Intrinsic::arm_neon_vld4lane:
12024 case Intrinsic::arm_neon_vst1:
12025 case Intrinsic::arm_neon_vst2:
12026 case Intrinsic::arm_neon_vst3:
12027 case Intrinsic::arm_neon_vst4:
12028 case Intrinsic::arm_neon_vst2lane:
12029 case Intrinsic::arm_neon_vst3lane:
12030 case Intrinsic::arm_neon_vst4lane:
12031 return PerformVLDCombine(N, DCI);
12039 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12041 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12044 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12047 bool *Fast) const {
12048 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12049 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12051 switch (VT.getSimpleVT().SimpleTy) {
12057 // Unaligned access can use (for example) LRDB, LRDH, LDR
12058 if (AllowsUnaligned) {
12060 *Fast = Subtarget->hasV7Ops();
12067 // For any little-endian targets with neon, we can support unaligned ld/st
12068 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12069 // A big-endian target may also explicitly support unaligned accesses
12070 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12080 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12081 unsigned AlignCheck) {
12082 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12083 (DstAlign == 0 || DstAlign % AlignCheck == 0));
12086 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12087 unsigned DstAlign, unsigned SrcAlign,
12088 bool IsMemset, bool ZeroMemset,
12090 MachineFunction &MF) const {
12091 const Function *F = MF.getFunction();
12093 // See if we can use NEON instructions for this...
12094 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12095 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12098 (memOpAlign(SrcAlign, DstAlign, 16) ||
12099 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12101 } else if (Size >= 8 &&
12102 (memOpAlign(SrcAlign, DstAlign, 8) ||
12103 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12109 // Lowering to i32/i16 if the size permits.
12112 else if (Size >= 2)
12115 // Let the target-independent logic figure it out.
12119 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12120 if (Val.getOpcode() != ISD::LOAD)
12123 EVT VT1 = Val.getValueType();
12124 if (!VT1.isSimple() || !VT1.isInteger() ||
12125 !VT2.isSimple() || !VT2.isInteger())
12128 switch (VT1.getSimpleVT().SimpleTy) {
12133 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12140 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12141 EVT VT = ExtVal.getValueType();
12143 if (!isTypeLegal(VT))
12146 // Don't create a loadext if we can fold the extension into a wide/long
12148 // If there's more than one user instruction, the loadext is desirable no
12149 // matter what. There can be two uses by the same instruction.
12150 if (ExtVal->use_empty() ||
12151 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12154 SDNode *U = *ExtVal->use_begin();
12155 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12156 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12162 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12163 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12166 if (!isTypeLegal(EVT::getEVT(Ty1)))
12169 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12171 // Assuming the caller doesn't have a zeroext or signext return parameter,
12172 // truncation all the way down to i1 is valid.
12176 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12177 const AddrMode &AM, Type *Ty,
12178 unsigned AS) const {
12179 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12180 if (Subtarget->hasFPAO())
12181 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12188 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12192 unsigned Scale = 1;
12193 switch (VT.getSimpleVT().SimpleTy) {
12194 default: return false;
12209 if ((V & (Scale - 1)) != 0)
12212 return V == (V & ((1LL << 5) - 1));
12215 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12216 const ARMSubtarget *Subtarget) {
12217 bool isNeg = false;
12223 switch (VT.getSimpleVT().SimpleTy) {
12224 default: return false;
12229 // + imm12 or - imm8
12231 return V == (V & ((1LL << 8) - 1));
12232 return V == (V & ((1LL << 12) - 1));
12235 // Same as ARM mode. FIXME: NEON?
12236 if (!Subtarget->hasVFP2())
12241 return V == (V & ((1LL << 8) - 1));
12245 /// isLegalAddressImmediate - Return true if the integer value can be used
12246 /// as the offset of the target addressing mode for load / store of the
12248 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12249 const ARMSubtarget *Subtarget) {
12253 if (!VT.isSimple())
12256 if (Subtarget->isThumb1Only())
12257 return isLegalT1AddressImmediate(V, VT);
12258 else if (Subtarget->isThumb2())
12259 return isLegalT2AddressImmediate(V, VT, Subtarget);
12264 switch (VT.getSimpleVT().SimpleTy) {
12265 default: return false;
12270 return V == (V & ((1LL << 12) - 1));
12273 return V == (V & ((1LL << 8) - 1));
12276 if (!Subtarget->hasVFP2()) // FIXME: NEON?
12281 return V == (V & ((1LL << 8) - 1));
12285 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12287 int Scale = AM.Scale;
12291 switch (VT.getSimpleVT().SimpleTy) {
12292 default: return false;
12300 Scale = Scale & ~1;
12301 return Scale == 2 || Scale == 4 || Scale == 8;
12304 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12308 // Note, we allow "void" uses (basically, uses that aren't loads or
12309 // stores), because arm allows folding a scale into many arithmetic
12310 // operations. This should be made more precise and revisited later.
12312 // Allow r << imm, but the imm has to be a multiple of two.
12313 if (Scale & 1) return false;
12314 return isPowerOf2_32(Scale);
12318 /// isLegalAddressingMode - Return true if the addressing mode represented
12319 /// by AM is legal for this target, for a load/store of the specified type.
12320 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12321 const AddrMode &AM, Type *Ty,
12322 unsigned AS) const {
12323 EVT VT = getValueType(DL, Ty, true);
12324 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12327 // Can never fold addr of global into load/store.
12331 switch (AM.Scale) {
12332 case 0: // no scale reg, must be "r+i" or "r", or "i".
12335 if (Subtarget->isThumb1Only())
12339 // ARM doesn't support any R+R*scale+imm addr modes.
12343 if (!VT.isSimple())
12346 if (Subtarget->isThumb2())
12347 return isLegalT2ScaledAddressingMode(AM, VT);
12349 int Scale = AM.Scale;
12350 switch (VT.getSimpleVT().SimpleTy) {
12351 default: return false;
12355 if (Scale < 0) Scale = -Scale;
12359 return isPowerOf2_32(Scale & ~1);
12363 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12368 // Note, we allow "void" uses (basically, uses that aren't loads or
12369 // stores), because arm allows folding a scale into many arithmetic
12370 // operations. This should be made more precise and revisited later.
12372 // Allow r << imm, but the imm has to be a multiple of two.
12373 if (Scale & 1) return false;
12374 return isPowerOf2_32(Scale);
12380 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12381 /// icmp immediate, that is the target has icmp instructions which can compare
12382 /// a register against the immediate without having to materialize the
12383 /// immediate into a register.
12384 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12385 // Thumb2 and ARM modes can use cmn for negative immediates.
12386 if (!Subtarget->isThumb())
12387 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12388 if (Subtarget->isThumb2())
12389 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12390 // Thumb1 doesn't have cmn, and only 8-bit immediates.
12391 return Imm >= 0 && Imm <= 255;
12394 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12395 /// *or sub* immediate, that is the target has add or sub instructions which can
12396 /// add a register with the immediate without having to materialize the
12397 /// immediate into a register.
12398 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12399 // Same encoding for add/sub, just flip the sign.
12400 int64_t AbsImm = std::abs(Imm);
12401 if (!Subtarget->isThumb())
12402 return ARM_AM::getSOImmVal(AbsImm) != -1;
12403 if (Subtarget->isThumb2())
12404 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12405 // Thumb1 only has 8-bit unsigned immediate.
12406 return AbsImm >= 0 && AbsImm <= 255;
12409 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12410 bool isSEXTLoad, SDValue &Base,
12411 SDValue &Offset, bool &isInc,
12412 SelectionDAG &DAG) {
12413 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12416 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12417 // AddressingMode 3
12418 Base = Ptr->getOperand(0);
12419 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12420 int RHSC = (int)RHS->getZExtValue();
12421 if (RHSC < 0 && RHSC > -256) {
12422 assert(Ptr->getOpcode() == ISD::ADD);
12424 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12428 isInc = (Ptr->getOpcode() == ISD::ADD);
12429 Offset = Ptr->getOperand(1);
12431 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12432 // AddressingMode 2
12433 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12434 int RHSC = (int)RHS->getZExtValue();
12435 if (RHSC < 0 && RHSC > -0x1000) {
12436 assert(Ptr->getOpcode() == ISD::ADD);
12438 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12439 Base = Ptr->getOperand(0);
12444 if (Ptr->getOpcode() == ISD::ADD) {
12446 ARM_AM::ShiftOpc ShOpcVal=
12447 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12448 if (ShOpcVal != ARM_AM::no_shift) {
12449 Base = Ptr->getOperand(1);
12450 Offset = Ptr->getOperand(0);
12452 Base = Ptr->getOperand(0);
12453 Offset = Ptr->getOperand(1);
12458 isInc = (Ptr->getOpcode() == ISD::ADD);
12459 Base = Ptr->getOperand(0);
12460 Offset = Ptr->getOperand(1);
12464 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12468 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12469 bool isSEXTLoad, SDValue &Base,
12470 SDValue &Offset, bool &isInc,
12471 SelectionDAG &DAG) {
12472 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12475 Base = Ptr->getOperand(0);
12476 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12477 int RHSC = (int)RHS->getZExtValue();
12478 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12479 assert(Ptr->getOpcode() == ISD::ADD);
12481 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12483 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12484 isInc = Ptr->getOpcode() == ISD::ADD;
12485 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12493 /// getPreIndexedAddressParts - returns true by value, base pointer and
12494 /// offset pointer and addressing mode by reference if the node's address
12495 /// can be legally represented as pre-indexed load / store address.
12497 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12499 ISD::MemIndexedMode &AM,
12500 SelectionDAG &DAG) const {
12501 if (Subtarget->isThumb1Only())
12506 bool isSEXTLoad = false;
12507 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12508 Ptr = LD->getBasePtr();
12509 VT = LD->getMemoryVT();
12510 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12511 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12512 Ptr = ST->getBasePtr();
12513 VT = ST->getMemoryVT();
12518 bool isLegal = false;
12519 if (Subtarget->isThumb2())
12520 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12521 Offset, isInc, DAG);
12523 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12524 Offset, isInc, DAG);
12528 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12532 /// getPostIndexedAddressParts - returns true by value, base pointer and
12533 /// offset pointer and addressing mode by reference if this node can be
12534 /// combined with a load / store to form a post-indexed load / store.
12535 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12538 ISD::MemIndexedMode &AM,
12539 SelectionDAG &DAG) const {
12542 bool isSEXTLoad = false, isNonExt;
12543 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12544 VT = LD->getMemoryVT();
12545 Ptr = LD->getBasePtr();
12546 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12547 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12548 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12549 VT = ST->getMemoryVT();
12550 Ptr = ST->getBasePtr();
12551 isNonExt = !ST->isTruncatingStore();
12555 if (Subtarget->isThumb1Only()) {
12556 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12557 // must be non-extending/truncating, i32, with an offset of 4.
12558 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12559 if (Op->getOpcode() != ISD::ADD || !isNonExt)
12561 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12562 if (!RHS || RHS->getZExtValue() != 4)
12565 Offset = Op->getOperand(1);
12566 Base = Op->getOperand(0);
12567 AM = ISD::POST_INC;
12572 bool isLegal = false;
12573 if (Subtarget->isThumb2())
12574 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12577 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12583 // Swap base ptr and offset to catch more post-index load / store when
12584 // it's legal. In Thumb2 mode, offset must be an immediate.
12585 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12586 !Subtarget->isThumb2())
12587 std::swap(Base, Offset);
12589 // Post-indexed load / store update the base pointer.
12594 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12598 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12601 const APInt &DemandedElts,
12602 const SelectionDAG &DAG,
12603 unsigned Depth) const {
12604 unsigned BitWidth = KnownOne.getBitWidth();
12605 KnownZero = KnownOne = APInt(BitWidth, 0);
12606 switch (Op.getOpcode()) {
12612 // These nodes' second result is a boolean
12613 if (Op.getResNo() == 0)
12615 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12617 case ARMISD::CMOV: {
12618 // Bits are known zero/one if known on the LHS and RHS.
12619 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
12620 if (KnownZero == 0 && KnownOne == 0) return;
12622 APInt KnownZeroRHS, KnownOneRHS;
12623 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
12624 KnownZero &= KnownZeroRHS;
12625 KnownOne &= KnownOneRHS;
12628 case ISD::INTRINSIC_W_CHAIN: {
12629 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12630 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12633 case Intrinsic::arm_ldaex:
12634 case Intrinsic::arm_ldrex: {
12635 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12636 unsigned MemBits = VT.getScalarSizeInBits();
12637 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12642 case ARMISD::BFI: {
12643 // Conservatively, we can recurse down the first operand
12644 // and just mask out all affected bits.
12645 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth + 1);
12647 // The operand to BFI is already a mask suitable for removing the bits it
12649 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
12650 const APInt &Mask = CI->getAPIntValue();
12658 //===----------------------------------------------------------------------===//
12659 // ARM Inline Assembly Support
12660 //===----------------------------------------------------------------------===//
12662 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12663 // Looking for "rev" which is V6+.
12664 if (!Subtarget->hasV6Ops())
12667 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12668 std::string AsmStr = IA->getAsmString();
12669 SmallVector<StringRef, 4> AsmPieces;
12670 SplitString(AsmStr, AsmPieces, ";\n");
12672 switch (AsmPieces.size()) {
12673 default: return false;
12675 AsmStr = AsmPieces[0];
12677 SplitString(AsmStr, AsmPieces, " \t,");
12680 if (AsmPieces.size() == 3 &&
12681 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12682 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12683 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12684 if (Ty && Ty->getBitWidth() == 32)
12685 return IntrinsicLowering::LowerToByteSwap(CI);
12693 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12694 // At this point, we have to lower this constraint to something else, so we
12695 // lower it to an "r" or "w". However, by doing this we will force the result
12696 // to be in register, while the X constraint is much more permissive.
12698 // Although we are correct (we are free to emit anything, without
12699 // constraints), we might break use cases that would expect us to be more
12700 // efficient and emit something else.
12701 if (!Subtarget->hasVFP2())
12703 if (ConstraintVT.isFloatingPoint())
12705 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12706 (ConstraintVT.getSizeInBits() == 64 ||
12707 ConstraintVT.getSizeInBits() == 128))
12713 /// getConstraintType - Given a constraint letter, return the type of
12714 /// constraint it is for this target.
12715 ARMTargetLowering::ConstraintType
12716 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12717 if (Constraint.size() == 1) {
12718 switch (Constraint[0]) {
12720 case 'l': return C_RegisterClass;
12721 case 'w': return C_RegisterClass;
12722 case 'h': return C_RegisterClass;
12723 case 'x': return C_RegisterClass;
12724 case 't': return C_RegisterClass;
12725 case 'j': return C_Other; // Constant for movw.
12726 // An address with a single base register. Due to the way we
12727 // currently handle addresses it is the same as an 'r' memory constraint.
12728 case 'Q': return C_Memory;
12730 } else if (Constraint.size() == 2) {
12731 switch (Constraint[0]) {
12733 // All 'U+' constraints are addresses.
12734 case 'U': return C_Memory;
12737 return TargetLowering::getConstraintType(Constraint);
12740 /// Examine constraint type and operand type and determine a weight value.
12741 /// This object must already have been set up with the operand type
12742 /// and the current alternative constraint selected.
12743 TargetLowering::ConstraintWeight
12744 ARMTargetLowering::getSingleConstraintMatchWeight(
12745 AsmOperandInfo &info, const char *constraint) const {
12746 ConstraintWeight weight = CW_Invalid;
12747 Value *CallOperandVal = info.CallOperandVal;
12748 // If we don't have a value, we can't do a match,
12749 // but allow it at the lowest weight.
12750 if (!CallOperandVal)
12752 Type *type = CallOperandVal->getType();
12753 // Look at the constraint type.
12754 switch (*constraint) {
12756 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12759 if (type->isIntegerTy()) {
12760 if (Subtarget->isThumb())
12761 weight = CW_SpecificReg;
12763 weight = CW_Register;
12767 if (type->isFloatingPointTy())
12768 weight = CW_Register;
12774 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12775 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12776 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12777 if (Constraint.size() == 1) {
12778 // GCC ARM Constraint Letters
12779 switch (Constraint[0]) {
12780 case 'l': // Low regs or general regs.
12781 if (Subtarget->isThumb())
12782 return RCPair(0U, &ARM::tGPRRegClass);
12783 return RCPair(0U, &ARM::GPRRegClass);
12784 case 'h': // High regs or no regs.
12785 if (Subtarget->isThumb())
12786 return RCPair(0U, &ARM::hGPRRegClass);
12789 if (Subtarget->isThumb1Only())
12790 return RCPair(0U, &ARM::tGPRRegClass);
12791 return RCPair(0U, &ARM::GPRRegClass);
12793 if (VT == MVT::Other)
12795 if (VT == MVT::f32)
12796 return RCPair(0U, &ARM::SPRRegClass);
12797 if (VT.getSizeInBits() == 64)
12798 return RCPair(0U, &ARM::DPRRegClass);
12799 if (VT.getSizeInBits() == 128)
12800 return RCPair(0U, &ARM::QPRRegClass);
12803 if (VT == MVT::Other)
12805 if (VT == MVT::f32)
12806 return RCPair(0U, &ARM::SPR_8RegClass);
12807 if (VT.getSizeInBits() == 64)
12808 return RCPair(0U, &ARM::DPR_8RegClass);
12809 if (VT.getSizeInBits() == 128)
12810 return RCPair(0U, &ARM::QPR_8RegClass);
12813 if (VT == MVT::f32)
12814 return RCPair(0U, &ARM::SPRRegClass);
12818 if (StringRef("{cc}").equals_lower(Constraint))
12819 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12821 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12824 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12825 /// vector. If it is invalid, don't add anything to Ops.
12826 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12827 std::string &Constraint,
12828 std::vector<SDValue>&Ops,
12829 SelectionDAG &DAG) const {
12832 // Currently only support length 1 constraints.
12833 if (Constraint.length() != 1) return;
12835 char ConstraintLetter = Constraint[0];
12836 switch (ConstraintLetter) {
12839 case 'I': case 'J': case 'K': case 'L':
12840 case 'M': case 'N': case 'O':
12841 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12845 int64_t CVal64 = C->getSExtValue();
12846 int CVal = (int) CVal64;
12847 // None of these constraints allow values larger than 32 bits. Check
12848 // that the value fits in an int.
12849 if (CVal != CVal64)
12852 switch (ConstraintLetter) {
12854 // Constant suitable for movw, must be between 0 and
12856 if (Subtarget->hasV6T2Ops())
12857 if (CVal >= 0 && CVal <= 65535)
12861 if (Subtarget->isThumb1Only()) {
12862 // This must be a constant between 0 and 255, for ADD
12864 if (CVal >= 0 && CVal <= 255)
12866 } else if (Subtarget->isThumb2()) {
12867 // A constant that can be used as an immediate value in a
12868 // data-processing instruction.
12869 if (ARM_AM::getT2SOImmVal(CVal) != -1)
12872 // A constant that can be used as an immediate value in a
12873 // data-processing instruction.
12874 if (ARM_AM::getSOImmVal(CVal) != -1)
12880 if (Subtarget->isThumb1Only()) {
12881 // This must be a constant between -255 and -1, for negated ADD
12882 // immediates. This can be used in GCC with an "n" modifier that
12883 // prints the negated value, for use with SUB instructions. It is
12884 // not useful otherwise but is implemented for compatibility.
12885 if (CVal >= -255 && CVal <= -1)
12888 // This must be a constant between -4095 and 4095. It is not clear
12889 // what this constraint is intended for. Implemented for
12890 // compatibility with GCC.
12891 if (CVal >= -4095 && CVal <= 4095)
12897 if (Subtarget->isThumb1Only()) {
12898 // A 32-bit value where only one byte has a nonzero value. Exclude
12899 // zero to match GCC. This constraint is used by GCC internally for
12900 // constants that can be loaded with a move/shift combination.
12901 // It is not useful otherwise but is implemented for compatibility.
12902 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12904 } else if (Subtarget->isThumb2()) {
12905 // A constant whose bitwise inverse can be used as an immediate
12906 // value in a data-processing instruction. This can be used in GCC
12907 // with a "B" modifier that prints the inverted value, for use with
12908 // BIC and MVN instructions. It is not useful otherwise but is
12909 // implemented for compatibility.
12910 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12913 // A constant whose bitwise inverse can be used as an immediate
12914 // value in a data-processing instruction. This can be used in GCC
12915 // with a "B" modifier that prints the inverted value, for use with
12916 // BIC and MVN instructions. It is not useful otherwise but is
12917 // implemented for compatibility.
12918 if (ARM_AM::getSOImmVal(~CVal) != -1)
12924 if (Subtarget->isThumb1Only()) {
12925 // This must be a constant between -7 and 7,
12926 // for 3-operand ADD/SUB immediate instructions.
12927 if (CVal >= -7 && CVal < 7)
12929 } else if (Subtarget->isThumb2()) {
12930 // A constant whose negation can be used as an immediate value in a
12931 // data-processing instruction. This can be used in GCC with an "n"
12932 // modifier that prints the negated value, for use with SUB
12933 // instructions. It is not useful otherwise but is implemented for
12935 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12938 // A constant whose negation can be used as an immediate value in a
12939 // data-processing instruction. This can be used in GCC with an "n"
12940 // modifier that prints the negated value, for use with SUB
12941 // instructions. It is not useful otherwise but is implemented for
12943 if (ARM_AM::getSOImmVal(-CVal) != -1)
12949 if (Subtarget->isThumb1Only()) {
12950 // This must be a multiple of 4 between 0 and 1020, for
12951 // ADD sp + immediate.
12952 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12955 // A power of two or a constant between 0 and 32. This is used in
12956 // GCC for the shift amount on shifted register operands, but it is
12957 // useful in general for any shift amounts.
12958 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12964 if (Subtarget->isThumb()) { // FIXME thumb2
12965 // This must be a constant between 0 and 31, for shift amounts.
12966 if (CVal >= 0 && CVal <= 31)
12972 if (Subtarget->isThumb()) { // FIXME thumb2
12973 // This must be a multiple of 4 between -508 and 508, for
12974 // ADD/SUB sp = sp + immediate.
12975 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12980 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12984 if (Result.getNode()) {
12985 Ops.push_back(Result);
12988 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12991 static RTLIB::Libcall getDivRemLibcall(
12992 const SDNode *N, MVT::SimpleValueType SVT) {
12993 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12994 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
12995 "Unhandled Opcode in getDivRemLibcall");
12996 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12997 N->getOpcode() == ISD::SREM;
13000 default: llvm_unreachable("Unexpected request for libcall!");
13001 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
13002 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13003 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13004 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13009 static TargetLowering::ArgListTy getDivRemArgList(
13010 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13011 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13012 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
13013 "Unhandled Opcode in getDivRemArgList");
13014 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13015 N->getOpcode() == ISD::SREM;
13016 TargetLowering::ArgListTy Args;
13017 TargetLowering::ArgListEntry Entry;
13018 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13019 EVT ArgVT = N->getOperand(i).getValueType();
13020 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13021 Entry.Node = N->getOperand(i);
13023 Entry.IsSExt = isSigned;
13024 Entry.IsZExt = !isSigned;
13025 Args.push_back(Entry);
13027 if (Subtarget->isTargetWindows() && Args.size() >= 2)
13028 std::swap(Args[0], Args[1]);
13032 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13033 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13034 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13035 Subtarget->isTargetWindows()) &&
13036 "Register-based DivRem lowering only");
13037 unsigned Opcode = Op->getOpcode();
13038 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13039 "Invalid opcode for Div/Rem lowering");
13040 bool isSigned = (Opcode == ISD::SDIVREM);
13041 EVT VT = Op->getValueType(0);
13042 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13045 // If the target has hardware divide, use divide + multiply + subtract:
13047 // rem = a - b * div
13048 // return {div, rem}
13049 // This should be lowered into UDIV/SDIV + MLS later on.
13050 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13051 : Subtarget->hasDivideInARMMode();
13052 if (hasDivide && Op->getValueType(0).isSimple() &&
13053 Op->getSimpleValueType(0) == MVT::i32) {
13054 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13055 const SDValue Dividend = Op->getOperand(0);
13056 const SDValue Divisor = Op->getOperand(1);
13057 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13058 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13059 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13061 SDValue Values[2] = {Div, Rem};
13062 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13065 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13066 VT.getSimpleVT().SimpleTy);
13067 SDValue InChain = DAG.getEntryNode();
13069 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13073 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13074 getPointerTy(DAG.getDataLayout()));
13076 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
13078 if (Subtarget->isTargetWindows())
13079 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13081 TargetLowering::CallLoweringInfo CLI(DAG);
13082 CLI.setDebugLoc(dl).setChain(InChain)
13083 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13084 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13086 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13087 return CallInfo.first;
13090 // Lowers REM using divmod helpers
13091 // see RTABI section 4.2/4.3
13092 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13093 // Build return types (div and rem)
13094 std::vector<Type*> RetTyParams;
13095 Type *RetTyElement;
13097 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13098 default: llvm_unreachable("Unexpected request for libcall!");
13099 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
13100 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13101 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13102 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13105 RetTyParams.push_back(RetTyElement);
13106 RetTyParams.push_back(RetTyElement);
13107 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13108 Type *RetTy = StructType::get(*DAG.getContext(), ret);
13110 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13112 SDValue InChain = DAG.getEntryNode();
13113 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13115 bool isSigned = N->getOpcode() == ISD::SREM;
13116 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13117 getPointerTy(DAG.getDataLayout()));
13119 if (Subtarget->isTargetWindows())
13120 InChain = WinDBZCheckDenominator(DAG, N, InChain);
13123 CallLoweringInfo CLI(DAG);
13124 CLI.setChain(InChain)
13125 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13126 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13127 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13129 // Return second (rem) result operand (first contains div)
13130 SDNode *ResNode = CallResult.first.getNode();
13131 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13132 return ResNode->getOperand(1);
13136 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13137 assert(Subtarget->isTargetWindows() && "unsupported target platform");
13141 SDValue Chain = Op.getOperand(0);
13142 SDValue Size = Op.getOperand(1);
13144 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13145 DAG.getConstant(2, DL, MVT::i32));
13148 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13149 Flag = Chain.getValue(1);
13151 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13152 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13154 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13155 Chain = NewSP.getValue(1);
13157 SDValue Ops[2] = { NewSP, Chain };
13158 return DAG.getMergeValues(Ops, DL);
13161 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13162 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13163 "Unexpected type for custom-lowering FP_EXTEND");
13166 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13168 SDValue SrcVal = Op.getOperand(0);
13169 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13173 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13174 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13175 Subtarget->isFPOnlySP() &&
13176 "Unexpected type for custom-lowering FP_ROUND");
13179 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13181 SDValue SrcVal = Op.getOperand(0);
13182 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13187 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13188 // The ARM target isn't yet aware of offsets.
13192 bool ARM::isBitFieldInvertedMask(unsigned v) {
13193 if (v == 0xffffffff)
13196 // there can be 1's on either or both "outsides", all the "inside"
13197 // bits must be 0's
13198 return isShiftedMask_32(~v);
13201 /// isFPImmLegal - Returns true if the target can instruction select the
13202 /// specified FP immediate natively. If false, the legalizer will
13203 /// materialize the FP immediate as a load from a constant pool.
13204 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13205 if (!Subtarget->hasVFP3())
13207 if (VT == MVT::f32)
13208 return ARM_AM::getFP32Imm(Imm) != -1;
13209 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13210 return ARM_AM::getFP64Imm(Imm) != -1;
13214 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13215 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
13216 /// specified in the intrinsic calls.
13217 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13219 unsigned Intrinsic) const {
13220 switch (Intrinsic) {
13221 case Intrinsic::arm_neon_vld1:
13222 case Intrinsic::arm_neon_vld2:
13223 case Intrinsic::arm_neon_vld3:
13224 case Intrinsic::arm_neon_vld4:
13225 case Intrinsic::arm_neon_vld2lane:
13226 case Intrinsic::arm_neon_vld3lane:
13227 case Intrinsic::arm_neon_vld4lane: {
13228 Info.opc = ISD::INTRINSIC_W_CHAIN;
13229 // Conservatively set memVT to the entire set of vectors loaded.
13230 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13231 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13232 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13233 Info.ptrVal = I.getArgOperand(0);
13235 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13236 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13237 Info.vol = false; // volatile loads with NEON intrinsics not supported
13238 Info.readMem = true;
13239 Info.writeMem = false;
13242 case Intrinsic::arm_neon_vst1:
13243 case Intrinsic::arm_neon_vst2:
13244 case Intrinsic::arm_neon_vst3:
13245 case Intrinsic::arm_neon_vst4:
13246 case Intrinsic::arm_neon_vst2lane:
13247 case Intrinsic::arm_neon_vst3lane:
13248 case Intrinsic::arm_neon_vst4lane: {
13249 Info.opc = ISD::INTRINSIC_VOID;
13250 // Conservatively set memVT to the entire set of vectors stored.
13251 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13252 unsigned NumElts = 0;
13253 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13254 Type *ArgTy = I.getArgOperand(ArgI)->getType();
13255 if (!ArgTy->isVectorTy())
13257 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13259 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13260 Info.ptrVal = I.getArgOperand(0);
13262 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13263 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13264 Info.vol = false; // volatile stores with NEON intrinsics not supported
13265 Info.readMem = false;
13266 Info.writeMem = true;
13269 case Intrinsic::arm_ldaex:
13270 case Intrinsic::arm_ldrex: {
13271 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13272 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13273 Info.opc = ISD::INTRINSIC_W_CHAIN;
13274 Info.memVT = MVT::getVT(PtrTy->getElementType());
13275 Info.ptrVal = I.getArgOperand(0);
13277 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13279 Info.readMem = true;
13280 Info.writeMem = false;
13283 case Intrinsic::arm_stlex:
13284 case Intrinsic::arm_strex: {
13285 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13286 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13287 Info.opc = ISD::INTRINSIC_W_CHAIN;
13288 Info.memVT = MVT::getVT(PtrTy->getElementType());
13289 Info.ptrVal = I.getArgOperand(1);
13291 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13293 Info.readMem = false;
13294 Info.writeMem = true;
13297 case Intrinsic::arm_stlexd:
13298 case Intrinsic::arm_strexd:
13299 Info.opc = ISD::INTRINSIC_W_CHAIN;
13300 Info.memVT = MVT::i64;
13301 Info.ptrVal = I.getArgOperand(2);
13305 Info.readMem = false;
13306 Info.writeMem = true;
13309 case Intrinsic::arm_ldaexd:
13310 case Intrinsic::arm_ldrexd:
13311 Info.opc = ISD::INTRINSIC_W_CHAIN;
13312 Info.memVT = MVT::i64;
13313 Info.ptrVal = I.getArgOperand(0);
13317 Info.readMem = true;
13318 Info.writeMem = false;
13328 /// \brief Returns true if it is beneficial to convert a load of a constant
13329 /// to just the constant itself.
13330 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13332 assert(Ty->isIntegerTy());
13334 unsigned Bits = Ty->getPrimitiveSizeInBits();
13335 if (Bits == 0 || Bits > 32)
13340 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT,
13341 unsigned Index) const {
13342 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13345 return (Index == 0 || Index == ResVT.getVectorNumElements());
13348 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13349 ARM_MB::MemBOpt Domain) const {
13350 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13352 // First, if the target has no DMB, see what fallback we can use.
13353 if (!Subtarget->hasDataBarrier()) {
13354 // Some ARMv6 cpus can support data barriers with an mcr instruction.
13355 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13357 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13358 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13359 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13360 Builder.getInt32(0), Builder.getInt32(7),
13361 Builder.getInt32(10), Builder.getInt32(5)};
13362 return Builder.CreateCall(MCR, args);
13364 // Instead of using barriers, atomic accesses on these subtargets use
13366 llvm_unreachable("makeDMB on a target so old that it has no barriers");
13369 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13370 // Only a full system barrier exists in the M-class architectures.
13371 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13372 Constant *CDomain = Builder.getInt32(Domain);
13373 return Builder.CreateCall(DMB, CDomain);
13377 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13378 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13379 AtomicOrdering Ord, bool IsStore,
13380 bool IsLoad) const {
13382 case AtomicOrdering::NotAtomic:
13383 case AtomicOrdering::Unordered:
13384 llvm_unreachable("Invalid fence: unordered/non-atomic");
13385 case AtomicOrdering::Monotonic:
13386 case AtomicOrdering::Acquire:
13387 return nullptr; // Nothing to do
13388 case AtomicOrdering::SequentiallyConsistent:
13390 return nullptr; // Nothing to do
13392 case AtomicOrdering::Release:
13393 case AtomicOrdering::AcquireRelease:
13394 if (Subtarget->preferISHSTBarriers())
13395 return makeDMB(Builder, ARM_MB::ISHST);
13396 // FIXME: add a comment with a link to documentation justifying this.
13398 return makeDMB(Builder, ARM_MB::ISH);
13400 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13403 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13404 AtomicOrdering Ord, bool IsStore,
13405 bool IsLoad) const {
13407 case AtomicOrdering::NotAtomic:
13408 case AtomicOrdering::Unordered:
13409 llvm_unreachable("Invalid fence: unordered/not-atomic");
13410 case AtomicOrdering::Monotonic:
13411 case AtomicOrdering::Release:
13412 return nullptr; // Nothing to do
13413 case AtomicOrdering::Acquire:
13414 case AtomicOrdering::AcquireRelease:
13415 case AtomicOrdering::SequentiallyConsistent:
13416 return makeDMB(Builder, ARM_MB::ISH);
13418 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13421 // Loads and stores less than 64-bits are already atomic; ones above that
13422 // are doomed anyway, so defer to the default libcall and blame the OS when
13423 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13424 // anything for those.
13425 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13426 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13427 return (Size == 64) && !Subtarget->isMClass();
13430 // Loads and stores less than 64-bits are already atomic; ones above that
13431 // are doomed anyway, so defer to the default libcall and blame the OS when
13432 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13433 // anything for those.
13434 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13435 // guarantee, see DDI0406C ARM architecture reference manual,
13436 // sections A8.8.72-74 LDRD)
13437 TargetLowering::AtomicExpansionKind
13438 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13439 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13440 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13441 : AtomicExpansionKind::None;
13444 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13445 // and up to 64 bits on the non-M profiles
13446 TargetLowering::AtomicExpansionKind
13447 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13448 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13449 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13450 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13451 ? AtomicExpansionKind::LLSC
13452 : AtomicExpansionKind::None;
13455 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13456 AtomicCmpXchgInst *AI) const {
13457 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13458 // implement cmpxchg without spilling. If the address being exchanged is also
13459 // on the stack and close enough to the spill slot, this can lead to a
13460 // situation where the monitor always gets cleared and the atomic operation
13461 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13462 bool hasAtomicCmpXchg =
13463 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13464 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13467 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13468 const Instruction *I) const {
13469 return InsertFencesForAtomic;
13472 // This has so far only been implemented for MachO.
13473 bool ARMTargetLowering::useLoadStackGuardNode() const {
13474 return Subtarget->isTargetMachO();
13477 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13478 unsigned &Cost) const {
13479 // If we do not have NEON, vector types are not natively supported.
13480 if (!Subtarget->hasNEON())
13483 // Floating point values and vector values map to the same register file.
13484 // Therefore, although we could do a store extract of a vector type, this is
13485 // better to leave at float as we have more freedom in the addressing mode for
13487 if (VectorTy->isFPOrFPVectorTy())
13490 // If the index is unknown at compile time, this is very expensive to lower
13491 // and it is not possible to combine the store with the extract.
13492 if (!isa<ConstantInt>(Idx))
13495 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13496 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13497 // We can do a store + vector extract on any vector that fits perfectly in a D
13499 if (BitWidth == 64 || BitWidth == 128) {
13506 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13507 return Subtarget->hasV6T2Ops();
13510 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13511 return Subtarget->hasV6T2Ops();
13514 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13515 AtomicOrdering Ord) const {
13516 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13517 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13518 bool IsAcquire = isAcquireOrStronger(Ord);
13520 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13521 // intrinsic must return {i32, i32} and we have to recombine them into a
13522 // single i64 here.
13523 if (ValTy->getPrimitiveSizeInBits() == 64) {
13524 Intrinsic::ID Int =
13525 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13526 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13528 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13529 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13531 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13532 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13533 if (!Subtarget->isLittle())
13534 std::swap (Lo, Hi);
13535 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13536 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13537 return Builder.CreateOr(
13538 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13541 Type *Tys[] = { Addr->getType() };
13542 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13543 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13545 return Builder.CreateTruncOrBitCast(
13546 Builder.CreateCall(Ldrex, Addr),
13547 cast<PointerType>(Addr->getType())->getElementType());
13550 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13551 IRBuilder<> &Builder) const {
13552 if (!Subtarget->hasV7Ops())
13554 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13555 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13558 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13560 AtomicOrdering Ord) const {
13561 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13562 bool IsRelease = isReleaseOrStronger(Ord);
13564 // Since the intrinsics must have legal type, the i64 intrinsics take two
13565 // parameters: "i32, i32". We must marshal Val into the appropriate form
13566 // before the call.
13567 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13568 Intrinsic::ID Int =
13569 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13570 Function *Strex = Intrinsic::getDeclaration(M, Int);
13571 Type *Int32Ty = Type::getInt32Ty(M->getContext());
13573 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13574 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13575 if (!Subtarget->isLittle())
13576 std::swap (Lo, Hi);
13577 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13578 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13581 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13582 Type *Tys[] = { Addr->getType() };
13583 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13585 return Builder.CreateCall(
13586 Strex, {Builder.CreateZExtOrBitCast(
13587 Val, Strex->getFunctionType()->getParamType(0)),
13591 /// A helper function for determining the number of interleaved accesses we
13592 /// will generate when lowering accesses of the given type.
13594 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13595 const DataLayout &DL) const {
13596 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13599 bool ARMTargetLowering::isLegalInterleavedAccessType(
13600 VectorType *VecTy, const DataLayout &DL) const {
13602 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13603 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13605 // Ensure the vector doesn't have f16 elements. Even though we could do an
13606 // i16 vldN, we can't hold the f16 vectors and will end up converting via
13608 if (VecTy->getElementType()->isHalfTy())
13611 // Ensure the number of vector elements is greater than 1.
13612 if (VecTy->getNumElements() < 2)
13615 // Ensure the element type is legal.
13616 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13619 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13620 // 128 will be split into multiple interleaved accesses.
13621 return VecSize == 64 || VecSize % 128 == 0;
13624 /// \brief Lower an interleaved load into a vldN intrinsic.
13626 /// E.g. Lower an interleaved load (Factor = 2):
13627 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13628 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
13629 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
13632 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13633 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13634 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13635 bool ARMTargetLowering::lowerInterleavedLoad(
13636 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13637 ArrayRef<unsigned> Indices, unsigned Factor) const {
13638 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13639 "Invalid interleave factor");
13640 assert(!Shuffles.empty() && "Empty shufflevector input");
13641 assert(Shuffles.size() == Indices.size() &&
13642 "Unmatched number of shufflevectors and indices");
13644 VectorType *VecTy = Shuffles[0]->getType();
13645 Type *EltTy = VecTy->getVectorElementType();
13647 const DataLayout &DL = LI->getModule()->getDataLayout();
13649 // Skip if we do not have NEON and skip illegal vector types. We can
13650 // "legalize" wide vector types into multiple interleaved accesses as long as
13651 // the vector types are divisible by 128.
13652 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13655 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13657 // A pointer vector can not be the return type of the ldN intrinsics. Need to
13658 // load integer vectors first and then convert to pointer vectors.
13659 if (EltTy->isPointerTy())
13661 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13663 IRBuilder<> Builder(LI);
13665 // The base address of the load.
13666 Value *BaseAddr = LI->getPointerOperand();
13668 if (NumLoads > 1) {
13669 // If we're going to generate more than one load, reset the sub-vector type
13670 // to something legal.
13671 VecTy = VectorType::get(VecTy->getVectorElementType(),
13672 VecTy->getVectorNumElements() / NumLoads);
13674 // We will compute the pointer operand of each load from the original base
13675 // address using GEPs. Cast the base address to a pointer to the scalar
13677 BaseAddr = Builder.CreateBitCast(
13678 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13679 LI->getPointerAddressSpace()));
13682 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13684 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13685 Type *Tys[] = {VecTy, Int8Ptr};
13686 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13687 Intrinsic::arm_neon_vld3,
13688 Intrinsic::arm_neon_vld4};
13689 Function *VldnFunc =
13690 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13692 // Holds sub-vectors extracted from the load intrinsic return values. The
13693 // sub-vectors are associated with the shufflevector instructions they will
13695 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13697 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13699 // If we're generating more than one load, compute the base address of
13700 // subsequent loads as an offset from the previous.
13702 BaseAddr = Builder.CreateConstGEP1_32(
13703 BaseAddr, VecTy->getVectorNumElements() * Factor);
13705 SmallVector<Value *, 2> Ops;
13706 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13707 Ops.push_back(Builder.getInt32(LI->getAlignment()));
13709 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13711 // Replace uses of each shufflevector with the corresponding vector loaded
13713 for (unsigned i = 0; i < Shuffles.size(); i++) {
13714 ShuffleVectorInst *SV = Shuffles[i];
13715 unsigned Index = Indices[i];
13717 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13719 // Convert the integer vector to pointer vector if the element is pointer.
13720 if (EltTy->isPointerTy())
13721 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13723 SubVecs[SV].push_back(SubVec);
13727 // Replace uses of the shufflevector instructions with the sub-vectors
13728 // returned by the load intrinsic. If a shufflevector instruction is
13729 // associated with more than one sub-vector, those sub-vectors will be
13730 // concatenated into a single wide vector.
13731 for (ShuffleVectorInst *SVI : Shuffles) {
13732 auto &SubVec = SubVecs[SVI];
13734 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13735 SVI->replaceAllUsesWith(WideVec);
13741 /// \brief Lower an interleaved store into a vstN intrinsic.
13743 /// E.g. Lower an interleaved store (Factor = 3):
13744 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13745 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13746 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13749 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13750 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13751 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13752 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13754 /// Note that the new shufflevectors will be removed and we'll only generate one
13755 /// vst3 instruction in CodeGen.
13757 /// Example for a more general valid mask (Factor 3). Lower:
13758 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
13759 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
13760 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
13763 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
13764 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
13765 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
13766 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13767 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13768 ShuffleVectorInst *SVI,
13769 unsigned Factor) const {
13770 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13771 "Invalid interleave factor");
13773 VectorType *VecTy = SVI->getType();
13774 assert(VecTy->getVectorNumElements() % Factor == 0 &&
13775 "Invalid interleaved store");
13777 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
13778 Type *EltTy = VecTy->getVectorElementType();
13779 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
13781 const DataLayout &DL = SI->getModule()->getDataLayout();
13783 // Skip if we do not have NEON and skip illegal vector types. We can
13784 // "legalize" wide vector types into multiple interleaved accesses as long as
13785 // the vector types are divisible by 128.
13786 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
13789 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
13791 Value *Op0 = SVI->getOperand(0);
13792 Value *Op1 = SVI->getOperand(1);
13793 IRBuilder<> Builder(SI);
13795 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13796 // vectors to integer vectors.
13797 if (EltTy->isPointerTy()) {
13798 Type *IntTy = DL.getIntPtrType(EltTy);
13800 // Convert to the corresponding integer vector.
13802 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13803 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13804 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13806 SubVecTy = VectorType::get(IntTy, LaneLen);
13809 // The base address of the store.
13810 Value *BaseAddr = SI->getPointerOperand();
13812 if (NumStores > 1) {
13813 // If we're going to generate more than one store, reset the lane length
13814 // and sub-vector type to something legal.
13815 LaneLen /= NumStores;
13816 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
13818 // We will compute the pointer operand of each store from the original base
13819 // address using GEPs. Cast the base address to a pointer to the scalar
13821 BaseAddr = Builder.CreateBitCast(
13822 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
13823 SI->getPointerAddressSpace()));
13826 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
13828 auto Mask = SVI->getShuffleMask();
13830 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13831 Type *Tys[] = {Int8Ptr, SubVecTy};
13832 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13833 Intrinsic::arm_neon_vst3,
13834 Intrinsic::arm_neon_vst4};
13836 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
13838 // If we generating more than one store, we compute the base address of
13839 // subsequent stores as an offset from the previous.
13840 if (StoreCount > 0)
13841 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
13843 SmallVector<Value *, 6> Ops;
13844 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13846 Function *VstNFunc =
13847 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
13849 // Split the shufflevector operands into sub vectors for the new vstN call.
13850 for (unsigned i = 0; i < Factor; i++) {
13851 unsigned IdxI = StoreCount * LaneLen * Factor + i;
13852 if (Mask[IdxI] >= 0) {
13853 Ops.push_back(Builder.CreateShuffleVector(
13854 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
13856 unsigned StartMask = 0;
13857 for (unsigned j = 1; j < LaneLen; j++) {
13858 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
13859 if (Mask[IdxJ * Factor + IdxI] >= 0) {
13860 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
13864 // Note: If all elements in a chunk are undefs, StartMask=0!
13865 // Note: Filling undef gaps with random elements is ok, since
13866 // those elements were being written anyway (with undefs).
13867 // In the case of all undefs we're defaulting to using elems from 0
13868 // Note: StartMask cannot be negative, it's checked in
13869 // isReInterleaveMask
13870 Ops.push_back(Builder.CreateShuffleVector(
13871 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
13875 Ops.push_back(Builder.getInt32(SI->getAlignment()));
13876 Builder.CreateCall(VstNFunc, Ops);
13889 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13890 uint64_t &Members) {
13891 if (auto *ST = dyn_cast<StructType>(Ty)) {
13892 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13893 uint64_t SubMembers = 0;
13894 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13896 Members += SubMembers;
13898 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13899 uint64_t SubMembers = 0;
13900 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13902 Members += SubMembers * AT->getNumElements();
13903 } else if (Ty->isFloatTy()) {
13904 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13908 } else if (Ty->isDoubleTy()) {
13909 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13913 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13920 return VT->getBitWidth() == 64;
13922 return VT->getBitWidth() == 128;
13924 switch (VT->getBitWidth()) {
13937 return (Members > 0 && Members <= 4);
13940 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13941 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13942 /// passing according to AAPCS rules.
13943 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13944 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13945 if (getEffectiveCallingConv(CallConv, isVarArg) !=
13946 CallingConv::ARM_AAPCS_VFP)
13949 HABaseType Base = HA_UNKNOWN;
13950 uint64_t Members = 0;
13951 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13952 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13954 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13955 return IsHA || IsIntArray;
13958 unsigned ARMTargetLowering::getExceptionPointerRegister(
13959 const Constant *PersonalityFn) const {
13960 // Platforms which do not use SjLj EH may return values in these registers
13961 // via the personality function.
13962 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
13965 unsigned ARMTargetLowering::getExceptionSelectorRegister(
13966 const Constant *PersonalityFn) const {
13967 // Platforms which do not use SjLj EH may return values in these registers
13968 // via the personality function.
13969 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
13972 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13973 // Update IsSplitCSR in ARMFunctionInfo.
13974 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
13975 AFI->setIsSplitCSR(true);
13978 void ARMTargetLowering::insertCopiesSplitCSR(
13979 MachineBasicBlock *Entry,
13980 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13981 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
13982 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13986 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13987 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13988 MachineBasicBlock::iterator MBBI = Entry->begin();
13989 for (const MCPhysReg *I = IStart; *I; ++I) {
13990 const TargetRegisterClass *RC = nullptr;
13991 if (ARM::GPRRegClass.contains(*I))
13992 RC = &ARM::GPRRegClass;
13993 else if (ARM::DPRRegClass.contains(*I))
13994 RC = &ARM::DPRRegClass;
13996 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13998 unsigned NewVR = MRI->createVirtualRegister(RC);
13999 // Create copy from CSR to a virtual register.
14000 // FIXME: this currently does not emit CFI pseudo-instructions, it works
14001 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14002 // nounwind. If we want to generalize this later, we may need to emit
14003 // CFI pseudo-instructions.
14004 assert(Entry->getParent()->getFunction()->hasFnAttribute(
14005 Attribute::NoUnwind) &&
14006 "Function should be nounwind in insertCopiesSplitCSR!");
14007 Entry->addLiveIn(*I);
14008 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14011 // Insert the copy-back instructions right before the terminator.
14012 for (auto *Exit : Exits)
14013 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14014 TII->get(TargetOpcode::COPY), *I)