1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (!VT.isFloatingPoint() &&
147 VT != MVT::v2i64 && VT != MVT::v1i64)
148 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
149 setOperationAction(Opcode, VT, Legal);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPairRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163 const ARMSubtarget &STI)
164 : TargetLowering(TM), Subtarget(&STI) {
165 RegInfo = Subtarget->getRegisterInfo();
166 Itins = Subtarget->getInstrItineraryData();
168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
170 if (Subtarget->isTargetMachO()) {
171 // Uses VFP for Thumb libfuncs if available.
172 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174 static const struct {
175 const RTLIB::Libcall Op;
176 const char * const Name;
177 const ISD::CondCode Cond;
179 // Single-precision floating-point arithmetic.
180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
185 // Double-precision floating-point arithmetic.
186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
191 // Single-precision comparisons.
192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
201 // Double-precision comparisons.
202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
211 // Floating-point to integer conversions.
212 // i64 conversions are done via library routines even when generating VFP
213 // instructions, so use the same ones.
214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
219 // Conversions between floating types.
220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
223 // Integer to floating-point conversions.
224 // i64 conversions are done via library routines even when generating VFP
225 // instructions, so use the same ones.
226 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227 // e.g., __floatunsidf vs. __floatunssidfvfp.
228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
234 for (const auto &LC : LibraryCalls) {
235 setLibcallName(LC.Op, LC.Name);
236 if (LC.Cond != ISD::SETCC_INVALID)
237 setCmpLibcallCC(LC.Op, LC.Cond);
241 // Set the correct calling convention for ARMv7k WatchOS. It's just
242 // AAPCS_VFP for functions as simple as libcalls.
243 if (Subtarget->isTargetWatchOS()) {
244 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
245 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
249 // These libcalls are not available in 32-bit.
250 setLibcallName(RTLIB::SHL_I128, nullptr);
251 setLibcallName(RTLIB::SRL_I128, nullptr);
252 setLibcallName(RTLIB::SRA_I128, nullptr);
255 if (Subtarget->isAAPCS_ABI() &&
256 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
257 Subtarget->isTargetAndroid())) {
258 static const struct {
259 const RTLIB::Libcall Op;
260 const char * const Name;
261 const CallingConv::ID CC;
262 const ISD::CondCode Cond;
264 // Double-precision floating-point arithmetic helper functions
265 // RTABI chapter 4.1.2, Table 2
266 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271 // Double-precision floating-point comparison helper functions
272 // RTABI chapter 4.1.2, Table 3
273 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
275 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282 // Single-precision floating-point arithmetic helper functions
283 // RTABI chapter 4.1.2, Table 4
284 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289 // Single-precision floating-point comparison helper functions
290 // RTABI chapter 4.1.2, Table 5
291 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
293 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300 // Floating-point to integer conversions.
301 // RTABI chapter 4.1.2, Table 6
302 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 // Conversions between floating types.
312 // RTABI chapter 4.1.2, Table 7
313 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 // Integer to floating-point conversions.
318 // RTABI chapter 4.1.2, Table 8
319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 // Long long helper functions
329 // RTABI chapter 4.2, Table 9
330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 // Integer division functions
336 // RTABI chapter 4.3.1
337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 for (const auto &LC : LibraryCalls) {
348 setLibcallName(LC.Op, LC.Name);
349 setLibcallCallingConv(LC.Op, LC.CC);
350 if (LC.Cond != ISD::SETCC_INVALID)
351 setCmpLibcallCC(LC.Op, LC.Cond);
354 // EABI dependent RTLIB
355 if (TM.Options.EABIVersion == EABI::EABI4 ||
356 TM.Options.EABIVersion == EABI::EABI5) {
357 static const struct {
358 const RTLIB::Libcall Op;
359 const char *const Name;
360 const CallingConv::ID CC;
361 const ISD::CondCode Cond;
362 } MemOpsLibraryCalls[] = {
364 // RTABI chapter 4.3.4
365 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370 for (const auto &LC : MemOpsLibraryCalls) {
371 setLibcallName(LC.Op, LC.Name);
372 setLibcallCallingConv(LC.Op, LC.CC);
373 if (LC.Cond != ISD::SETCC_INVALID)
374 setCmpLibcallCC(LC.Op, LC.Cond);
379 if (Subtarget->isTargetWindows()) {
380 static const struct {
381 const RTLIB::Libcall Op;
382 const char * const Name;
383 const CallingConv::ID CC;
385 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
386 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
387 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
388 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
389 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
390 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
391 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
392 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
393 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
394 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
395 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
396 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
399 for (const auto &LC : LibraryCalls) {
400 setLibcallName(LC.Op, LC.Name);
401 setLibcallCallingConv(LC.Op, LC.CC);
405 // Use divmod compiler-rt calls for iOS 5.0 and later.
406 if (Subtarget->isTargetWatchOS() ||
407 (Subtarget->isTargetIOS() &&
408 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
409 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
410 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
413 // The half <-> float conversion functions are always soft-float, but are
414 // needed for some targets which use a hard-float calling convention by
416 if (Subtarget->isAAPCS_ABI()) {
417 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
418 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
421 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
422 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
423 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
426 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
427 // a __gnu_ prefix (which is the default).
428 if (Subtarget->isTargetAEABI()) {
429 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
430 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
431 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f");
434 if (Subtarget->isThumb1Only())
435 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
437 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
439 !Subtarget->isThumb1Only()) {
440 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
444 for (MVT VT : MVT::vector_valuetypes()) {
445 for (MVT InnerVT : MVT::vector_valuetypes()) {
446 setTruncStoreAction(VT, InnerVT, Expand);
447 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
448 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
449 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
452 setOperationAction(ISD::MULHS, VT, Expand);
453 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454 setOperationAction(ISD::MULHU, VT, Expand);
455 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::BSWAP, VT, Expand);
460 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
461 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
463 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
464 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
466 if (Subtarget->hasNEON()) {
467 addDRTypeForNEON(MVT::v2f32);
468 addDRTypeForNEON(MVT::v8i8);
469 addDRTypeForNEON(MVT::v4i16);
470 addDRTypeForNEON(MVT::v2i32);
471 addDRTypeForNEON(MVT::v1i64);
473 addQRTypeForNEON(MVT::v4f32);
474 addQRTypeForNEON(MVT::v2f64);
475 addQRTypeForNEON(MVT::v16i8);
476 addQRTypeForNEON(MVT::v8i16);
477 addQRTypeForNEON(MVT::v4i32);
478 addQRTypeForNEON(MVT::v2i64);
480 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
481 // neither Neon nor VFP support any arithmetic operations on it.
482 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
483 // supported for v4f32.
484 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
485 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
486 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
487 // FIXME: Code duplication: FDIV and FREM are expanded always, see
488 // ARMTargetLowering::addTypeForNEON method for details.
489 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
490 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
491 // FIXME: Create unittest.
492 // In another words, find a way when "copysign" appears in DAG with vector
494 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
495 // FIXME: Code duplication: SETCC has custom operation action, see
496 // ARMTargetLowering::addTypeForNEON method for details.
497 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
498 // FIXME: Create unittest for FNEG and for FABS.
499 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
501 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
502 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
503 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
504 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
505 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
506 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
507 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
508 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
509 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
510 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
511 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
512 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
513 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
514 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
515 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
516 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
517 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
519 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
520 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
521 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
522 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
523 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
524 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
525 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
526 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
527 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
528 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
529 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
530 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
531 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
532 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
533 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
535 // Mark v2f32 intrinsics.
536 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
537 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
538 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
539 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
540 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
541 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
542 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
543 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
544 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
545 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
546 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
547 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
548 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
549 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
550 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
552 // Neon does not support some operations on v1i64 and v2i64 types.
553 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
554 // Custom handling for some quad-vector types to detect VMULL.
555 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
556 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
557 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
558 // Custom handling for some vector types to avoid expensive expansions
559 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
560 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
561 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
562 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
563 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
564 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
565 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
566 // a destination type that is wider than the source, and nor does
567 // it have a FP_TO_[SU]INT instruction with a narrower destination than
569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
570 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
571 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
572 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
574 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
575 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
577 // NEON does not have single instruction CTPOP for vectors with element
578 // types wider than 8-bits. However, custom lowering can leverage the
579 // v8i8/v16i8 vcnt instruction.
580 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
581 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
582 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
583 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
585 // NEON does not have single instruction CTTZ for vectors.
586 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
587 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
588 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
589 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
591 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
592 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
593 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
594 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
596 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
597 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
598 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
603 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
606 // NEON only has FMA instructions as of VFP4.
607 if (!Subtarget->hasVFP4()) {
608 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
609 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
612 setTargetDAGCombine(ISD::INTRINSIC_VOID);
613 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
614 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
615 setTargetDAGCombine(ISD::SHL);
616 setTargetDAGCombine(ISD::SRL);
617 setTargetDAGCombine(ISD::SRA);
618 setTargetDAGCombine(ISD::SIGN_EXTEND);
619 setTargetDAGCombine(ISD::ZERO_EXTEND);
620 setTargetDAGCombine(ISD::ANY_EXTEND);
621 setTargetDAGCombine(ISD::BUILD_VECTOR);
622 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
623 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
624 setTargetDAGCombine(ISD::STORE);
625 setTargetDAGCombine(ISD::FP_TO_SINT);
626 setTargetDAGCombine(ISD::FP_TO_UINT);
627 setTargetDAGCombine(ISD::FDIV);
628 setTargetDAGCombine(ISD::LOAD);
630 // It is legal to extload from v4i8 to v4i16 or v4i32.
631 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
633 for (MVT VT : MVT::integer_vector_valuetypes()) {
634 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
635 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
636 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
641 // ARM and Thumb2 support UMLAL/SMLAL.
642 if (!Subtarget->isThumb1Only())
643 setTargetDAGCombine(ISD::ADDC);
645 if (Subtarget->isFPOnlySP()) {
646 // When targeting a floating-point unit with only single-precision
647 // operations, f64 is legal for the few double-precision instructions which
648 // are present However, no double-precision operations other than moves,
649 // loads and stores are provided by the hardware.
650 setOperationAction(ISD::FADD, MVT::f64, Expand);
651 setOperationAction(ISD::FSUB, MVT::f64, Expand);
652 setOperationAction(ISD::FMUL, MVT::f64, Expand);
653 setOperationAction(ISD::FMA, MVT::f64, Expand);
654 setOperationAction(ISD::FDIV, MVT::f64, Expand);
655 setOperationAction(ISD::FREM, MVT::f64, Expand);
656 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
657 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
658 setOperationAction(ISD::FNEG, MVT::f64, Expand);
659 setOperationAction(ISD::FABS, MVT::f64, Expand);
660 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
661 setOperationAction(ISD::FSIN, MVT::f64, Expand);
662 setOperationAction(ISD::FCOS, MVT::f64, Expand);
663 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
664 setOperationAction(ISD::FPOW, MVT::f64, Expand);
665 setOperationAction(ISD::FLOG, MVT::f64, Expand);
666 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
667 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
668 setOperationAction(ISD::FEXP, MVT::f64, Expand);
669 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
670 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
671 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
672 setOperationAction(ISD::FRINT, MVT::f64, Expand);
673 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
674 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
675 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
676 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
677 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
678 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
679 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
680 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
681 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
682 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
685 computeRegisterProperties(Subtarget->getRegisterInfo());
687 // ARM does not have floating-point extending loads.
688 for (MVT VT : MVT::fp_valuetypes()) {
689 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
690 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
693 // ... or truncating stores
694 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
695 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
696 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
698 // ARM does not have i1 sign extending load.
699 for (MVT VT : MVT::integer_valuetypes())
700 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
702 // ARM supports all 4 flavors of integer indexed load / store.
703 if (!Subtarget->isThumb1Only()) {
704 for (unsigned im = (unsigned)ISD::PRE_INC;
705 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
706 setIndexedLoadAction(im, MVT::i1, Legal);
707 setIndexedLoadAction(im, MVT::i8, Legal);
708 setIndexedLoadAction(im, MVT::i16, Legal);
709 setIndexedLoadAction(im, MVT::i32, Legal);
710 setIndexedStoreAction(im, MVT::i1, Legal);
711 setIndexedStoreAction(im, MVT::i8, Legal);
712 setIndexedStoreAction(im, MVT::i16, Legal);
713 setIndexedStoreAction(im, MVT::i32, Legal);
717 setOperationAction(ISD::SADDO, MVT::i32, Custom);
718 setOperationAction(ISD::UADDO, MVT::i32, Custom);
719 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
720 setOperationAction(ISD::USUBO, MVT::i32, Custom);
722 // i64 operation support.
723 setOperationAction(ISD::MUL, MVT::i64, Expand);
724 setOperationAction(ISD::MULHU, MVT::i32, Expand);
725 if (Subtarget->isThumb1Only()) {
726 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
727 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
729 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
730 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
731 setOperationAction(ISD::MULHS, MVT::i32, Expand);
733 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
734 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
735 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
736 setOperationAction(ISD::SRL, MVT::i64, Custom);
737 setOperationAction(ISD::SRA, MVT::i64, Custom);
739 if (!Subtarget->isThumb1Only()) {
740 // FIXME: We should do this for Thumb1 as well.
741 setOperationAction(ISD::ADDC, MVT::i32, Custom);
742 setOperationAction(ISD::ADDE, MVT::i32, Custom);
743 setOperationAction(ISD::SUBC, MVT::i32, Custom);
744 setOperationAction(ISD::SUBE, MVT::i32, Custom);
747 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
748 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
750 // ARM does not have ROTL.
751 setOperationAction(ISD::ROTL, MVT::i32, Expand);
752 for (MVT VT : MVT::vector_valuetypes()) {
753 setOperationAction(ISD::ROTL, VT, Expand);
754 setOperationAction(ISD::ROTR, VT, Expand);
756 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
757 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
758 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
759 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
761 // These just redirect to CTTZ and CTLZ on ARM.
762 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
763 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
765 // @llvm.readcyclecounter requires the Performance Monitors extension.
766 // Default to the 0 expansion on unsupported platforms.
767 // FIXME: Technically there are older ARM CPUs that have
768 // implementation-specific ways of obtaining this information.
769 if (Subtarget->hasPerfMon())
770 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
772 // Only ARMv6 has BSWAP.
773 if (!Subtarget->hasV6Ops())
774 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
776 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
777 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
778 // These are expanded into libcalls if the cpu doesn't have HW divider.
779 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
780 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
783 setOperationAction(ISD::SREM, MVT::i32, Expand);
784 setOperationAction(ISD::UREM, MVT::i32, Expand);
785 // Register based DivRem for AEABI (RTABI 4.2)
786 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
787 setOperationAction(ISD::SREM, MVT::i64, Custom);
788 setOperationAction(ISD::UREM, MVT::i64, Custom);
790 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
791 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
792 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
793 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
794 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
795 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
796 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
797 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
799 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
800 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
801 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
802 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
803 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
804 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
805 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
806 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
808 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
809 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
811 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
812 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
815 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
816 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
817 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
818 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
820 setOperationAction(ISD::TRAP, MVT::Other, Legal);
822 // Use the default implementation.
823 setOperationAction(ISD::VASTART, MVT::Other, Custom);
824 setOperationAction(ISD::VAARG, MVT::Other, Expand);
825 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
826 setOperationAction(ISD::VAEND, MVT::Other, Expand);
827 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
828 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
830 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
831 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
833 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
835 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
836 // the default expansion. If we are targeting a single threaded system,
837 // then set them all for expand so we can lower them later into their
839 if (TM.Options.ThreadModel == ThreadModel::Single)
840 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
841 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
842 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
843 // to ldrex/strex loops already.
844 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
846 // On v8, we have particularly efficient implementations of atomic fences
847 // if they can be combined with nearby atomic loads and stores.
848 if (!Subtarget->hasV8Ops()) {
849 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
850 setInsertFencesForAtomic(true);
853 // If there's anything we can use as a barrier, go through custom lowering
855 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
856 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
858 // Set them all for expansion, which will force libcalls.
859 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
860 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
861 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
862 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
863 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
864 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
865 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
866 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
867 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
868 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
869 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
870 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
871 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
872 // Unordered/Monotonic case.
873 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
874 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
877 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
879 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
880 if (!Subtarget->hasV6Ops()) {
881 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
882 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
884 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
886 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
887 !Subtarget->isThumb1Only()) {
888 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
889 // iff target supports vfp2.
890 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
891 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
894 // We want to custom lower some of our intrinsics.
895 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
896 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
897 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
898 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
899 if (Subtarget->useSjLjEH())
900 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
902 setOperationAction(ISD::SETCC, MVT::i32, Expand);
903 setOperationAction(ISD::SETCC, MVT::f32, Expand);
904 setOperationAction(ISD::SETCC, MVT::f64, Expand);
905 setOperationAction(ISD::SELECT, MVT::i32, Custom);
906 setOperationAction(ISD::SELECT, MVT::f32, Custom);
907 setOperationAction(ISD::SELECT, MVT::f64, Custom);
908 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
909 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
910 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
912 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
913 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
914 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
915 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
916 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
918 // We don't support sin/cos/fmod/copysign/pow
919 setOperationAction(ISD::FSIN, MVT::f64, Expand);
920 setOperationAction(ISD::FSIN, MVT::f32, Expand);
921 setOperationAction(ISD::FCOS, MVT::f32, Expand);
922 setOperationAction(ISD::FCOS, MVT::f64, Expand);
923 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
924 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
925 setOperationAction(ISD::FREM, MVT::f64, Expand);
926 setOperationAction(ISD::FREM, MVT::f32, Expand);
927 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
928 !Subtarget->isThumb1Only()) {
929 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
930 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
932 setOperationAction(ISD::FPOW, MVT::f64, Expand);
933 setOperationAction(ISD::FPOW, MVT::f32, Expand);
935 if (!Subtarget->hasVFP4()) {
936 setOperationAction(ISD::FMA, MVT::f64, Expand);
937 setOperationAction(ISD::FMA, MVT::f32, Expand);
940 // Various VFP goodness
941 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
942 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
943 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
944 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
945 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
948 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
949 if (!Subtarget->hasFP16()) {
950 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
951 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
955 // Combine sin / cos into one node or libcall if possible.
956 if (Subtarget->hasSinCos()) {
957 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
958 setLibcallName(RTLIB::SINCOS_F64, "sincos");
959 if (Subtarget->isTargetWatchOS()) {
960 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
961 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
963 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
964 // For iOS, we don't want to the normal expansion of a libcall to
965 // sincos. We want to issue a libcall to __sincos_stret.
966 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
967 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
971 // FP-ARMv8 implements a lot of rounding-like FP operations.
972 if (Subtarget->hasFPARMv8()) {
973 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
974 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
975 setOperationAction(ISD::FROUND, MVT::f32, Legal);
976 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
977 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
978 setOperationAction(ISD::FRINT, MVT::f32, Legal);
979 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
980 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
981 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
982 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
983 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
984 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
986 if (!Subtarget->isFPOnlySP()) {
987 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
988 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
989 setOperationAction(ISD::FROUND, MVT::f64, Legal);
990 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
991 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
992 setOperationAction(ISD::FRINT, MVT::f64, Legal);
993 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
994 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
998 if (Subtarget->hasNEON()) {
999 // vmin and vmax aren't available in a scalar form, so we use
1000 // a NEON instruction with an undef lane instead.
1001 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1002 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1003 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1004 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1005 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1006 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1009 // We have target-specific dag combine patterns for the following nodes:
1010 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1011 setTargetDAGCombine(ISD::ADD);
1012 setTargetDAGCombine(ISD::SUB);
1013 setTargetDAGCombine(ISD::MUL);
1014 setTargetDAGCombine(ISD::AND);
1015 setTargetDAGCombine(ISD::OR);
1016 setTargetDAGCombine(ISD::XOR);
1018 if (Subtarget->hasV6Ops())
1019 setTargetDAGCombine(ISD::SRL);
1021 setStackPointerRegisterToSaveRestore(ARM::SP);
1023 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1024 !Subtarget->hasVFP2())
1025 setSchedulingPreference(Sched::RegPressure);
1027 setSchedulingPreference(Sched::Hybrid);
1029 //// temporary - rewrite interface to use type
1030 MaxStoresPerMemset = 8;
1031 MaxStoresPerMemsetOptSize = 4;
1032 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1033 MaxStoresPerMemcpyOptSize = 2;
1034 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1035 MaxStoresPerMemmoveOptSize = 2;
1037 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1038 // are at least 4 bytes aligned.
1039 setMinStackArgumentAlignment(4);
1041 // Prefer likely predicted branches to selects on out-of-order cores.
1042 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1044 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1047 bool ARMTargetLowering::useSoftFloat() const {
1048 return Subtarget->useSoftFloat();
1051 // FIXME: It might make sense to define the representative register class as the
1052 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1053 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1054 // SPR's representative would be DPR_VFP2. This should work well if register
1055 // pressure tracking were modified such that a register use would increment the
1056 // pressure of the register class's representative and all of it's super
1057 // classes' representatives transitively. We have not implemented this because
1058 // of the difficulty prior to coalescing of modeling operand register classes
1059 // due to the common occurrence of cross class copies and subregister insertions
1061 std::pair<const TargetRegisterClass *, uint8_t>
1062 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1064 const TargetRegisterClass *RRC = nullptr;
1066 switch (VT.SimpleTy) {
1068 return TargetLowering::findRepresentativeClass(TRI, VT);
1069 // Use DPR as representative register class for all floating point
1070 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1071 // the cost is 1 for both f32 and f64.
1072 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1073 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1074 RRC = &ARM::DPRRegClass;
1075 // When NEON is used for SP, only half of the register file is available
1076 // because operations that define both SP and DP results will be constrained
1077 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1078 // coalescing by double-counting the SP regs. See the FIXME above.
1079 if (Subtarget->useNEONForSinglePrecisionFP())
1082 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1083 case MVT::v4f32: case MVT::v2f64:
1084 RRC = &ARM::DPRRegClass;
1088 RRC = &ARM::DPRRegClass;
1092 RRC = &ARM::DPRRegClass;
1096 return std::make_pair(RRC, Cost);
1099 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1100 switch ((ARMISD::NodeType)Opcode) {
1101 case ARMISD::FIRST_NUMBER: break;
1102 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1103 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1104 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1105 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1106 case ARMISD::CALL: return "ARMISD::CALL";
1107 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1108 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1109 case ARMISD::tCALL: return "ARMISD::tCALL";
1110 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1111 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1112 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1113 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1114 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1115 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1116 case ARMISD::CMP: return "ARMISD::CMP";
1117 case ARMISD::CMN: return "ARMISD::CMN";
1118 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1119 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1120 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1121 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1122 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1124 case ARMISD::CMOV: return "ARMISD::CMOV";
1126 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1127 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1128 case ARMISD::RRX: return "ARMISD::RRX";
1130 case ARMISD::ADDC: return "ARMISD::ADDC";
1131 case ARMISD::ADDE: return "ARMISD::ADDE";
1132 case ARMISD::SUBC: return "ARMISD::SUBC";
1133 case ARMISD::SUBE: return "ARMISD::SUBE";
1135 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1136 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1138 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1139 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1140 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1142 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1144 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1146 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1148 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1150 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1152 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1153 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1155 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1156 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1157 case ARMISD::VCGE: return "ARMISD::VCGE";
1158 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1159 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1160 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1161 case ARMISD::VCGT: return "ARMISD::VCGT";
1162 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1163 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1164 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1165 case ARMISD::VTST: return "ARMISD::VTST";
1167 case ARMISD::VSHL: return "ARMISD::VSHL";
1168 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1169 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1170 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1171 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1172 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1173 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1174 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1175 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1176 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1177 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1178 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1179 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1180 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1181 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1182 case ARMISD::VSLI: return "ARMISD::VSLI";
1183 case ARMISD::VSRI: return "ARMISD::VSRI";
1184 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1185 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1186 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1187 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1188 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1189 case ARMISD::VDUP: return "ARMISD::VDUP";
1190 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1191 case ARMISD::VEXT: return "ARMISD::VEXT";
1192 case ARMISD::VREV64: return "ARMISD::VREV64";
1193 case ARMISD::VREV32: return "ARMISD::VREV32";
1194 case ARMISD::VREV16: return "ARMISD::VREV16";
1195 case ARMISD::VZIP: return "ARMISD::VZIP";
1196 case ARMISD::VUZP: return "ARMISD::VUZP";
1197 case ARMISD::VTRN: return "ARMISD::VTRN";
1198 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1199 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1200 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1201 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1202 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1203 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1204 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1205 case ARMISD::BFI: return "ARMISD::BFI";
1206 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1207 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1208 case ARMISD::VBSL: return "ARMISD::VBSL";
1209 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1210 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1211 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1212 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1213 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1214 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1215 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1216 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1217 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1218 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1219 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1220 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1221 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1222 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1223 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1224 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1225 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1226 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1227 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1228 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1229 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1234 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1237 return getPointerTy(DL);
1238 return VT.changeVectorElementTypeToInteger();
1241 /// getRegClassFor - Return the register class that should be used for the
1242 /// specified value type.
1243 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1244 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1245 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1246 // load / store 4 to 8 consecutive D registers.
1247 if (Subtarget->hasNEON()) {
1248 if (VT == MVT::v4i64)
1249 return &ARM::QQPRRegClass;
1250 if (VT == MVT::v8i64)
1251 return &ARM::QQQQPRRegClass;
1253 return TargetLowering::getRegClassFor(VT);
1256 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1257 // source/dest is aligned and the copy size is large enough. We therefore want
1258 // to align such objects passed to memory intrinsics.
1259 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1260 unsigned &PrefAlign) const {
1261 if (!isa<MemIntrinsic>(CI))
1264 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1265 // cycle faster than 4-byte aligned LDM.
1266 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1270 // Create a fast isel object.
1272 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1273 const TargetLibraryInfo *libInfo) const {
1274 return ARM::createFastISel(funcInfo, libInfo);
1277 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1278 unsigned NumVals = N->getNumValues();
1280 return Sched::RegPressure;
1282 for (unsigned i = 0; i != NumVals; ++i) {
1283 EVT VT = N->getValueType(i);
1284 if (VT == MVT::Glue || VT == MVT::Other)
1286 if (VT.isFloatingPoint() || VT.isVector())
1290 if (!N->isMachineOpcode())
1291 return Sched::RegPressure;
1293 // Load are scheduled for latency even if there instruction itinerary
1294 // is not available.
1295 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1296 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1298 if (MCID.getNumDefs() == 0)
1299 return Sched::RegPressure;
1300 if (!Itins->isEmpty() &&
1301 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1304 return Sched::RegPressure;
1307 //===----------------------------------------------------------------------===//
1309 //===----------------------------------------------------------------------===//
1311 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1312 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1314 default: llvm_unreachable("Unknown condition code!");
1315 case ISD::SETNE: return ARMCC::NE;
1316 case ISD::SETEQ: return ARMCC::EQ;
1317 case ISD::SETGT: return ARMCC::GT;
1318 case ISD::SETGE: return ARMCC::GE;
1319 case ISD::SETLT: return ARMCC::LT;
1320 case ISD::SETLE: return ARMCC::LE;
1321 case ISD::SETUGT: return ARMCC::HI;
1322 case ISD::SETUGE: return ARMCC::HS;
1323 case ISD::SETULT: return ARMCC::LO;
1324 case ISD::SETULE: return ARMCC::LS;
1328 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1329 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1330 ARMCC::CondCodes &CondCode2) {
1331 CondCode2 = ARMCC::AL;
1333 default: llvm_unreachable("Unknown FP condition!");
1335 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1337 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1339 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1340 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1341 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1342 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1343 case ISD::SETO: CondCode = ARMCC::VC; break;
1344 case ISD::SETUO: CondCode = ARMCC::VS; break;
1345 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1346 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1347 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1349 case ISD::SETULT: CondCode = ARMCC::LT; break;
1351 case ISD::SETULE: CondCode = ARMCC::LE; break;
1353 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1357 //===----------------------------------------------------------------------===//
1358 // Calling Convention Implementation
1359 //===----------------------------------------------------------------------===//
1361 #include "ARMGenCallingConv.inc"
1363 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1364 /// account presence of floating point hardware and calling convention
1365 /// limitations, such as support for variadic functions.
1367 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1368 bool isVarArg) const {
1371 llvm_unreachable("Unsupported calling convention");
1372 case CallingConv::ARM_AAPCS:
1373 case CallingConv::ARM_APCS:
1374 case CallingConv::GHC:
1376 case CallingConv::ARM_AAPCS_VFP:
1377 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1378 case CallingConv::C:
1379 if (!Subtarget->isAAPCS_ABI())
1380 return CallingConv::ARM_APCS;
1381 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1382 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1384 return CallingConv::ARM_AAPCS_VFP;
1386 return CallingConv::ARM_AAPCS;
1387 case CallingConv::Fast:
1388 case CallingConv::CXX_FAST_TLS:
1389 if (!Subtarget->isAAPCS_ABI()) {
1390 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1391 return CallingConv::Fast;
1392 return CallingConv::ARM_APCS;
1393 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1394 return CallingConv::ARM_AAPCS_VFP;
1396 return CallingConv::ARM_AAPCS;
1400 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1401 /// CallingConvention.
1402 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1404 bool isVarArg) const {
1405 switch (getEffectiveCallingConv(CC, isVarArg)) {
1407 llvm_unreachable("Unsupported calling convention");
1408 case CallingConv::ARM_APCS:
1409 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1410 case CallingConv::ARM_AAPCS:
1411 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1412 case CallingConv::ARM_AAPCS_VFP:
1413 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1414 case CallingConv::Fast:
1415 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1416 case CallingConv::GHC:
1417 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1421 /// LowerCallResult - Lower the result values of a call into the
1422 /// appropriate copies out of appropriate physical registers.
1424 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1425 CallingConv::ID CallConv, bool isVarArg,
1426 const SmallVectorImpl<ISD::InputArg> &Ins,
1427 SDLoc dl, SelectionDAG &DAG,
1428 SmallVectorImpl<SDValue> &InVals,
1429 bool isThisReturn, SDValue ThisVal) const {
1431 // Assign locations to each value returned by this call.
1432 SmallVector<CCValAssign, 16> RVLocs;
1433 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1434 *DAG.getContext(), Call);
1435 CCInfo.AnalyzeCallResult(Ins,
1436 CCAssignFnForNode(CallConv, /* Return*/ true,
1439 // Copy all of the result registers out of their specified physreg.
1440 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1441 CCValAssign VA = RVLocs[i];
1443 // Pass 'this' value directly from the argument to return value, to avoid
1444 // reg unit interference
1445 if (i == 0 && isThisReturn) {
1446 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1447 "unexpected return calling convention register assignment");
1448 InVals.push_back(ThisVal);
1453 if (VA.needsCustom()) {
1454 // Handle f64 or half of a v2f64.
1455 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1457 Chain = Lo.getValue(1);
1458 InFlag = Lo.getValue(2);
1459 VA = RVLocs[++i]; // skip ahead to next loc
1460 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1462 Chain = Hi.getValue(1);
1463 InFlag = Hi.getValue(2);
1464 if (!Subtarget->isLittle())
1466 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1468 if (VA.getLocVT() == MVT::v2f64) {
1469 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1470 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1471 DAG.getConstant(0, dl, MVT::i32));
1473 VA = RVLocs[++i]; // skip ahead to next loc
1474 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1475 Chain = Lo.getValue(1);
1476 InFlag = Lo.getValue(2);
1477 VA = RVLocs[++i]; // skip ahead to next loc
1478 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1479 Chain = Hi.getValue(1);
1480 InFlag = Hi.getValue(2);
1481 if (!Subtarget->isLittle())
1483 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1484 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1485 DAG.getConstant(1, dl, MVT::i32));
1488 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1490 Chain = Val.getValue(1);
1491 InFlag = Val.getValue(2);
1494 switch (VA.getLocInfo()) {
1495 default: llvm_unreachable("Unknown loc info!");
1496 case CCValAssign::Full: break;
1497 case CCValAssign::BCvt:
1498 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1502 InVals.push_back(Val);
1508 /// LowerMemOpCallTo - Store the argument to the stack.
1510 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1511 SDValue StackPtr, SDValue Arg,
1512 SDLoc dl, SelectionDAG &DAG,
1513 const CCValAssign &VA,
1514 ISD::ArgFlagsTy Flags) const {
1515 unsigned LocMemOffset = VA.getLocMemOffset();
1516 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1517 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1519 return DAG.getStore(
1520 Chain, dl, Arg, PtrOff,
1521 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1525 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1526 SDValue Chain, SDValue &Arg,
1527 RegsToPassVector &RegsToPass,
1528 CCValAssign &VA, CCValAssign &NextVA,
1530 SmallVectorImpl<SDValue> &MemOpChains,
1531 ISD::ArgFlagsTy Flags) const {
1533 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1534 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1535 unsigned id = Subtarget->isLittle() ? 0 : 1;
1536 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1538 if (NextVA.isRegLoc())
1539 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1541 assert(NextVA.isMemLoc());
1542 if (!StackPtr.getNode())
1543 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1544 getPointerTy(DAG.getDataLayout()));
1546 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1552 /// LowerCall - Lowering a call into a callseq_start <-
1553 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1556 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1557 SmallVectorImpl<SDValue> &InVals) const {
1558 SelectionDAG &DAG = CLI.DAG;
1560 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1561 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1562 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1563 SDValue Chain = CLI.Chain;
1564 SDValue Callee = CLI.Callee;
1565 bool &isTailCall = CLI.IsTailCall;
1566 CallingConv::ID CallConv = CLI.CallConv;
1567 bool doesNotRet = CLI.DoesNotReturn;
1568 bool isVarArg = CLI.IsVarArg;
1570 MachineFunction &MF = DAG.getMachineFunction();
1571 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1572 bool isThisReturn = false;
1573 bool isSibCall = false;
1574 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1576 // Disable tail calls if they're not supported.
1577 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1581 // Check if it's really possible to do a tail call.
1582 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1583 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1584 Outs, OutVals, Ins, DAG);
1585 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1586 report_fatal_error("failed to perform tail call elimination on a call "
1587 "site marked musttail");
1588 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1589 // detected sibcalls.
1596 // Analyze operands of the call, assigning locations to each operand.
1597 SmallVector<CCValAssign, 16> ArgLocs;
1598 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1599 *DAG.getContext(), Call);
1600 CCInfo.AnalyzeCallOperands(Outs,
1601 CCAssignFnForNode(CallConv, /* Return*/ false,
1604 // Get a count of how many bytes are to be pushed on the stack.
1605 unsigned NumBytes = CCInfo.getNextStackOffset();
1607 // For tail calls, memory operands are available in our caller's stack.
1611 // Adjust the stack pointer for the new arguments...
1612 // These operations are automatically eliminated by the prolog/epilog pass
1614 Chain = DAG.getCALLSEQ_START(Chain,
1615 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1618 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1620 RegsToPassVector RegsToPass;
1621 SmallVector<SDValue, 8> MemOpChains;
1623 // Walk the register/memloc assignments, inserting copies/loads. In the case
1624 // of tail call optimization, arguments are handled later.
1625 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1627 ++i, ++realArgIdx) {
1628 CCValAssign &VA = ArgLocs[i];
1629 SDValue Arg = OutVals[realArgIdx];
1630 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1631 bool isByVal = Flags.isByVal();
1633 // Promote the value if needed.
1634 switch (VA.getLocInfo()) {
1635 default: llvm_unreachable("Unknown loc info!");
1636 case CCValAssign::Full: break;
1637 case CCValAssign::SExt:
1638 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1640 case CCValAssign::ZExt:
1641 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1643 case CCValAssign::AExt:
1644 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1646 case CCValAssign::BCvt:
1647 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1651 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1652 if (VA.needsCustom()) {
1653 if (VA.getLocVT() == MVT::v2f64) {
1654 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1655 DAG.getConstant(0, dl, MVT::i32));
1656 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1657 DAG.getConstant(1, dl, MVT::i32));
1659 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1660 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1662 VA = ArgLocs[++i]; // skip ahead to next loc
1663 if (VA.isRegLoc()) {
1664 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1665 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1667 assert(VA.isMemLoc());
1669 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1670 dl, DAG, VA, Flags));
1673 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1674 StackPtr, MemOpChains, Flags);
1676 } else if (VA.isRegLoc()) {
1677 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1678 assert(VA.getLocVT() == MVT::i32 &&
1679 "unexpected calling convention register assignment");
1680 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1681 "unexpected use of 'returned'");
1682 isThisReturn = true;
1684 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1685 } else if (isByVal) {
1686 assert(VA.isMemLoc());
1687 unsigned offset = 0;
1689 // True if this byval aggregate will be split between registers
1691 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1692 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1694 if (CurByValIdx < ByValArgsCount) {
1696 unsigned RegBegin, RegEnd;
1697 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1700 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1702 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1703 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1704 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1705 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1706 MachinePointerInfo(),
1707 false, false, false,
1708 DAG.InferPtrAlignment(AddArg));
1709 MemOpChains.push_back(Load.getValue(1));
1710 RegsToPass.push_back(std::make_pair(j, Load));
1713 // If parameter size outsides register area, "offset" value
1714 // helps us to calculate stack slot for remained part properly.
1715 offset = RegEnd - RegBegin;
1717 CCInfo.nextInRegsParam();
1720 if (Flags.getByValSize() > 4*offset) {
1721 auto PtrVT = getPointerTy(DAG.getDataLayout());
1722 unsigned LocMemOffset = VA.getLocMemOffset();
1723 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1724 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1725 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1726 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1727 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1729 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1732 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1733 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1734 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1737 } else if (!isSibCall) {
1738 assert(VA.isMemLoc());
1740 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1741 dl, DAG, VA, Flags));
1745 if (!MemOpChains.empty())
1746 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1748 // Build a sequence of copy-to-reg nodes chained together with token chain
1749 // and flag operands which copy the outgoing args into the appropriate regs.
1751 // Tail call byval lowering might overwrite argument registers so in case of
1752 // tail call optimization the copies to registers are lowered later.
1754 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1755 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1756 RegsToPass[i].second, InFlag);
1757 InFlag = Chain.getValue(1);
1760 // For tail calls lower the arguments to the 'real' stack slot.
1762 // Force all the incoming stack arguments to be loaded from the stack
1763 // before any new outgoing arguments are stored to the stack, because the
1764 // outgoing stack slots may alias the incoming argument stack slots, and
1765 // the alias isn't otherwise explicit. This is slightly more conservative
1766 // than necessary, because it means that each store effectively depends
1767 // on every argument instead of just those arguments it would clobber.
1769 // Do not flag preceding copytoreg stuff together with the following stuff.
1771 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1772 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1773 RegsToPass[i].second, InFlag);
1774 InFlag = Chain.getValue(1);
1779 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1780 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1781 // node so that legalize doesn't hack it.
1782 bool isDirect = false;
1783 bool isARMFunc = false;
1784 bool isLocalARMFunc = false;
1785 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1786 auto PtrVt = getPointerTy(DAG.getDataLayout());
1788 if (Subtarget->genLongCalls()) {
1789 assert((Subtarget->isTargetWindows() ||
1790 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1791 "long-calls with non-static relocation model!");
1792 // Handle a global address or an external symbol. If it's not one of
1793 // those, the target's already in a register, so we don't need to do
1795 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1796 const GlobalValue *GV = G->getGlobal();
1797 // Create a constant pool entry for the callee address
1798 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1799 ARMConstantPoolValue *CPV =
1800 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1802 // Get the address of the callee into a register
1803 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1804 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1805 Callee = DAG.getLoad(
1806 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1807 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1809 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1810 const char *Sym = S->getSymbol();
1812 // Create a constant pool entry for the callee address
1813 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1814 ARMConstantPoolValue *CPV =
1815 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1816 ARMPCLabelIndex, 0);
1817 // Get the address of the callee into a register
1818 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1819 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1820 Callee = DAG.getLoad(
1821 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1822 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1825 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1826 const GlobalValue *GV = G->getGlobal();
1828 bool isDef = GV->isStrongDefinitionForLinker();
1829 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1830 getTargetMachine().getRelocationModel() != Reloc::Static;
1831 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1832 // ARM call to a local ARM function is predicable.
1833 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1834 // tBX takes a register source operand.
1835 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1836 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1837 Callee = DAG.getNode(
1838 ARMISD::WrapperPIC, dl, PtrVt,
1839 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1840 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1841 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1842 false, false, true, 0);
1843 } else if (Subtarget->isTargetCOFF()) {
1844 assert(Subtarget->isTargetWindows() &&
1845 "Windows is the only supported COFF target");
1846 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1847 ? ARMII::MO_DLLIMPORT
1848 : ARMII::MO_NO_FLAG;
1850 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1851 if (GV->hasDLLImportStorageClass())
1853 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1854 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1855 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1856 false, false, false, 0);
1858 // On ELF targets for PIC code, direct calls should go through the PLT
1859 unsigned OpFlags = 0;
1860 if (Subtarget->isTargetELF() &&
1861 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1862 OpFlags = ARMII::MO_PLT;
1863 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1865 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1867 bool isStub = Subtarget->isTargetMachO() &&
1868 getTargetMachine().getRelocationModel() != Reloc::Static;
1869 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1870 // tBX takes a register source operand.
1871 const char *Sym = S->getSymbol();
1872 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1873 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1874 ARMConstantPoolValue *CPV =
1875 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1876 ARMPCLabelIndex, 4);
1877 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1878 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1879 Callee = DAG.getLoad(
1880 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1881 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1883 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1884 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1886 unsigned OpFlags = 0;
1887 // On ELF targets for PIC code, direct calls should go through the PLT
1888 if (Subtarget->isTargetELF() &&
1889 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1890 OpFlags = ARMII::MO_PLT;
1891 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1895 // FIXME: handle tail calls differently.
1897 if (Subtarget->isThumb()) {
1898 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1899 CallOpc = ARMISD::CALL_NOLINK;
1901 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1903 if (!isDirect && !Subtarget->hasV5TOps())
1904 CallOpc = ARMISD::CALL_NOLINK;
1905 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1906 // Emit regular call when code size is the priority
1907 !MF.getFunction()->optForMinSize())
1908 // "mov lr, pc; b _foo" to avoid confusing the RSP
1909 CallOpc = ARMISD::CALL_NOLINK;
1911 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1914 std::vector<SDValue> Ops;
1915 Ops.push_back(Chain);
1916 Ops.push_back(Callee);
1918 // Add argument registers to the end of the list so that they are known live
1920 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1921 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1922 RegsToPass[i].second.getValueType()));
1924 // Add a register mask operand representing the call-preserved registers.
1926 const uint32_t *Mask;
1927 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1929 // For 'this' returns, use the R0-preserving mask if applicable
1930 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1932 // Set isThisReturn to false if the calling convention is not one that
1933 // allows 'returned' to be modeled in this way, so LowerCallResult does
1934 // not try to pass 'this' straight through
1935 isThisReturn = false;
1936 Mask = ARI->getCallPreservedMask(MF, CallConv);
1939 Mask = ARI->getCallPreservedMask(MF, CallConv);
1941 assert(Mask && "Missing call preserved mask for calling convention");
1942 Ops.push_back(DAG.getRegisterMask(Mask));
1945 if (InFlag.getNode())
1946 Ops.push_back(InFlag);
1948 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1950 MF.getFrameInfo()->setHasTailCall();
1951 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1954 // Returns a chain and a flag for retval copy to use.
1955 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1956 InFlag = Chain.getValue(1);
1958 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1959 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1961 InFlag = Chain.getValue(1);
1963 // Handle result values, copying them out of physregs into vregs that we
1965 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1966 InVals, isThisReturn,
1967 isThisReturn ? OutVals[0] : SDValue());
1970 /// HandleByVal - Every parameter *after* a byval parameter is passed
1971 /// on the stack. Remember the next parameter register to allocate,
1972 /// and then confiscate the rest of the parameter registers to insure
1974 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1975 unsigned Align) const {
1976 assert((State->getCallOrPrologue() == Prologue ||
1977 State->getCallOrPrologue() == Call) &&
1978 "unhandled ParmContext");
1980 // Byval (as with any stack) slots are always at least 4 byte aligned.
1981 Align = std::max(Align, 4U);
1983 unsigned Reg = State->AllocateReg(GPRArgRegs);
1987 unsigned AlignInRegs = Align / 4;
1988 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1989 for (unsigned i = 0; i < Waste; ++i)
1990 Reg = State->AllocateReg(GPRArgRegs);
1995 unsigned Excess = 4 * (ARM::R4 - Reg);
1997 // Special case when NSAA != SP and parameter size greater than size of
1998 // all remained GPR regs. In that case we can't split parameter, we must
1999 // send it to stack. We also must set NCRN to R4, so waste all
2000 // remained registers.
2001 const unsigned NSAAOffset = State->getNextStackOffset();
2002 if (NSAAOffset != 0 && Size > Excess) {
2003 while (State->AllocateReg(GPRArgRegs))
2008 // First register for byval parameter is the first register that wasn't
2009 // allocated before this method call, so it would be "reg".
2010 // If parameter is small enough to be saved in range [reg, r4), then
2011 // the end (first after last) register would be reg + param-size-in-regs,
2012 // else parameter would be splitted between registers and stack,
2013 // end register would be r4 in this case.
2014 unsigned ByValRegBegin = Reg;
2015 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2016 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2017 // Note, first register is allocated in the beginning of function already,
2018 // allocate remained amount of registers we need.
2019 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2020 State->AllocateReg(GPRArgRegs);
2021 // A byval parameter that is split between registers and memory needs its
2022 // size truncated here.
2023 // In the case where the entire structure fits in registers, we set the
2024 // size in memory to zero.
2025 Size = std::max<int>(Size - Excess, 0);
2028 /// MatchingStackOffset - Return true if the given stack call argument is
2029 /// already available in the same position (relatively) of the caller's
2030 /// incoming argument stack.
2032 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2033 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2034 const TargetInstrInfo *TII) {
2035 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2037 if (Arg.getOpcode() == ISD::CopyFromReg) {
2038 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2039 if (!TargetRegisterInfo::isVirtualRegister(VR))
2041 MachineInstr *Def = MRI->getVRegDef(VR);
2044 if (!Flags.isByVal()) {
2045 if (!TII->isLoadFromStackSlot(Def, FI))
2050 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2051 if (Flags.isByVal())
2052 // ByVal argument is passed in as a pointer but it's now being
2053 // dereferenced. e.g.
2054 // define @foo(%struct.X* %A) {
2055 // tail call @bar(%struct.X* byval %A)
2058 SDValue Ptr = Ld->getBasePtr();
2059 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2062 FI = FINode->getIndex();
2066 assert(FI != INT_MAX);
2067 if (!MFI->isFixedObjectIndex(FI))
2069 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2072 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2073 /// for tail call optimization. Targets which want to do tail call
2074 /// optimization should implement this function.
2076 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2077 CallingConv::ID CalleeCC,
2079 bool isCalleeStructRet,
2080 bool isCallerStructRet,
2081 const SmallVectorImpl<ISD::OutputArg> &Outs,
2082 const SmallVectorImpl<SDValue> &OutVals,
2083 const SmallVectorImpl<ISD::InputArg> &Ins,
2084 SelectionDAG& DAG) const {
2085 const Function *CallerF = DAG.getMachineFunction().getFunction();
2086 CallingConv::ID CallerCC = CallerF->getCallingConv();
2087 bool CCMatch = CallerCC == CalleeCC;
2089 assert(Subtarget->supportsTailCall());
2091 // Look for obvious safe cases to perform tail call optimization that do not
2092 // require ABI changes. This is what gcc calls sibcall.
2094 // Do not sibcall optimize vararg calls unless the call site is not passing
2096 if (isVarArg && !Outs.empty())
2099 // Exception-handling functions need a special set of instructions to indicate
2100 // a return to the hardware. Tail-calling another function would probably
2102 if (CallerF->hasFnAttribute("interrupt"))
2105 // Also avoid sibcall optimization if either caller or callee uses struct
2106 // return semantics.
2107 if (isCalleeStructRet || isCallerStructRet)
2110 // Externally-defined functions with weak linkage should not be
2111 // tail-called on ARM when the OS does not support dynamic
2112 // pre-emption of symbols, as the AAELF spec requires normal calls
2113 // to undefined weak functions to be replaced with a NOP or jump to the
2114 // next instruction. The behaviour of branch instructions in this
2115 // situation (as used for tail calls) is implementation-defined, so we
2116 // cannot rely on the linker replacing the tail call with a return.
2117 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2118 const GlobalValue *GV = G->getGlobal();
2119 const Triple &TT = getTargetMachine().getTargetTriple();
2120 if (GV->hasExternalWeakLinkage() &&
2121 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2125 // If the calling conventions do not match, then we'd better make sure the
2126 // results are returned in the same way as what the caller expects.
2128 SmallVector<CCValAssign, 16> RVLocs1;
2129 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2130 *DAG.getContext(), Call);
2131 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2133 SmallVector<CCValAssign, 16> RVLocs2;
2134 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2135 *DAG.getContext(), Call);
2136 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2138 if (RVLocs1.size() != RVLocs2.size())
2140 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2141 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2143 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2145 if (RVLocs1[i].isRegLoc()) {
2146 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2149 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2155 // If Caller's vararg or byval argument has been split between registers and
2156 // stack, do not perform tail call, since part of the argument is in caller's
2158 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2159 getInfo<ARMFunctionInfo>();
2160 if (AFI_Caller->getArgRegsSaveSize())
2163 // If the callee takes no arguments then go on to check the results of the
2165 if (!Outs.empty()) {
2166 // Check if stack adjustment is needed. For now, do not do this if any
2167 // argument is passed on the stack.
2168 SmallVector<CCValAssign, 16> ArgLocs;
2169 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2170 *DAG.getContext(), Call);
2171 CCInfo.AnalyzeCallOperands(Outs,
2172 CCAssignFnForNode(CalleeCC, false, isVarArg));
2173 if (CCInfo.getNextStackOffset()) {
2174 MachineFunction &MF = DAG.getMachineFunction();
2176 // Check if the arguments are already laid out in the right way as
2177 // the caller's fixed stack objects.
2178 MachineFrameInfo *MFI = MF.getFrameInfo();
2179 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2180 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2181 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2183 ++i, ++realArgIdx) {
2184 CCValAssign &VA = ArgLocs[i];
2185 EVT RegVT = VA.getLocVT();
2186 SDValue Arg = OutVals[realArgIdx];
2187 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2188 if (VA.getLocInfo() == CCValAssign::Indirect)
2190 if (VA.needsCustom()) {
2191 // f64 and vector types are split into multiple registers or
2192 // register/stack-slot combinations. The types will not match
2193 // the registers; give up on memory f64 refs until we figure
2194 // out what to do about this.
2197 if (!ArgLocs[++i].isRegLoc())
2199 if (RegVT == MVT::v2f64) {
2200 if (!ArgLocs[++i].isRegLoc())
2202 if (!ArgLocs[++i].isRegLoc())
2205 } else if (!VA.isRegLoc()) {
2206 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2218 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2219 MachineFunction &MF, bool isVarArg,
2220 const SmallVectorImpl<ISD::OutputArg> &Outs,
2221 LLVMContext &Context) const {
2222 SmallVector<CCValAssign, 16> RVLocs;
2223 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2224 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2228 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2229 SDLoc DL, SelectionDAG &DAG) {
2230 const MachineFunction &MF = DAG.getMachineFunction();
2231 const Function *F = MF.getFunction();
2233 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2235 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2236 // version of the "preferred return address". These offsets affect the return
2237 // instruction if this is a return from PL1 without hypervisor extensions.
2238 // IRQ/FIQ: +4 "subs pc, lr, #4"
2239 // SWI: 0 "subs pc, lr, #0"
2240 // ABORT: +4 "subs pc, lr, #4"
2241 // UNDEF: +4/+2 "subs pc, lr, #0"
2242 // UNDEF varies depending on where the exception came from ARM or Thumb
2243 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2246 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2249 else if (IntKind == "SWI" || IntKind == "UNDEF")
2252 report_fatal_error("Unsupported interrupt attribute. If present, value "
2253 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2255 RetOps.insert(RetOps.begin() + 1,
2256 DAG.getConstant(LROffset, DL, MVT::i32, false));
2258 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2262 ARMTargetLowering::LowerReturn(SDValue Chain,
2263 CallingConv::ID CallConv, bool isVarArg,
2264 const SmallVectorImpl<ISD::OutputArg> &Outs,
2265 const SmallVectorImpl<SDValue> &OutVals,
2266 SDLoc dl, SelectionDAG &DAG) const {
2268 // CCValAssign - represent the assignment of the return value to a location.
2269 SmallVector<CCValAssign, 16> RVLocs;
2271 // CCState - Info about the registers and stack slots.
2272 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2273 *DAG.getContext(), Call);
2275 // Analyze outgoing return values.
2276 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2280 SmallVector<SDValue, 4> RetOps;
2281 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2282 bool isLittleEndian = Subtarget->isLittle();
2284 MachineFunction &MF = DAG.getMachineFunction();
2285 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2286 AFI->setReturnRegsCount(RVLocs.size());
2288 // Copy the result values into the output registers.
2289 for (unsigned i = 0, realRVLocIdx = 0;
2291 ++i, ++realRVLocIdx) {
2292 CCValAssign &VA = RVLocs[i];
2293 assert(VA.isRegLoc() && "Can only return in registers!");
2295 SDValue Arg = OutVals[realRVLocIdx];
2297 switch (VA.getLocInfo()) {
2298 default: llvm_unreachable("Unknown loc info!");
2299 case CCValAssign::Full: break;
2300 case CCValAssign::BCvt:
2301 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2305 if (VA.needsCustom()) {
2306 if (VA.getLocVT() == MVT::v2f64) {
2307 // Extract the first half and return it in two registers.
2308 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2309 DAG.getConstant(0, dl, MVT::i32));
2310 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2311 DAG.getVTList(MVT::i32, MVT::i32), Half);
2313 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2314 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2316 Flag = Chain.getValue(1);
2317 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2318 VA = RVLocs[++i]; // skip ahead to next loc
2319 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2320 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2322 Flag = Chain.getValue(1);
2323 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2324 VA = RVLocs[++i]; // skip ahead to next loc
2326 // Extract the 2nd half and fall through to handle it as an f64 value.
2327 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2328 DAG.getConstant(1, dl, MVT::i32));
2330 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2332 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2333 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2334 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2335 fmrrd.getValue(isLittleEndian ? 0 : 1),
2337 Flag = Chain.getValue(1);
2338 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2339 VA = RVLocs[++i]; // skip ahead to next loc
2340 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2341 fmrrd.getValue(isLittleEndian ? 1 : 0),
2344 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2346 // Guarantee that all emitted copies are
2347 // stuck together, avoiding something bad.
2348 Flag = Chain.getValue(1);
2349 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2351 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2352 const MCPhysReg *I =
2353 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2356 if (ARM::GPRRegClass.contains(*I))
2357 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2358 else if (ARM::DPRRegClass.contains(*I))
2359 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2361 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2365 // Update chain and glue.
2368 RetOps.push_back(Flag);
2370 // CPUs which aren't M-class use a special sequence to return from
2371 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2372 // though we use "subs pc, lr, #N").
2374 // M-class CPUs actually use a normal return sequence with a special
2375 // (hardware-provided) value in LR, so the normal code path works.
2376 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2377 !Subtarget->isMClass()) {
2378 if (Subtarget->isThumb1Only())
2379 report_fatal_error("interrupt attribute is not supported in Thumb1");
2380 return LowerInterruptReturn(RetOps, dl, DAG);
2383 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2386 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2387 if (N->getNumValues() != 1)
2389 if (!N->hasNUsesOfValue(1, 0))
2392 SDValue TCChain = Chain;
2393 SDNode *Copy = *N->use_begin();
2394 if (Copy->getOpcode() == ISD::CopyToReg) {
2395 // If the copy has a glue operand, we conservatively assume it isn't safe to
2396 // perform a tail call.
2397 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2399 TCChain = Copy->getOperand(0);
2400 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2401 SDNode *VMov = Copy;
2402 // f64 returned in a pair of GPRs.
2403 SmallPtrSet<SDNode*, 2> Copies;
2404 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2406 if (UI->getOpcode() != ISD::CopyToReg)
2410 if (Copies.size() > 2)
2413 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2415 SDValue UseChain = UI->getOperand(0);
2416 if (Copies.count(UseChain.getNode()))
2420 // We are at the top of this chain.
2421 // If the copy has a glue operand, we conservatively assume it
2422 // isn't safe to perform a tail call.
2423 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2429 } else if (Copy->getOpcode() == ISD::BITCAST) {
2430 // f32 returned in a single GPR.
2431 if (!Copy->hasOneUse())
2433 Copy = *Copy->use_begin();
2434 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2436 // If the copy has a glue operand, we conservatively assume it isn't safe to
2437 // perform a tail call.
2438 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2440 TCChain = Copy->getOperand(0);
2445 bool HasRet = false;
2446 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2448 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2449 UI->getOpcode() != ARMISD::INTRET_FLAG)
2461 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2462 if (!Subtarget->supportsTailCall())
2466 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2467 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2473 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2474 // and pass the lower and high parts through.
2475 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2477 SDValue WriteValue = Op->getOperand(2);
2479 // This function is only supposed to be called for i64 type argument.
2480 assert(WriteValue.getValueType() == MVT::i64
2481 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2483 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2484 DAG.getConstant(0, DL, MVT::i32));
2485 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2486 DAG.getConstant(1, DL, MVT::i32));
2487 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2488 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2491 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2492 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2493 // one of the above mentioned nodes. It has to be wrapped because otherwise
2494 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2495 // be used to form addressing mode. These wrapped nodes will be selected
2497 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2498 EVT PtrVT = Op.getValueType();
2499 // FIXME there is no actual debug info here
2501 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2503 if (CP->isMachineConstantPoolEntry())
2504 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2505 CP->getAlignment());
2507 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2508 CP->getAlignment());
2509 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2512 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2513 return MachineJumpTableInfo::EK_Inline;
2516 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2517 SelectionDAG &DAG) const {
2518 MachineFunction &MF = DAG.getMachineFunction();
2519 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2520 unsigned ARMPCLabelIndex = 0;
2522 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2523 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2524 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2526 if (RelocM == Reloc::Static) {
2527 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2529 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2530 ARMPCLabelIndex = AFI->createPICLabelUId();
2531 ARMConstantPoolValue *CPV =
2532 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2533 ARMCP::CPBlockAddress, PCAdj);
2534 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2536 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2538 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2539 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2540 false, false, false, 0);
2541 if (RelocM == Reloc::Static)
2543 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2544 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2547 /// \brief Convert a TLS address reference into the correct sequence of loads
2548 /// and calls to compute the variable's address for Darwin, and return an
2549 /// SDValue containing the final node.
2551 /// Darwin only has one TLS scheme which must be capable of dealing with the
2552 /// fully general situation, in the worst case. This means:
2553 /// + "extern __thread" declaration.
2554 /// + Defined in a possibly unknown dynamic library.
2556 /// The general system is that each __thread variable has a [3 x i32] descriptor
2557 /// which contains information used by the runtime to calculate the address. The
2558 /// only part of this the compiler needs to know about is the first word, which
2559 /// contains a function pointer that must be called with the address of the
2560 /// entire descriptor in "r0".
2562 /// Since this descriptor may be in a different unit, in general access must
2563 /// proceed along the usual ARM rules. A common sequence to produce is:
2565 /// movw rT1, :lower16:_var$non_lazy_ptr
2566 /// movt rT1, :upper16:_var$non_lazy_ptr
2570 /// [...address now in r0...]
2572 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2573 SelectionDAG &DAG) const {
2574 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2577 // First step is to get the address of the actua global symbol. This is where
2578 // the TLS descriptor lives.
2579 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2581 // The first entry in the descriptor is a function pointer that we must call
2582 // to obtain the address of the variable.
2583 SDValue Chain = DAG.getEntryNode();
2584 SDValue FuncTLVGet =
2585 DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2586 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2587 false, true, true, 4);
2588 Chain = FuncTLVGet.getValue(1);
2590 MachineFunction &F = DAG.getMachineFunction();
2591 MachineFrameInfo *MFI = F.getFrameInfo();
2592 MFI->setAdjustsStack(true);
2594 // TLS calls preserve all registers except those that absolutely must be
2595 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2598 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2599 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2600 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2602 // Finally, we can make the call. This is just a degenerate version of a
2603 // normal AArch64 call node: r0 takes the address of the descriptor, and
2604 // returns the address of the variable in this thread.
2605 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2607 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2608 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2609 DAG.getRegisterMask(Mask), Chain.getValue(1));
2610 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2613 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2615 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2616 SelectionDAG &DAG) const {
2618 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2619 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2620 MachineFunction &MF = DAG.getMachineFunction();
2621 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2622 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2623 ARMConstantPoolValue *CPV =
2624 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2625 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2626 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2627 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2629 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2630 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2631 false, false, false, 0);
2632 SDValue Chain = Argument.getValue(1);
2634 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2635 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2637 // call __tls_get_addr.
2640 Entry.Node = Argument;
2641 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2642 Args.push_back(Entry);
2644 // FIXME: is there useful debug info available here?
2645 TargetLowering::CallLoweringInfo CLI(DAG);
2646 CLI.setDebugLoc(dl).setChain(Chain)
2647 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2648 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2651 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2652 return CallResult.first;
2655 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2656 // "local exec" model.
2658 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2660 TLSModel::Model model) const {
2661 const GlobalValue *GV = GA->getGlobal();
2664 SDValue Chain = DAG.getEntryNode();
2665 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2666 // Get the Thread Pointer
2667 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2669 if (model == TLSModel::InitialExec) {
2670 MachineFunction &MF = DAG.getMachineFunction();
2671 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2672 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2673 // Initial exec model.
2674 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2675 ARMConstantPoolValue *CPV =
2676 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2677 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2679 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2680 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2681 Offset = DAG.getLoad(
2682 PtrVT, dl, Chain, Offset,
2683 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2685 Chain = Offset.getValue(1);
2687 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2688 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2690 Offset = DAG.getLoad(
2691 PtrVT, dl, Chain, Offset,
2692 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2696 assert(model == TLSModel::LocalExec);
2697 ARMConstantPoolValue *CPV =
2698 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2699 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2701 Offset = DAG.getLoad(
2702 PtrVT, dl, Chain, Offset,
2703 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2707 // The address of the thread local variable is the add of the thread
2708 // pointer with the offset of the variable.
2709 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2713 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2714 if (Subtarget->isTargetDarwin())
2715 return LowerGlobalTLSAddressDarwin(Op, DAG);
2717 // TODO: implement the "local dynamic" model
2718 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2719 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2720 if (DAG.getTarget().Options.EmulatedTLS)
2721 return LowerToTLSEmulatedModel(GA, DAG);
2723 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2726 case TLSModel::GeneralDynamic:
2727 case TLSModel::LocalDynamic:
2728 return LowerToTLSGeneralDynamicModel(GA, DAG);
2729 case TLSModel::InitialExec:
2730 case TLSModel::LocalExec:
2731 return LowerToTLSExecModels(GA, DAG, model);
2733 llvm_unreachable("bogus TLS model");
2736 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2737 SelectionDAG &DAG) const {
2738 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2740 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2741 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2743 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2745 MachineFunction &MF = DAG.getMachineFunction();
2746 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2747 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2748 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2750 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2751 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2752 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2753 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2754 /*AddCurrentAddress=*/UseGOT_PREL);
2755 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2756 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2757 SDValue Result = DAG.getLoad(
2758 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2759 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2761 SDValue Chain = Result.getValue(1);
2762 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2763 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2765 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2766 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2767 false, false, false, 0);
2771 // If we have T2 ops, we can materialize the address directly via movt/movw
2772 // pair. This is always cheaper.
2773 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2775 // FIXME: Once remat is capable of dealing with instructions with register
2776 // operands, expand this into two nodes.
2777 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2778 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2780 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2781 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2783 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2784 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2789 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2790 SelectionDAG &DAG) const {
2791 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2793 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2794 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2796 if (Subtarget->useMovt(DAG.getMachineFunction()))
2799 // FIXME: Once remat is capable of dealing with instructions with register
2800 // operands, expand this into multiple nodes
2802 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2804 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2805 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2807 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2808 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2809 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2810 false, false, false, 0);
2814 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2815 SelectionDAG &DAG) const {
2816 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2817 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2818 "Windows on ARM expects to use movw/movt");
2820 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2821 const ARMII::TOF TargetFlags =
2822 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2823 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2829 // FIXME: Once remat is capable of dealing with instructions with register
2830 // operands, expand this into two nodes.
2831 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2832 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2834 if (GV->hasDLLImportStorageClass())
2835 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2836 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2837 false, false, false, 0);
2842 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2844 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2845 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2846 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2847 Op.getOperand(1), Val);
2851 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2853 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2854 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2857 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2858 SelectionDAG &DAG) const {
2860 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2865 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2866 const ARMSubtarget *Subtarget) const {
2867 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2870 default: return SDValue(); // Don't custom lower most intrinsics.
2871 case Intrinsic::arm_rbit: {
2872 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2873 "RBIT intrinsic must have i32 type!");
2874 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2876 case Intrinsic::arm_thread_pointer: {
2877 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2878 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2880 case Intrinsic::eh_sjlj_lsda: {
2881 MachineFunction &MF = DAG.getMachineFunction();
2882 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2883 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2884 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2885 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2887 unsigned PCAdj = (RelocM != Reloc::PIC_)
2888 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2889 ARMConstantPoolValue *CPV =
2890 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2891 ARMCP::CPLSDA, PCAdj);
2892 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2893 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2894 SDValue Result = DAG.getLoad(
2895 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2896 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2899 if (RelocM == Reloc::PIC_) {
2900 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2901 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2905 case Intrinsic::arm_neon_vmulls:
2906 case Intrinsic::arm_neon_vmullu: {
2907 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2908 ? ARMISD::VMULLs : ARMISD::VMULLu;
2909 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2910 Op.getOperand(1), Op.getOperand(2));
2912 case Intrinsic::arm_neon_vminnm:
2913 case Intrinsic::arm_neon_vmaxnm: {
2914 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2915 ? ISD::FMINNUM : ISD::FMAXNUM;
2916 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2917 Op.getOperand(1), Op.getOperand(2));
2919 case Intrinsic::arm_neon_vminu:
2920 case Intrinsic::arm_neon_vmaxu: {
2921 if (Op.getValueType().isFloatingPoint())
2923 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2924 ? ISD::UMIN : ISD::UMAX;
2925 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2926 Op.getOperand(1), Op.getOperand(2));
2928 case Intrinsic::arm_neon_vmins:
2929 case Intrinsic::arm_neon_vmaxs: {
2930 // v{min,max}s is overloaded between signed integers and floats.
2931 if (!Op.getValueType().isFloatingPoint()) {
2932 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2933 ? ISD::SMIN : ISD::SMAX;
2934 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2935 Op.getOperand(1), Op.getOperand(2));
2937 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2938 ? ISD::FMINNAN : ISD::FMAXNAN;
2939 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2940 Op.getOperand(1), Op.getOperand(2));
2945 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2946 const ARMSubtarget *Subtarget) {
2947 // FIXME: handle "fence singlethread" more efficiently.
2949 if (!Subtarget->hasDataBarrier()) {
2950 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2951 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2953 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2954 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2955 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2956 DAG.getConstant(0, dl, MVT::i32));
2959 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2960 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2961 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2962 if (Subtarget->isMClass()) {
2963 // Only a full system barrier exists in the M-class architectures.
2964 Domain = ARM_MB::SY;
2965 } else if (Subtarget->isSwift() && Ord == Release) {
2966 // Swift happens to implement ISHST barriers in a way that's compatible with
2967 // Release semantics but weaker than ISH so we'd be fools not to use
2968 // it. Beware: other processors probably don't!
2969 Domain = ARM_MB::ISHST;
2972 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2973 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2974 DAG.getConstant(Domain, dl, MVT::i32));
2977 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2978 const ARMSubtarget *Subtarget) {
2979 // ARM pre v5TE and Thumb1 does not have preload instructions.
2980 if (!(Subtarget->isThumb2() ||
2981 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2982 // Just preserve the chain.
2983 return Op.getOperand(0);
2986 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2988 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2989 // ARMv7 with MP extension has PLDW.
2990 return Op.getOperand(0);
2992 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2993 if (Subtarget->isThumb()) {
2995 isRead = ~isRead & 1;
2996 isData = ~isData & 1;
2999 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3000 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3001 DAG.getConstant(isData, dl, MVT::i32));
3004 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3005 MachineFunction &MF = DAG.getMachineFunction();
3006 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3008 // vastart just stores the address of the VarArgsFrameIndex slot into the
3009 // memory location argument.
3011 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3012 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3013 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3014 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3015 MachinePointerInfo(SV), false, false, 0);
3019 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
3020 SDValue &Root, SelectionDAG &DAG,
3022 MachineFunction &MF = DAG.getMachineFunction();
3023 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3025 const TargetRegisterClass *RC;
3026 if (AFI->isThumb1OnlyFunction())
3027 RC = &ARM::tGPRRegClass;
3029 RC = &ARM::GPRRegClass;
3031 // Transform the arguments stored in physical registers into virtual ones.
3032 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3033 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3036 if (NextVA.isMemLoc()) {
3037 MachineFrameInfo *MFI = MF.getFrameInfo();
3038 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3040 // Create load node to retrieve arguments from the stack.
3041 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3042 ArgValue2 = DAG.getLoad(
3043 MVT::i32, dl, Root, FIN,
3044 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3047 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3048 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3050 if (!Subtarget->isLittle())
3051 std::swap (ArgValue, ArgValue2);
3052 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3055 // The remaining GPRs hold either the beginning of variable-argument
3056 // data, or the beginning of an aggregate passed by value (usually
3057 // byval). Either way, we allocate stack slots adjacent to the data
3058 // provided by our caller, and store the unallocated registers there.
3059 // If this is a variadic function, the va_list pointer will begin with
3060 // these values; otherwise, this reassembles a (byval) structure that
3061 // was split between registers and memory.
3062 // Return: The frame index registers were stored into.
3064 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3065 SDLoc dl, SDValue &Chain,
3066 const Value *OrigArg,
3067 unsigned InRegsParamRecordIdx,
3069 unsigned ArgSize) const {
3070 // Currently, two use-cases possible:
3071 // Case #1. Non-var-args function, and we meet first byval parameter.
3072 // Setup first unallocated register as first byval register;
3073 // eat all remained registers
3074 // (these two actions are performed by HandleByVal method).
3075 // Then, here, we initialize stack frame with
3076 // "store-reg" instructions.
3077 // Case #2. Var-args function, that doesn't contain byval parameters.
3078 // The same: eat all remained unallocated registers,
3079 // initialize stack frame.
3081 MachineFunction &MF = DAG.getMachineFunction();
3082 MachineFrameInfo *MFI = MF.getFrameInfo();
3083 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3084 unsigned RBegin, REnd;
3085 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3086 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3088 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3089 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3094 ArgOffset = -4 * (ARM::R4 - RBegin);
3096 auto PtrVT = getPointerTy(DAG.getDataLayout());
3097 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3098 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3100 SmallVector<SDValue, 4> MemOps;
3101 const TargetRegisterClass *RC =
3102 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3104 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3105 unsigned VReg = MF.addLiveIn(Reg, RC);
3106 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3108 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3109 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3110 MemOps.push_back(Store);
3111 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3114 if (!MemOps.empty())
3115 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3119 // Setup stack frame, the va_list pointer will start from.
3121 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3122 SDLoc dl, SDValue &Chain,
3124 unsigned TotalArgRegsSaveSize,
3125 bool ForceMutable) const {
3126 MachineFunction &MF = DAG.getMachineFunction();
3127 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3129 // Try to store any remaining integer argument regs
3130 // to their spots on the stack so that they may be loaded by deferencing
3131 // the result of va_next.
3132 // If there is no regs to be stored, just point address after last
3133 // argument passed via stack.
3134 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3135 CCInfo.getInRegsParamsCount(),
3136 CCInfo.getNextStackOffset(), 4);
3137 AFI->setVarArgsFrameIndex(FrameIndex);
3141 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3142 CallingConv::ID CallConv, bool isVarArg,
3143 const SmallVectorImpl<ISD::InputArg>
3145 SDLoc dl, SelectionDAG &DAG,
3146 SmallVectorImpl<SDValue> &InVals)
3148 MachineFunction &MF = DAG.getMachineFunction();
3149 MachineFrameInfo *MFI = MF.getFrameInfo();
3151 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3153 // Assign locations to all of the incoming arguments.
3154 SmallVector<CCValAssign, 16> ArgLocs;
3155 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3156 *DAG.getContext(), Prologue);
3157 CCInfo.AnalyzeFormalArguments(Ins,
3158 CCAssignFnForNode(CallConv, /* Return*/ false,
3161 SmallVector<SDValue, 16> ArgValues;
3163 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3164 unsigned CurArgIdx = 0;
3166 // Initially ArgRegsSaveSize is zero.
3167 // Then we increase this value each time we meet byval parameter.
3168 // We also increase this value in case of varargs function.
3169 AFI->setArgRegsSaveSize(0);
3171 // Calculate the amount of stack space that we need to allocate to store
3172 // byval and variadic arguments that are passed in registers.
3173 // We need to know this before we allocate the first byval or variadic
3174 // argument, as they will be allocated a stack slot below the CFA (Canonical
3175 // Frame Address, the stack pointer at entry to the function).
3176 unsigned ArgRegBegin = ARM::R4;
3177 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3178 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3181 CCValAssign &VA = ArgLocs[i];
3182 unsigned Index = VA.getValNo();
3183 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3184 if (!Flags.isByVal())
3187 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3188 unsigned RBegin, REnd;
3189 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3190 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3192 CCInfo.nextInRegsParam();
3194 CCInfo.rewindByValRegsInfo();
3196 int lastInsIndex = -1;
3197 if (isVarArg && MFI->hasVAStart()) {
3198 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3199 if (RegIdx != array_lengthof(GPRArgRegs))
3200 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3203 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3204 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3205 auto PtrVT = getPointerTy(DAG.getDataLayout());
3207 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3208 CCValAssign &VA = ArgLocs[i];
3209 if (Ins[VA.getValNo()].isOrigArg()) {
3210 std::advance(CurOrigArg,
3211 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3212 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3214 // Arguments stored in registers.
3215 if (VA.isRegLoc()) {
3216 EVT RegVT = VA.getLocVT();
3218 if (VA.needsCustom()) {
3219 // f64 and vector types are split up into multiple registers or
3220 // combinations of registers and stack slots.
3221 if (VA.getLocVT() == MVT::v2f64) {
3222 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3224 VA = ArgLocs[++i]; // skip ahead to next loc
3226 if (VA.isMemLoc()) {
3227 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3228 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3229 ArgValue2 = DAG.getLoad(
3230 MVT::f64, dl, Chain, FIN,
3231 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3232 false, false, false, 0);
3234 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3237 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3238 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3239 ArgValue, ArgValue1,
3240 DAG.getIntPtrConstant(0, dl));
3241 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3242 ArgValue, ArgValue2,
3243 DAG.getIntPtrConstant(1, dl));
3245 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3248 const TargetRegisterClass *RC;
3250 if (RegVT == MVT::f32)
3251 RC = &ARM::SPRRegClass;
3252 else if (RegVT == MVT::f64)
3253 RC = &ARM::DPRRegClass;
3254 else if (RegVT == MVT::v2f64)
3255 RC = &ARM::QPRRegClass;
3256 else if (RegVT == MVT::i32)
3257 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3258 : &ARM::GPRRegClass;
3260 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3262 // Transform the arguments in physical registers into virtual ones.
3263 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3264 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3267 // If this is an 8 or 16-bit value, it is really passed promoted
3268 // to 32 bits. Insert an assert[sz]ext to capture this, then
3269 // truncate to the right size.
3270 switch (VA.getLocInfo()) {
3271 default: llvm_unreachable("Unknown loc info!");
3272 case CCValAssign::Full: break;
3273 case CCValAssign::BCvt:
3274 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3276 case CCValAssign::SExt:
3277 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3278 DAG.getValueType(VA.getValVT()));
3279 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3281 case CCValAssign::ZExt:
3282 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3283 DAG.getValueType(VA.getValVT()));
3284 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3288 InVals.push_back(ArgValue);
3290 } else { // VA.isRegLoc()
3293 assert(VA.isMemLoc());
3294 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3296 int index = VA.getValNo();
3298 // Some Ins[] entries become multiple ArgLoc[] entries.
3299 // Process them only once.
3300 if (index != lastInsIndex)
3302 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3303 // FIXME: For now, all byval parameter objects are marked mutable.
3304 // This can be changed with more analysis.
3305 // In case of tail call optimization mark all arguments mutable.
3306 // Since they could be overwritten by lowering of arguments in case of
3308 if (Flags.isByVal()) {
3309 assert(Ins[index].isOrigArg() &&
3310 "Byval arguments cannot be implicit");
3311 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3313 int FrameIndex = StoreByValRegs(
3314 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3315 VA.getLocMemOffset(), Flags.getByValSize());
3316 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3317 CCInfo.nextInRegsParam();
3319 unsigned FIOffset = VA.getLocMemOffset();
3320 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3323 // Create load nodes to retrieve arguments from the stack.
3324 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3325 InVals.push_back(DAG.getLoad(
3326 VA.getValVT(), dl, Chain, FIN,
3327 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3328 false, false, false, 0));
3330 lastInsIndex = index;
3336 if (isVarArg && MFI->hasVAStart())
3337 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3338 CCInfo.getNextStackOffset(),
3339 TotalArgRegsSaveSize);
3341 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3346 /// isFloatingPointZero - Return true if this is +0.0.
3347 static bool isFloatingPointZero(SDValue Op) {
3348 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3349 return CFP->getValueAPF().isPosZero();
3350 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3351 // Maybe this has already been legalized into the constant pool?
3352 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3353 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3354 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3355 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3356 return CFP->getValueAPF().isPosZero();
3358 } else if (Op->getOpcode() == ISD::BITCAST &&
3359 Op->getValueType(0) == MVT::f64) {
3360 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3361 // created by LowerConstantFP().
3362 SDValue BitcastOp = Op->getOperand(0);
3363 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3364 isNullConstant(BitcastOp->getOperand(0)))
3370 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3371 /// the given operands.
3373 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3374 SDValue &ARMcc, SelectionDAG &DAG,
3376 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3377 unsigned C = RHSC->getZExtValue();
3378 if (!isLegalICmpImmediate(C)) {
3379 // Constant does not fit, try adjusting it by one?
3384 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3385 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3386 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3391 if (C != 0 && isLegalICmpImmediate(C-1)) {
3392 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3393 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3398 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3399 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3400 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3405 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3406 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3407 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3414 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3415 ARMISD::NodeType CompareType;
3418 CompareType = ARMISD::CMP;
3423 CompareType = ARMISD::CMPZ;
3426 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3427 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3430 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3432 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3434 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3436 if (!isFloatingPointZero(RHS))
3437 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3439 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3440 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3443 /// duplicateCmp - Glue values can have only one use, so this function
3444 /// duplicates a comparison node.
3446 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3447 unsigned Opc = Cmp.getOpcode();
3449 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3450 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3452 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3453 Cmp = Cmp.getOperand(0);
3454 Opc = Cmp.getOpcode();
3455 if (Opc == ARMISD::CMPFP)
3456 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3458 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3459 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3461 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3464 std::pair<SDValue, SDValue>
3465 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3466 SDValue &ARMcc) const {
3467 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3469 SDValue Value, OverflowCmp;
3470 SDValue LHS = Op.getOperand(0);
3471 SDValue RHS = Op.getOperand(1);
3474 // FIXME: We are currently always generating CMPs because we don't support
3475 // generating CMN through the backend. This is not as good as the natural
3476 // CMP case because it causes a register dependency and cannot be folded
3479 switch (Op.getOpcode()) {
3481 llvm_unreachable("Unknown overflow instruction!");
3483 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3484 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3485 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3488 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3489 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3490 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3493 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3494 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3495 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3498 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3499 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3500 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3504 return std::make_pair(Value, OverflowCmp);
3509 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3510 // Let legalize expand this if it isn't a legal type yet.
3511 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3514 SDValue Value, OverflowCmp;
3516 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3517 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3519 // We use 0 and 1 as false and true values.
3520 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3521 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3522 EVT VT = Op.getValueType();
3524 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3525 ARMcc, CCR, OverflowCmp);
3527 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3528 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3532 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3533 SDValue Cond = Op.getOperand(0);
3534 SDValue SelectTrue = Op.getOperand(1);
3535 SDValue SelectFalse = Op.getOperand(2);
3537 unsigned Opc = Cond.getOpcode();
3539 if (Cond.getResNo() == 1 &&
3540 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3541 Opc == ISD::USUBO)) {
3542 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3545 SDValue Value, OverflowCmp;
3547 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3548 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3549 EVT VT = Op.getValueType();
3551 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3557 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3558 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3560 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3561 const ConstantSDNode *CMOVTrue =
3562 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3563 const ConstantSDNode *CMOVFalse =
3564 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3566 if (CMOVTrue && CMOVFalse) {
3567 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3568 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3572 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3574 False = SelectFalse;
3575 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3580 if (True.getNode() && False.getNode()) {
3581 EVT VT = Op.getValueType();
3582 SDValue ARMcc = Cond.getOperand(2);
3583 SDValue CCR = Cond.getOperand(3);
3584 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3585 assert(True.getValueType() == VT);
3586 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3591 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3592 // undefined bits before doing a full-word comparison with zero.
3593 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3594 DAG.getConstant(1, dl, Cond.getValueType()));
3596 return DAG.getSelectCC(dl, Cond,
3597 DAG.getConstant(0, dl, Cond.getValueType()),
3598 SelectTrue, SelectFalse, ISD::SETNE);
3601 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3602 bool &swpCmpOps, bool &swpVselOps) {
3603 // Start by selecting the GE condition code for opcodes that return true for
3605 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3607 CondCode = ARMCC::GE;
3609 // and GT for opcodes that return false for 'equality'.
3610 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3612 CondCode = ARMCC::GT;
3614 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3615 // to swap the compare operands.
3616 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3620 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3621 // If we have an unordered opcode, we need to swap the operands to the VSEL
3622 // instruction (effectively negating the condition).
3624 // This also has the effect of swapping which one of 'less' or 'greater'
3625 // returns true, so we also swap the compare operands. It also switches
3626 // whether we return true for 'equality', so we compensate by picking the
3627 // opposite condition code to our original choice.
3628 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3629 CC == ISD::SETUGT) {
3630 swpCmpOps = !swpCmpOps;
3631 swpVselOps = !swpVselOps;
3632 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3635 // 'ordered' is 'anything but unordered', so use the VS condition code and
3636 // swap the VSEL operands.
3637 if (CC == ISD::SETO) {
3638 CondCode = ARMCC::VS;
3642 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3643 // code and swap the VSEL operands.
3644 if (CC == ISD::SETUNE) {
3645 CondCode = ARMCC::EQ;
3650 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3651 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3652 SDValue Cmp, SelectionDAG &DAG) const {
3653 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3654 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3655 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3656 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3657 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3659 SDValue TrueLow = TrueVal.getValue(0);
3660 SDValue TrueHigh = TrueVal.getValue(1);
3661 SDValue FalseLow = FalseVal.getValue(0);
3662 SDValue FalseHigh = FalseVal.getValue(1);
3664 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3666 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3667 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3669 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3671 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3676 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3677 EVT VT = Op.getValueType();
3678 SDValue LHS = Op.getOperand(0);
3679 SDValue RHS = Op.getOperand(1);
3680 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3681 SDValue TrueVal = Op.getOperand(2);
3682 SDValue FalseVal = Op.getOperand(3);
3685 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3686 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3689 // If softenSetCCOperands only returned one value, we should compare it to
3691 if (!RHS.getNode()) {
3692 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3697 if (LHS.getValueType() == MVT::i32) {
3698 // Try to generate VSEL on ARMv8.
3699 // The VSEL instruction can't use all the usual ARM condition
3700 // codes: it only has two bits to select the condition code, so it's
3701 // constrained to use only GE, GT, VS and EQ.
3703 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3704 // swap the operands of the previous compare instruction (effectively
3705 // inverting the compare condition, swapping 'less' and 'greater') and
3706 // sometimes need to swap the operands to the VSEL (which inverts the
3707 // condition in the sense of firing whenever the previous condition didn't)
3708 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3709 TrueVal.getValueType() == MVT::f64)) {
3710 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3711 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3712 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3713 CC = ISD::getSetCCInverse(CC, true);
3714 std::swap(TrueVal, FalseVal);
3719 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3720 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3721 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3724 ARMCC::CondCodes CondCode, CondCode2;
3725 FPCCToARMCC(CC, CondCode, CondCode2);
3727 // Try to generate VMAXNM/VMINNM on ARMv8.
3728 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3729 TrueVal.getValueType() == MVT::f64)) {
3730 bool swpCmpOps = false;
3731 bool swpVselOps = false;
3732 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3734 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3735 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3737 std::swap(LHS, RHS);
3739 std::swap(TrueVal, FalseVal);
3743 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3744 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3745 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3746 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3747 if (CondCode2 != ARMCC::AL) {
3748 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3749 // FIXME: Needs another CMP because flag can have but one use.
3750 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3751 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3756 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3757 /// to morph to an integer compare sequence.
3758 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3759 const ARMSubtarget *Subtarget) {
3760 SDNode *N = Op.getNode();
3761 if (!N->hasOneUse())
3762 // Otherwise it requires moving the value from fp to integer registers.
3764 if (!N->getNumValues())
3766 EVT VT = Op.getValueType();
3767 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3768 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3769 // vmrs are very slow, e.g. cortex-a8.
3772 if (isFloatingPointZero(Op)) {
3776 return ISD::isNormalLoad(N);
3779 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3780 if (isFloatingPointZero(Op))
3781 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3783 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3784 return DAG.getLoad(MVT::i32, SDLoc(Op),
3785 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3786 Ld->isVolatile(), Ld->isNonTemporal(),
3787 Ld->isInvariant(), Ld->getAlignment());
3789 llvm_unreachable("Unknown VFP cmp argument!");
3792 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3793 SDValue &RetVal1, SDValue &RetVal2) {
3796 if (isFloatingPointZero(Op)) {
3797 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3798 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3802 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3803 SDValue Ptr = Ld->getBasePtr();
3804 RetVal1 = DAG.getLoad(MVT::i32, dl,
3805 Ld->getChain(), Ptr,
3806 Ld->getPointerInfo(),
3807 Ld->isVolatile(), Ld->isNonTemporal(),
3808 Ld->isInvariant(), Ld->getAlignment());
3810 EVT PtrType = Ptr.getValueType();
3811 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3812 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3813 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3814 RetVal2 = DAG.getLoad(MVT::i32, dl,
3815 Ld->getChain(), NewPtr,
3816 Ld->getPointerInfo().getWithOffset(4),
3817 Ld->isVolatile(), Ld->isNonTemporal(),
3818 Ld->isInvariant(), NewAlign);
3822 llvm_unreachable("Unknown VFP cmp argument!");
3825 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3826 /// f32 and even f64 comparisons to integer ones.
3828 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3829 SDValue Chain = Op.getOperand(0);
3830 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3831 SDValue LHS = Op.getOperand(2);
3832 SDValue RHS = Op.getOperand(3);
3833 SDValue Dest = Op.getOperand(4);
3836 bool LHSSeenZero = false;
3837 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3838 bool RHSSeenZero = false;
3839 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3840 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3841 // If unsafe fp math optimization is enabled and there are no other uses of
3842 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3843 // to an integer comparison.
3844 if (CC == ISD::SETOEQ)
3846 else if (CC == ISD::SETUNE)
3849 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3851 if (LHS.getValueType() == MVT::f32) {
3852 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3853 bitcastf32Toi32(LHS, DAG), Mask);
3854 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3855 bitcastf32Toi32(RHS, DAG), Mask);
3856 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3857 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3858 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3859 Chain, Dest, ARMcc, CCR, Cmp);
3864 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3865 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3866 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3867 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3868 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3869 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3870 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3871 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3872 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3878 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3879 SDValue Chain = Op.getOperand(0);
3880 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3881 SDValue LHS = Op.getOperand(2);
3882 SDValue RHS = Op.getOperand(3);
3883 SDValue Dest = Op.getOperand(4);
3886 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3887 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3890 // If softenSetCCOperands only returned one value, we should compare it to
3892 if (!RHS.getNode()) {
3893 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3898 if (LHS.getValueType() == MVT::i32) {
3900 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3901 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3902 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3903 Chain, Dest, ARMcc, CCR, Cmp);
3906 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3908 if (getTargetMachine().Options.UnsafeFPMath &&
3909 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3910 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3911 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3912 if (Result.getNode())
3916 ARMCC::CondCodes CondCode, CondCode2;
3917 FPCCToARMCC(CC, CondCode, CondCode2);
3919 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3920 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3921 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3922 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3923 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3924 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3925 if (CondCode2 != ARMCC::AL) {
3926 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3927 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3928 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3933 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3934 SDValue Chain = Op.getOperand(0);
3935 SDValue Table = Op.getOperand(1);
3936 SDValue Index = Op.getOperand(2);
3939 EVT PTy = getPointerTy(DAG.getDataLayout());
3940 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3941 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3942 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3943 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3944 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3945 if (Subtarget->isThumb2()) {
3946 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3947 // which does another jump to the destination. This also makes it easier
3948 // to translate it to TBB / TBH later.
3949 // FIXME: This might not work if the function is extremely large.
3950 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3951 Addr, Op.getOperand(2), JTI);
3953 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3955 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3956 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3957 false, false, false, 0);
3958 Chain = Addr.getValue(1);
3959 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3960 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3963 DAG.getLoad(PTy, dl, Chain, Addr,
3964 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3965 false, false, false, 0);
3966 Chain = Addr.getValue(1);
3967 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3971 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3972 EVT VT = Op.getValueType();
3975 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3976 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3978 return DAG.UnrollVectorOp(Op.getNode());
3981 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3982 "Invalid type for custom lowering!");
3983 if (VT != MVT::v4i16)
3984 return DAG.UnrollVectorOp(Op.getNode());
3986 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3987 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3990 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3991 EVT VT = Op.getValueType();
3993 return LowerVectorFP_TO_INT(Op, DAG);
3994 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3996 if (Op.getOpcode() == ISD::FP_TO_SINT)
3997 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4000 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4002 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4003 /*isSigned*/ false, SDLoc(Op)).first;
4009 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4010 EVT VT = Op.getValueType();
4013 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4014 if (VT.getVectorElementType() == MVT::f32)
4016 return DAG.UnrollVectorOp(Op.getNode());
4019 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4020 "Invalid type for custom lowering!");
4021 if (VT != MVT::v4f32)
4022 return DAG.UnrollVectorOp(Op.getNode());
4026 switch (Op.getOpcode()) {
4027 default: llvm_unreachable("Invalid opcode!");
4028 case ISD::SINT_TO_FP:
4029 CastOpc = ISD::SIGN_EXTEND;
4030 Opc = ISD::SINT_TO_FP;
4032 case ISD::UINT_TO_FP:
4033 CastOpc = ISD::ZERO_EXTEND;
4034 Opc = ISD::UINT_TO_FP;
4038 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4039 return DAG.getNode(Opc, dl, VT, Op);
4042 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4043 EVT VT = Op.getValueType();
4045 return LowerVectorINT_TO_FP(Op, DAG);
4046 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4048 if (Op.getOpcode() == ISD::SINT_TO_FP)
4049 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4052 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4054 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4055 /*isSigned*/ false, SDLoc(Op)).first;
4061 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4062 // Implement fcopysign with a fabs and a conditional fneg.
4063 SDValue Tmp0 = Op.getOperand(0);
4064 SDValue Tmp1 = Op.getOperand(1);
4066 EVT VT = Op.getValueType();
4067 EVT SrcVT = Tmp1.getValueType();
4068 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4069 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4070 bool UseNEON = !InGPR && Subtarget->hasNEON();
4073 // Use VBSL to copy the sign bit.
4074 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4075 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4076 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4077 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4079 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4080 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4081 DAG.getConstant(32, dl, MVT::i32));
4082 else /*if (VT == MVT::f32)*/
4083 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4084 if (SrcVT == MVT::f32) {
4085 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4087 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4088 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4089 DAG.getConstant(32, dl, MVT::i32));
4090 } else if (VT == MVT::f32)
4091 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4092 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4093 DAG.getConstant(32, dl, MVT::i32));
4094 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4095 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4097 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4099 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4100 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4101 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4103 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4104 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4105 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4106 if (VT == MVT::f32) {
4107 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4108 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4109 DAG.getConstant(0, dl, MVT::i32));
4111 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4117 // Bitcast operand 1 to i32.
4118 if (SrcVT == MVT::f64)
4119 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4121 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4123 // Or in the signbit with integer operations.
4124 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4125 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4126 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4127 if (VT == MVT::f32) {
4128 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4129 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4130 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4131 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4134 // f64: Or the high part with signbit and then combine two parts.
4135 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4137 SDValue Lo = Tmp0.getValue(0);
4138 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4139 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4140 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4143 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4144 MachineFunction &MF = DAG.getMachineFunction();
4145 MachineFrameInfo *MFI = MF.getFrameInfo();
4146 MFI->setReturnAddressIsTaken(true);
4148 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4151 EVT VT = Op.getValueType();
4153 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4155 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4156 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4157 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4158 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4159 MachinePointerInfo(), false, false, false, 0);
4162 // Return LR, which contains the return address. Mark it an implicit live-in.
4163 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4164 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4167 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4168 const ARMBaseRegisterInfo &ARI =
4169 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4170 MachineFunction &MF = DAG.getMachineFunction();
4171 MachineFrameInfo *MFI = MF.getFrameInfo();
4172 MFI->setFrameAddressIsTaken(true);
4174 EVT VT = Op.getValueType();
4175 SDLoc dl(Op); // FIXME probably not meaningful
4176 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4177 unsigned FrameReg = ARI.getFrameRegister(MF);
4178 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4180 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4181 MachinePointerInfo(),
4182 false, false, false, 0);
4186 // FIXME? Maybe this could be a TableGen attribute on some registers and
4187 // this table could be generated automatically from RegInfo.
4188 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4189 SelectionDAG &DAG) const {
4190 unsigned Reg = StringSwitch<unsigned>(RegName)
4191 .Case("sp", ARM::SP)
4195 report_fatal_error(Twine("Invalid register name \""
4196 + StringRef(RegName) + "\"."));
4199 // Result is 64 bit value so split into two 32 bit values and return as a
4201 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4202 SelectionDAG &DAG) {
4205 // This function is only supposed to be called for i64 type destination.
4206 assert(N->getValueType(0) == MVT::i64
4207 && "ExpandREAD_REGISTER called for non-i64 type result.");
4209 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4210 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4214 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4216 Results.push_back(Read.getOperand(0));
4219 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4220 /// When \p DstVT, the destination type of \p BC, is on the vector
4221 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4222 /// it might be possible to combine them, such that everything stays on the
4223 /// vector register bank.
4224 /// \p return The node that would replace \p BT, if the combine
4226 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4227 SelectionDAG &DAG) {
4228 SDValue Op = BC->getOperand(0);
4229 EVT DstVT = BC->getValueType(0);
4231 // The only vector instruction that can produce a scalar (remember,
4232 // since the bitcast was about to be turned into VMOVDRR, the source
4233 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4234 // Moreover, we can do this combine only if there is one use.
4235 // Finally, if the destination type is not a vector, there is not
4236 // much point on forcing everything on the vector bank.
4237 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4241 // If the index is not constant, we will introduce an additional
4242 // multiply that will stick.
4243 // Give up in that case.
4244 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4247 unsigned DstNumElt = DstVT.getVectorNumElements();
4249 // Compute the new index.
4250 const APInt &APIntIndex = Index->getAPIntValue();
4251 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4252 NewIndex *= APIntIndex;
4253 // Check if the new constant index fits into i32.
4254 if (NewIndex.getBitWidth() > 32)
4257 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4258 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4260 SDValue ExtractSrc = Op.getOperand(0);
4261 EVT VecVT = EVT::getVectorVT(
4262 *DAG.getContext(), DstVT.getScalarType(),
4263 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4264 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4265 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4266 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4269 /// ExpandBITCAST - If the target supports VFP, this function is called to
4270 /// expand a bit convert where either the source or destination type is i64 to
4271 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4272 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4273 /// vectors), since the legalizer won't know what to do with that.
4274 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4275 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4277 SDValue Op = N->getOperand(0);
4279 // This function is only supposed to be called for i64 types, either as the
4280 // source or destination of the bit convert.
4281 EVT SrcVT = Op.getValueType();
4282 EVT DstVT = N->getValueType(0);
4283 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4284 "ExpandBITCAST called for non-i64 type");
4286 // Turn i64->f64 into VMOVDRR.
4287 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4288 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4289 // if we can combine the bitcast with its source.
4290 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4293 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4294 DAG.getConstant(0, dl, MVT::i32));
4295 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4296 DAG.getConstant(1, dl, MVT::i32));
4297 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4298 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4301 // Turn f64->i64 into VMOVRRD.
4302 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4304 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4305 SrcVT.getVectorNumElements() > 1)
4306 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4307 DAG.getVTList(MVT::i32, MVT::i32),
4308 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4310 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4311 DAG.getVTList(MVT::i32, MVT::i32), Op);
4312 // Merge the pieces into a single i64 value.
4313 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4319 /// getZeroVector - Returns a vector of specified type with all zero elements.
4320 /// Zero vectors are used to represent vector negation and in those cases
4321 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4322 /// not support i64 elements, so sometimes the zero vectors will need to be
4323 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4325 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4326 assert(VT.isVector() && "Expected a vector type");
4327 // The canonical modified immediate encoding of a zero vector is....0!
4328 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4329 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4330 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4331 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4334 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4335 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4336 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4337 SelectionDAG &DAG) const {
4338 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4339 EVT VT = Op.getValueType();
4340 unsigned VTBits = VT.getSizeInBits();
4342 SDValue ShOpLo = Op.getOperand(0);
4343 SDValue ShOpHi = Op.getOperand(1);
4344 SDValue ShAmt = Op.getOperand(2);
4346 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4348 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4350 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4351 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4352 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4353 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4354 DAG.getConstant(VTBits, dl, MVT::i32));
4355 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4356 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4357 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4359 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4360 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4361 ISD::SETGE, ARMcc, DAG, dl);
4362 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4363 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4366 SDValue Ops[2] = { Lo, Hi };
4367 return DAG.getMergeValues(Ops, dl);
4370 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4371 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4372 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4373 SelectionDAG &DAG) const {
4374 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4375 EVT VT = Op.getValueType();
4376 unsigned VTBits = VT.getSizeInBits();
4378 SDValue ShOpLo = Op.getOperand(0);
4379 SDValue ShOpHi = Op.getOperand(1);
4380 SDValue ShAmt = Op.getOperand(2);
4383 assert(Op.getOpcode() == ISD::SHL_PARTS);
4384 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4385 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4386 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4387 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4388 DAG.getConstant(VTBits, dl, MVT::i32));
4389 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4390 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4392 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4393 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4394 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4395 ISD::SETGE, ARMcc, DAG, dl);
4396 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4397 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4400 SDValue Ops[2] = { Lo, Hi };
4401 return DAG.getMergeValues(Ops, dl);
4404 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4405 SelectionDAG &DAG) const {
4406 // The rounding mode is in bits 23:22 of the FPSCR.
4407 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4408 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4409 // so that the shift + and get folded into a bitfield extract.
4411 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4412 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4414 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4415 DAG.getConstant(1U << 22, dl, MVT::i32));
4416 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4417 DAG.getConstant(22, dl, MVT::i32));
4418 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4419 DAG.getConstant(3, dl, MVT::i32));
4422 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4423 const ARMSubtarget *ST) {
4425 EVT VT = N->getValueType(0);
4426 if (VT.isVector()) {
4427 assert(ST->hasNEON());
4429 // Compute the least significant set bit: LSB = X & -X
4430 SDValue X = N->getOperand(0);
4431 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4432 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4434 EVT ElemTy = VT.getVectorElementType();
4436 if (ElemTy == MVT::i8) {
4437 // Compute with: cttz(x) = ctpop(lsb - 1)
4438 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4439 DAG.getTargetConstant(1, dl, ElemTy));
4440 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4441 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4444 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4445 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4446 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4447 unsigned NumBits = ElemTy.getSizeInBits();
4448 SDValue WidthMinus1 =
4449 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4450 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4451 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4452 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4455 // Compute with: cttz(x) = ctpop(lsb - 1)
4457 // Since we can only compute the number of bits in a byte with vcnt.8, we
4458 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4463 if (ElemTy == MVT::i64) {
4464 // Load constant 0xffff'ffff'ffff'ffff to register.
4465 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4466 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4467 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4469 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4470 DAG.getTargetConstant(1, dl, ElemTy));
4471 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4474 // Count #bits with vcnt.8.
4475 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4476 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4477 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4479 // Gather the #bits with vpaddl (pairwise add.)
4480 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4481 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4482 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4484 if (ElemTy == MVT::i16)
4487 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4488 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4489 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4491 if (ElemTy == MVT::i32)
4494 assert(ElemTy == MVT::i64);
4495 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4496 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4501 if (!ST->hasV6T2Ops())
4504 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4505 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4508 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4509 /// for each 16-bit element from operand, repeated. The basic idea is to
4510 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4512 /// Trace for v4i16:
4513 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4514 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4515 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4516 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4517 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4518 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4519 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4520 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4521 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4522 EVT VT = N->getValueType(0);
4525 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4526 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4527 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4528 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4529 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4530 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4533 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4534 /// bit-count for each 16-bit element from the operand. We need slightly
4535 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4536 /// 64/128-bit registers.
4538 /// Trace for v4i16:
4539 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4540 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4541 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4542 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4543 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4544 EVT VT = N->getValueType(0);
4547 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4548 if (VT.is64BitVector()) {
4549 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4550 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4551 DAG.getIntPtrConstant(0, DL));
4553 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4554 BitCounts, DAG.getIntPtrConstant(0, DL));
4555 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4559 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4560 /// bit-count for each 32-bit element from the operand. The idea here is
4561 /// to split the vector into 16-bit elements, leverage the 16-bit count
4562 /// routine, and then combine the results.
4564 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4565 /// input = [v0 v1 ] (vi: 32-bit elements)
4566 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4567 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4568 /// vrev: N0 = [k1 k0 k3 k2 ]
4570 /// N1 =+[k1 k0 k3 k2 ]
4572 /// N2 =+[k1 k3 k0 k2 ]
4574 /// Extended =+[k1 k3 k0 k2 ]
4576 /// Extracted=+[k1 k3 ]
4578 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4579 EVT VT = N->getValueType(0);
4582 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4584 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4585 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4586 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4587 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4588 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4590 if (VT.is64BitVector()) {
4591 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4592 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4593 DAG.getIntPtrConstant(0, DL));
4595 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4596 DAG.getIntPtrConstant(0, DL));
4597 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4601 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4602 const ARMSubtarget *ST) {
4603 EVT VT = N->getValueType(0);
4605 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4606 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4607 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4608 "Unexpected type for custom ctpop lowering");
4610 if (VT.getVectorElementType() == MVT::i32)
4611 return lowerCTPOP32BitElements(N, DAG);
4613 return lowerCTPOP16BitElements(N, DAG);
4616 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4617 const ARMSubtarget *ST) {
4618 EVT VT = N->getValueType(0);
4624 // Lower vector shifts on NEON to use VSHL.
4625 assert(ST->hasNEON() && "unexpected vector shift");
4627 // Left shifts translate directly to the vshiftu intrinsic.
4628 if (N->getOpcode() == ISD::SHL)
4629 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4630 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4632 N->getOperand(0), N->getOperand(1));
4634 assert((N->getOpcode() == ISD::SRA ||
4635 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4637 // NEON uses the same intrinsics for both left and right shifts. For
4638 // right shifts, the shift amounts are negative, so negate the vector of
4640 EVT ShiftVT = N->getOperand(1).getValueType();
4641 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4642 getZeroVector(ShiftVT, DAG, dl),
4644 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4645 Intrinsic::arm_neon_vshifts :
4646 Intrinsic::arm_neon_vshiftu);
4647 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4648 DAG.getConstant(vshiftInt, dl, MVT::i32),
4649 N->getOperand(0), NegatedCount);
4652 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4653 const ARMSubtarget *ST) {
4654 EVT VT = N->getValueType(0);
4657 // We can get here for a node like i32 = ISD::SHL i32, i64
4661 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4662 "Unknown shift to lower!");
4664 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4665 if (!isOneConstant(N->getOperand(1)))
4668 // If we are in thumb mode, we don't have RRX.
4669 if (ST->isThumb1Only()) return SDValue();
4671 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4672 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4673 DAG.getConstant(0, dl, MVT::i32));
4674 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4675 DAG.getConstant(1, dl, MVT::i32));
4677 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4678 // captures the result into a carry flag.
4679 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4680 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4682 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4683 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4685 // Merge the pieces into a single i64 value.
4686 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4689 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4690 SDValue TmpOp0, TmpOp1;
4691 bool Invert = false;
4695 SDValue Op0 = Op.getOperand(0);
4696 SDValue Op1 = Op.getOperand(1);
4697 SDValue CC = Op.getOperand(2);
4698 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4699 EVT VT = Op.getValueType();
4700 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4703 if (CmpVT.getVectorElementType() == MVT::i64)
4704 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4705 // but it's possible that our operands are 64-bit but our result is 32-bit.
4706 // Bail in this case.
4709 if (Op1.getValueType().isFloatingPoint()) {
4710 switch (SetCCOpcode) {
4711 default: llvm_unreachable("Illegal FP comparison");
4713 case ISD::SETNE: Invert = true; // Fallthrough
4715 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4717 case ISD::SETLT: Swap = true; // Fallthrough
4719 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4721 case ISD::SETLE: Swap = true; // Fallthrough
4723 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4724 case ISD::SETUGE: Swap = true; // Fallthrough
4725 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4726 case ISD::SETUGT: Swap = true; // Fallthrough
4727 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4728 case ISD::SETUEQ: Invert = true; // Fallthrough
4730 // Expand this to (OLT | OGT).
4734 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4735 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4737 case ISD::SETUO: Invert = true; // Fallthrough
4739 // Expand this to (OLT | OGE).
4743 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4744 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4748 // Integer comparisons.
4749 switch (SetCCOpcode) {
4750 default: llvm_unreachable("Illegal integer comparison");
4751 case ISD::SETNE: Invert = true;
4752 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4753 case ISD::SETLT: Swap = true;
4754 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4755 case ISD::SETLE: Swap = true;
4756 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4757 case ISD::SETULT: Swap = true;
4758 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4759 case ISD::SETULE: Swap = true;
4760 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4763 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4764 if (Opc == ARMISD::VCEQ) {
4767 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4769 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4772 // Ignore bitconvert.
4773 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4774 AndOp = AndOp.getOperand(0);
4776 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4778 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4779 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4786 std::swap(Op0, Op1);
4788 // If one of the operands is a constant vector zero, attempt to fold the
4789 // comparison to a specialized compare-against-zero form.
4791 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4793 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4794 if (Opc == ARMISD::VCGE)
4795 Opc = ARMISD::VCLEZ;
4796 else if (Opc == ARMISD::VCGT)
4797 Opc = ARMISD::VCLTZ;
4802 if (SingleOp.getNode()) {
4805 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4807 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4809 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4811 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4813 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4815 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4818 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4821 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4824 Result = DAG.getNOT(dl, Result, VT);
4829 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4830 /// valid vector constant for a NEON instruction with a "modified immediate"
4831 /// operand (e.g., VMOV). If so, return the encoded value.
4832 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4833 unsigned SplatBitSize, SelectionDAG &DAG,
4834 SDLoc dl, EVT &VT, bool is128Bits,
4835 NEONModImmType type) {
4836 unsigned OpCmode, Imm;
4838 // SplatBitSize is set to the smallest size that splats the vector, so a
4839 // zero vector will always have SplatBitSize == 8. However, NEON modified
4840 // immediate instructions others than VMOV do not support the 8-bit encoding
4841 // of a zero vector, and the default encoding of zero is supposed to be the
4846 switch (SplatBitSize) {
4848 if (type != VMOVModImm)
4850 // Any 1-byte value is OK. Op=0, Cmode=1110.
4851 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4854 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4858 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4859 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4860 if ((SplatBits & ~0xff) == 0) {
4861 // Value = 0x00nn: Op=x, Cmode=100x.
4866 if ((SplatBits & ~0xff00) == 0) {
4867 // Value = 0xnn00: Op=x, Cmode=101x.
4869 Imm = SplatBits >> 8;
4875 // NEON's 32-bit VMOV supports splat values where:
4876 // * only one byte is nonzero, or
4877 // * the least significant byte is 0xff and the second byte is nonzero, or
4878 // * the least significant 2 bytes are 0xff and the third is nonzero.
4879 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4880 if ((SplatBits & ~0xff) == 0) {
4881 // Value = 0x000000nn: Op=x, Cmode=000x.
4886 if ((SplatBits & ~0xff00) == 0) {
4887 // Value = 0x0000nn00: Op=x, Cmode=001x.
4889 Imm = SplatBits >> 8;
4892 if ((SplatBits & ~0xff0000) == 0) {
4893 // Value = 0x00nn0000: Op=x, Cmode=010x.
4895 Imm = SplatBits >> 16;
4898 if ((SplatBits & ~0xff000000) == 0) {
4899 // Value = 0xnn000000: Op=x, Cmode=011x.
4901 Imm = SplatBits >> 24;
4905 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4906 if (type == OtherModImm) return SDValue();
4908 if ((SplatBits & ~0xffff) == 0 &&
4909 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4910 // Value = 0x0000nnff: Op=x, Cmode=1100.
4912 Imm = SplatBits >> 8;
4916 if ((SplatBits & ~0xffffff) == 0 &&
4917 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4918 // Value = 0x00nnffff: Op=x, Cmode=1101.
4920 Imm = SplatBits >> 16;
4924 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4925 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4926 // VMOV.I32. A (very) minor optimization would be to replicate the value
4927 // and fall through here to test for a valid 64-bit splat. But, then the
4928 // caller would also need to check and handle the change in size.
4932 if (type != VMOVModImm)
4934 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4935 uint64_t BitMask = 0xff;
4937 unsigned ImmMask = 1;
4939 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4940 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4943 } else if ((SplatBits & BitMask) != 0) {
4950 if (DAG.getDataLayout().isBigEndian())
4951 // swap higher and lower 32 bit word
4952 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4954 // Op=1, Cmode=1110.
4956 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4961 llvm_unreachable("unexpected size for isNEONModifiedImm");
4964 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4965 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4968 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4969 const ARMSubtarget *ST) const {
4973 bool IsDouble = Op.getValueType() == MVT::f64;
4974 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4976 // Use the default (constant pool) lowering for double constants when we have
4978 if (IsDouble && Subtarget->isFPOnlySP())
4981 // Try splatting with a VMOV.f32...
4982 APFloat FPVal = CFP->getValueAPF();
4983 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4986 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4987 // We have code in place to select a valid ConstantFP already, no need to
4992 // It's a float and we are trying to use NEON operations where
4993 // possible. Lower it to a splat followed by an extract.
4995 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4996 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4998 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4999 DAG.getConstant(0, DL, MVT::i32));
5002 // The rest of our options are NEON only, make sure that's allowed before
5004 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5008 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5010 // It wouldn't really be worth bothering for doubles except for one very
5011 // important value, which does happen to match: 0.0. So make sure we don't do
5013 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5016 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5017 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5018 VMovVT, false, VMOVModImm);
5019 if (NewVal != SDValue()) {
5021 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5024 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5026 // It's a float: cast and extract a vector element.
5027 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5029 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5030 DAG.getConstant(0, DL, MVT::i32));
5033 // Finally, try a VMVN.i32
5034 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5036 if (NewVal != SDValue()) {
5038 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5041 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5043 // It's a float: cast and extract a vector element.
5044 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5046 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5047 DAG.getConstant(0, DL, MVT::i32));
5053 // check if an VEXT instruction can handle the shuffle mask when the
5054 // vector sources of the shuffle are the same.
5055 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5056 unsigned NumElts = VT.getVectorNumElements();
5058 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5064 // If this is a VEXT shuffle, the immediate value is the index of the first
5065 // element. The other shuffle indices must be the successive elements after
5067 unsigned ExpectedElt = Imm;
5068 for (unsigned i = 1; i < NumElts; ++i) {
5069 // Increment the expected index. If it wraps around, just follow it
5070 // back to index zero and keep going.
5072 if (ExpectedElt == NumElts)
5075 if (M[i] < 0) continue; // ignore UNDEF indices
5076 if (ExpectedElt != static_cast<unsigned>(M[i]))
5084 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5085 bool &ReverseVEXT, unsigned &Imm) {
5086 unsigned NumElts = VT.getVectorNumElements();
5087 ReverseVEXT = false;
5089 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5095 // If this is a VEXT shuffle, the immediate value is the index of the first
5096 // element. The other shuffle indices must be the successive elements after
5098 unsigned ExpectedElt = Imm;
5099 for (unsigned i = 1; i < NumElts; ++i) {
5100 // Increment the expected index. If it wraps around, it may still be
5101 // a VEXT but the source vectors must be swapped.
5103 if (ExpectedElt == NumElts * 2) {
5108 if (M[i] < 0) continue; // ignore UNDEF indices
5109 if (ExpectedElt != static_cast<unsigned>(M[i]))
5113 // Adjust the index value if the source operands will be swapped.
5120 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5121 /// instruction with the specified blocksize. (The order of the elements
5122 /// within each block of the vector is reversed.)
5123 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5124 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5125 "Only possible block sizes for VREV are: 16, 32, 64");
5127 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5131 unsigned NumElts = VT.getVectorNumElements();
5132 unsigned BlockElts = M[0] + 1;
5133 // If the first shuffle index is UNDEF, be optimistic.
5135 BlockElts = BlockSize / EltSz;
5137 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5140 for (unsigned i = 0; i < NumElts; ++i) {
5141 if (M[i] < 0) continue; // ignore UNDEF indices
5142 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5149 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5150 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5151 // range, then 0 is placed into the resulting vector. So pretty much any mask
5152 // of 8 elements can work here.
5153 return VT == MVT::v8i8 && M.size() == 8;
5156 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5157 // checking that pairs of elements in the shuffle mask represent the same index
5158 // in each vector, incrementing the expected index by 2 at each step.
5159 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5160 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5162 // WhichResult gives the offset for each element in the mask based on which
5163 // of the two results it belongs to.
5165 // The transpose can be represented either as:
5166 // result1 = shufflevector v1, v2, result1_shuffle_mask
5167 // result2 = shufflevector v1, v2, result2_shuffle_mask
5168 // where v1/v2 and the shuffle masks have the same number of elements
5169 // (here WhichResult (see below) indicates which result is being checked)
5172 // results = shufflevector v1, v2, shuffle_mask
5173 // where both results are returned in one vector and the shuffle mask has twice
5174 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5175 // want to check the low half and high half of the shuffle mask as if it were
5177 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5178 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5182 unsigned NumElts = VT.getVectorNumElements();
5183 if (M.size() != NumElts && M.size() != NumElts*2)
5186 // If the mask is twice as long as the input vector then we need to check the
5187 // upper and lower parts of the mask with a matching value for WhichResult
5188 // FIXME: A mask with only even values will be rejected in case the first
5189 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5190 // M[0] is used to determine WhichResult
5191 for (unsigned i = 0; i < M.size(); i += NumElts) {
5192 if (M.size() == NumElts * 2)
5193 WhichResult = i / NumElts;
5195 WhichResult = M[i] == 0 ? 0 : 1;
5196 for (unsigned j = 0; j < NumElts; j += 2) {
5197 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5198 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5203 if (M.size() == NumElts*2)
5209 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5210 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5211 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5212 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5213 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5217 unsigned NumElts = VT.getVectorNumElements();
5218 if (M.size() != NumElts && M.size() != NumElts*2)
5221 for (unsigned i = 0; i < M.size(); i += NumElts) {
5222 if (M.size() == NumElts * 2)
5223 WhichResult = i / NumElts;
5225 WhichResult = M[i] == 0 ? 0 : 1;
5226 for (unsigned j = 0; j < NumElts; j += 2) {
5227 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5228 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5233 if (M.size() == NumElts*2)
5239 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5240 // that the mask elements are either all even and in steps of size 2 or all odd
5241 // and in steps of size 2.
5242 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5243 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5245 // Requires similar checks to that of isVTRNMask with
5246 // respect the how results are returned.
5247 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5248 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5252 unsigned NumElts = VT.getVectorNumElements();
5253 if (M.size() != NumElts && M.size() != NumElts*2)
5256 for (unsigned i = 0; i < M.size(); i += NumElts) {
5257 WhichResult = M[i] == 0 ? 0 : 1;
5258 for (unsigned j = 0; j < NumElts; ++j) {
5259 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5264 if (M.size() == NumElts*2)
5267 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5268 if (VT.is64BitVector() && EltSz == 32)
5274 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5275 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5276 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5277 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5278 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5282 unsigned NumElts = VT.getVectorNumElements();
5283 if (M.size() != NumElts && M.size() != NumElts*2)
5286 unsigned Half = NumElts / 2;
5287 for (unsigned i = 0; i < M.size(); i += NumElts) {
5288 WhichResult = M[i] == 0 ? 0 : 1;
5289 for (unsigned j = 0; j < NumElts; j += Half) {
5290 unsigned Idx = WhichResult;
5291 for (unsigned k = 0; k < Half; ++k) {
5292 int MIdx = M[i + j + k];
5293 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5300 if (M.size() == NumElts*2)
5303 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5304 if (VT.is64BitVector() && EltSz == 32)
5310 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5311 // that pairs of elements of the shufflemask represent the same index in each
5312 // vector incrementing sequentially through the vectors.
5313 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5314 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5316 // Requires similar checks to that of isVTRNMask with respect the how results
5318 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5319 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5323 unsigned NumElts = VT.getVectorNumElements();
5324 if (M.size() != NumElts && M.size() != NumElts*2)
5327 for (unsigned i = 0; i < M.size(); i += NumElts) {
5328 WhichResult = M[i] == 0 ? 0 : 1;
5329 unsigned Idx = WhichResult * NumElts / 2;
5330 for (unsigned j = 0; j < NumElts; j += 2) {
5331 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5332 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5338 if (M.size() == NumElts*2)
5341 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5342 if (VT.is64BitVector() && EltSz == 32)
5348 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5349 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5350 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5351 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5352 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5356 unsigned NumElts = VT.getVectorNumElements();
5357 if (M.size() != NumElts && M.size() != NumElts*2)
5360 for (unsigned i = 0; i < M.size(); i += NumElts) {
5361 WhichResult = M[i] == 0 ? 0 : 1;
5362 unsigned Idx = WhichResult * NumElts / 2;
5363 for (unsigned j = 0; j < NumElts; j += 2) {
5364 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5365 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5371 if (M.size() == NumElts*2)
5374 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5375 if (VT.is64BitVector() && EltSz == 32)
5381 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5382 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5383 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5384 unsigned &WhichResult,
5387 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5388 return ARMISD::VTRN;
5389 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5390 return ARMISD::VUZP;
5391 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5392 return ARMISD::VZIP;
5395 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5396 return ARMISD::VTRN;
5397 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5398 return ARMISD::VUZP;
5399 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5400 return ARMISD::VZIP;
5405 /// \return true if this is a reverse operation on an vector.
5406 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5407 unsigned NumElts = VT.getVectorNumElements();
5408 // Make sure the mask has the right size.
5409 if (NumElts != M.size())
5412 // Look for <15, ..., 3, -1, 1, 0>.
5413 for (unsigned i = 0; i != NumElts; ++i)
5414 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5420 // If N is an integer constant that can be moved into a register in one
5421 // instruction, return an SDValue of such a constant (will become a MOV
5422 // instruction). Otherwise return null.
5423 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5424 const ARMSubtarget *ST, SDLoc dl) {
5426 if (!isa<ConstantSDNode>(N))
5428 Val = cast<ConstantSDNode>(N)->getZExtValue();
5430 if (ST->isThumb1Only()) {
5431 if (Val <= 255 || ~Val <= 255)
5432 return DAG.getConstant(Val, dl, MVT::i32);
5434 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5435 return DAG.getConstant(Val, dl, MVT::i32);
5440 // If this is a case we can't handle, return null and let the default
5441 // expansion code take care of it.
5442 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5443 const ARMSubtarget *ST) const {
5444 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5446 EVT VT = Op.getValueType();
5448 APInt SplatBits, SplatUndef;
5449 unsigned SplatBitSize;
5451 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5452 if (SplatBitSize <= 64) {
5453 // Check if an immediate VMOV works.
5455 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5456 SplatUndef.getZExtValue(), SplatBitSize,
5457 DAG, dl, VmovVT, VT.is128BitVector(),
5459 if (Val.getNode()) {
5460 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5461 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5464 // Try an immediate VMVN.
5465 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5466 Val = isNEONModifiedImm(NegatedImm,
5467 SplatUndef.getZExtValue(), SplatBitSize,
5468 DAG, dl, VmovVT, VT.is128BitVector(),
5470 if (Val.getNode()) {
5471 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5472 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5475 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5476 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5477 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5479 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5480 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5486 // Scan through the operands to see if only one value is used.
5488 // As an optimisation, even if more than one value is used it may be more
5489 // profitable to splat with one value then change some lanes.
5491 // Heuristically we decide to do this if the vector has a "dominant" value,
5492 // defined as splatted to more than half of the lanes.
5493 unsigned NumElts = VT.getVectorNumElements();
5494 bool isOnlyLowElement = true;
5495 bool usesOnlyOneValue = true;
5496 bool hasDominantValue = false;
5497 bool isConstant = true;
5499 // Map of the number of times a particular SDValue appears in the
5501 DenseMap<SDValue, unsigned> ValueCounts;
5503 for (unsigned i = 0; i < NumElts; ++i) {
5504 SDValue V = Op.getOperand(i);
5505 if (V.getOpcode() == ISD::UNDEF)
5508 isOnlyLowElement = false;
5509 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5512 ValueCounts.insert(std::make_pair(V, 0));
5513 unsigned &Count = ValueCounts[V];
5515 // Is this value dominant? (takes up more than half of the lanes)
5516 if (++Count > (NumElts / 2)) {
5517 hasDominantValue = true;
5521 if (ValueCounts.size() != 1)
5522 usesOnlyOneValue = false;
5523 if (!Value.getNode() && ValueCounts.size() > 0)
5524 Value = ValueCounts.begin()->first;
5526 if (ValueCounts.size() == 0)
5527 return DAG.getUNDEF(VT);
5529 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5530 // Keep going if we are hitting this case.
5531 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5532 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5534 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5536 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5537 // i32 and try again.
5538 if (hasDominantValue && EltSize <= 32) {
5542 // If we are VDUPing a value that comes directly from a vector, that will
5543 // cause an unnecessary move to and from a GPR, where instead we could
5544 // just use VDUPLANE. We can only do this if the lane being extracted
5545 // is at a constant index, as the VDUP from lane instructions only have
5546 // constant-index forms.
5547 ConstantSDNode *constIndex;
5548 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5549 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5550 // We need to create a new undef vector to use for the VDUPLANE if the
5551 // size of the vector from which we get the value is different than the
5552 // size of the vector that we need to create. We will insert the element
5553 // such that the register coalescer will remove unnecessary copies.
5554 if (VT != Value->getOperand(0).getValueType()) {
5555 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5556 VT.getVectorNumElements();
5557 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5558 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5559 Value, DAG.getConstant(index, dl, MVT::i32)),
5560 DAG.getConstant(index, dl, MVT::i32));
5562 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5563 Value->getOperand(0), Value->getOperand(1));
5565 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5567 if (!usesOnlyOneValue) {
5568 // The dominant value was splatted as 'N', but we now have to insert
5569 // all differing elements.
5570 for (unsigned I = 0; I < NumElts; ++I) {
5571 if (Op.getOperand(I) == Value)
5573 SmallVector<SDValue, 3> Ops;
5575 Ops.push_back(Op.getOperand(I));
5576 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5577 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5582 if (VT.getVectorElementType().isFloatingPoint()) {
5583 SmallVector<SDValue, 8> Ops;
5584 for (unsigned i = 0; i < NumElts; ++i)
5585 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5587 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5588 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5589 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5591 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5593 if (usesOnlyOneValue) {
5594 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5595 if (isConstant && Val.getNode())
5596 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5600 // If all elements are constants and the case above didn't get hit, fall back
5601 // to the default expansion, which will generate a load from the constant
5606 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5608 SDValue shuffle = ReconstructShuffle(Op, DAG);
5609 if (shuffle != SDValue())
5613 // Vectors with 32- or 64-bit elements can be built by directly assigning
5614 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5615 // will be legalized.
5616 if (EltSize >= 32) {
5617 // Do the expansion with floating-point types, since that is what the VFP
5618 // registers are defined to use, and since i64 is not legal.
5619 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5620 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5621 SmallVector<SDValue, 8> Ops;
5622 for (unsigned i = 0; i < NumElts; ++i)
5623 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5624 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5625 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5628 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5629 // know the default expansion would otherwise fall back on something even
5630 // worse. For a vector with one or two non-undef values, that's
5631 // scalar_to_vector for the elements followed by a shuffle (provided the
5632 // shuffle is valid for the target) and materialization element by element
5633 // on the stack followed by a load for everything else.
5634 if (!isConstant && !usesOnlyOneValue) {
5635 SDValue Vec = DAG.getUNDEF(VT);
5636 for (unsigned i = 0 ; i < NumElts; ++i) {
5637 SDValue V = Op.getOperand(i);
5638 if (V.getOpcode() == ISD::UNDEF)
5640 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5641 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5649 // Gather data to see if the operation can be modelled as a
5650 // shuffle in combination with VEXTs.
5651 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5652 SelectionDAG &DAG) const {
5653 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5655 EVT VT = Op.getValueType();
5656 unsigned NumElts = VT.getVectorNumElements();
5658 struct ShuffleSourceInfo {
5663 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5664 // be compatible with the shuffle we intend to construct. As a result
5665 // ShuffleVec will be some sliding window into the original Vec.
5668 // Code should guarantee that element i in Vec starts at element "WindowBase
5669 // + i * WindowScale in ShuffleVec".
5673 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5674 ShuffleSourceInfo(SDValue Vec)
5675 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5679 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5681 SmallVector<ShuffleSourceInfo, 2> Sources;
5682 for (unsigned i = 0; i < NumElts; ++i) {
5683 SDValue V = Op.getOperand(i);
5684 if (V.getOpcode() == ISD::UNDEF)
5686 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5687 // A shuffle can only come from building a vector from various
5688 // elements of other vectors.
5690 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5691 // Furthermore, shuffles require a constant mask, whereas extractelts
5692 // accept variable indices.
5696 // Add this element source to the list if it's not already there.
5697 SDValue SourceVec = V.getOperand(0);
5698 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5699 if (Source == Sources.end())
5700 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5702 // Update the minimum and maximum lane number seen.
5703 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5704 Source->MinElt = std::min(Source->MinElt, EltNo);
5705 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5708 // Currently only do something sane when at most two source vectors
5710 if (Sources.size() > 2)
5713 // Find out the smallest element size among result and two sources, and use
5714 // it as element size to build the shuffle_vector.
5715 EVT SmallestEltTy = VT.getVectorElementType();
5716 for (auto &Source : Sources) {
5717 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5718 if (SrcEltTy.bitsLT(SmallestEltTy))
5719 SmallestEltTy = SrcEltTy;
5721 unsigned ResMultiplier =
5722 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5723 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5724 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5726 // If the source vector is too wide or too narrow, we may nevertheless be able
5727 // to construct a compatible shuffle either by concatenating it with UNDEF or
5728 // extracting a suitable range of elements.
5729 for (auto &Src : Sources) {
5730 EVT SrcVT = Src.ShuffleVec.getValueType();
5732 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5735 // This stage of the search produces a source with the same element type as
5736 // the original, but with a total width matching the BUILD_VECTOR output.
5737 EVT EltVT = SrcVT.getVectorElementType();
5738 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5739 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5741 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5742 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5744 // We can pad out the smaller vector for free, so if it's part of a
5747 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5748 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5752 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5755 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5756 // Span too large for a VEXT to cope
5760 if (Src.MinElt >= NumSrcElts) {
5761 // The extraction can just take the second half
5763 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5764 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5765 Src.WindowBase = -NumSrcElts;
5766 } else if (Src.MaxElt < NumSrcElts) {
5767 // The extraction can just take the first half
5769 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5770 DAG.getConstant(0, dl, MVT::i32));
5772 // An actual VEXT is needed
5774 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5775 DAG.getConstant(0, dl, MVT::i32));
5777 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5778 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5780 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5782 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5783 Src.WindowBase = -Src.MinElt;
5787 // Another possible incompatibility occurs from the vector element types. We
5788 // can fix this by bitcasting the source vectors to the same type we intend
5790 for (auto &Src : Sources) {
5791 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5792 if (SrcEltTy == SmallestEltTy)
5794 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5795 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5796 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5797 Src.WindowBase *= Src.WindowScale;
5800 // Final sanity check before we try to actually produce a shuffle.
5802 for (auto Src : Sources)
5803 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5806 // The stars all align, our next step is to produce the mask for the shuffle.
5807 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5808 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5809 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5810 SDValue Entry = Op.getOperand(i);
5811 if (Entry.getOpcode() == ISD::UNDEF)
5814 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5815 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5817 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5818 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5820 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5821 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5822 VT.getVectorElementType().getSizeInBits());
5823 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5825 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5826 // starting at the appropriate offset.
5827 int *LaneMask = &Mask[i * ResMultiplier];
5829 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5830 ExtractBase += NumElts * (Src - Sources.begin());
5831 for (int j = 0; j < LanesDefined; ++j)
5832 LaneMask[j] = ExtractBase + j;
5835 // Final check before we try to produce nonsense...
5836 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5839 // We can't handle more than two sources. This should have already
5840 // been checked before this point.
5841 assert(Sources.size() <= 2 && "Too many sources!");
5843 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5844 for (unsigned i = 0; i < Sources.size(); ++i)
5845 ShuffleOps[i] = Sources[i].ShuffleVec;
5847 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5848 ShuffleOps[1], &Mask[0]);
5849 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5852 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5853 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5854 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5855 /// are assumed to be legal.
5857 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5859 if (VT.getVectorNumElements() == 4 &&
5860 (VT.is128BitVector() || VT.is64BitVector())) {
5861 unsigned PFIndexes[4];
5862 for (unsigned i = 0; i != 4; ++i) {
5866 PFIndexes[i] = M[i];
5869 // Compute the index in the perfect shuffle table.
5870 unsigned PFTableIndex =
5871 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5872 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5873 unsigned Cost = (PFEntry >> 30);
5879 bool ReverseVEXT, isV_UNDEF;
5880 unsigned Imm, WhichResult;
5882 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5883 return (EltSize >= 32 ||
5884 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5885 isVREVMask(M, VT, 64) ||
5886 isVREVMask(M, VT, 32) ||
5887 isVREVMask(M, VT, 16) ||
5888 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5889 isVTBLMask(M, VT) ||
5890 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5891 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5894 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5895 /// the specified operations to build the shuffle.
5896 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5897 SDValue RHS, SelectionDAG &DAG,
5899 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5900 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5901 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5904 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5913 OP_VUZPL, // VUZP, left result
5914 OP_VUZPR, // VUZP, right result
5915 OP_VZIPL, // VZIP, left result
5916 OP_VZIPR, // VZIP, right result
5917 OP_VTRNL, // VTRN, left result
5918 OP_VTRNR // VTRN, right result
5921 if (OpNum == OP_COPY) {
5922 if (LHSID == (1*9+2)*9+3) return LHS;
5923 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5927 SDValue OpLHS, OpRHS;
5928 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5929 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5930 EVT VT = OpLHS.getValueType();
5933 default: llvm_unreachable("Unknown shuffle opcode!");
5935 // VREV divides the vector in half and swaps within the half.
5936 if (VT.getVectorElementType() == MVT::i32 ||
5937 VT.getVectorElementType() == MVT::f32)
5938 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5939 // vrev <4 x i16> -> VREV32
5940 if (VT.getVectorElementType() == MVT::i16)
5941 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5942 // vrev <4 x i8> -> VREV16
5943 assert(VT.getVectorElementType() == MVT::i8);
5944 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5949 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5950 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5954 return DAG.getNode(ARMISD::VEXT, dl, VT,
5956 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5959 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5960 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5963 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5964 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5967 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5968 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5972 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5973 ArrayRef<int> ShuffleMask,
5974 SelectionDAG &DAG) {
5975 // Check to see if we can use the VTBL instruction.
5976 SDValue V1 = Op.getOperand(0);
5977 SDValue V2 = Op.getOperand(1);
5980 SmallVector<SDValue, 8> VTBLMask;
5981 for (ArrayRef<int>::iterator
5982 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5983 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5985 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5986 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5987 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5989 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5990 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5993 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5994 SelectionDAG &DAG) {
5996 SDValue OpLHS = Op.getOperand(0);
5997 EVT VT = OpLHS.getValueType();
5999 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6000 "Expect an v8i16/v16i8 type");
6001 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6002 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6003 // extract the first 8 bytes into the top double word and the last 8 bytes
6004 // into the bottom double word. The v8i16 case is similar.
6005 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6006 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6007 DAG.getConstant(ExtractNum, DL, MVT::i32));
6010 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6011 SDValue V1 = Op.getOperand(0);
6012 SDValue V2 = Op.getOperand(1);
6014 EVT VT = Op.getValueType();
6015 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6017 // Convert shuffles that are directly supported on NEON to target-specific
6018 // DAG nodes, instead of keeping them as shuffles and matching them again
6019 // during code selection. This is more efficient and avoids the possibility
6020 // of inconsistencies between legalization and selection.
6021 // FIXME: floating-point vectors should be canonicalized to integer vectors
6022 // of the same time so that they get CSEd properly.
6023 ArrayRef<int> ShuffleMask = SVN->getMask();
6025 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6026 if (EltSize <= 32) {
6027 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
6028 int Lane = SVN->getSplatIndex();
6029 // If this is undef splat, generate it via "just" vdup, if possible.
6030 if (Lane == -1) Lane = 0;
6032 // Test if V1 is a SCALAR_TO_VECTOR.
6033 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6034 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6036 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6037 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6039 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6040 !isa<ConstantSDNode>(V1.getOperand(0))) {
6041 bool IsScalarToVector = true;
6042 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6043 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
6044 IsScalarToVector = false;
6047 if (IsScalarToVector)
6048 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6050 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6051 DAG.getConstant(Lane, dl, MVT::i32));
6056 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6059 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6060 DAG.getConstant(Imm, dl, MVT::i32));
6063 if (isVREVMask(ShuffleMask, VT, 64))
6064 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6065 if (isVREVMask(ShuffleMask, VT, 32))
6066 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6067 if (isVREVMask(ShuffleMask, VT, 16))
6068 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6070 if (V2->getOpcode() == ISD::UNDEF &&
6071 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6072 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6073 DAG.getConstant(Imm, dl, MVT::i32));
6076 // Check for Neon shuffles that modify both input vectors in place.
6077 // If both results are used, i.e., if there are two shuffles with the same
6078 // source operands and with masks corresponding to both results of one of
6079 // these operations, DAG memoization will ensure that a single node is
6080 // used for both shuffles.
6081 unsigned WhichResult;
6083 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6084 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6087 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6088 .getValue(WhichResult);
6091 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6092 // shuffles that produce a result larger than their operands with:
6093 // shuffle(concat(v1, undef), concat(v2, undef))
6095 // shuffle(concat(v1, v2), undef)
6096 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6098 // This is useful in the general case, but there are special cases where
6099 // native shuffles produce larger results: the two-result ops.
6101 // Look through the concat when lowering them:
6102 // shuffle(concat(v1, v2), undef)
6104 // concat(VZIP(v1, v2):0, :1)
6106 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6107 V2->getOpcode() == ISD::UNDEF) {
6108 SDValue SubV1 = V1->getOperand(0);
6109 SDValue SubV2 = V1->getOperand(1);
6110 EVT SubVT = SubV1.getValueType();
6112 // We expect these to have been canonicalized to -1.
6113 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6114 return i < (int)VT.getVectorNumElements();
6115 }) && "Unexpected shuffle index into UNDEF operand!");
6117 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6118 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6121 assert((WhichResult == 0) &&
6122 "In-place shuffle of concat can only have one result!");
6123 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6125 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6131 // If the shuffle is not directly supported and it has 4 elements, use
6132 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6133 unsigned NumElts = VT.getVectorNumElements();
6135 unsigned PFIndexes[4];
6136 for (unsigned i = 0; i != 4; ++i) {
6137 if (ShuffleMask[i] < 0)
6140 PFIndexes[i] = ShuffleMask[i];
6143 // Compute the index in the perfect shuffle table.
6144 unsigned PFTableIndex =
6145 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6146 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6147 unsigned Cost = (PFEntry >> 30);
6150 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6153 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6154 if (EltSize >= 32) {
6155 // Do the expansion with floating-point types, since that is what the VFP
6156 // registers are defined to use, and since i64 is not legal.
6157 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6158 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6159 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6160 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6161 SmallVector<SDValue, 8> Ops;
6162 for (unsigned i = 0; i < NumElts; ++i) {
6163 if (ShuffleMask[i] < 0)
6164 Ops.push_back(DAG.getUNDEF(EltVT));
6166 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6167 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6168 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6171 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6172 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6175 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6176 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6178 if (VT == MVT::v8i8) {
6179 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6180 if (NewOp.getNode())
6187 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6188 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6189 SDValue Lane = Op.getOperand(2);
6190 if (!isa<ConstantSDNode>(Lane))
6196 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6197 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6198 SDValue Lane = Op.getOperand(1);
6199 if (!isa<ConstantSDNode>(Lane))
6202 SDValue Vec = Op.getOperand(0);
6203 if (Op.getValueType() == MVT::i32 &&
6204 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6206 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6212 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6213 // The only time a CONCAT_VECTORS operation can have legal types is when
6214 // two 64-bit vectors are concatenated to a 128-bit vector.
6215 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6216 "unexpected CONCAT_VECTORS");
6218 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6219 SDValue Op0 = Op.getOperand(0);
6220 SDValue Op1 = Op.getOperand(1);
6221 if (Op0.getOpcode() != ISD::UNDEF)
6222 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6223 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6224 DAG.getIntPtrConstant(0, dl));
6225 if (Op1.getOpcode() != ISD::UNDEF)
6226 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6227 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6228 DAG.getIntPtrConstant(1, dl));
6229 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6232 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6233 /// element has been zero/sign-extended, depending on the isSigned parameter,
6234 /// from an integer type half its size.
6235 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6237 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6238 EVT VT = N->getValueType(0);
6239 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6240 SDNode *BVN = N->getOperand(0).getNode();
6241 if (BVN->getValueType(0) != MVT::v4i32 ||
6242 BVN->getOpcode() != ISD::BUILD_VECTOR)
6244 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6245 unsigned HiElt = 1 - LoElt;
6246 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6247 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6248 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6249 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6250 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6253 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6254 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6257 if (Hi0->isNullValue() && Hi1->isNullValue())
6263 if (N->getOpcode() != ISD::BUILD_VECTOR)
6266 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6267 SDNode *Elt = N->getOperand(i).getNode();
6268 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6269 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6270 unsigned HalfSize = EltSize / 2;
6272 if (!isIntN(HalfSize, C->getSExtValue()))
6275 if (!isUIntN(HalfSize, C->getZExtValue()))
6286 /// isSignExtended - Check if a node is a vector value that is sign-extended
6287 /// or a constant BUILD_VECTOR with sign-extended elements.
6288 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6289 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6291 if (isExtendedBUILD_VECTOR(N, DAG, true))
6296 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6297 /// or a constant BUILD_VECTOR with zero-extended elements.
6298 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6299 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6301 if (isExtendedBUILD_VECTOR(N, DAG, false))
6306 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6307 if (OrigVT.getSizeInBits() >= 64)
6310 assert(OrigVT.isSimple() && "Expecting a simple value type");
6312 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6313 switch (OrigSimpleTy) {
6314 default: llvm_unreachable("Unexpected Vector Type");
6323 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6324 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6325 /// We insert the required extension here to get the vector to fill a D register.
6326 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6329 unsigned ExtOpcode) {
6330 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6331 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6332 // 64-bits we need to insert a new extension so that it will be 64-bits.
6333 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6334 if (OrigTy.getSizeInBits() >= 64)
6337 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6338 EVT NewVT = getExtensionTo64Bits(OrigTy);
6340 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6343 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6344 /// does not do any sign/zero extension. If the original vector is less
6345 /// than 64 bits, an appropriate extension will be added after the load to
6346 /// reach a total size of 64 bits. We have to add the extension separately
6347 /// because ARM does not have a sign/zero extending load for vectors.
6348 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6349 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6351 // The load already has the right type.
6352 if (ExtendedTy == LD->getMemoryVT())
6353 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6354 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6355 LD->isNonTemporal(), LD->isInvariant(),
6356 LD->getAlignment());
6358 // We need to create a zextload/sextload. We cannot just create a load
6359 // followed by a zext/zext node because LowerMUL is also run during normal
6360 // operation legalization where we can't create illegal types.
6361 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6362 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6363 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6364 LD->isNonTemporal(), LD->getAlignment());
6367 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6368 /// extending load, or BUILD_VECTOR with extended elements, return the
6369 /// unextended value. The unextended vector should be 64 bits so that it can
6370 /// be used as an operand to a VMULL instruction. If the original vector size
6371 /// before extension is less than 64 bits we add a an extension to resize
6372 /// the vector to 64 bits.
6373 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6374 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6375 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6376 N->getOperand(0)->getValueType(0),
6380 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6381 return SkipLoadExtensionForVMULL(LD, DAG);
6383 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6384 // have been legalized as a BITCAST from v4i32.
6385 if (N->getOpcode() == ISD::BITCAST) {
6386 SDNode *BVN = N->getOperand(0).getNode();
6387 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6388 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6389 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6390 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6391 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6393 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6394 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6395 EVT VT = N->getValueType(0);
6396 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6397 unsigned NumElts = VT.getVectorNumElements();
6398 MVT TruncVT = MVT::getIntegerVT(EltSize);
6399 SmallVector<SDValue, 8> Ops;
6401 for (unsigned i = 0; i != NumElts; ++i) {
6402 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6403 const APInt &CInt = C->getAPIntValue();
6404 // Element types smaller than 32 bits are not legal, so use i32 elements.
6405 // The values are implicitly truncated so sext vs. zext doesn't matter.
6406 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6408 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6409 MVT::getVectorVT(TruncVT, NumElts), Ops);
6412 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6413 unsigned Opcode = N->getOpcode();
6414 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6415 SDNode *N0 = N->getOperand(0).getNode();
6416 SDNode *N1 = N->getOperand(1).getNode();
6417 return N0->hasOneUse() && N1->hasOneUse() &&
6418 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6423 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6424 unsigned Opcode = N->getOpcode();
6425 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6426 SDNode *N0 = N->getOperand(0).getNode();
6427 SDNode *N1 = N->getOperand(1).getNode();
6428 return N0->hasOneUse() && N1->hasOneUse() &&
6429 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6434 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6435 // Multiplications are only custom-lowered for 128-bit vectors so that
6436 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6437 EVT VT = Op.getValueType();
6438 assert(VT.is128BitVector() && VT.isInteger() &&
6439 "unexpected type for custom-lowering ISD::MUL");
6440 SDNode *N0 = Op.getOperand(0).getNode();
6441 SDNode *N1 = Op.getOperand(1).getNode();
6442 unsigned NewOpc = 0;
6444 bool isN0SExt = isSignExtended(N0, DAG);
6445 bool isN1SExt = isSignExtended(N1, DAG);
6446 if (isN0SExt && isN1SExt)
6447 NewOpc = ARMISD::VMULLs;
6449 bool isN0ZExt = isZeroExtended(N0, DAG);
6450 bool isN1ZExt = isZeroExtended(N1, DAG);
6451 if (isN0ZExt && isN1ZExt)
6452 NewOpc = ARMISD::VMULLu;
6453 else if (isN1SExt || isN1ZExt) {
6454 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6455 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6456 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6457 NewOpc = ARMISD::VMULLs;
6459 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6460 NewOpc = ARMISD::VMULLu;
6462 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6464 NewOpc = ARMISD::VMULLu;
6470 if (VT == MVT::v2i64)
6471 // Fall through to expand this. It is not legal.
6474 // Other vector multiplications are legal.
6479 // Legalize to a VMULL instruction.
6482 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6484 Op0 = SkipExtensionForVMULL(N0, DAG);
6485 assert(Op0.getValueType().is64BitVector() &&
6486 Op1.getValueType().is64BitVector() &&
6487 "unexpected types for extended operands to VMULL");
6488 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6491 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6492 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6499 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6500 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6501 EVT Op1VT = Op1.getValueType();
6502 return DAG.getNode(N0->getOpcode(), DL, VT,
6503 DAG.getNode(NewOpc, DL, VT,
6504 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6505 DAG.getNode(NewOpc, DL, VT,
6506 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6510 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6511 // TODO: Should this propagate fast-math-flags?
6514 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6515 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6516 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6517 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6518 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6519 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6520 // Get reciprocal estimate.
6521 // float4 recip = vrecpeq_f32(yf);
6522 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6523 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6525 // Because char has a smaller range than uchar, we can actually get away
6526 // without any newton steps. This requires that we use a weird bias
6527 // of 0xb000, however (again, this has been exhaustively tested).
6528 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6529 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6530 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6531 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6532 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6533 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6534 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6535 // Convert back to short.
6536 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6537 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6542 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6543 // TODO: Should this propagate fast-math-flags?
6546 // Convert to float.
6547 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6548 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6549 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6550 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6551 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6552 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6554 // Use reciprocal estimate and one refinement step.
6555 // float4 recip = vrecpeq_f32(yf);
6556 // recip *= vrecpsq_f32(yf, recip);
6557 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6558 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6560 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6561 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6563 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6564 // Because short has a smaller range than ushort, we can actually get away
6565 // with only a single newton step. This requires that we use a weird bias
6566 // of 89, however (again, this has been exhaustively tested).
6567 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6568 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6569 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6570 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6571 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6572 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6573 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6574 // Convert back to integer and return.
6575 // return vmovn_s32(vcvt_s32_f32(result));
6576 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6577 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6581 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6582 EVT VT = Op.getValueType();
6583 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6584 "unexpected type for custom-lowering ISD::SDIV");
6587 SDValue N0 = Op.getOperand(0);
6588 SDValue N1 = Op.getOperand(1);
6591 if (VT == MVT::v8i8) {
6592 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6593 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6595 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6596 DAG.getIntPtrConstant(4, dl));
6597 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6598 DAG.getIntPtrConstant(4, dl));
6599 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6600 DAG.getIntPtrConstant(0, dl));
6601 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6602 DAG.getIntPtrConstant(0, dl));
6604 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6605 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6607 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6608 N0 = LowerCONCAT_VECTORS(N0, DAG);
6610 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6613 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6616 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6617 // TODO: Should this propagate fast-math-flags?
6618 EVT VT = Op.getValueType();
6619 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6620 "unexpected type for custom-lowering ISD::UDIV");
6623 SDValue N0 = Op.getOperand(0);
6624 SDValue N1 = Op.getOperand(1);
6627 if (VT == MVT::v8i8) {
6628 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6629 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6631 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6632 DAG.getIntPtrConstant(4, dl));
6633 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6634 DAG.getIntPtrConstant(4, dl));
6635 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6636 DAG.getIntPtrConstant(0, dl));
6637 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6638 DAG.getIntPtrConstant(0, dl));
6640 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6641 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6643 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6644 N0 = LowerCONCAT_VECTORS(N0, DAG);
6646 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6647 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6653 // v4i16 sdiv ... Convert to float.
6654 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6655 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6656 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6657 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6658 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6659 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6661 // Use reciprocal estimate and two refinement steps.
6662 // float4 recip = vrecpeq_f32(yf);
6663 // recip *= vrecpsq_f32(yf, recip);
6664 // recip *= vrecpsq_f32(yf, recip);
6665 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6666 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6668 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6669 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6671 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6672 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6673 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6675 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6676 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6677 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6678 // and that it will never cause us to return an answer too large).
6679 // float4 result = as_float4(as_int4(xf*recip) + 2);
6680 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6681 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6682 N1 = DAG.getConstant(2, dl, MVT::i32);
6683 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6684 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6685 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6686 // Convert back to integer and return.
6687 // return vmovn_u32(vcvt_s32_f32(result));
6688 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6689 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6693 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6694 EVT VT = Op.getNode()->getValueType(0);
6695 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6698 bool ExtraOp = false;
6699 switch (Op.getOpcode()) {
6700 default: llvm_unreachable("Invalid code");
6701 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6702 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6703 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6704 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6708 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6710 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6711 Op.getOperand(1), Op.getOperand(2));
6714 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6715 assert(Subtarget->isTargetDarwin());
6717 // For iOS, we want to call an alternative entry point: __sincos_stret,
6718 // return values are passed via sret.
6720 SDValue Arg = Op.getOperand(0);
6721 EVT ArgVT = Arg.getValueType();
6722 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6723 auto PtrVT = getPointerTy(DAG.getDataLayout());
6725 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6726 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6728 // Pair of floats / doubles used to pass the result.
6729 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6730 auto &DL = DAG.getDataLayout();
6733 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6735 if (ShouldUseSRet) {
6736 // Create stack object for sret.
6737 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6738 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6739 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6740 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6744 Entry.Ty = RetTy->getPointerTo();
6745 Entry.isSExt = false;
6746 Entry.isZExt = false;
6747 Entry.isSRet = true;
6748 Args.push_back(Entry);
6749 RetTy = Type::getVoidTy(*DAG.getContext());
6755 Entry.isSExt = false;
6756 Entry.isZExt = false;
6757 Args.push_back(Entry);
6759 const char *LibcallName =
6760 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6762 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6763 CallingConv::ID CC = getLibcallCallingConv(LC);
6764 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6766 TargetLowering::CallLoweringInfo CLI(DAG);
6768 .setChain(DAG.getEntryNode())
6769 .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6770 .setDiscardResult(ShouldUseSRet);
6771 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6774 return CallResult.first;
6776 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6777 MachinePointerInfo(), false, false, false, 0);
6779 // Address of cos field.
6780 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6781 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6782 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6783 MachinePointerInfo(), false, false, false, 0);
6785 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6786 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6787 LoadSin.getValue(0), LoadCos.getValue(0));
6790 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6792 SDValue &Chain) const {
6793 EVT VT = Op.getValueType();
6794 assert((VT == MVT::i32 || VT == MVT::i64) &&
6795 "unexpected type for custom lowering DIV");
6798 const auto &DL = DAG.getDataLayout();
6799 const auto &TLI = DAG.getTargetLoweringInfo();
6801 const char *Name = nullptr;
6803 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6805 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6807 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6809 ARMTargetLowering::ArgListTy Args;
6811 for (auto AI : {1, 0}) {
6813 Arg.Node = Op.getOperand(AI);
6814 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6815 Args.push_back(Arg);
6818 CallLoweringInfo CLI(DAG);
6821 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6822 ES, std::move(Args), 0);
6824 return LowerCallTo(CLI).first;
6827 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6828 bool Signed) const {
6829 assert(Op.getValueType() == MVT::i32 &&
6830 "unexpected type for custom lowering DIV");
6833 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6834 DAG.getEntryNode(), Op.getOperand(1));
6836 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6839 void ARMTargetLowering::ExpandDIV_Windows(
6840 SDValue Op, SelectionDAG &DAG, bool Signed,
6841 SmallVectorImpl<SDValue> &Results) const {
6842 const auto &DL = DAG.getDataLayout();
6843 const auto &TLI = DAG.getTargetLoweringInfo();
6845 assert(Op.getValueType() == MVT::i64 &&
6846 "unexpected type for custom lowering DIV");
6849 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6850 DAG.getConstant(0, dl, MVT::i32));
6851 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6852 DAG.getConstant(1, dl, MVT::i32));
6853 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6856 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6858 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6860 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6861 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6862 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6863 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6865 Results.push_back(Lower);
6866 Results.push_back(Upper);
6869 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6870 // Monotonic load/store is legal for all targets
6871 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6874 // Acquire/Release load/store is not legal for targets without a
6875 // dmb or equivalent available.
6879 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6880 SmallVectorImpl<SDValue> &Results,
6882 const ARMSubtarget *Subtarget) {
6884 // Under Power Management extensions, the cycle-count is:
6885 // mrc p15, #0, <Rt>, c9, c13, #0
6886 SDValue Ops[] = { N->getOperand(0), // Chain
6887 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6888 DAG.getConstant(15, DL, MVT::i32),
6889 DAG.getConstant(0, DL, MVT::i32),
6890 DAG.getConstant(9, DL, MVT::i32),
6891 DAG.getConstant(13, DL, MVT::i32),
6892 DAG.getConstant(0, DL, MVT::i32)
6895 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6896 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6897 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6898 DAG.getConstant(0, DL, MVT::i32)));
6899 Results.push_back(Cycles32.getValue(1));
6902 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6903 switch (Op.getOpcode()) {
6904 default: llvm_unreachable("Don't know how to custom lower this!");
6905 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6906 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6907 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6908 case ISD::GlobalAddress:
6909 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6910 default: llvm_unreachable("unknown object format");
6912 return LowerGlobalAddressWindows(Op, DAG);
6914 return LowerGlobalAddressELF(Op, DAG);
6916 return LowerGlobalAddressDarwin(Op, DAG);
6918 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6919 case ISD::SELECT: return LowerSELECT(Op, DAG);
6920 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6921 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6922 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6923 case ISD::VASTART: return LowerVASTART(Op, DAG);
6924 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6925 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6926 case ISD::SINT_TO_FP:
6927 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6928 case ISD::FP_TO_SINT:
6929 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6930 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6931 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6932 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6933 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6934 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6935 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6936 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6938 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6941 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6942 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6943 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6944 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6945 case ISD::SRL_PARTS:
6946 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6948 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6949 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6950 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6951 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6952 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6953 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6954 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6955 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6956 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6957 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6958 case ISD::MUL: return LowerMUL(Op, DAG);
6959 case ISD::SDIV: return LowerSDIV(Op, DAG);
6960 case ISD::UDIV: return LowerUDIV(Op, DAG);
6964 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6969 return LowerXALUO(Op, DAG);
6970 case ISD::ATOMIC_LOAD:
6971 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6972 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6974 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6975 case ISD::DYNAMIC_STACKALLOC:
6976 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6977 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6978 llvm_unreachable("Don't know how to custom lower this!");
6979 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6980 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6981 case ARMISD::WIN__DBZCHK: return SDValue();
6985 /// ReplaceNodeResults - Replace the results of node with an illegal result
6986 /// type with new values built out of custom code.
6987 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6988 SmallVectorImpl<SDValue> &Results,
6989 SelectionDAG &DAG) const {
6991 switch (N->getOpcode()) {
6993 llvm_unreachable("Don't know how to custom expand this!");
6994 case ISD::READ_REGISTER:
6995 ExpandREAD_REGISTER(N, Results, DAG);
6998 Res = ExpandBITCAST(N, DAG);
7002 Res = Expand64BitShift(N, DAG, Subtarget);
7006 Res = LowerREM(N, DAG);
7008 case ISD::READCYCLECOUNTER:
7009 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7013 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7014 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7018 Results.push_back(Res);
7021 //===----------------------------------------------------------------------===//
7022 // ARM Scheduler Hooks
7023 //===----------------------------------------------------------------------===//
7025 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7026 /// registers the function context.
7027 void ARMTargetLowering::
7028 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
7029 MachineBasicBlock *DispatchBB, int FI) const {
7030 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7031 DebugLoc dl = MI->getDebugLoc();
7032 MachineFunction *MF = MBB->getParent();
7033 MachineRegisterInfo *MRI = &MF->getRegInfo();
7034 MachineConstantPool *MCP = MF->getConstantPool();
7035 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7036 const Function *F = MF->getFunction();
7038 bool isThumb = Subtarget->isThumb();
7039 bool isThumb2 = Subtarget->isThumb2();
7041 unsigned PCLabelId = AFI->createPICLabelUId();
7042 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7043 ARMConstantPoolValue *CPV =
7044 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7045 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7047 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7048 : &ARM::GPRRegClass;
7050 // Grab constant pool and fixed stack memory operands.
7051 MachineMemOperand *CPMMO =
7052 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7053 MachineMemOperand::MOLoad, 4, 4);
7055 MachineMemOperand *FIMMOSt =
7056 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7057 MachineMemOperand::MOStore, 4, 4);
7059 // Load the address of the dispatch MBB into the jump buffer.
7061 // Incoming value: jbuf
7062 // ldr.n r5, LCPI1_1
7065 // str r5, [$jbuf, #+4] ; &jbuf[1]
7066 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7067 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7068 .addConstantPoolIndex(CPI)
7069 .addMemOperand(CPMMO));
7070 // Set the low bit because of thumb mode.
7071 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7073 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7074 .addReg(NewVReg1, RegState::Kill)
7076 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7077 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7078 .addReg(NewVReg2, RegState::Kill)
7080 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7081 .addReg(NewVReg3, RegState::Kill)
7083 .addImm(36) // &jbuf[1] :: pc
7084 .addMemOperand(FIMMOSt));
7085 } else if (isThumb) {
7086 // Incoming value: jbuf
7087 // ldr.n r1, LCPI1_4
7091 // add r2, $jbuf, #+4 ; &jbuf[1]
7093 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7094 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7095 .addConstantPoolIndex(CPI)
7096 .addMemOperand(CPMMO));
7097 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7098 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7099 .addReg(NewVReg1, RegState::Kill)
7101 // Set the low bit because of thumb mode.
7102 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7103 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7104 .addReg(ARM::CPSR, RegState::Define)
7106 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7107 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7108 .addReg(ARM::CPSR, RegState::Define)
7109 .addReg(NewVReg2, RegState::Kill)
7110 .addReg(NewVReg3, RegState::Kill));
7111 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7112 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7114 .addImm(36); // &jbuf[1] :: pc
7115 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7116 .addReg(NewVReg4, RegState::Kill)
7117 .addReg(NewVReg5, RegState::Kill)
7119 .addMemOperand(FIMMOSt));
7121 // Incoming value: jbuf
7124 // str r1, [$jbuf, #+4] ; &jbuf[1]
7125 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7126 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7127 .addConstantPoolIndex(CPI)
7129 .addMemOperand(CPMMO));
7130 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7131 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7132 .addReg(NewVReg1, RegState::Kill)
7133 .addImm(PCLabelId));
7134 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7135 .addReg(NewVReg2, RegState::Kill)
7137 .addImm(36) // &jbuf[1] :: pc
7138 .addMemOperand(FIMMOSt));
7142 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7143 MachineBasicBlock *MBB) const {
7144 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7145 DebugLoc dl = MI->getDebugLoc();
7146 MachineFunction *MF = MBB->getParent();
7147 MachineRegisterInfo *MRI = &MF->getRegInfo();
7148 MachineFrameInfo *MFI = MF->getFrameInfo();
7149 int FI = MFI->getFunctionContextIndex();
7151 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7152 : &ARM::GPRnopcRegClass;
7154 // Get a mapping of the call site numbers to all of the landing pads they're
7156 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7157 unsigned MaxCSNum = 0;
7158 MachineModuleInfo &MMI = MF->getMMI();
7159 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7161 if (!BB->isEHPad()) continue;
7163 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7165 for (MachineBasicBlock::iterator
7166 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7167 if (!II->isEHLabel()) continue;
7169 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7170 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7172 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7173 for (SmallVectorImpl<unsigned>::iterator
7174 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7175 CSI != CSE; ++CSI) {
7176 CallSiteNumToLPad[*CSI].push_back(&*BB);
7177 MaxCSNum = std::max(MaxCSNum, *CSI);
7183 // Get an ordered list of the machine basic blocks for the jump table.
7184 std::vector<MachineBasicBlock*> LPadList;
7185 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7186 LPadList.reserve(CallSiteNumToLPad.size());
7187 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7188 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7189 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7190 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7191 LPadList.push_back(*II);
7192 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7196 assert(!LPadList.empty() &&
7197 "No landing pad destinations for the dispatch jump table!");
7199 // Create the jump table and associated information.
7200 MachineJumpTableInfo *JTI =
7201 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7202 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7203 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7205 // Create the MBBs for the dispatch code.
7207 // Shove the dispatch's address into the return slot in the function context.
7208 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7209 DispatchBB->setIsEHPad();
7211 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7212 unsigned trap_opcode;
7213 if (Subtarget->isThumb())
7214 trap_opcode = ARM::tTRAP;
7216 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7218 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7219 DispatchBB->addSuccessor(TrapBB);
7221 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7222 DispatchBB->addSuccessor(DispContBB);
7225 MF->insert(MF->end(), DispatchBB);
7226 MF->insert(MF->end(), DispContBB);
7227 MF->insert(MF->end(), TrapBB);
7229 // Insert code into the entry block that creates and registers the function
7231 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7233 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7234 MachinePointerInfo::getFixedStack(*MF, FI),
7235 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7237 MachineInstrBuilder MIB;
7238 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7240 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7241 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7243 // Add a register mask with no preserved registers. This results in all
7244 // registers being marked as clobbered.
7245 MIB.addRegMask(RI.getNoPreservedMask());
7247 unsigned NumLPads = LPadList.size();
7248 if (Subtarget->isThumb2()) {
7249 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7250 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7253 .addMemOperand(FIMMOLd));
7255 if (NumLPads < 256) {
7256 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7258 .addImm(LPadList.size()));
7260 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7261 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7262 .addImm(NumLPads & 0xFFFF));
7264 unsigned VReg2 = VReg1;
7265 if ((NumLPads & 0xFFFF0000) != 0) {
7266 VReg2 = MRI->createVirtualRegister(TRC);
7267 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7269 .addImm(NumLPads >> 16));
7272 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7277 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7282 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7283 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7284 .addJumpTableIndex(MJTI));
7286 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7289 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7290 .addReg(NewVReg3, RegState::Kill)
7292 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7294 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7295 .addReg(NewVReg4, RegState::Kill)
7297 .addJumpTableIndex(MJTI);
7298 } else if (Subtarget->isThumb()) {
7299 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7300 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7303 .addMemOperand(FIMMOLd));
7305 if (NumLPads < 256) {
7306 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7310 MachineConstantPool *ConstantPool = MF->getConstantPool();
7311 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7312 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7314 // MachineConstantPool wants an explicit alignment.
7315 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7317 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7318 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7320 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7321 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7322 .addReg(VReg1, RegState::Define)
7323 .addConstantPoolIndex(Idx));
7324 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7329 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7334 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7335 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7336 .addReg(ARM::CPSR, RegState::Define)
7340 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7341 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7342 .addJumpTableIndex(MJTI));
7344 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7345 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7346 .addReg(ARM::CPSR, RegState::Define)
7347 .addReg(NewVReg2, RegState::Kill)
7350 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7351 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7353 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7354 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7355 .addReg(NewVReg4, RegState::Kill)
7357 .addMemOperand(JTMMOLd));
7359 unsigned NewVReg6 = NewVReg5;
7360 if (RelocM == Reloc::PIC_) {
7361 NewVReg6 = MRI->createVirtualRegister(TRC);
7362 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7363 .addReg(ARM::CPSR, RegState::Define)
7364 .addReg(NewVReg5, RegState::Kill)
7368 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7369 .addReg(NewVReg6, RegState::Kill)
7370 .addJumpTableIndex(MJTI);
7372 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7373 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7376 .addMemOperand(FIMMOLd));
7378 if (NumLPads < 256) {
7379 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7382 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7383 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7384 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7385 .addImm(NumLPads & 0xFFFF));
7387 unsigned VReg2 = VReg1;
7388 if ((NumLPads & 0xFFFF0000) != 0) {
7389 VReg2 = MRI->createVirtualRegister(TRC);
7390 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7392 .addImm(NumLPads >> 16));
7395 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7399 MachineConstantPool *ConstantPool = MF->getConstantPool();
7400 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7401 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7403 // MachineConstantPool wants an explicit alignment.
7404 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7406 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7407 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7409 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7410 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7411 .addReg(VReg1, RegState::Define)
7412 .addConstantPoolIndex(Idx)
7414 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7416 .addReg(VReg1, RegState::Kill));
7419 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7424 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7426 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7428 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7429 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7430 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7431 .addJumpTableIndex(MJTI));
7433 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7434 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7435 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7437 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7438 .addReg(NewVReg3, RegState::Kill)
7441 .addMemOperand(JTMMOLd));
7443 if (RelocM == Reloc::PIC_) {
7444 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7445 .addReg(NewVReg5, RegState::Kill)
7447 .addJumpTableIndex(MJTI);
7449 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7450 .addReg(NewVReg5, RegState::Kill)
7451 .addJumpTableIndex(MJTI);
7455 // Add the jump table entries as successors to the MBB.
7456 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7457 for (std::vector<MachineBasicBlock*>::iterator
7458 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7459 MachineBasicBlock *CurMBB = *I;
7460 if (SeenMBBs.insert(CurMBB).second)
7461 DispContBB->addSuccessor(CurMBB);
7464 // N.B. the order the invoke BBs are processed in doesn't matter here.
7465 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7466 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7467 for (MachineBasicBlock *BB : InvokeBBs) {
7469 // Remove the landing pad successor from the invoke block and replace it
7470 // with the new dispatch block.
7471 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7473 while (!Successors.empty()) {
7474 MachineBasicBlock *SMBB = Successors.pop_back_val();
7475 if (SMBB->isEHPad()) {
7476 BB->removeSuccessor(SMBB);
7477 MBBLPads.push_back(SMBB);
7481 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7482 BB->normalizeSuccProbs();
7484 // Find the invoke call and mark all of the callee-saved registers as
7485 // 'implicit defined' so that they're spilled. This prevents code from
7486 // moving instructions to before the EH block, where they will never be
7488 for (MachineBasicBlock::reverse_iterator
7489 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7490 if (!II->isCall()) continue;
7492 DenseMap<unsigned, bool> DefRegs;
7493 for (MachineInstr::mop_iterator
7494 OI = II->operands_begin(), OE = II->operands_end();
7496 if (!OI->isReg()) continue;
7497 DefRegs[OI->getReg()] = true;
7500 MachineInstrBuilder MIB(*MF, &*II);
7502 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7503 unsigned Reg = SavedRegs[i];
7504 if (Subtarget->isThumb2() &&
7505 !ARM::tGPRRegClass.contains(Reg) &&
7506 !ARM::hGPRRegClass.contains(Reg))
7508 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7510 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7513 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7520 // Mark all former landing pads as non-landing pads. The dispatch is the only
7522 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7523 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7524 (*I)->setIsEHPad(false);
7526 // The instruction is gone now.
7527 MI->eraseFromParent();
7531 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7532 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7533 E = MBB->succ_end(); I != E; ++I)
7536 llvm_unreachable("Expecting a BB with two successors!");
7539 /// Return the load opcode for a given load size. If load size >= 8,
7540 /// neon opcode will be returned.
7541 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7543 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7544 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7546 return LdSize == 4 ? ARM::tLDRi
7547 : LdSize == 2 ? ARM::tLDRHi
7548 : LdSize == 1 ? ARM::tLDRBi : 0;
7550 return LdSize == 4 ? ARM::t2LDR_POST
7551 : LdSize == 2 ? ARM::t2LDRH_POST
7552 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7553 return LdSize == 4 ? ARM::LDR_POST_IMM
7554 : LdSize == 2 ? ARM::LDRH_POST
7555 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7558 /// Return the store opcode for a given store size. If store size >= 8,
7559 /// neon opcode will be returned.
7560 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7562 return StSize == 16 ? ARM::VST1q32wb_fixed
7563 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7565 return StSize == 4 ? ARM::tSTRi
7566 : StSize == 2 ? ARM::tSTRHi
7567 : StSize == 1 ? ARM::tSTRBi : 0;
7569 return StSize == 4 ? ARM::t2STR_POST
7570 : StSize == 2 ? ARM::t2STRH_POST
7571 : StSize == 1 ? ARM::t2STRB_POST : 0;
7572 return StSize == 4 ? ARM::STR_POST_IMM
7573 : StSize == 2 ? ARM::STRH_POST
7574 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7577 /// Emit a post-increment load operation with given size. The instructions
7578 /// will be added to BB at Pos.
7579 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7580 const TargetInstrInfo *TII, DebugLoc dl,
7581 unsigned LdSize, unsigned Data, unsigned AddrIn,
7582 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7583 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7584 assert(LdOpc != 0 && "Should have a load opcode");
7586 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7587 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7589 } else if (IsThumb1) {
7590 // load + update AddrIn
7591 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7592 .addReg(AddrIn).addImm(0));
7593 MachineInstrBuilder MIB =
7594 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7595 MIB = AddDefaultT1CC(MIB);
7596 MIB.addReg(AddrIn).addImm(LdSize);
7597 AddDefaultPred(MIB);
7598 } else if (IsThumb2) {
7599 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7600 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7603 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7604 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7605 .addReg(0).addImm(LdSize));
7609 /// Emit a post-increment store operation with given size. The instructions
7610 /// will be added to BB at Pos.
7611 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7612 const TargetInstrInfo *TII, DebugLoc dl,
7613 unsigned StSize, unsigned Data, unsigned AddrIn,
7614 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7615 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7616 assert(StOpc != 0 && "Should have a store opcode");
7618 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7619 .addReg(AddrIn).addImm(0).addReg(Data));
7620 } else if (IsThumb1) {
7621 // store + update AddrIn
7622 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7623 .addReg(AddrIn).addImm(0));
7624 MachineInstrBuilder MIB =
7625 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7626 MIB = AddDefaultT1CC(MIB);
7627 MIB.addReg(AddrIn).addImm(StSize);
7628 AddDefaultPred(MIB);
7629 } else if (IsThumb2) {
7630 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7631 .addReg(Data).addReg(AddrIn).addImm(StSize));
7633 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7634 .addReg(Data).addReg(AddrIn).addReg(0)
7640 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7641 MachineBasicBlock *BB) const {
7642 // This pseudo instruction has 3 operands: dst, src, size
7643 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7644 // Otherwise, we will generate unrolled scalar copies.
7645 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7646 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7647 MachineFunction::iterator It = ++BB->getIterator();
7649 unsigned dest = MI->getOperand(0).getReg();
7650 unsigned src = MI->getOperand(1).getReg();
7651 unsigned SizeVal = MI->getOperand(2).getImm();
7652 unsigned Align = MI->getOperand(3).getImm();
7653 DebugLoc dl = MI->getDebugLoc();
7655 MachineFunction *MF = BB->getParent();
7656 MachineRegisterInfo &MRI = MF->getRegInfo();
7657 unsigned UnitSize = 0;
7658 const TargetRegisterClass *TRC = nullptr;
7659 const TargetRegisterClass *VecTRC = nullptr;
7661 bool IsThumb1 = Subtarget->isThumb1Only();
7662 bool IsThumb2 = Subtarget->isThumb2();
7666 } else if (Align & 2) {
7669 // Check whether we can use NEON instructions.
7670 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7671 Subtarget->hasNEON()) {
7672 if ((Align % 16 == 0) && SizeVal >= 16)
7674 else if ((Align % 8 == 0) && SizeVal >= 8)
7677 // Can't use NEON instructions.
7682 // Select the correct opcode and register class for unit size load/store
7683 bool IsNeon = UnitSize >= 8;
7684 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7686 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7687 : UnitSize == 8 ? &ARM::DPRRegClass
7690 unsigned BytesLeft = SizeVal % UnitSize;
7691 unsigned LoopSize = SizeVal - BytesLeft;
7693 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7694 // Use LDR and STR to copy.
7695 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7696 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7697 unsigned srcIn = src;
7698 unsigned destIn = dest;
7699 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7700 unsigned srcOut = MRI.createVirtualRegister(TRC);
7701 unsigned destOut = MRI.createVirtualRegister(TRC);
7702 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7703 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7704 IsThumb1, IsThumb2);
7705 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7706 IsThumb1, IsThumb2);
7711 // Handle the leftover bytes with LDRB and STRB.
7712 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7713 // [destOut] = STRB_POST(scratch, destIn, 1)
7714 for (unsigned i = 0; i < BytesLeft; i++) {
7715 unsigned srcOut = MRI.createVirtualRegister(TRC);
7716 unsigned destOut = MRI.createVirtualRegister(TRC);
7717 unsigned scratch = MRI.createVirtualRegister(TRC);
7718 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7719 IsThumb1, IsThumb2);
7720 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7721 IsThumb1, IsThumb2);
7725 MI->eraseFromParent(); // The instruction is gone now.
7729 // Expand the pseudo op to a loop.
7732 // movw varEnd, # --> with thumb2
7734 // ldrcp varEnd, idx --> without thumb2
7735 // fallthrough --> loopMBB
7737 // PHI varPhi, varEnd, varLoop
7738 // PHI srcPhi, src, srcLoop
7739 // PHI destPhi, dst, destLoop
7740 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7741 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7742 // subs varLoop, varPhi, #UnitSize
7744 // fallthrough --> exitMBB
7746 // epilogue to handle left-over bytes
7747 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7748 // [destOut] = STRB_POST(scratch, destLoop, 1)
7749 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7750 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7751 MF->insert(It, loopMBB);
7752 MF->insert(It, exitMBB);
7754 // Transfer the remainder of BB and its successor edges to exitMBB.
7755 exitMBB->splice(exitMBB->begin(), BB,
7756 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7757 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7759 // Load an immediate to varEnd.
7760 unsigned varEnd = MRI.createVirtualRegister(TRC);
7761 if (Subtarget->useMovt(*MF)) {
7762 unsigned Vtmp = varEnd;
7763 if ((LoopSize & 0xFFFF0000) != 0)
7764 Vtmp = MRI.createVirtualRegister(TRC);
7765 AddDefaultPred(BuildMI(BB, dl,
7766 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7767 Vtmp).addImm(LoopSize & 0xFFFF));
7769 if ((LoopSize & 0xFFFF0000) != 0)
7770 AddDefaultPred(BuildMI(BB, dl,
7771 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7774 .addImm(LoopSize >> 16));
7776 MachineConstantPool *ConstantPool = MF->getConstantPool();
7777 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7778 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7780 // MachineConstantPool wants an explicit alignment.
7781 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7783 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7784 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7787 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7788 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7790 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7791 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7793 BB->addSuccessor(loopMBB);
7795 // Generate the loop body:
7796 // varPhi = PHI(varLoop, varEnd)
7797 // srcPhi = PHI(srcLoop, src)
7798 // destPhi = PHI(destLoop, dst)
7799 MachineBasicBlock *entryBB = BB;
7801 unsigned varLoop = MRI.createVirtualRegister(TRC);
7802 unsigned varPhi = MRI.createVirtualRegister(TRC);
7803 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7804 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7805 unsigned destLoop = MRI.createVirtualRegister(TRC);
7806 unsigned destPhi = MRI.createVirtualRegister(TRC);
7808 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7809 .addReg(varLoop).addMBB(loopMBB)
7810 .addReg(varEnd).addMBB(entryBB);
7811 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7812 .addReg(srcLoop).addMBB(loopMBB)
7813 .addReg(src).addMBB(entryBB);
7814 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7815 .addReg(destLoop).addMBB(loopMBB)
7816 .addReg(dest).addMBB(entryBB);
7818 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7819 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7820 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7821 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7822 IsThumb1, IsThumb2);
7823 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7824 IsThumb1, IsThumb2);
7826 // Decrement loop variable by UnitSize.
7828 MachineInstrBuilder MIB =
7829 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7830 MIB = AddDefaultT1CC(MIB);
7831 MIB.addReg(varPhi).addImm(UnitSize);
7832 AddDefaultPred(MIB);
7834 MachineInstrBuilder MIB =
7835 BuildMI(*BB, BB->end(), dl,
7836 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7837 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7838 MIB->getOperand(5).setReg(ARM::CPSR);
7839 MIB->getOperand(5).setIsDef(true);
7841 BuildMI(*BB, BB->end(), dl,
7842 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7843 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7845 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7846 BB->addSuccessor(loopMBB);
7847 BB->addSuccessor(exitMBB);
7849 // Add epilogue to handle BytesLeft.
7851 MachineInstr *StartOfExit = exitMBB->begin();
7853 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7854 // [destOut] = STRB_POST(scratch, destLoop, 1)
7855 unsigned srcIn = srcLoop;
7856 unsigned destIn = destLoop;
7857 for (unsigned i = 0; i < BytesLeft; i++) {
7858 unsigned srcOut = MRI.createVirtualRegister(TRC);
7859 unsigned destOut = MRI.createVirtualRegister(TRC);
7860 unsigned scratch = MRI.createVirtualRegister(TRC);
7861 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7862 IsThumb1, IsThumb2);
7863 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7864 IsThumb1, IsThumb2);
7869 MI->eraseFromParent(); // The instruction is gone now.
7874 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7875 MachineBasicBlock *MBB) const {
7876 const TargetMachine &TM = getTargetMachine();
7877 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7878 DebugLoc DL = MI->getDebugLoc();
7880 assert(Subtarget->isTargetWindows() &&
7881 "__chkstk is only supported on Windows");
7882 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7884 // __chkstk takes the number of words to allocate on the stack in R4, and
7885 // returns the stack adjustment in number of bytes in R4. This will not
7886 // clober any other registers (other than the obvious lr).
7888 // Although, technically, IP should be considered a register which may be
7889 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7890 // thumb-2 environment, so there is no interworking required. As a result, we
7891 // do not expect a veneer to be emitted by the linker, clobbering IP.
7893 // Each module receives its own copy of __chkstk, so no import thunk is
7894 // required, again, ensuring that IP is not clobbered.
7896 // Finally, although some linkers may theoretically provide a trampoline for
7897 // out of range calls (which is quite common due to a 32M range limitation of
7898 // branches for Thumb), we can generate the long-call version via
7899 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7902 switch (TM.getCodeModel()) {
7903 case CodeModel::Small:
7904 case CodeModel::Medium:
7905 case CodeModel::Default:
7906 case CodeModel::Kernel:
7907 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7908 .addImm((unsigned)ARMCC::AL).addReg(0)
7909 .addExternalSymbol("__chkstk")
7910 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7911 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7912 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7914 case CodeModel::Large:
7915 case CodeModel::JITDefault: {
7916 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7917 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7919 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7920 .addExternalSymbol("__chkstk");
7921 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7922 .addImm((unsigned)ARMCC::AL).addReg(0)
7923 .addReg(Reg, RegState::Kill)
7924 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7925 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7926 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7931 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7933 .addReg(ARM::SP).addReg(ARM::R4)));
7935 MI->eraseFromParent();
7940 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7941 MachineBasicBlock *MBB) const {
7942 DebugLoc DL = MI->getDebugLoc();
7943 MachineFunction *MF = MBB->getParent();
7944 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7946 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7947 MF->push_back(ContBB);
7948 ContBB->splice(ContBB->begin(), MBB,
7949 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7950 MBB->addSuccessor(ContBB);
7952 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7953 MF->push_back(TrapBB);
7954 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7955 MBB->addSuccessor(TrapBB);
7957 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7958 .addReg(MI->getOperand(0).getReg())
7961 MI->eraseFromParent();
7966 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7967 MachineBasicBlock *BB) const {
7968 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7969 DebugLoc dl = MI->getDebugLoc();
7970 bool isThumb2 = Subtarget->isThumb2();
7971 switch (MI->getOpcode()) {
7974 llvm_unreachable("Unexpected instr type to insert");
7976 // The Thumb2 pre-indexed stores have the same MI operands, they just
7977 // define them differently in the .td files from the isel patterns, so
7978 // they need pseudos.
7979 case ARM::t2STR_preidx:
7980 MI->setDesc(TII->get(ARM::t2STR_PRE));
7982 case ARM::t2STRB_preidx:
7983 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7985 case ARM::t2STRH_preidx:
7986 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7989 case ARM::STRi_preidx:
7990 case ARM::STRBi_preidx: {
7991 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7992 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7993 // Decode the offset.
7994 unsigned Offset = MI->getOperand(4).getImm();
7995 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7996 Offset = ARM_AM::getAM2Offset(Offset);
8000 MachineMemOperand *MMO = *MI->memoperands_begin();
8001 BuildMI(*BB, MI, dl, TII->get(NewOpc))
8002 .addOperand(MI->getOperand(0)) // Rn_wb
8003 .addOperand(MI->getOperand(1)) // Rt
8004 .addOperand(MI->getOperand(2)) // Rn
8005 .addImm(Offset) // offset (skip GPR==zero_reg)
8006 .addOperand(MI->getOperand(5)) // pred
8007 .addOperand(MI->getOperand(6))
8008 .addMemOperand(MMO);
8009 MI->eraseFromParent();
8012 case ARM::STRr_preidx:
8013 case ARM::STRBr_preidx:
8014 case ARM::STRH_preidx: {
8016 switch (MI->getOpcode()) {
8017 default: llvm_unreachable("unexpected opcode!");
8018 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8019 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8020 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8022 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8023 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
8024 MIB.addOperand(MI->getOperand(i));
8025 MI->eraseFromParent();
8029 case ARM::tMOVCCr_pseudo: {
8030 // To "insert" a SELECT_CC instruction, we actually have to insert the
8031 // diamond control-flow pattern. The incoming instruction knows the
8032 // destination vreg to set, the condition code register to branch on, the
8033 // true/false values to select between, and a branch opcode to use.
8034 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8035 MachineFunction::iterator It = ++BB->getIterator();
8040 // cmpTY ccX, r1, r2
8042 // fallthrough --> copy0MBB
8043 MachineBasicBlock *thisMBB = BB;
8044 MachineFunction *F = BB->getParent();
8045 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8046 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8047 F->insert(It, copy0MBB);
8048 F->insert(It, sinkMBB);
8050 // Transfer the remainder of BB and its successor edges to sinkMBB.
8051 sinkMBB->splice(sinkMBB->begin(), BB,
8052 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8053 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8055 BB->addSuccessor(copy0MBB);
8056 BB->addSuccessor(sinkMBB);
8058 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
8059 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
8062 // %FalseValue = ...
8063 // # fallthrough to sinkMBB
8066 // Update machine-CFG edges
8067 BB->addSuccessor(sinkMBB);
8070 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8073 BuildMI(*BB, BB->begin(), dl,
8074 TII->get(ARM::PHI), MI->getOperand(0).getReg())
8075 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8076 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8078 MI->eraseFromParent(); // The pseudo instruction is gone now.
8083 case ARM::BCCZi64: {
8084 // If there is an unconditional branch to the other successor, remove it.
8085 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8087 // Compare both parts that make up the double comparison separately for
8089 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8091 unsigned LHS1 = MI->getOperand(1).getReg();
8092 unsigned LHS2 = MI->getOperand(2).getReg();
8094 AddDefaultPred(BuildMI(BB, dl,
8095 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8096 .addReg(LHS1).addImm(0));
8097 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8098 .addReg(LHS2).addImm(0)
8099 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8101 unsigned RHS1 = MI->getOperand(3).getReg();
8102 unsigned RHS2 = MI->getOperand(4).getReg();
8103 AddDefaultPred(BuildMI(BB, dl,
8104 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8105 .addReg(LHS1).addReg(RHS1));
8106 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8107 .addReg(LHS2).addReg(RHS2)
8108 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8111 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8112 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8113 if (MI->getOperand(0).getImm() == ARMCC::NE)
8114 std::swap(destMBB, exitMBB);
8116 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8117 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8119 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8121 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8123 MI->eraseFromParent(); // The pseudo instruction is gone now.
8127 case ARM::Int_eh_sjlj_setjmp:
8128 case ARM::Int_eh_sjlj_setjmp_nofp:
8129 case ARM::tInt_eh_sjlj_setjmp:
8130 case ARM::t2Int_eh_sjlj_setjmp:
8131 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8134 case ARM::Int_eh_sjlj_setup_dispatch:
8135 EmitSjLjDispatchBlock(MI, BB);
8140 // To insert an ABS instruction, we have to insert the
8141 // diamond control-flow pattern. The incoming instruction knows the
8142 // source vreg to test against 0, the destination vreg to set,
8143 // the condition code register to branch on, the
8144 // true/false values to select between, and a branch opcode to use.
8149 // BCC (branch to SinkBB if V0 >= 0)
8150 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8151 // SinkBB: V1 = PHI(V2, V3)
8152 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8153 MachineFunction::iterator BBI = ++BB->getIterator();
8154 MachineFunction *Fn = BB->getParent();
8155 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8156 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8157 Fn->insert(BBI, RSBBB);
8158 Fn->insert(BBI, SinkBB);
8160 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8161 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8162 bool ABSSrcKIll = MI->getOperand(1).isKill();
8163 bool isThumb2 = Subtarget->isThumb2();
8164 MachineRegisterInfo &MRI = Fn->getRegInfo();
8165 // In Thumb mode S must not be specified if source register is the SP or
8166 // PC and if destination register is the SP, so restrict register class
8167 unsigned NewRsbDstReg =
8168 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8170 // Transfer the remainder of BB and its successor edges to sinkMBB.
8171 SinkBB->splice(SinkBB->begin(), BB,
8172 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8173 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8175 BB->addSuccessor(RSBBB);
8176 BB->addSuccessor(SinkBB);
8178 // fall through to SinkMBB
8179 RSBBB->addSuccessor(SinkBB);
8181 // insert a cmp at the end of BB
8182 AddDefaultPred(BuildMI(BB, dl,
8183 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8184 .addReg(ABSSrcReg).addImm(0));
8186 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8188 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8189 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8191 // insert rsbri in RSBBB
8192 // Note: BCC and rsbri will be converted into predicated rsbmi
8193 // by if-conversion pass
8194 BuildMI(*RSBBB, RSBBB->begin(), dl,
8195 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8196 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8197 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8199 // insert PHI in SinkBB,
8200 // reuse ABSDstReg to not change uses of ABS instruction
8201 BuildMI(*SinkBB, SinkBB->begin(), dl,
8202 TII->get(ARM::PHI), ABSDstReg)
8203 .addReg(NewRsbDstReg).addMBB(RSBBB)
8204 .addReg(ABSSrcReg).addMBB(BB);
8206 // remove ABS instruction
8207 MI->eraseFromParent();
8209 // return last added BB
8212 case ARM::COPY_STRUCT_BYVAL_I32:
8214 return EmitStructByval(MI, BB);
8215 case ARM::WIN__CHKSTK:
8216 return EmitLowered__chkstk(MI, BB);
8217 case ARM::WIN__DBZCHK:
8218 return EmitLowered__dbzchk(MI, BB);
8222 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8223 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8224 /// instead of as a custom inserter because we need the use list from the SDNode.
8225 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8226 MachineInstr *MI, const SDNode *Node) {
8227 bool isThumb1 = Subtarget->isThumb1Only();
8229 DebugLoc DL = MI->getDebugLoc();
8230 MachineFunction *MF = MI->getParent()->getParent();
8231 MachineRegisterInfo &MRI = MF->getRegInfo();
8232 MachineInstrBuilder MIB(*MF, MI);
8234 // If the new dst/src is unused mark it as dead.
8235 if (!Node->hasAnyUseOfValue(0)) {
8236 MI->getOperand(0).setIsDead(true);
8238 if (!Node->hasAnyUseOfValue(1)) {
8239 MI->getOperand(1).setIsDead(true);
8242 // The MEMCPY both defines and kills the scratch registers.
8243 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8244 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8245 : &ARM::GPRRegClass);
8246 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8250 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8251 SDNode *Node) const {
8252 if (MI->getOpcode() == ARM::MEMCPY) {
8253 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8257 const MCInstrDesc *MCID = &MI->getDesc();
8258 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8259 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8260 // operand is still set to noreg. If needed, set the optional operand's
8261 // register to CPSR, and remove the redundant implicit def.
8263 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8265 // Rename pseudo opcodes.
8266 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8268 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8269 MCID = &TII->get(NewOpc);
8271 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8272 "converted opcode should be the same except for cc_out");
8276 // Add the optional cc_out operand
8277 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8279 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8281 // Any ARM instruction that sets the 's' bit should specify an optional
8282 // "cc_out" operand in the last operand position.
8283 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8284 assert(!NewOpc && "Optional cc_out operand required");
8287 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8288 // since we already have an optional CPSR def.
8289 bool definesCPSR = false;
8290 bool deadCPSR = false;
8291 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8293 const MachineOperand &MO = MI->getOperand(i);
8294 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8298 MI->RemoveOperand(i);
8303 assert(!NewOpc && "Optional cc_out operand required");
8306 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8308 assert(!MI->getOperand(ccOutIdx).getReg() &&
8309 "expect uninitialized optional cc_out operand");
8313 // If this instruction was defined with an optional CPSR def and its dag node
8314 // had a live implicit CPSR def, then activate the optional CPSR def.
8315 MachineOperand &MO = MI->getOperand(ccOutIdx);
8316 MO.setReg(ARM::CPSR);
8320 //===----------------------------------------------------------------------===//
8321 // ARM Optimization Hooks
8322 //===----------------------------------------------------------------------===//
8324 // Helper function that checks if N is a null or all ones constant.
8325 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8326 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8329 // Return true if N is conditionally 0 or all ones.
8330 // Detects these expressions where cc is an i1 value:
8332 // (select cc 0, y) [AllOnes=0]
8333 // (select cc y, 0) [AllOnes=0]
8334 // (zext cc) [AllOnes=0]
8335 // (sext cc) [AllOnes=0/1]
8336 // (select cc -1, y) [AllOnes=1]
8337 // (select cc y, -1) [AllOnes=1]
8339 // Invert is set when N is the null/all ones constant when CC is false.
8340 // OtherOp is set to the alternative value of N.
8341 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8342 SDValue &CC, bool &Invert,
8344 SelectionDAG &DAG) {
8345 switch (N->getOpcode()) {
8346 default: return false;
8348 CC = N->getOperand(0);
8349 SDValue N1 = N->getOperand(1);
8350 SDValue N2 = N->getOperand(2);
8351 if (isZeroOrAllOnes(N1, AllOnes)) {
8356 if (isZeroOrAllOnes(N2, AllOnes)) {
8363 case ISD::ZERO_EXTEND:
8364 // (zext cc) can never be the all ones value.
8368 case ISD::SIGN_EXTEND: {
8370 EVT VT = N->getValueType(0);
8371 CC = N->getOperand(0);
8372 if (CC.getValueType() != MVT::i1)
8376 // When looking for an AllOnes constant, N is an sext, and the 'other'
8378 OtherOp = DAG.getConstant(0, dl, VT);
8379 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8380 // When looking for a 0 constant, N can be zext or sext.
8381 OtherOp = DAG.getConstant(1, dl, VT);
8383 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8390 // Combine a constant select operand into its use:
8392 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8393 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8394 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8395 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8396 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8398 // The transform is rejected if the select doesn't have a constant operand that
8399 // is null, or all ones when AllOnes is set.
8401 // Also recognize sext/zext from i1:
8403 // (add (zext cc), x) -> (select cc (add x, 1), x)
8404 // (add (sext cc), x) -> (select cc (add x, -1), x)
8406 // These transformations eventually create predicated instructions.
8408 // @param N The node to transform.
8409 // @param Slct The N operand that is a select.
8410 // @param OtherOp The other N operand (x above).
8411 // @param DCI Context.
8412 // @param AllOnes Require the select constant to be all ones instead of null.
8413 // @returns The new node, or SDValue() on failure.
8415 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8416 TargetLowering::DAGCombinerInfo &DCI,
8417 bool AllOnes = false) {
8418 SelectionDAG &DAG = DCI.DAG;
8419 EVT VT = N->getValueType(0);
8420 SDValue NonConstantVal;
8423 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8424 NonConstantVal, DAG))
8427 // Slct is now know to be the desired identity constant when CC is true.
8428 SDValue TrueVal = OtherOp;
8429 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8430 OtherOp, NonConstantVal);
8431 // Unless SwapSelectOps says CC should be false.
8433 std::swap(TrueVal, FalseVal);
8435 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8436 CCOp, TrueVal, FalseVal);
8439 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8441 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8442 TargetLowering::DAGCombinerInfo &DCI) {
8443 SDValue N0 = N->getOperand(0);
8444 SDValue N1 = N->getOperand(1);
8445 if (N0.getNode()->hasOneUse()) {
8446 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8447 if (Result.getNode())
8450 if (N1.getNode()->hasOneUse()) {
8451 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8452 if (Result.getNode())
8458 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8459 // (only after legalization).
8460 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8461 TargetLowering::DAGCombinerInfo &DCI,
8462 const ARMSubtarget *Subtarget) {
8464 // Only perform optimization if after legalize, and if NEON is available. We
8465 // also expected both operands to be BUILD_VECTORs.
8466 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8467 || N0.getOpcode() != ISD::BUILD_VECTOR
8468 || N1.getOpcode() != ISD::BUILD_VECTOR)
8471 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8472 EVT VT = N->getValueType(0);
8473 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8476 // Check that the vector operands are of the right form.
8477 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8478 // operands, where N is the size of the formed vector.
8479 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8480 // index such that we have a pair wise add pattern.
8482 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8483 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8485 SDValue Vec = N0->getOperand(0)->getOperand(0);
8486 SDNode *V = Vec.getNode();
8487 unsigned nextIndex = 0;
8489 // For each operands to the ADD which are BUILD_VECTORs,
8490 // check to see if each of their operands are an EXTRACT_VECTOR with
8491 // the same vector and appropriate index.
8492 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8493 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8494 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8496 SDValue ExtVec0 = N0->getOperand(i);
8497 SDValue ExtVec1 = N1->getOperand(i);
8499 // First operand is the vector, verify its the same.
8500 if (V != ExtVec0->getOperand(0).getNode() ||
8501 V != ExtVec1->getOperand(0).getNode())
8504 // Second is the constant, verify its correct.
8505 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8506 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8508 // For the constant, we want to see all the even or all the odd.
8509 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8510 || C1->getZExtValue() != nextIndex+1)
8519 // Create VPADDL node.
8520 SelectionDAG &DAG = DCI.DAG;
8521 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8525 // Build operand list.
8526 SmallVector<SDValue, 8> Ops;
8527 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8528 TLI.getPointerTy(DAG.getDataLayout())));
8530 // Input is the vector.
8533 // Get widened type and narrowed type.
8535 unsigned numElem = VT.getVectorNumElements();
8537 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8538 switch (inputLaneType.getSimpleVT().SimpleTy) {
8539 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8540 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8541 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8543 llvm_unreachable("Invalid vector element type for padd optimization.");
8546 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8547 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8548 return DAG.getNode(ExtOp, dl, VT, tmp);
8551 static SDValue findMUL_LOHI(SDValue V) {
8552 if (V->getOpcode() == ISD::UMUL_LOHI ||
8553 V->getOpcode() == ISD::SMUL_LOHI)
8558 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8559 TargetLowering::DAGCombinerInfo &DCI,
8560 const ARMSubtarget *Subtarget) {
8562 if (Subtarget->isThumb1Only()) return SDValue();
8564 // Only perform the checks after legalize when the pattern is available.
8565 if (DCI.isBeforeLegalize()) return SDValue();
8567 // Look for multiply add opportunities.
8568 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8569 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8570 // a glue link from the first add to the second add.
8571 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8572 // a S/UMLAL instruction.
8575 // / \ [no multiline comment]
8581 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8582 SDValue AddcOp0 = AddcNode->getOperand(0);
8583 SDValue AddcOp1 = AddcNode->getOperand(1);
8585 // Check if the two operands are from the same mul_lohi node.
8586 if (AddcOp0.getNode() == AddcOp1.getNode())
8589 assert(AddcNode->getNumValues() == 2 &&
8590 AddcNode->getValueType(0) == MVT::i32 &&
8591 "Expect ADDC with two result values. First: i32");
8593 // Check that we have a glued ADDC node.
8594 if (AddcNode->getValueType(1) != MVT::Glue)
8597 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8598 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8599 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8600 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8601 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8604 // Look for the glued ADDE.
8605 SDNode* AddeNode = AddcNode->getGluedUser();
8609 // Make sure it is really an ADDE.
8610 if (AddeNode->getOpcode() != ISD::ADDE)
8613 assert(AddeNode->getNumOperands() == 3 &&
8614 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8615 "ADDE node has the wrong inputs");
8617 // Check for the triangle shape.
8618 SDValue AddeOp0 = AddeNode->getOperand(0);
8619 SDValue AddeOp1 = AddeNode->getOperand(1);
8621 // Make sure that the ADDE operands are not coming from the same node.
8622 if (AddeOp0.getNode() == AddeOp1.getNode())
8625 // Find the MUL_LOHI node walking up ADDE's operands.
8626 bool IsLeftOperandMUL = false;
8627 SDValue MULOp = findMUL_LOHI(AddeOp0);
8628 if (MULOp == SDValue())
8629 MULOp = findMUL_LOHI(AddeOp1);
8631 IsLeftOperandMUL = true;
8632 if (MULOp == SDValue())
8635 // Figure out the right opcode.
8636 unsigned Opc = MULOp->getOpcode();
8637 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8639 // Figure out the high and low input values to the MLAL node.
8640 SDValue* HiAdd = nullptr;
8641 SDValue* LoMul = nullptr;
8642 SDValue* LowAdd = nullptr;
8644 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8645 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8648 if (IsLeftOperandMUL)
8654 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8655 // whose low result is fed to the ADDC we are checking.
8657 if (AddcOp0 == MULOp.getValue(0)) {
8661 if (AddcOp1 == MULOp.getValue(0)) {
8669 // Create the merged node.
8670 SelectionDAG &DAG = DCI.DAG;
8672 // Build operand list.
8673 SmallVector<SDValue, 8> Ops;
8674 Ops.push_back(LoMul->getOperand(0));
8675 Ops.push_back(LoMul->getOperand(1));
8676 Ops.push_back(*LowAdd);
8677 Ops.push_back(*HiAdd);
8679 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8680 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8682 // Replace the ADDs' nodes uses by the MLA node's values.
8683 SDValue HiMLALResult(MLALNode.getNode(), 1);
8684 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8686 SDValue LoMLALResult(MLALNode.getNode(), 0);
8687 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8689 // Return original node to notify the driver to stop replacing.
8690 SDValue resNode(AddcNode, 0);
8694 /// PerformADDCCombine - Target-specific dag combine transform from
8695 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8696 static SDValue PerformADDCCombine(SDNode *N,
8697 TargetLowering::DAGCombinerInfo &DCI,
8698 const ARMSubtarget *Subtarget) {
8700 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8704 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8705 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8706 /// called with the default operands, and if that fails, with commuted
8708 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8709 TargetLowering::DAGCombinerInfo &DCI,
8710 const ARMSubtarget *Subtarget){
8712 // Attempt to create vpaddl for this add.
8713 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8714 if (Result.getNode())
8717 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8718 if (N0.getNode()->hasOneUse()) {
8719 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8720 if (Result.getNode()) return Result;
8725 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8727 static SDValue PerformADDCombine(SDNode *N,
8728 TargetLowering::DAGCombinerInfo &DCI,
8729 const ARMSubtarget *Subtarget) {
8730 SDValue N0 = N->getOperand(0);
8731 SDValue N1 = N->getOperand(1);
8733 // First try with the default operand order.
8734 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8735 if (Result.getNode())
8738 // If that didn't work, try again with the operands commuted.
8739 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8742 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8744 static SDValue PerformSUBCombine(SDNode *N,
8745 TargetLowering::DAGCombinerInfo &DCI) {
8746 SDValue N0 = N->getOperand(0);
8747 SDValue N1 = N->getOperand(1);
8749 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8750 if (N1.getNode()->hasOneUse()) {
8751 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8752 if (Result.getNode()) return Result;
8758 /// PerformVMULCombine
8759 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8760 /// special multiplier accumulator forwarding.
8766 // However, for (A + B) * (A + B),
8773 static SDValue PerformVMULCombine(SDNode *N,
8774 TargetLowering::DAGCombinerInfo &DCI,
8775 const ARMSubtarget *Subtarget) {
8776 if (!Subtarget->hasVMLxForwarding())
8779 SelectionDAG &DAG = DCI.DAG;
8780 SDValue N0 = N->getOperand(0);
8781 SDValue N1 = N->getOperand(1);
8782 unsigned Opcode = N0.getOpcode();
8783 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8784 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8785 Opcode = N1.getOpcode();
8786 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8787 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8795 EVT VT = N->getValueType(0);
8797 SDValue N00 = N0->getOperand(0);
8798 SDValue N01 = N0->getOperand(1);
8799 return DAG.getNode(Opcode, DL, VT,
8800 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8801 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8804 static SDValue PerformMULCombine(SDNode *N,
8805 TargetLowering::DAGCombinerInfo &DCI,
8806 const ARMSubtarget *Subtarget) {
8807 SelectionDAG &DAG = DCI.DAG;
8809 if (Subtarget->isThumb1Only())
8812 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8815 EVT VT = N->getValueType(0);
8816 if (VT.is64BitVector() || VT.is128BitVector())
8817 return PerformVMULCombine(N, DCI, Subtarget);
8821 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8825 int64_t MulAmt = C->getSExtValue();
8826 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8828 ShiftAmt = ShiftAmt & (32 - 1);
8829 SDValue V = N->getOperand(0);
8833 MulAmt >>= ShiftAmt;
8836 if (isPowerOf2_32(MulAmt - 1)) {
8837 // (mul x, 2^N + 1) => (add (shl x, N), x)
8838 Res = DAG.getNode(ISD::ADD, DL, VT,
8840 DAG.getNode(ISD::SHL, DL, VT,
8842 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8844 } else if (isPowerOf2_32(MulAmt + 1)) {
8845 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8846 Res = DAG.getNode(ISD::SUB, DL, VT,
8847 DAG.getNode(ISD::SHL, DL, VT,
8849 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8855 uint64_t MulAmtAbs = -MulAmt;
8856 if (isPowerOf2_32(MulAmtAbs + 1)) {
8857 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8858 Res = DAG.getNode(ISD::SUB, DL, VT,
8860 DAG.getNode(ISD::SHL, DL, VT,
8862 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8864 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8865 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8866 Res = DAG.getNode(ISD::ADD, DL, VT,
8868 DAG.getNode(ISD::SHL, DL, VT,
8870 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8872 Res = DAG.getNode(ISD::SUB, DL, VT,
8873 DAG.getConstant(0, DL, MVT::i32), Res);
8880 Res = DAG.getNode(ISD::SHL, DL, VT,
8881 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8883 // Do not add new nodes to DAG combiner worklist.
8884 DCI.CombineTo(N, Res, false);
8888 static SDValue PerformANDCombine(SDNode *N,
8889 TargetLowering::DAGCombinerInfo &DCI,
8890 const ARMSubtarget *Subtarget) {
8892 // Attempt to use immediate-form VBIC
8893 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8895 EVT VT = N->getValueType(0);
8896 SelectionDAG &DAG = DCI.DAG;
8898 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8901 APInt SplatBits, SplatUndef;
8902 unsigned SplatBitSize;
8905 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8906 if (SplatBitSize <= 64) {
8908 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8909 SplatUndef.getZExtValue(), SplatBitSize,
8910 DAG, dl, VbicVT, VT.is128BitVector(),
8912 if (Val.getNode()) {
8914 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8915 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8916 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8921 if (!Subtarget->isThumb1Only()) {
8922 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8923 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8924 if (Result.getNode())
8931 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8932 static SDValue PerformORCombine(SDNode *N,
8933 TargetLowering::DAGCombinerInfo &DCI,
8934 const ARMSubtarget *Subtarget) {
8935 // Attempt to use immediate-form VORR
8936 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8938 EVT VT = N->getValueType(0);
8939 SelectionDAG &DAG = DCI.DAG;
8941 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8944 APInt SplatBits, SplatUndef;
8945 unsigned SplatBitSize;
8947 if (BVN && Subtarget->hasNEON() &&
8948 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8949 if (SplatBitSize <= 64) {
8951 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8952 SplatUndef.getZExtValue(), SplatBitSize,
8953 DAG, dl, VorrVT, VT.is128BitVector(),
8955 if (Val.getNode()) {
8957 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8958 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8959 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8964 if (!Subtarget->isThumb1Only()) {
8965 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8966 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8967 if (Result.getNode())
8971 // The code below optimizes (or (and X, Y), Z).
8972 // The AND operand needs to have a single user to make these optimizations
8974 SDValue N0 = N->getOperand(0);
8975 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8977 SDValue N1 = N->getOperand(1);
8979 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8980 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8981 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8983 unsigned SplatBitSize;
8986 APInt SplatBits0, SplatBits1;
8987 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8988 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8989 // Ensure that the second operand of both ands are constants
8990 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8991 HasAnyUndefs) && !HasAnyUndefs) {
8992 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8993 HasAnyUndefs) && !HasAnyUndefs) {
8994 // Ensure that the bit width of the constants are the same and that
8995 // the splat arguments are logical inverses as per the pattern we
8996 // are trying to simplify.
8997 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8998 SplatBits0 == ~SplatBits1) {
8999 // Canonicalize the vector type to make instruction selection
9001 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9002 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9006 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9012 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9015 // BFI is only available on V6T2+
9016 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9020 // 1) or (and A, mask), val => ARMbfi A, val, mask
9021 // iff (val & mask) == val
9023 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9024 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9025 // && mask == ~mask2
9026 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9027 // && ~mask == mask2
9028 // (i.e., copy a bitfield value into another bitfield of the same width)
9033 SDValue N00 = N0.getOperand(0);
9035 // The value and the mask need to be constants so we can verify this is
9036 // actually a bitfield set. If the mask is 0xffff, we can do better
9037 // via a movt instruction, so don't use BFI in that case.
9038 SDValue MaskOp = N0.getOperand(1);
9039 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9042 unsigned Mask = MaskC->getZExtValue();
9046 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9049 unsigned Val = N1C->getZExtValue();
9050 if ((Val & ~Mask) != Val)
9053 if (ARM::isBitFieldInvertedMask(Mask)) {
9054 Val >>= countTrailingZeros(~Mask);
9056 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9057 DAG.getConstant(Val, DL, MVT::i32),
9058 DAG.getConstant(Mask, DL, MVT::i32));
9060 // Do not add new nodes to DAG combiner worklist.
9061 DCI.CombineTo(N, Res, false);
9064 } else if (N1.getOpcode() == ISD::AND) {
9065 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9066 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9069 unsigned Mask2 = N11C->getZExtValue();
9071 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9073 if (ARM::isBitFieldInvertedMask(Mask) &&
9075 // The pack halfword instruction works better for masks that fit it,
9076 // so use that when it's available.
9077 if (Subtarget->hasT2ExtractPack() &&
9078 (Mask == 0xffff || Mask == 0xffff0000))
9081 unsigned amt = countTrailingZeros(Mask2);
9082 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9083 DAG.getConstant(amt, DL, MVT::i32));
9084 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9085 DAG.getConstant(Mask, DL, MVT::i32));
9086 // Do not add new nodes to DAG combiner worklist.
9087 DCI.CombineTo(N, Res, false);
9089 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9091 // The pack halfword instruction works better for masks that fit it,
9092 // so use that when it's available.
9093 if (Subtarget->hasT2ExtractPack() &&
9094 (Mask2 == 0xffff || Mask2 == 0xffff0000))
9097 unsigned lsb = countTrailingZeros(Mask);
9098 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9099 DAG.getConstant(lsb, DL, MVT::i32));
9100 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9101 DAG.getConstant(Mask2, DL, MVT::i32));
9102 // Do not add new nodes to DAG combiner worklist.
9103 DCI.CombineTo(N, Res, false);
9108 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9109 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9110 ARM::isBitFieldInvertedMask(~Mask)) {
9111 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9112 // where lsb(mask) == #shamt and masked bits of B are known zero.
9113 SDValue ShAmt = N00.getOperand(1);
9114 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9115 unsigned LSB = countTrailingZeros(Mask);
9119 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9120 DAG.getConstant(~Mask, DL, MVT::i32));
9122 // Do not add new nodes to DAG combiner worklist.
9123 DCI.CombineTo(N, Res, false);
9129 static SDValue PerformXORCombine(SDNode *N,
9130 TargetLowering::DAGCombinerInfo &DCI,
9131 const ARMSubtarget *Subtarget) {
9132 EVT VT = N->getValueType(0);
9133 SelectionDAG &DAG = DCI.DAG;
9135 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9138 if (!Subtarget->isThumb1Only()) {
9139 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9140 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9141 if (Result.getNode())
9148 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9149 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9150 // their position in "to" (Rd).
9151 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9152 assert(N->getOpcode() == ARMISD::BFI);
9154 SDValue From = N->getOperand(1);
9155 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9156 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9158 // If the Base came from a SHR #C, we can deduce that it is really testing bit
9159 // #C in the base of the SHR.
9160 if (From->getOpcode() == ISD::SRL &&
9161 isa<ConstantSDNode>(From->getOperand(1))) {
9162 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9163 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9164 FromMask <<= Shift.getLimitedValue(31);
9165 From = From->getOperand(0);
9171 // If A and B contain one contiguous set of bits, does A | B == A . B?
9173 // Neither A nor B must be zero.
9174 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9175 unsigned LastActiveBitInA = A.countTrailingZeros();
9176 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9177 return LastActiveBitInA - 1 == FirstActiveBitInB;
9180 static SDValue FindBFIToCombineWith(SDNode *N) {
9181 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9183 APInt ToMask, FromMask;
9184 SDValue From = ParseBFI(N, ToMask, FromMask);
9185 SDValue To = N->getOperand(0);
9187 // Now check for a compatible BFI to merge with. We can pass through BFIs that
9188 // aren't compatible, but not if they set the same bit in their destination as
9189 // we do (or that of any BFI we're going to combine with).
9191 APInt CombinedToMask = ToMask;
9192 while (V.getOpcode() == ARMISD::BFI) {
9193 APInt NewToMask, NewFromMask;
9194 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9195 if (NewFrom != From) {
9196 // This BFI has a different base. Keep going.
9197 CombinedToMask |= NewToMask;
9198 V = V.getOperand(0);
9202 // Do the written bits conflict with any we've seen so far?
9203 if ((NewToMask & CombinedToMask).getBoolValue())
9204 // Conflicting bits - bail out because going further is unsafe.
9207 // Are the new bits contiguous when combined with the old bits?
9208 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9209 BitsProperlyConcatenate(FromMask, NewFromMask))
9211 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9212 BitsProperlyConcatenate(NewFromMask, FromMask))
9215 // We've seen a write to some bits, so track it.
9216 CombinedToMask |= NewToMask;
9218 V = V.getOperand(0);
9224 static SDValue PerformBFICombine(SDNode *N,
9225 TargetLowering::DAGCombinerInfo &DCI) {
9226 SDValue N1 = N->getOperand(1);
9227 if (N1.getOpcode() == ISD::AND) {
9228 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9229 // the bits being cleared by the AND are not demanded by the BFI.
9230 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9233 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9234 unsigned LSB = countTrailingZeros(~InvMask);
9235 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9237 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9238 "undefined behavior");
9239 unsigned Mask = (1u << Width) - 1;
9240 unsigned Mask2 = N11C->getZExtValue();
9241 if ((Mask & (~Mask2)) == 0)
9242 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9243 N->getOperand(0), N1.getOperand(0),
9245 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9246 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9247 // Keep track of any consecutive bits set that all come from the same base
9248 // value. We can combine these together into a single BFI.
9249 SDValue CombineBFI = FindBFIToCombineWith(N);
9250 if (CombineBFI == SDValue())
9253 // We've found a BFI.
9254 APInt ToMask1, FromMask1;
9255 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9257 APInt ToMask2, FromMask2;
9258 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9259 assert(From1 == From2);
9262 // First, unlink CombineBFI.
9263 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9264 // Then create a new BFI, combining the two together.
9265 APInt NewFromMask = FromMask1 | FromMask2;
9266 APInt NewToMask = ToMask1 | ToMask2;
9268 EVT VT = N->getValueType(0);
9271 if (NewFromMask[0] == 0)
9272 From1 = DCI.DAG.getNode(
9273 ISD::SRL, dl, VT, From1,
9274 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9275 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9276 DCI.DAG.getConstant(~NewToMask, dl, VT));
9281 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9282 /// ARMISD::VMOVRRD.
9283 static SDValue PerformVMOVRRDCombine(SDNode *N,
9284 TargetLowering::DAGCombinerInfo &DCI,
9285 const ARMSubtarget *Subtarget) {
9286 // vmovrrd(vmovdrr x, y) -> x,y
9287 SDValue InDouble = N->getOperand(0);
9288 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9289 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9291 // vmovrrd(load f64) -> (load i32), (load i32)
9292 SDNode *InNode = InDouble.getNode();
9293 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9294 InNode->getValueType(0) == MVT::f64 &&
9295 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9296 !cast<LoadSDNode>(InNode)->isVolatile()) {
9297 // TODO: Should this be done for non-FrameIndex operands?
9298 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9300 SelectionDAG &DAG = DCI.DAG;
9302 SDValue BasePtr = LD->getBasePtr();
9303 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9304 LD->getPointerInfo(), LD->isVolatile(),
9305 LD->isNonTemporal(), LD->isInvariant(),
9306 LD->getAlignment());
9308 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9309 DAG.getConstant(4, DL, MVT::i32));
9310 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9311 LD->getPointerInfo(), LD->isVolatile(),
9312 LD->isNonTemporal(), LD->isInvariant(),
9313 std::min(4U, LD->getAlignment() / 2));
9315 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9316 if (DCI.DAG.getDataLayout().isBigEndian())
9317 std::swap (NewLD1, NewLD2);
9318 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9325 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9326 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9327 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9328 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9329 SDValue Op0 = N->getOperand(0);
9330 SDValue Op1 = N->getOperand(1);
9331 if (Op0.getOpcode() == ISD::BITCAST)
9332 Op0 = Op0.getOperand(0);
9333 if (Op1.getOpcode() == ISD::BITCAST)
9334 Op1 = Op1.getOperand(0);
9335 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9336 Op0.getNode() == Op1.getNode() &&
9337 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9338 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9339 N->getValueType(0), Op0.getOperand(0));
9343 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9344 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9345 /// i64 vector to have f64 elements, since the value can then be loaded
9346 /// directly into a VFP register.
9347 static bool hasNormalLoadOperand(SDNode *N) {
9348 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9349 for (unsigned i = 0; i < NumElts; ++i) {
9350 SDNode *Elt = N->getOperand(i).getNode();
9351 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9357 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9358 /// ISD::BUILD_VECTOR.
9359 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9360 TargetLowering::DAGCombinerInfo &DCI,
9361 const ARMSubtarget *Subtarget) {
9362 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9363 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9364 // into a pair of GPRs, which is fine when the value is used as a scalar,
9365 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9366 SelectionDAG &DAG = DCI.DAG;
9367 if (N->getNumOperands() == 2) {
9368 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9373 // Load i64 elements as f64 values so that type legalization does not split
9374 // them up into i32 values.
9375 EVT VT = N->getValueType(0);
9376 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9379 SmallVector<SDValue, 8> Ops;
9380 unsigned NumElts = VT.getVectorNumElements();
9381 for (unsigned i = 0; i < NumElts; ++i) {
9382 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9384 // Make the DAGCombiner fold the bitcast.
9385 DCI.AddToWorklist(V.getNode());
9387 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9388 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9389 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9392 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9394 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9395 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9396 // At that time, we may have inserted bitcasts from integer to float.
9397 // If these bitcasts have survived DAGCombine, change the lowering of this
9398 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9399 // force to use floating point types.
9401 // Make sure we can change the type of the vector.
9402 // This is possible iff:
9403 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9404 // 1.1. Vector is used only once.
9405 // 1.2. Use is a bit convert to an integer type.
9406 // 2. The size of its operands are 32-bits (64-bits are not legal).
9407 EVT VT = N->getValueType(0);
9408 EVT EltVT = VT.getVectorElementType();
9410 // Check 1.1. and 2.
9411 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9414 // By construction, the input type must be float.
9415 assert(EltVT == MVT::f32 && "Unexpected type!");
9418 SDNode *Use = *N->use_begin();
9419 if (Use->getOpcode() != ISD::BITCAST ||
9420 Use->getValueType(0).isFloatingPoint())
9423 // Check profitability.
9424 // Model is, if more than half of the relevant operands are bitcast from
9425 // i32, turn the build_vector into a sequence of insert_vector_elt.
9426 // Relevant operands are everything that is not statically
9427 // (i.e., at compile time) bitcasted.
9428 unsigned NumOfBitCastedElts = 0;
9429 unsigned NumElts = VT.getVectorNumElements();
9430 unsigned NumOfRelevantElts = NumElts;
9431 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9432 SDValue Elt = N->getOperand(Idx);
9433 if (Elt->getOpcode() == ISD::BITCAST) {
9434 // Assume only bit cast to i32 will go away.
9435 if (Elt->getOperand(0).getValueType() == MVT::i32)
9436 ++NumOfBitCastedElts;
9437 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9438 // Constants are statically casted, thus do not count them as
9439 // relevant operands.
9440 --NumOfRelevantElts;
9443 // Check if more than half of the elements require a non-free bitcast.
9444 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9447 SelectionDAG &DAG = DCI.DAG;
9448 // Create the new vector type.
9449 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9450 // Check if the type is legal.
9451 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9452 if (!TLI.isTypeLegal(VecVT))
9456 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9457 // => BITCAST INSERT_VECTOR_ELT
9458 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9460 SDValue Vec = DAG.getUNDEF(VecVT);
9462 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9463 SDValue V = N->getOperand(Idx);
9464 if (V.getOpcode() == ISD::UNDEF)
9466 if (V.getOpcode() == ISD::BITCAST &&
9467 V->getOperand(0).getValueType() == MVT::i32)
9468 // Fold obvious case.
9469 V = V.getOperand(0);
9471 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9472 // Make the DAGCombiner fold the bitcasts.
9473 DCI.AddToWorklist(V.getNode());
9475 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9476 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9478 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9479 // Make the DAGCombiner fold the bitcasts.
9480 DCI.AddToWorklist(Vec.getNode());
9484 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9485 /// ISD::INSERT_VECTOR_ELT.
9486 static SDValue PerformInsertEltCombine(SDNode *N,
9487 TargetLowering::DAGCombinerInfo &DCI) {
9488 // Bitcast an i64 load inserted into a vector to f64.
9489 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9490 EVT VT = N->getValueType(0);
9491 SDNode *Elt = N->getOperand(1).getNode();
9492 if (VT.getVectorElementType() != MVT::i64 ||
9493 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9496 SelectionDAG &DAG = DCI.DAG;
9498 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9499 VT.getVectorNumElements());
9500 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9501 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9502 // Make the DAGCombiner fold the bitcasts.
9503 DCI.AddToWorklist(Vec.getNode());
9504 DCI.AddToWorklist(V.getNode());
9505 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9506 Vec, V, N->getOperand(2));
9507 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9510 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9511 /// ISD::VECTOR_SHUFFLE.
9512 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9513 // The LLVM shufflevector instruction does not require the shuffle mask
9514 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9515 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9516 // operands do not match the mask length, they are extended by concatenating
9517 // them with undef vectors. That is probably the right thing for other
9518 // targets, but for NEON it is better to concatenate two double-register
9519 // size vector operands into a single quad-register size vector. Do that
9520 // transformation here:
9521 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9522 // shuffle(concat(v1, v2), undef)
9523 SDValue Op0 = N->getOperand(0);
9524 SDValue Op1 = N->getOperand(1);
9525 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9526 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9527 Op0.getNumOperands() != 2 ||
9528 Op1.getNumOperands() != 2)
9530 SDValue Concat0Op1 = Op0.getOperand(1);
9531 SDValue Concat1Op1 = Op1.getOperand(1);
9532 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9533 Concat1Op1.getOpcode() != ISD::UNDEF)
9535 // Skip the transformation if any of the types are illegal.
9536 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9537 EVT VT = N->getValueType(0);
9538 if (!TLI.isTypeLegal(VT) ||
9539 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9540 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9543 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9544 Op0.getOperand(0), Op1.getOperand(0));
9545 // Translate the shuffle mask.
9546 SmallVector<int, 16> NewMask;
9547 unsigned NumElts = VT.getVectorNumElements();
9548 unsigned HalfElts = NumElts/2;
9549 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9550 for (unsigned n = 0; n < NumElts; ++n) {
9551 int MaskElt = SVN->getMaskElt(n);
9553 if (MaskElt < (int)HalfElts)
9555 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9556 NewElt = HalfElts + MaskElt - NumElts;
9557 NewMask.push_back(NewElt);
9559 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9560 DAG.getUNDEF(VT), NewMask.data());
9563 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9564 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9565 /// base address updates.
9566 /// For generic load/stores, the memory type is assumed to be a vector.
9567 /// The caller is assumed to have checked legality.
9568 static SDValue CombineBaseUpdate(SDNode *N,
9569 TargetLowering::DAGCombinerInfo &DCI) {
9570 SelectionDAG &DAG = DCI.DAG;
9571 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9572 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9573 const bool isStore = N->getOpcode() == ISD::STORE;
9574 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9575 SDValue Addr = N->getOperand(AddrOpIdx);
9576 MemSDNode *MemN = cast<MemSDNode>(N);
9579 // Search for a use of the address operand that is an increment.
9580 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9581 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9583 if (User->getOpcode() != ISD::ADD ||
9584 UI.getUse().getResNo() != Addr.getResNo())
9587 // Check that the add is independent of the load/store. Otherwise, folding
9588 // it would create a cycle.
9589 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9592 // Find the new opcode for the updating load/store.
9593 bool isLoadOp = true;
9594 bool isLaneOp = false;
9595 unsigned NewOpc = 0;
9596 unsigned NumVecs = 0;
9598 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9600 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9601 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9603 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9605 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9607 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9609 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9610 NumVecs = 2; isLaneOp = true; break;
9611 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9612 NumVecs = 3; isLaneOp = true; break;
9613 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9614 NumVecs = 4; isLaneOp = true; break;
9615 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9616 NumVecs = 1; isLoadOp = false; break;
9617 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9618 NumVecs = 2; isLoadOp = false; break;
9619 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9620 NumVecs = 3; isLoadOp = false; break;
9621 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9622 NumVecs = 4; isLoadOp = false; break;
9623 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9624 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9625 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9626 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9627 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9628 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9632 switch (N->getOpcode()) {
9633 default: llvm_unreachable("unexpected opcode for Neon base update");
9634 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9635 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9636 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9637 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9638 NumVecs = 1; isLaneOp = false; break;
9639 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9640 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9644 // Find the size of memory referenced by the load/store.
9647 VecTy = N->getValueType(0);
9648 } else if (isIntrinsic) {
9649 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9651 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9652 VecTy = N->getOperand(1).getValueType();
9655 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9657 NumBytes /= VecTy.getVectorNumElements();
9659 // If the increment is a constant, it must match the memory ref size.
9660 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9661 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9662 uint64_t IncVal = CInc->getZExtValue();
9663 if (IncVal != NumBytes)
9665 } else if (NumBytes >= 3 * 16) {
9666 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9667 // separate instructions that make it harder to use a non-constant update.
9671 // OK, we found an ADD we can fold into the base update.
9672 // Now, create a _UPD node, taking care of not breaking alignment.
9674 EVT AlignedVecTy = VecTy;
9675 unsigned Alignment = MemN->getAlignment();
9677 // If this is a less-than-standard-aligned load/store, change the type to
9678 // match the standard alignment.
9679 // The alignment is overlooked when selecting _UPD variants; and it's
9680 // easier to introduce bitcasts here than fix that.
9681 // There are 3 ways to get to this base-update combine:
9682 // - intrinsics: they are assumed to be properly aligned (to the standard
9683 // alignment of the memory type), so we don't need to do anything.
9684 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9685 // intrinsics, so, likewise, there's nothing to do.
9686 // - generic load/store instructions: the alignment is specified as an
9687 // explicit operand, rather than implicitly as the standard alignment
9688 // of the memory type (like the intrisics). We need to change the
9689 // memory type to match the explicit alignment. That way, we don't
9690 // generate non-standard-aligned ARMISD::VLDx nodes.
9691 if (isa<LSBaseSDNode>(N)) {
9694 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9695 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9696 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9697 assert(!isLaneOp && "Unexpected generic load/store lane.");
9698 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9699 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9701 // Don't set an explicit alignment on regular load/stores that we want
9702 // to transform to VLD/VST 1_UPD nodes.
9703 // This matches the behavior of regular load/stores, which only get an
9704 // explicit alignment if the MMO alignment is larger than the standard
9705 // alignment of the memory type.
9706 // Intrinsics, however, always get an explicit alignment, set to the
9707 // alignment of the MMO.
9711 // Create the new updating load/store node.
9712 // First, create an SDVTList for the new updating node's results.
9714 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9716 for (n = 0; n < NumResultVecs; ++n)
9717 Tys[n] = AlignedVecTy;
9718 Tys[n++] = MVT::i32;
9719 Tys[n] = MVT::Other;
9720 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9722 // Then, gather the new node's operands.
9723 SmallVector<SDValue, 8> Ops;
9724 Ops.push_back(N->getOperand(0)); // incoming chain
9725 Ops.push_back(N->getOperand(AddrOpIdx));
9728 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9729 // Try to match the intrinsic's signature
9730 Ops.push_back(StN->getValue());
9732 // Loads (and of course intrinsics) match the intrinsics' signature,
9733 // so just add all but the alignment operand.
9734 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9735 Ops.push_back(N->getOperand(i));
9738 // For all node types, the alignment operand is always the last one.
9739 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9741 // If this is a non-standard-aligned STORE, the penultimate operand is the
9742 // stored value. Bitcast it to the aligned type.
9743 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9744 SDValue &StVal = Ops[Ops.size()-2];
9745 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9748 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9750 MemN->getMemOperand());
9753 SmallVector<SDValue, 5> NewResults;
9754 for (unsigned i = 0; i < NumResultVecs; ++i)
9755 NewResults.push_back(SDValue(UpdN.getNode(), i));
9757 // If this is an non-standard-aligned LOAD, the first result is the loaded
9758 // value. Bitcast it to the expected result type.
9759 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9760 SDValue &LdVal = NewResults[0];
9761 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9764 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9765 DCI.CombineTo(N, NewResults);
9766 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9773 static SDValue PerformVLDCombine(SDNode *N,
9774 TargetLowering::DAGCombinerInfo &DCI) {
9775 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9778 return CombineBaseUpdate(N, DCI);
9781 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9782 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9783 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9785 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9786 SelectionDAG &DAG = DCI.DAG;
9787 EVT VT = N->getValueType(0);
9788 // vldN-dup instructions only support 64-bit vectors for N > 1.
9789 if (!VT.is64BitVector())
9792 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9793 SDNode *VLD = N->getOperand(0).getNode();
9794 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9796 unsigned NumVecs = 0;
9797 unsigned NewOpc = 0;
9798 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9799 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9801 NewOpc = ARMISD::VLD2DUP;
9802 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9804 NewOpc = ARMISD::VLD3DUP;
9805 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9807 NewOpc = ARMISD::VLD4DUP;
9812 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9813 // numbers match the load.
9814 unsigned VLDLaneNo =
9815 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9816 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9818 // Ignore uses of the chain result.
9819 if (UI.getUse().getResNo() == NumVecs)
9822 if (User->getOpcode() != ARMISD::VDUPLANE ||
9823 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9827 // Create the vldN-dup node.
9830 for (n = 0; n < NumVecs; ++n)
9832 Tys[n] = MVT::Other;
9833 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9834 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9835 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9836 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9837 Ops, VLDMemInt->getMemoryVT(),
9838 VLDMemInt->getMemOperand());
9841 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9843 unsigned ResNo = UI.getUse().getResNo();
9844 // Ignore uses of the chain result.
9845 if (ResNo == NumVecs)
9848 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9851 // Now the vldN-lane intrinsic is dead except for its chain result.
9852 // Update uses of the chain.
9853 std::vector<SDValue> VLDDupResults;
9854 for (unsigned n = 0; n < NumVecs; ++n)
9855 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9856 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9857 DCI.CombineTo(VLD, VLDDupResults);
9862 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9863 /// ARMISD::VDUPLANE.
9864 static SDValue PerformVDUPLANECombine(SDNode *N,
9865 TargetLowering::DAGCombinerInfo &DCI) {
9866 SDValue Op = N->getOperand(0);
9868 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9869 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9870 if (CombineVLDDUP(N, DCI))
9871 return SDValue(N, 0);
9873 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9874 // redundant. Ignore bit_converts for now; element sizes are checked below.
9875 while (Op.getOpcode() == ISD::BITCAST)
9876 Op = Op.getOperand(0);
9877 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9880 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9881 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9882 // The canonical VMOV for a zero vector uses a 32-bit element size.
9883 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9885 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9887 EVT VT = N->getValueType(0);
9888 if (EltSize > VT.getVectorElementType().getSizeInBits())
9891 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9894 static SDValue PerformLOADCombine(SDNode *N,
9895 TargetLowering::DAGCombinerInfo &DCI) {
9896 EVT VT = N->getValueType(0);
9898 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9899 if (ISD::isNormalLoad(N) && VT.isVector() &&
9900 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9901 return CombineBaseUpdate(N, DCI);
9906 /// PerformSTORECombine - Target-specific dag combine xforms for
9908 static SDValue PerformSTORECombine(SDNode *N,
9909 TargetLowering::DAGCombinerInfo &DCI) {
9910 StoreSDNode *St = cast<StoreSDNode>(N);
9911 if (St->isVolatile())
9914 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9915 // pack all of the elements in one place. Next, store to memory in fewer
9917 SDValue StVal = St->getValue();
9918 EVT VT = StVal.getValueType();
9919 if (St->isTruncatingStore() && VT.isVector()) {
9920 SelectionDAG &DAG = DCI.DAG;
9921 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9922 EVT StVT = St->getMemoryVT();
9923 unsigned NumElems = VT.getVectorNumElements();
9924 assert(StVT != VT && "Cannot truncate to the same type");
9925 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9926 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9928 // From, To sizes and ElemCount must be pow of two
9929 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9931 // We are going to use the original vector elt for storing.
9932 // Accumulated smaller vector elements must be a multiple of the store size.
9933 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9935 unsigned SizeRatio = FromEltSz / ToEltSz;
9936 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9938 // Create a type on which we perform the shuffle.
9939 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9940 NumElems*SizeRatio);
9941 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9944 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9945 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9946 for (unsigned i = 0; i < NumElems; ++i)
9947 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9948 ? (i + 1) * SizeRatio - 1
9951 // Can't shuffle using an illegal type.
9952 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9954 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9955 DAG.getUNDEF(WideVec.getValueType()),
9957 // At this point all of the data is stored at the bottom of the
9958 // register. We now need to save it to mem.
9960 // Find the largest store unit
9961 MVT StoreType = MVT::i8;
9962 for (MVT Tp : MVT::integer_valuetypes()) {
9963 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9966 // Didn't find a legal store type.
9967 if (!TLI.isTypeLegal(StoreType))
9970 // Bitcast the original vector into a vector of store-size units
9971 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9972 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9973 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9974 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9975 SmallVector<SDValue, 8> Chains;
9976 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9977 TLI.getPointerTy(DAG.getDataLayout()));
9978 SDValue BasePtr = St->getBasePtr();
9980 // Perform one or more big stores into memory.
9981 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9982 for (unsigned I = 0; I < E; I++) {
9983 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9984 StoreType, ShuffWide,
9985 DAG.getIntPtrConstant(I, DL));
9986 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9987 St->getPointerInfo(), St->isVolatile(),
9988 St->isNonTemporal(), St->getAlignment());
9989 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9991 Chains.push_back(Ch);
9993 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9996 if (!ISD::isNormalStore(St))
9999 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10000 // ARM stores of arguments in the same cache line.
10001 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10002 StVal.getNode()->hasOneUse()) {
10003 SelectionDAG &DAG = DCI.DAG;
10004 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10006 SDValue BasePtr = St->getBasePtr();
10007 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
10008 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
10009 BasePtr, St->getPointerInfo(), St->isVolatile(),
10010 St->isNonTemporal(), St->getAlignment());
10012 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10013 DAG.getConstant(4, DL, MVT::i32));
10014 return DAG.getStore(NewST1.getValue(0), DL,
10015 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10016 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
10017 St->isNonTemporal(),
10018 std::min(4U, St->getAlignment() / 2));
10021 if (StVal.getValueType() == MVT::i64 &&
10022 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10024 // Bitcast an i64 store extracted from a vector to f64.
10025 // Otherwise, the i64 value will be legalized to a pair of i32 values.
10026 SelectionDAG &DAG = DCI.DAG;
10028 SDValue IntVec = StVal.getOperand(0);
10029 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10030 IntVec.getValueType().getVectorNumElements());
10031 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10032 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10033 Vec, StVal.getOperand(1));
10035 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10036 // Make the DAGCombiner fold the bitcasts.
10037 DCI.AddToWorklist(Vec.getNode());
10038 DCI.AddToWorklist(ExtElt.getNode());
10039 DCI.AddToWorklist(V.getNode());
10040 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10041 St->getPointerInfo(), St->isVolatile(),
10042 St->isNonTemporal(), St->getAlignment(),
10046 // If this is a legal vector store, try to combine it into a VST1_UPD.
10047 if (ISD::isNormalStore(N) && VT.isVector() &&
10048 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10049 return CombineBaseUpdate(N, DCI);
10054 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10055 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10056 /// when the VMUL has a constant operand that is a power of 2.
10058 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10059 /// vmul.f32 d16, d17, d16
10060 /// vcvt.s32.f32 d16, d16
10062 /// vcvt.s32.f32 d16, d16, #3
10063 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10064 const ARMSubtarget *Subtarget) {
10065 if (!Subtarget->hasNEON())
10068 SDValue Op = N->getOperand(0);
10069 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
10072 SDValue ConstVec = Op->getOperand(1);
10073 if (!isa<BuildVectorSDNode>(ConstVec))
10076 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10077 uint32_t FloatBits = FloatTy.getSizeInBits();
10078 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10079 uint32_t IntBits = IntTy.getSizeInBits();
10080 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10081 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10082 // These instructions only exist converting from f32 to i32. We can handle
10083 // smaller integers by generating an extra truncate, but larger ones would
10084 // be lossy. We also can't handle more then 4 lanes, since these intructions
10085 // only support v2i32/v4i32 types.
10089 BitVector UndefElements;
10090 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10091 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10092 if (C == -1 || C == 0 || C > 32)
10096 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10097 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10098 Intrinsic::arm_neon_vcvtfp2fxu;
10099 SDValue FixConv = DAG.getNode(
10100 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10101 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10102 DAG.getConstant(C, dl, MVT::i32));
10104 if (IntBits < FloatBits)
10105 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10110 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10111 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10112 /// when the VDIV has a constant operand that is a power of 2.
10114 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10115 /// vcvt.f32.s32 d16, d16
10116 /// vdiv.f32 d16, d17, d16
10118 /// vcvt.f32.s32 d16, d16, #3
10119 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10120 const ARMSubtarget *Subtarget) {
10121 if (!Subtarget->hasNEON())
10124 SDValue Op = N->getOperand(0);
10125 unsigned OpOpcode = Op.getNode()->getOpcode();
10126 if (!N->getValueType(0).isVector() ||
10127 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10130 SDValue ConstVec = N->getOperand(1);
10131 if (!isa<BuildVectorSDNode>(ConstVec))
10134 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10135 uint32_t FloatBits = FloatTy.getSizeInBits();
10136 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10137 uint32_t IntBits = IntTy.getSizeInBits();
10138 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10139 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10140 // These instructions only exist converting from i32 to f32. We can handle
10141 // smaller integers by generating an extra extend, but larger ones would
10142 // be lossy. We also can't handle more then 4 lanes, since these intructions
10143 // only support v2i32/v4i32 types.
10147 BitVector UndefElements;
10148 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10149 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10150 if (C == -1 || C == 0 || C > 32)
10154 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10155 SDValue ConvInput = Op.getOperand(0);
10156 if (IntBits < FloatBits)
10157 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10158 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10161 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10162 Intrinsic::arm_neon_vcvtfxu2fp;
10163 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10165 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10166 ConvInput, DAG.getConstant(C, dl, MVT::i32));
10169 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10170 /// operand of a vector shift operation, where all the elements of the
10171 /// build_vector must have the same constant integer value.
10172 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10173 // Ignore bit_converts.
10174 while (Op.getOpcode() == ISD::BITCAST)
10175 Op = Op.getOperand(0);
10176 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10177 APInt SplatBits, SplatUndef;
10178 unsigned SplatBitSize;
10180 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10181 HasAnyUndefs, ElementBits) ||
10182 SplatBitSize > ElementBits)
10184 Cnt = SplatBits.getSExtValue();
10188 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10189 /// operand of a vector shift left operation. That value must be in the range:
10190 /// 0 <= Value < ElementBits for a left shift; or
10191 /// 0 <= Value <= ElementBits for a long left shift.
10192 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10193 assert(VT.isVector() && "vector shift count is not a vector type");
10194 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10195 if (! getVShiftImm(Op, ElementBits, Cnt))
10197 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10200 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10201 /// operand of a vector shift right operation. For a shift opcode, the value
10202 /// is positive, but for an intrinsic the value count must be negative. The
10203 /// absolute value must be in the range:
10204 /// 1 <= |Value| <= ElementBits for a right shift; or
10205 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
10206 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10208 assert(VT.isVector() && "vector shift count is not a vector type");
10209 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10210 if (! getVShiftImm(Op, ElementBits, Cnt))
10213 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10214 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10221 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10222 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10223 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10226 // Don't do anything for most intrinsics.
10229 // Vector shifts: check for immediate versions and lower them.
10230 // Note: This is done during DAG combining instead of DAG legalizing because
10231 // the build_vectors for 64-bit vector element shift counts are generally
10232 // not legal, and it is hard to see their values after they get legalized to
10233 // loads from a constant pool.
10234 case Intrinsic::arm_neon_vshifts:
10235 case Intrinsic::arm_neon_vshiftu:
10236 case Intrinsic::arm_neon_vrshifts:
10237 case Intrinsic::arm_neon_vrshiftu:
10238 case Intrinsic::arm_neon_vrshiftn:
10239 case Intrinsic::arm_neon_vqshifts:
10240 case Intrinsic::arm_neon_vqshiftu:
10241 case Intrinsic::arm_neon_vqshiftsu:
10242 case Intrinsic::arm_neon_vqshiftns:
10243 case Intrinsic::arm_neon_vqshiftnu:
10244 case Intrinsic::arm_neon_vqshiftnsu:
10245 case Intrinsic::arm_neon_vqrshiftns:
10246 case Intrinsic::arm_neon_vqrshiftnu:
10247 case Intrinsic::arm_neon_vqrshiftnsu: {
10248 EVT VT = N->getOperand(1).getValueType();
10250 unsigned VShiftOpc = 0;
10253 case Intrinsic::arm_neon_vshifts:
10254 case Intrinsic::arm_neon_vshiftu:
10255 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10256 VShiftOpc = ARMISD::VSHL;
10259 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10260 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10261 ARMISD::VSHRs : ARMISD::VSHRu);
10266 case Intrinsic::arm_neon_vrshifts:
10267 case Intrinsic::arm_neon_vrshiftu:
10268 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10272 case Intrinsic::arm_neon_vqshifts:
10273 case Intrinsic::arm_neon_vqshiftu:
10274 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10278 case Intrinsic::arm_neon_vqshiftsu:
10279 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10281 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10283 case Intrinsic::arm_neon_vrshiftn:
10284 case Intrinsic::arm_neon_vqshiftns:
10285 case Intrinsic::arm_neon_vqshiftnu:
10286 case Intrinsic::arm_neon_vqshiftnsu:
10287 case Intrinsic::arm_neon_vqrshiftns:
10288 case Intrinsic::arm_neon_vqrshiftnu:
10289 case Intrinsic::arm_neon_vqrshiftnsu:
10290 // Narrowing shifts require an immediate right shift.
10291 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10293 llvm_unreachable("invalid shift count for narrowing vector shift "
10297 llvm_unreachable("unhandled vector shift");
10301 case Intrinsic::arm_neon_vshifts:
10302 case Intrinsic::arm_neon_vshiftu:
10303 // Opcode already set above.
10305 case Intrinsic::arm_neon_vrshifts:
10306 VShiftOpc = ARMISD::VRSHRs; break;
10307 case Intrinsic::arm_neon_vrshiftu:
10308 VShiftOpc = ARMISD::VRSHRu; break;
10309 case Intrinsic::arm_neon_vrshiftn:
10310 VShiftOpc = ARMISD::VRSHRN; break;
10311 case Intrinsic::arm_neon_vqshifts:
10312 VShiftOpc = ARMISD::VQSHLs; break;
10313 case Intrinsic::arm_neon_vqshiftu:
10314 VShiftOpc = ARMISD::VQSHLu; break;
10315 case Intrinsic::arm_neon_vqshiftsu:
10316 VShiftOpc = ARMISD::VQSHLsu; break;
10317 case Intrinsic::arm_neon_vqshiftns:
10318 VShiftOpc = ARMISD::VQSHRNs; break;
10319 case Intrinsic::arm_neon_vqshiftnu:
10320 VShiftOpc = ARMISD::VQSHRNu; break;
10321 case Intrinsic::arm_neon_vqshiftnsu:
10322 VShiftOpc = ARMISD::VQSHRNsu; break;
10323 case Intrinsic::arm_neon_vqrshiftns:
10324 VShiftOpc = ARMISD::VQRSHRNs; break;
10325 case Intrinsic::arm_neon_vqrshiftnu:
10326 VShiftOpc = ARMISD::VQRSHRNu; break;
10327 case Intrinsic::arm_neon_vqrshiftnsu:
10328 VShiftOpc = ARMISD::VQRSHRNsu; break;
10332 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10333 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10336 case Intrinsic::arm_neon_vshiftins: {
10337 EVT VT = N->getOperand(1).getValueType();
10339 unsigned VShiftOpc = 0;
10341 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10342 VShiftOpc = ARMISD::VSLI;
10343 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10344 VShiftOpc = ARMISD::VSRI;
10346 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10350 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10351 N->getOperand(1), N->getOperand(2),
10352 DAG.getConstant(Cnt, dl, MVT::i32));
10355 case Intrinsic::arm_neon_vqrshifts:
10356 case Intrinsic::arm_neon_vqrshiftu:
10357 // No immediate versions of these to check for.
10364 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10365 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10366 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10367 /// vector element shift counts are generally not legal, and it is hard to see
10368 /// their values after they get legalized to loads from a constant pool.
10369 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10370 const ARMSubtarget *ST) {
10371 EVT VT = N->getValueType(0);
10372 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10373 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10374 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10375 SDValue N1 = N->getOperand(1);
10376 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10377 SDValue N0 = N->getOperand(0);
10378 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10379 DAG.MaskedValueIsZero(N0.getOperand(0),
10380 APInt::getHighBitsSet(32, 16)))
10381 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10385 // Nothing to be done for scalar shifts.
10386 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10387 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10390 assert(ST->hasNEON() && "unexpected vector shift");
10393 switch (N->getOpcode()) {
10394 default: llvm_unreachable("unexpected shift opcode");
10397 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10399 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10400 DAG.getConstant(Cnt, dl, MVT::i32));
10406 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10407 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10408 ARMISD::VSHRs : ARMISD::VSHRu);
10410 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10411 DAG.getConstant(Cnt, dl, MVT::i32));
10417 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10418 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10419 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10420 const ARMSubtarget *ST) {
10421 SDValue N0 = N->getOperand(0);
10423 // Check for sign- and zero-extensions of vector extract operations of 8-
10424 // and 16-bit vector elements. NEON supports these directly. They are
10425 // handled during DAG combining because type legalization will promote them
10426 // to 32-bit types and it is messy to recognize the operations after that.
10427 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10428 SDValue Vec = N0.getOperand(0);
10429 SDValue Lane = N0.getOperand(1);
10430 EVT VT = N->getValueType(0);
10431 EVT EltVT = N0.getValueType();
10432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10434 if (VT == MVT::i32 &&
10435 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10436 TLI.isTypeLegal(Vec.getValueType()) &&
10437 isa<ConstantSDNode>(Lane)) {
10440 switch (N->getOpcode()) {
10441 default: llvm_unreachable("unexpected opcode");
10442 case ISD::SIGN_EXTEND:
10443 Opc = ARMISD::VGETLANEs;
10445 case ISD::ZERO_EXTEND:
10446 case ISD::ANY_EXTEND:
10447 Opc = ARMISD::VGETLANEu;
10450 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10457 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10459 if (Op.getOpcode() == ARMISD::BFI) {
10460 // Conservatively, we can recurse down the first operand
10461 // and just mask out all affected bits.
10462 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10464 // The operand to BFI is already a mask suitable for removing the bits it
10466 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10467 APInt Mask = CI->getAPIntValue();
10472 if (Op.getOpcode() == ARMISD::CMOV) {
10473 APInt KZ2(KnownZero.getBitWidth(), 0);
10474 APInt KO2(KnownOne.getBitWidth(), 0);
10475 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10476 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10482 return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10485 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10486 // If we have a CMOV, OR and AND combination such as:
10491 // * CN is a single bit;
10492 // * All bits covered by CM are known zero in y
10494 // Then we can convert this into a sequence of BFI instructions. This will
10495 // always be a win if CM is a single bit, will always be no worse than the
10496 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10497 // three bits (due to the extra IT instruction).
10499 SDValue Op0 = CMOV->getOperand(0);
10500 SDValue Op1 = CMOV->getOperand(1);
10501 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10502 auto CC = CCNode->getAPIntValue().getLimitedValue();
10503 SDValue CmpZ = CMOV->getOperand(4);
10505 // The compare must be against zero.
10506 if (!isNullConstant(CmpZ->getOperand(1)))
10509 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10510 SDValue And = CmpZ->getOperand(0);
10511 if (And->getOpcode() != ISD::AND)
10513 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10514 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10516 SDValue X = And->getOperand(0);
10518 if (CC == ARMCC::EQ) {
10519 // We're performing an "equal to zero" compare. Swap the operands so we
10520 // canonicalize on a "not equal to zero" compare.
10521 std::swap(Op0, Op1);
10523 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10526 if (Op1->getOpcode() != ISD::OR)
10529 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10532 SDValue Y = Op1->getOperand(0);
10537 // Now, is it profitable to continue?
10538 APInt OrCI = OrC->getAPIntValue();
10539 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10540 if (OrCI.countPopulation() > Heuristic)
10543 // Lastly, can we determine that the bits defined by OrCI
10545 APInt KnownZero, KnownOne;
10546 computeKnownBits(DAG, Y, KnownZero, KnownOne);
10547 if ((OrCI & KnownZero) != OrCI)
10550 // OK, we can do the combine.
10553 EVT VT = X.getValueType();
10554 unsigned BitInX = AndC->getAPIntValue().logBase2();
10557 // We must shift X first.
10558 X = DAG.getNode(ISD::SRL, dl, VT, X,
10559 DAG.getConstant(BitInX, dl, VT));
10562 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10563 BitInY < NumActiveBits; ++BitInY) {
10564 if (OrCI[BitInY] == 0)
10566 APInt Mask(VT.getSizeInBits(), 0);
10567 Mask.setBit(BitInY);
10568 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10569 // Confusingly, the operand is an *inverted* mask.
10570 DAG.getConstant(~Mask, dl, VT));
10576 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10578 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10579 SDValue Cmp = N->getOperand(4);
10580 if (Cmp.getOpcode() != ARMISD::CMPZ)
10581 // Only looking at EQ and NE cases.
10584 EVT VT = N->getValueType(0);
10586 SDValue LHS = Cmp.getOperand(0);
10587 SDValue RHS = Cmp.getOperand(1);
10588 SDValue FalseVal = N->getOperand(0);
10589 SDValue TrueVal = N->getOperand(1);
10590 SDValue ARMcc = N->getOperand(2);
10591 ARMCC::CondCodes CC =
10592 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10594 // BFI is only available on V6T2+.
10595 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10596 SDValue R = PerformCMOVToBFICombine(N, DAG);
10617 /// FIXME: Turn this into a target neutral optimization?
10619 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10620 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10621 N->getOperand(3), Cmp);
10622 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10624 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10625 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10626 N->getOperand(3), NewCmp);
10629 if (Res.getNode()) {
10630 APInt KnownZero, KnownOne;
10631 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10632 // Capture demanded bits information that would be otherwise lost.
10633 if (KnownZero == 0xfffffffe)
10634 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10635 DAG.getValueType(MVT::i1));
10636 else if (KnownZero == 0xffffff00)
10637 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10638 DAG.getValueType(MVT::i8));
10639 else if (KnownZero == 0xffff0000)
10640 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10641 DAG.getValueType(MVT::i16));
10647 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10648 DAGCombinerInfo &DCI) const {
10649 switch (N->getOpcode()) {
10651 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10652 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10653 case ISD::SUB: return PerformSUBCombine(N, DCI);
10654 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10655 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10656 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10657 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10658 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10659 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10660 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10661 case ISD::STORE: return PerformSTORECombine(N, DCI);
10662 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10663 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10664 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10665 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10666 case ISD::FP_TO_SINT:
10667 case ISD::FP_TO_UINT:
10668 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10670 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10671 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10674 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10675 case ISD::SIGN_EXTEND:
10676 case ISD::ZERO_EXTEND:
10677 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10678 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10679 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10680 case ARMISD::VLD2DUP:
10681 case ARMISD::VLD3DUP:
10682 case ARMISD::VLD4DUP:
10683 return PerformVLDCombine(N, DCI);
10684 case ARMISD::BUILD_VECTOR:
10685 return PerformARMBUILD_VECTORCombine(N, DCI);
10686 case ISD::INTRINSIC_VOID:
10687 case ISD::INTRINSIC_W_CHAIN:
10688 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10689 case Intrinsic::arm_neon_vld1:
10690 case Intrinsic::arm_neon_vld2:
10691 case Intrinsic::arm_neon_vld3:
10692 case Intrinsic::arm_neon_vld4:
10693 case Intrinsic::arm_neon_vld2lane:
10694 case Intrinsic::arm_neon_vld3lane:
10695 case Intrinsic::arm_neon_vld4lane:
10696 case Intrinsic::arm_neon_vst1:
10697 case Intrinsic::arm_neon_vst2:
10698 case Intrinsic::arm_neon_vst3:
10699 case Intrinsic::arm_neon_vst4:
10700 case Intrinsic::arm_neon_vst2lane:
10701 case Intrinsic::arm_neon_vst3lane:
10702 case Intrinsic::arm_neon_vst4lane:
10703 return PerformVLDCombine(N, DCI);
10711 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10713 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10716 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10719 bool *Fast) const {
10720 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10721 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10723 switch (VT.getSimpleVT().SimpleTy) {
10729 // Unaligned access can use (for example) LRDB, LRDH, LDR
10730 if (AllowsUnaligned) {
10732 *Fast = Subtarget->hasV7Ops();
10739 // For any little-endian targets with neon, we can support unaligned ld/st
10740 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10741 // A big-endian target may also explicitly support unaligned accesses
10742 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10752 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10753 unsigned AlignCheck) {
10754 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10755 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10758 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10759 unsigned DstAlign, unsigned SrcAlign,
10760 bool IsMemset, bool ZeroMemset,
10762 MachineFunction &MF) const {
10763 const Function *F = MF.getFunction();
10765 // See if we can use NEON instructions for this...
10766 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10767 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10770 (memOpAlign(SrcAlign, DstAlign, 16) ||
10771 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10773 } else if (Size >= 8 &&
10774 (memOpAlign(SrcAlign, DstAlign, 8) ||
10775 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10781 // Lowering to i32/i16 if the size permits.
10784 else if (Size >= 2)
10787 // Let the target-independent logic figure it out.
10791 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10792 if (Val.getOpcode() != ISD::LOAD)
10795 EVT VT1 = Val.getValueType();
10796 if (!VT1.isSimple() || !VT1.isInteger() ||
10797 !VT2.isSimple() || !VT2.isInteger())
10800 switch (VT1.getSimpleVT().SimpleTy) {
10805 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10812 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10813 EVT VT = ExtVal.getValueType();
10815 if (!isTypeLegal(VT))
10818 // Don't create a loadext if we can fold the extension into a wide/long
10820 // If there's more than one user instruction, the loadext is desirable no
10821 // matter what. There can be two uses by the same instruction.
10822 if (ExtVal->use_empty() ||
10823 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10826 SDNode *U = *ExtVal->use_begin();
10827 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10828 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10834 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10835 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10838 if (!isTypeLegal(EVT::getEVT(Ty1)))
10841 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10843 // Assuming the caller doesn't have a zeroext or signext return parameter,
10844 // truncation all the way down to i1 is valid.
10849 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10853 unsigned Scale = 1;
10854 switch (VT.getSimpleVT().SimpleTy) {
10855 default: return false;
10870 if ((V & (Scale - 1)) != 0)
10873 return V == (V & ((1LL << 5) - 1));
10876 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10877 const ARMSubtarget *Subtarget) {
10878 bool isNeg = false;
10884 switch (VT.getSimpleVT().SimpleTy) {
10885 default: return false;
10890 // + imm12 or - imm8
10892 return V == (V & ((1LL << 8) - 1));
10893 return V == (V & ((1LL << 12) - 1));
10896 // Same as ARM mode. FIXME: NEON?
10897 if (!Subtarget->hasVFP2())
10902 return V == (V & ((1LL << 8) - 1));
10906 /// isLegalAddressImmediate - Return true if the integer value can be used
10907 /// as the offset of the target addressing mode for load / store of the
10909 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10910 const ARMSubtarget *Subtarget) {
10914 if (!VT.isSimple())
10917 if (Subtarget->isThumb1Only())
10918 return isLegalT1AddressImmediate(V, VT);
10919 else if (Subtarget->isThumb2())
10920 return isLegalT2AddressImmediate(V, VT, Subtarget);
10925 switch (VT.getSimpleVT().SimpleTy) {
10926 default: return false;
10931 return V == (V & ((1LL << 12) - 1));
10934 return V == (V & ((1LL << 8) - 1));
10937 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10942 return V == (V & ((1LL << 8) - 1));
10946 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10948 int Scale = AM.Scale;
10952 switch (VT.getSimpleVT().SimpleTy) {
10953 default: return false;
10961 Scale = Scale & ~1;
10962 return Scale == 2 || Scale == 4 || Scale == 8;
10965 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10969 // Note, we allow "void" uses (basically, uses that aren't loads or
10970 // stores), because arm allows folding a scale into many arithmetic
10971 // operations. This should be made more precise and revisited later.
10973 // Allow r << imm, but the imm has to be a multiple of two.
10974 if (Scale & 1) return false;
10975 return isPowerOf2_32(Scale);
10979 /// isLegalAddressingMode - Return true if the addressing mode represented
10980 /// by AM is legal for this target, for a load/store of the specified type.
10981 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10982 const AddrMode &AM, Type *Ty,
10983 unsigned AS) const {
10984 EVT VT = getValueType(DL, Ty, true);
10985 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10988 // Can never fold addr of global into load/store.
10992 switch (AM.Scale) {
10993 case 0: // no scale reg, must be "r+i" or "r", or "i".
10996 if (Subtarget->isThumb1Only())
11000 // ARM doesn't support any R+R*scale+imm addr modes.
11004 if (!VT.isSimple())
11007 if (Subtarget->isThumb2())
11008 return isLegalT2ScaledAddressingMode(AM, VT);
11010 int Scale = AM.Scale;
11011 switch (VT.getSimpleVT().SimpleTy) {
11012 default: return false;
11016 if (Scale < 0) Scale = -Scale;
11020 return isPowerOf2_32(Scale & ~1);
11024 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11029 // Note, we allow "void" uses (basically, uses that aren't loads or
11030 // stores), because arm allows folding a scale into many arithmetic
11031 // operations. This should be made more precise and revisited later.
11033 // Allow r << imm, but the imm has to be a multiple of two.
11034 if (Scale & 1) return false;
11035 return isPowerOf2_32(Scale);
11041 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11042 /// icmp immediate, that is the target has icmp instructions which can compare
11043 /// a register against the immediate without having to materialize the
11044 /// immediate into a register.
11045 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11046 // Thumb2 and ARM modes can use cmn for negative immediates.
11047 if (!Subtarget->isThumb())
11048 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11049 if (Subtarget->isThumb2())
11050 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11051 // Thumb1 doesn't have cmn, and only 8-bit immediates.
11052 return Imm >= 0 && Imm <= 255;
11055 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11056 /// *or sub* immediate, that is the target has add or sub instructions which can
11057 /// add a register with the immediate without having to materialize the
11058 /// immediate into a register.
11059 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11060 // Same encoding for add/sub, just flip the sign.
11061 int64_t AbsImm = std::abs(Imm);
11062 if (!Subtarget->isThumb())
11063 return ARM_AM::getSOImmVal(AbsImm) != -1;
11064 if (Subtarget->isThumb2())
11065 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11066 // Thumb1 only has 8-bit unsigned immediate.
11067 return AbsImm >= 0 && AbsImm <= 255;
11070 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11071 bool isSEXTLoad, SDValue &Base,
11072 SDValue &Offset, bool &isInc,
11073 SelectionDAG &DAG) {
11074 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11077 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11078 // AddressingMode 3
11079 Base = Ptr->getOperand(0);
11080 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11081 int RHSC = (int)RHS->getZExtValue();
11082 if (RHSC < 0 && RHSC > -256) {
11083 assert(Ptr->getOpcode() == ISD::ADD);
11085 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11089 isInc = (Ptr->getOpcode() == ISD::ADD);
11090 Offset = Ptr->getOperand(1);
11092 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11093 // AddressingMode 2
11094 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11095 int RHSC = (int)RHS->getZExtValue();
11096 if (RHSC < 0 && RHSC > -0x1000) {
11097 assert(Ptr->getOpcode() == ISD::ADD);
11099 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11100 Base = Ptr->getOperand(0);
11105 if (Ptr->getOpcode() == ISD::ADD) {
11107 ARM_AM::ShiftOpc ShOpcVal=
11108 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11109 if (ShOpcVal != ARM_AM::no_shift) {
11110 Base = Ptr->getOperand(1);
11111 Offset = Ptr->getOperand(0);
11113 Base = Ptr->getOperand(0);
11114 Offset = Ptr->getOperand(1);
11119 isInc = (Ptr->getOpcode() == ISD::ADD);
11120 Base = Ptr->getOperand(0);
11121 Offset = Ptr->getOperand(1);
11125 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11129 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11130 bool isSEXTLoad, SDValue &Base,
11131 SDValue &Offset, bool &isInc,
11132 SelectionDAG &DAG) {
11133 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11136 Base = Ptr->getOperand(0);
11137 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11138 int RHSC = (int)RHS->getZExtValue();
11139 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11140 assert(Ptr->getOpcode() == ISD::ADD);
11142 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11144 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11145 isInc = Ptr->getOpcode() == ISD::ADD;
11146 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11154 /// getPreIndexedAddressParts - returns true by value, base pointer and
11155 /// offset pointer and addressing mode by reference if the node's address
11156 /// can be legally represented as pre-indexed load / store address.
11158 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11160 ISD::MemIndexedMode &AM,
11161 SelectionDAG &DAG) const {
11162 if (Subtarget->isThumb1Only())
11167 bool isSEXTLoad = false;
11168 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11169 Ptr = LD->getBasePtr();
11170 VT = LD->getMemoryVT();
11171 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11172 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11173 Ptr = ST->getBasePtr();
11174 VT = ST->getMemoryVT();
11179 bool isLegal = false;
11180 if (Subtarget->isThumb2())
11181 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11182 Offset, isInc, DAG);
11184 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11185 Offset, isInc, DAG);
11189 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11193 /// getPostIndexedAddressParts - returns true by value, base pointer and
11194 /// offset pointer and addressing mode by reference if this node can be
11195 /// combined with a load / store to form a post-indexed load / store.
11196 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11199 ISD::MemIndexedMode &AM,
11200 SelectionDAG &DAG) const {
11201 if (Subtarget->isThumb1Only())
11206 bool isSEXTLoad = false;
11207 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11208 VT = LD->getMemoryVT();
11209 Ptr = LD->getBasePtr();
11210 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11211 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11212 VT = ST->getMemoryVT();
11213 Ptr = ST->getBasePtr();
11218 bool isLegal = false;
11219 if (Subtarget->isThumb2())
11220 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11223 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11229 // Swap base ptr and offset to catch more post-index load / store when
11230 // it's legal. In Thumb2 mode, offset must be an immediate.
11231 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11232 !Subtarget->isThumb2())
11233 std::swap(Base, Offset);
11235 // Post-indexed load / store update the base pointer.
11240 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11244 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11247 const SelectionDAG &DAG,
11248 unsigned Depth) const {
11249 unsigned BitWidth = KnownOne.getBitWidth();
11250 KnownZero = KnownOne = APInt(BitWidth, 0);
11251 switch (Op.getOpcode()) {
11257 // These nodes' second result is a boolean
11258 if (Op.getResNo() == 0)
11260 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11262 case ARMISD::CMOV: {
11263 // Bits are known zero/one if known on the LHS and RHS.
11264 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11265 if (KnownZero == 0 && KnownOne == 0) return;
11267 APInt KnownZeroRHS, KnownOneRHS;
11268 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11269 KnownZero &= KnownZeroRHS;
11270 KnownOne &= KnownOneRHS;
11273 case ISD::INTRINSIC_W_CHAIN: {
11274 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11275 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11278 case Intrinsic::arm_ldaex:
11279 case Intrinsic::arm_ldrex: {
11280 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11281 unsigned MemBits = VT.getScalarType().getSizeInBits();
11282 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11290 //===----------------------------------------------------------------------===//
11291 // ARM Inline Assembly Support
11292 //===----------------------------------------------------------------------===//
11294 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11295 // Looking for "rev" which is V6+.
11296 if (!Subtarget->hasV6Ops())
11299 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11300 std::string AsmStr = IA->getAsmString();
11301 SmallVector<StringRef, 4> AsmPieces;
11302 SplitString(AsmStr, AsmPieces, ";\n");
11304 switch (AsmPieces.size()) {
11305 default: return false;
11307 AsmStr = AsmPieces[0];
11309 SplitString(AsmStr, AsmPieces, " \t,");
11312 if (AsmPieces.size() == 3 &&
11313 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11314 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11315 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11316 if (Ty && Ty->getBitWidth() == 32)
11317 return IntrinsicLowering::LowerToByteSwap(CI);
11325 /// getConstraintType - Given a constraint letter, return the type of
11326 /// constraint it is for this target.
11327 ARMTargetLowering::ConstraintType
11328 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11329 if (Constraint.size() == 1) {
11330 switch (Constraint[0]) {
11332 case 'l': return C_RegisterClass;
11333 case 'w': return C_RegisterClass;
11334 case 'h': return C_RegisterClass;
11335 case 'x': return C_RegisterClass;
11336 case 't': return C_RegisterClass;
11337 case 'j': return C_Other; // Constant for movw.
11338 // An address with a single base register. Due to the way we
11339 // currently handle addresses it is the same as an 'r' memory constraint.
11340 case 'Q': return C_Memory;
11342 } else if (Constraint.size() == 2) {
11343 switch (Constraint[0]) {
11345 // All 'U+' constraints are addresses.
11346 case 'U': return C_Memory;
11349 return TargetLowering::getConstraintType(Constraint);
11352 /// Examine constraint type and operand type and determine a weight value.
11353 /// This object must already have been set up with the operand type
11354 /// and the current alternative constraint selected.
11355 TargetLowering::ConstraintWeight
11356 ARMTargetLowering::getSingleConstraintMatchWeight(
11357 AsmOperandInfo &info, const char *constraint) const {
11358 ConstraintWeight weight = CW_Invalid;
11359 Value *CallOperandVal = info.CallOperandVal;
11360 // If we don't have a value, we can't do a match,
11361 // but allow it at the lowest weight.
11362 if (!CallOperandVal)
11364 Type *type = CallOperandVal->getType();
11365 // Look at the constraint type.
11366 switch (*constraint) {
11368 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11371 if (type->isIntegerTy()) {
11372 if (Subtarget->isThumb())
11373 weight = CW_SpecificReg;
11375 weight = CW_Register;
11379 if (type->isFloatingPointTy())
11380 weight = CW_Register;
11386 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11387 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11388 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11389 if (Constraint.size() == 1) {
11390 // GCC ARM Constraint Letters
11391 switch (Constraint[0]) {
11392 case 'l': // Low regs or general regs.
11393 if (Subtarget->isThumb())
11394 return RCPair(0U, &ARM::tGPRRegClass);
11395 return RCPair(0U, &ARM::GPRRegClass);
11396 case 'h': // High regs or no regs.
11397 if (Subtarget->isThumb())
11398 return RCPair(0U, &ARM::hGPRRegClass);
11401 if (Subtarget->isThumb1Only())
11402 return RCPair(0U, &ARM::tGPRRegClass);
11403 return RCPair(0U, &ARM::GPRRegClass);
11405 if (VT == MVT::Other)
11407 if (VT == MVT::f32)
11408 return RCPair(0U, &ARM::SPRRegClass);
11409 if (VT.getSizeInBits() == 64)
11410 return RCPair(0U, &ARM::DPRRegClass);
11411 if (VT.getSizeInBits() == 128)
11412 return RCPair(0U, &ARM::QPRRegClass);
11415 if (VT == MVT::Other)
11417 if (VT == MVT::f32)
11418 return RCPair(0U, &ARM::SPR_8RegClass);
11419 if (VT.getSizeInBits() == 64)
11420 return RCPair(0U, &ARM::DPR_8RegClass);
11421 if (VT.getSizeInBits() == 128)
11422 return RCPair(0U, &ARM::QPR_8RegClass);
11425 if (VT == MVT::f32)
11426 return RCPair(0U, &ARM::SPRRegClass);
11430 if (StringRef("{cc}").equals_lower(Constraint))
11431 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11433 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11436 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11437 /// vector. If it is invalid, don't add anything to Ops.
11438 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11439 std::string &Constraint,
11440 std::vector<SDValue>&Ops,
11441 SelectionDAG &DAG) const {
11444 // Currently only support length 1 constraints.
11445 if (Constraint.length() != 1) return;
11447 char ConstraintLetter = Constraint[0];
11448 switch (ConstraintLetter) {
11451 case 'I': case 'J': case 'K': case 'L':
11452 case 'M': case 'N': case 'O':
11453 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11457 int64_t CVal64 = C->getSExtValue();
11458 int CVal = (int) CVal64;
11459 // None of these constraints allow values larger than 32 bits. Check
11460 // that the value fits in an int.
11461 if (CVal != CVal64)
11464 switch (ConstraintLetter) {
11466 // Constant suitable for movw, must be between 0 and
11468 if (Subtarget->hasV6T2Ops())
11469 if (CVal >= 0 && CVal <= 65535)
11473 if (Subtarget->isThumb1Only()) {
11474 // This must be a constant between 0 and 255, for ADD
11476 if (CVal >= 0 && CVal <= 255)
11478 } else if (Subtarget->isThumb2()) {
11479 // A constant that can be used as an immediate value in a
11480 // data-processing instruction.
11481 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11484 // A constant that can be used as an immediate value in a
11485 // data-processing instruction.
11486 if (ARM_AM::getSOImmVal(CVal) != -1)
11492 if (Subtarget->isThumb1Only()) {
11493 // This must be a constant between -255 and -1, for negated ADD
11494 // immediates. This can be used in GCC with an "n" modifier that
11495 // prints the negated value, for use with SUB instructions. It is
11496 // not useful otherwise but is implemented for compatibility.
11497 if (CVal >= -255 && CVal <= -1)
11500 // This must be a constant between -4095 and 4095. It is not clear
11501 // what this constraint is intended for. Implemented for
11502 // compatibility with GCC.
11503 if (CVal >= -4095 && CVal <= 4095)
11509 if (Subtarget->isThumb1Only()) {
11510 // A 32-bit value where only one byte has a nonzero value. Exclude
11511 // zero to match GCC. This constraint is used by GCC internally for
11512 // constants that can be loaded with a move/shift combination.
11513 // It is not useful otherwise but is implemented for compatibility.
11514 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11516 } else if (Subtarget->isThumb2()) {
11517 // A constant whose bitwise inverse can be used as an immediate
11518 // value in a data-processing instruction. This can be used in GCC
11519 // with a "B" modifier that prints the inverted value, for use with
11520 // BIC and MVN instructions. It is not useful otherwise but is
11521 // implemented for compatibility.
11522 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11525 // A constant whose bitwise inverse can be used as an immediate
11526 // value in a data-processing instruction. This can be used in GCC
11527 // with a "B" modifier that prints the inverted value, for use with
11528 // BIC and MVN instructions. It is not useful otherwise but is
11529 // implemented for compatibility.
11530 if (ARM_AM::getSOImmVal(~CVal) != -1)
11536 if (Subtarget->isThumb1Only()) {
11537 // This must be a constant between -7 and 7,
11538 // for 3-operand ADD/SUB immediate instructions.
11539 if (CVal >= -7 && CVal < 7)
11541 } else if (Subtarget->isThumb2()) {
11542 // A constant whose negation can be used as an immediate value in a
11543 // data-processing instruction. This can be used in GCC with an "n"
11544 // modifier that prints the negated value, for use with SUB
11545 // instructions. It is not useful otherwise but is implemented for
11547 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11550 // A constant whose negation can be used as an immediate value in a
11551 // data-processing instruction. This can be used in GCC with an "n"
11552 // modifier that prints the negated value, for use with SUB
11553 // instructions. It is not useful otherwise but is implemented for
11555 if (ARM_AM::getSOImmVal(-CVal) != -1)
11561 if (Subtarget->isThumb1Only()) {
11562 // This must be a multiple of 4 between 0 and 1020, for
11563 // ADD sp + immediate.
11564 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11567 // A power of two or a constant between 0 and 32. This is used in
11568 // GCC for the shift amount on shifted register operands, but it is
11569 // useful in general for any shift amounts.
11570 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11576 if (Subtarget->isThumb()) { // FIXME thumb2
11577 // This must be a constant between 0 and 31, for shift amounts.
11578 if (CVal >= 0 && CVal <= 31)
11584 if (Subtarget->isThumb()) { // FIXME thumb2
11585 // This must be a multiple of 4 between -508 and 508, for
11586 // ADD/SUB sp = sp + immediate.
11587 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11592 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11596 if (Result.getNode()) {
11597 Ops.push_back(Result);
11600 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11603 static RTLIB::Libcall getDivRemLibcall(
11604 const SDNode *N, MVT::SimpleValueType SVT) {
11605 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11606 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11607 "Unhandled Opcode in getDivRemLibcall");
11608 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11609 N->getOpcode() == ISD::SREM;
11612 default: llvm_unreachable("Unexpected request for libcall!");
11613 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11614 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11615 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11616 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11621 static TargetLowering::ArgListTy getDivRemArgList(
11622 const SDNode *N, LLVMContext *Context) {
11623 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11624 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11625 "Unhandled Opcode in getDivRemArgList");
11626 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11627 N->getOpcode() == ISD::SREM;
11628 TargetLowering::ArgListTy Args;
11629 TargetLowering::ArgListEntry Entry;
11630 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11631 EVT ArgVT = N->getOperand(i).getValueType();
11632 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11633 Entry.Node = N->getOperand(i);
11635 Entry.isSExt = isSigned;
11636 Entry.isZExt = !isSigned;
11637 Args.push_back(Entry);
11642 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11643 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11644 "Register-based DivRem lowering only");
11645 unsigned Opcode = Op->getOpcode();
11646 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11647 "Invalid opcode for Div/Rem lowering");
11648 bool isSigned = (Opcode == ISD::SDIVREM);
11649 EVT VT = Op->getValueType(0);
11650 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11652 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11653 VT.getSimpleVT().SimpleTy);
11654 SDValue InChain = DAG.getEntryNode();
11656 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11659 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11660 getPointerTy(DAG.getDataLayout()));
11662 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11665 TargetLowering::CallLoweringInfo CLI(DAG);
11666 CLI.setDebugLoc(dl).setChain(InChain)
11667 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11668 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11670 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11671 return CallInfo.first;
11674 // Lowers REM using divmod helpers
11675 // see RTABI section 4.2/4.3
11676 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11677 // Build return types (div and rem)
11678 std::vector<Type*> RetTyParams;
11679 Type *RetTyElement;
11681 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11682 default: llvm_unreachable("Unexpected request for libcall!");
11683 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11684 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11685 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11686 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11689 RetTyParams.push_back(RetTyElement);
11690 RetTyParams.push_back(RetTyElement);
11691 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11692 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11694 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11696 SDValue InChain = DAG.getEntryNode();
11697 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11698 bool isSigned = N->getOpcode() == ISD::SREM;
11699 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11700 getPointerTy(DAG.getDataLayout()));
11703 CallLoweringInfo CLI(DAG);
11704 CLI.setChain(InChain)
11705 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11706 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11707 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11709 // Return second (rem) result operand (first contains div)
11710 SDNode *ResNode = CallResult.first.getNode();
11711 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11712 return ResNode->getOperand(1);
11716 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11717 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11721 SDValue Chain = Op.getOperand(0);
11722 SDValue Size = Op.getOperand(1);
11724 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11725 DAG.getConstant(2, DL, MVT::i32));
11728 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11729 Flag = Chain.getValue(1);
11731 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11732 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11734 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11735 Chain = NewSP.getValue(1);
11737 SDValue Ops[2] = { NewSP, Chain };
11738 return DAG.getMergeValues(Ops, DL);
11741 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11742 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11743 "Unexpected type for custom-lowering FP_EXTEND");
11746 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11748 SDValue SrcVal = Op.getOperand(0);
11749 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11753 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11754 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11755 Subtarget->isFPOnlySP() &&
11756 "Unexpected type for custom-lowering FP_ROUND");
11759 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11761 SDValue SrcVal = Op.getOperand(0);
11762 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11767 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11768 // The ARM target isn't yet aware of offsets.
11772 bool ARM::isBitFieldInvertedMask(unsigned v) {
11773 if (v == 0xffffffff)
11776 // there can be 1's on either or both "outsides", all the "inside"
11777 // bits must be 0's
11778 return isShiftedMask_32(~v);
11781 /// isFPImmLegal - Returns true if the target can instruction select the
11782 /// specified FP immediate natively. If false, the legalizer will
11783 /// materialize the FP immediate as a load from a constant pool.
11784 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11785 if (!Subtarget->hasVFP3())
11787 if (VT == MVT::f32)
11788 return ARM_AM::getFP32Imm(Imm) != -1;
11789 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11790 return ARM_AM::getFP64Imm(Imm) != -1;
11794 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11795 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11796 /// specified in the intrinsic calls.
11797 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11799 unsigned Intrinsic) const {
11800 switch (Intrinsic) {
11801 case Intrinsic::arm_neon_vld1:
11802 case Intrinsic::arm_neon_vld2:
11803 case Intrinsic::arm_neon_vld3:
11804 case Intrinsic::arm_neon_vld4:
11805 case Intrinsic::arm_neon_vld2lane:
11806 case Intrinsic::arm_neon_vld3lane:
11807 case Intrinsic::arm_neon_vld4lane: {
11808 Info.opc = ISD::INTRINSIC_W_CHAIN;
11809 // Conservatively set memVT to the entire set of vectors loaded.
11810 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11811 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11812 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11813 Info.ptrVal = I.getArgOperand(0);
11815 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11816 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11817 Info.vol = false; // volatile loads with NEON intrinsics not supported
11818 Info.readMem = true;
11819 Info.writeMem = false;
11822 case Intrinsic::arm_neon_vst1:
11823 case Intrinsic::arm_neon_vst2:
11824 case Intrinsic::arm_neon_vst3:
11825 case Intrinsic::arm_neon_vst4:
11826 case Intrinsic::arm_neon_vst2lane:
11827 case Intrinsic::arm_neon_vst3lane:
11828 case Intrinsic::arm_neon_vst4lane: {
11829 Info.opc = ISD::INTRINSIC_VOID;
11830 // Conservatively set memVT to the entire set of vectors stored.
11831 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11832 unsigned NumElts = 0;
11833 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11834 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11835 if (!ArgTy->isVectorTy())
11837 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11839 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11840 Info.ptrVal = I.getArgOperand(0);
11842 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11843 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11844 Info.vol = false; // volatile stores with NEON intrinsics not supported
11845 Info.readMem = false;
11846 Info.writeMem = true;
11849 case Intrinsic::arm_ldaex:
11850 case Intrinsic::arm_ldrex: {
11851 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11852 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11853 Info.opc = ISD::INTRINSIC_W_CHAIN;
11854 Info.memVT = MVT::getVT(PtrTy->getElementType());
11855 Info.ptrVal = I.getArgOperand(0);
11857 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11859 Info.readMem = true;
11860 Info.writeMem = false;
11863 case Intrinsic::arm_stlex:
11864 case Intrinsic::arm_strex: {
11865 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11866 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11867 Info.opc = ISD::INTRINSIC_W_CHAIN;
11868 Info.memVT = MVT::getVT(PtrTy->getElementType());
11869 Info.ptrVal = I.getArgOperand(1);
11871 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11873 Info.readMem = false;
11874 Info.writeMem = true;
11877 case Intrinsic::arm_stlexd:
11878 case Intrinsic::arm_strexd: {
11879 Info.opc = ISD::INTRINSIC_W_CHAIN;
11880 Info.memVT = MVT::i64;
11881 Info.ptrVal = I.getArgOperand(2);
11885 Info.readMem = false;
11886 Info.writeMem = true;
11889 case Intrinsic::arm_ldaexd:
11890 case Intrinsic::arm_ldrexd: {
11891 Info.opc = ISD::INTRINSIC_W_CHAIN;
11892 Info.memVT = MVT::i64;
11893 Info.ptrVal = I.getArgOperand(0);
11897 Info.readMem = true;
11898 Info.writeMem = false;
11908 /// \brief Returns true if it is beneficial to convert a load of a constant
11909 /// to just the constant itself.
11910 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11912 assert(Ty->isIntegerTy());
11914 unsigned Bits = Ty->getPrimitiveSizeInBits();
11915 if (Bits == 0 || Bits > 32)
11920 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11921 ARM_MB::MemBOpt Domain) const {
11922 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11924 // First, if the target has no DMB, see what fallback we can use.
11925 if (!Subtarget->hasDataBarrier()) {
11926 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11927 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11929 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11930 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11931 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11932 Builder.getInt32(0), Builder.getInt32(7),
11933 Builder.getInt32(10), Builder.getInt32(5)};
11934 return Builder.CreateCall(MCR, args);
11936 // Instead of using barriers, atomic accesses on these subtargets use
11938 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11941 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11942 // Only a full system barrier exists in the M-class architectures.
11943 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11944 Constant *CDomain = Builder.getInt32(Domain);
11945 return Builder.CreateCall(DMB, CDomain);
11949 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11950 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11951 AtomicOrdering Ord, bool IsStore,
11952 bool IsLoad) const {
11953 if (!getInsertFencesForAtomic())
11959 llvm_unreachable("Invalid fence: unordered/non-atomic");
11962 return nullptr; // Nothing to do
11963 case SequentiallyConsistent:
11965 return nullptr; // Nothing to do
11968 case AcquireRelease:
11969 if (Subtarget->isSwift())
11970 return makeDMB(Builder, ARM_MB::ISHST);
11971 // FIXME: add a comment with a link to documentation justifying this.
11973 return makeDMB(Builder, ARM_MB::ISH);
11975 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11978 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11979 AtomicOrdering Ord, bool IsStore,
11980 bool IsLoad) const {
11981 if (!getInsertFencesForAtomic())
11987 llvm_unreachable("Invalid fence: unordered/not-atomic");
11990 return nullptr; // Nothing to do
11992 case AcquireRelease:
11993 case SequentiallyConsistent:
11994 return makeDMB(Builder, ARM_MB::ISH);
11996 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11999 // Loads and stores less than 64-bits are already atomic; ones above that
12000 // are doomed anyway, so defer to the default libcall and blame the OS when
12001 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12002 // anything for those.
12003 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12004 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12005 return (Size == 64) && !Subtarget->isMClass();
12008 // Loads and stores less than 64-bits are already atomic; ones above that
12009 // are doomed anyway, so defer to the default libcall and blame the OS when
12010 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12011 // anything for those.
12012 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12013 // guarantee, see DDI0406C ARM architecture reference manual,
12014 // sections A8.8.72-74 LDRD)
12015 TargetLowering::AtomicExpansionKind
12016 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12017 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12018 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12019 : AtomicExpansionKind::None;
12022 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12023 // and up to 64 bits on the non-M profiles
12024 TargetLowering::AtomicExpansionKind
12025 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12026 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12027 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12028 ? AtomicExpansionKind::LLSC
12029 : AtomicExpansionKind::None;
12032 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12033 AtomicCmpXchgInst *AI) const {
12037 // This has so far only been implemented for MachO.
12038 bool ARMTargetLowering::useLoadStackGuardNode() const {
12039 return Subtarget->isTargetMachO();
12042 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12043 unsigned &Cost) const {
12044 // If we do not have NEON, vector types are not natively supported.
12045 if (!Subtarget->hasNEON())
12048 // Floating point values and vector values map to the same register file.
12049 // Therefore, although we could do a store extract of a vector type, this is
12050 // better to leave at float as we have more freedom in the addressing mode for
12052 if (VectorTy->isFPOrFPVectorTy())
12055 // If the index is unknown at compile time, this is very expensive to lower
12056 // and it is not possible to combine the store with the extract.
12057 if (!isa<ConstantInt>(Idx))
12060 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12061 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12062 // We can do a store + vector extract on any vector that fits perfectly in a D
12064 if (BitWidth == 64 || BitWidth == 128) {
12071 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12072 return Subtarget->hasV6T2Ops();
12075 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12076 return Subtarget->hasV6T2Ops();
12079 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12080 AtomicOrdering Ord) const {
12081 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12082 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12083 bool IsAcquire = isAtLeastAcquire(Ord);
12085 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12086 // intrinsic must return {i32, i32} and we have to recombine them into a
12087 // single i64 here.
12088 if (ValTy->getPrimitiveSizeInBits() == 64) {
12089 Intrinsic::ID Int =
12090 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12091 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12093 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12094 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12096 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12097 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12098 if (!Subtarget->isLittle())
12099 std::swap (Lo, Hi);
12100 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12101 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12102 return Builder.CreateOr(
12103 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12106 Type *Tys[] = { Addr->getType() };
12107 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12108 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12110 return Builder.CreateTruncOrBitCast(
12111 Builder.CreateCall(Ldrex, Addr),
12112 cast<PointerType>(Addr->getType())->getElementType());
12115 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12116 IRBuilder<> &Builder) const {
12117 if (!Subtarget->hasV7Ops())
12119 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12120 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12123 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12125 AtomicOrdering Ord) const {
12126 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12127 bool IsRelease = isAtLeastRelease(Ord);
12129 // Since the intrinsics must have legal type, the i64 intrinsics take two
12130 // parameters: "i32, i32". We must marshal Val into the appropriate form
12131 // before the call.
12132 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12133 Intrinsic::ID Int =
12134 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12135 Function *Strex = Intrinsic::getDeclaration(M, Int);
12136 Type *Int32Ty = Type::getInt32Ty(M->getContext());
12138 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12139 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12140 if (!Subtarget->isLittle())
12141 std::swap (Lo, Hi);
12142 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12143 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12146 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12147 Type *Tys[] = { Addr->getType() };
12148 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12150 return Builder.CreateCall(
12151 Strex, {Builder.CreateZExtOrBitCast(
12152 Val, Strex->getFunctionType()->getParamType(0)),
12156 /// \brief Lower an interleaved load into a vldN intrinsic.
12158 /// E.g. Lower an interleaved load (Factor = 2):
12159 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12160 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
12161 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
12164 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12165 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12166 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12167 bool ARMTargetLowering::lowerInterleavedLoad(
12168 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12169 ArrayRef<unsigned> Indices, unsigned Factor) const {
12170 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12171 "Invalid interleave factor");
12172 assert(!Shuffles.empty() && "Empty shufflevector input");
12173 assert(Shuffles.size() == Indices.size() &&
12174 "Unmatched number of shufflevectors and indices");
12176 VectorType *VecTy = Shuffles[0]->getType();
12177 Type *EltTy = VecTy->getVectorElementType();
12179 const DataLayout &DL = LI->getModule()->getDataLayout();
12180 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12181 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12183 // Skip if we do not have NEON and skip illegal vector types and vector types
12184 // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12185 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12188 // A pointer vector can not be the return type of the ldN intrinsics. Need to
12189 // load integer vectors first and then convert to pointer vectors.
12190 if (EltTy->isPointerTy())
12192 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12194 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12195 Intrinsic::arm_neon_vld3,
12196 Intrinsic::arm_neon_vld4};
12198 IRBuilder<> Builder(LI);
12199 SmallVector<Value *, 2> Ops;
12201 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12202 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12203 Ops.push_back(Builder.getInt32(LI->getAlignment()));
12205 Type *Tys[] = { VecTy, Int8Ptr };
12206 Function *VldnFunc =
12207 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12208 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12210 // Replace uses of each shufflevector with the corresponding vector loaded
12212 for (unsigned i = 0; i < Shuffles.size(); i++) {
12213 ShuffleVectorInst *SV = Shuffles[i];
12214 unsigned Index = Indices[i];
12216 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12218 // Convert the integer vector to pointer vector if the element is pointer.
12219 if (EltTy->isPointerTy())
12220 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12222 SV->replaceAllUsesWith(SubVec);
12228 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12230 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12231 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12232 unsigned NumElts) {
12233 SmallVector<Constant *, 16> Mask;
12234 for (unsigned i = 0; i < NumElts; i++)
12235 Mask.push_back(Builder.getInt32(Start + i));
12237 return ConstantVector::get(Mask);
12240 /// \brief Lower an interleaved store into a vstN intrinsic.
12242 /// E.g. Lower an interleaved store (Factor = 3):
12243 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12244 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12245 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12248 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12249 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12250 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12251 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12253 /// Note that the new shufflevectors will be removed and we'll only generate one
12254 /// vst3 instruction in CodeGen.
12255 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12256 ShuffleVectorInst *SVI,
12257 unsigned Factor) const {
12258 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12259 "Invalid interleave factor");
12261 VectorType *VecTy = SVI->getType();
12262 assert(VecTy->getVectorNumElements() % Factor == 0 &&
12263 "Invalid interleaved store");
12265 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12266 Type *EltTy = VecTy->getVectorElementType();
12267 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12269 const DataLayout &DL = SI->getModule()->getDataLayout();
12270 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12271 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12273 // Skip if we do not have NEON and skip illegal vector types and vector types
12274 // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12275 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12279 Value *Op0 = SVI->getOperand(0);
12280 Value *Op1 = SVI->getOperand(1);
12281 IRBuilder<> Builder(SI);
12283 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12284 // vectors to integer vectors.
12285 if (EltTy->isPointerTy()) {
12286 Type *IntTy = DL.getIntPtrType(EltTy);
12288 // Convert to the corresponding integer vector.
12290 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12291 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12292 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12294 SubVecTy = VectorType::get(IntTy, NumSubElts);
12297 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12298 Intrinsic::arm_neon_vst3,
12299 Intrinsic::arm_neon_vst4};
12300 SmallVector<Value *, 6> Ops;
12302 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12303 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12305 Type *Tys[] = { Int8Ptr, SubVecTy };
12306 Function *VstNFunc = Intrinsic::getDeclaration(
12307 SI->getModule(), StoreInts[Factor - 2], Tys);
12309 // Split the shufflevector operands into sub vectors for the new vstN call.
12310 for (unsigned i = 0; i < Factor; i++)
12311 Ops.push_back(Builder.CreateShuffleVector(
12312 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12314 Ops.push_back(Builder.getInt32(SI->getAlignment()));
12315 Builder.CreateCall(VstNFunc, Ops);
12327 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12328 uint64_t &Members) {
12329 if (auto *ST = dyn_cast<StructType>(Ty)) {
12330 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12331 uint64_t SubMembers = 0;
12332 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12334 Members += SubMembers;
12336 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12337 uint64_t SubMembers = 0;
12338 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12340 Members += SubMembers * AT->getNumElements();
12341 } else if (Ty->isFloatTy()) {
12342 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12346 } else if (Ty->isDoubleTy()) {
12347 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12351 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12358 return VT->getBitWidth() == 64;
12360 return VT->getBitWidth() == 128;
12362 switch (VT->getBitWidth()) {
12375 return (Members > 0 && Members <= 4);
12378 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12379 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12380 /// passing according to AAPCS rules.
12381 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12382 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12383 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12384 CallingConv::ARM_AAPCS_VFP)
12387 HABaseType Base = HA_UNKNOWN;
12388 uint64_t Members = 0;
12389 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12390 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12392 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12393 return IsHA || IsIntArray;
12396 unsigned ARMTargetLowering::getExceptionPointerRegister(
12397 const Constant *PersonalityFn) const {
12398 // Platforms which do not use SjLj EH may return values in these registers
12399 // via the personality function.
12400 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12403 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12404 const Constant *PersonalityFn) const {
12405 // Platforms which do not use SjLj EH may return values in these registers
12406 // via the personality function.
12407 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12410 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12411 // Update IsSplitCSR in ARMFunctionInfo.
12412 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12413 AFI->setIsSplitCSR(true);
12416 void ARMTargetLowering::insertCopiesSplitCSR(
12417 MachineBasicBlock *Entry,
12418 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12419 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12420 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12424 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12425 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12426 for (const MCPhysReg *I = IStart; *I; ++I) {
12427 const TargetRegisterClass *RC = nullptr;
12428 if (ARM::GPRRegClass.contains(*I))
12429 RC = &ARM::GPRRegClass;
12430 else if (ARM::DPRRegClass.contains(*I))
12431 RC = &ARM::DPRRegClass;
12433 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12435 unsigned NewVR = MRI->createVirtualRegister(RC);
12436 // Create copy from CSR to a virtual register.
12437 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12438 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12439 // nounwind. If we want to generalize this later, we may need to emit
12440 // CFI pseudo-instructions.
12441 assert(Entry->getParent()->getFunction()->hasFnAttribute(
12442 Attribute::NoUnwind) &&
12443 "Function should be nounwind in insertCopiesSplitCSR!");
12444 Entry->addLiveIn(*I);
12445 BuildMI(*Entry, Entry->begin(), DebugLoc(), TII->get(TargetOpcode::COPY),
12449 for (auto *Exit : Exits)
12450 BuildMI(*Exit, Exit->begin(), DebugLoc(), TII->get(TargetOpcode::COPY),