1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (VT.isInteger()) {
147 setOperationAction(ISD::SABSDIFF, VT, Legal);
148 setOperationAction(ISD::UABSDIFF, VT, Legal);
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);
242 // These libcalls are not available in 32-bit.
243 setLibcallName(RTLIB::SHL_I128, nullptr);
244 setLibcallName(RTLIB::SRL_I128, nullptr);
245 setLibcallName(RTLIB::SRA_I128, nullptr);
247 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248 !Subtarget->isTargetWindows()) {
249 static const struct {
250 const RTLIB::Libcall Op;
251 const char * const Name;
252 const CallingConv::ID CC;
253 const ISD::CondCode Cond;
255 // Double-precision floating-point arithmetic helper functions
256 // RTABI chapter 4.1.2, Table 2
257 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262 // Double-precision floating-point comparison helper functions
263 // RTABI chapter 4.1.2, Table 3
264 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
273 // Single-precision floating-point arithmetic helper functions
274 // RTABI chapter 4.1.2, Table 4
275 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280 // Single-precision floating-point comparison helper functions
281 // RTABI chapter 4.1.2, Table 5
282 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
291 // Floating-point to integer conversions.
292 // RTABI chapter 4.1.2, Table 6
293 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 // Conversions between floating types.
303 // RTABI chapter 4.1.2, Table 7
304 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 // Integer to floating-point conversions.
309 // RTABI chapter 4.1.2, Table 8
310 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 // Long long helper functions
320 // RTABI chapter 4.2, Table 9
321 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 // Integer division functions
327 // RTABI chapter 4.3.1
328 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 // RTABI chapter 4.3.4
339 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 for (const auto &LC : LibraryCalls) {
345 setLibcallName(LC.Op, LC.Name);
346 setLibcallCallingConv(LC.Op, LC.CC);
347 if (LC.Cond != ISD::SETCC_INVALID)
348 setCmpLibcallCC(LC.Op, LC.Cond);
352 if (Subtarget->isTargetWindows()) {
353 static const struct {
354 const RTLIB::Libcall Op;
355 const char * const Name;
356 const CallingConv::ID CC;
358 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
373 for (const auto &LC : LibraryCalls) {
374 setLibcallName(LC.Op, LC.Name);
375 setLibcallCallingConv(LC.Op, LC.CC);
379 // Use divmod compiler-rt calls for iOS 5.0 and later.
380 if (Subtarget->getTargetTriple().isiOS() &&
381 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
386 // The half <-> float conversion functions are always soft-float, but are
387 // needed for some targets which use a hard-float calling convention by
389 if (Subtarget->isAAPCS_ABI()) {
390 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
399 if (Subtarget->isThumb1Only())
400 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404 !Subtarget->isThumb1Only()) {
405 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
409 for (MVT VT : MVT::vector_valuetypes()) {
410 for (MVT InnerVT : MVT::vector_valuetypes()) {
411 setTruncStoreAction(VT, InnerVT, Expand);
412 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
417 setOperationAction(ISD::MULHS, VT, Expand);
418 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422 setOperationAction(ISD::BSWAP, VT, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
431 if (Subtarget->hasNEON()) {
432 addDRTypeForNEON(MVT::v2f32);
433 addDRTypeForNEON(MVT::v8i8);
434 addDRTypeForNEON(MVT::v4i16);
435 addDRTypeForNEON(MVT::v2i32);
436 addDRTypeForNEON(MVT::v1i64);
438 addQRTypeForNEON(MVT::v4f32);
439 addQRTypeForNEON(MVT::v2f64);
440 addQRTypeForNEON(MVT::v16i8);
441 addQRTypeForNEON(MVT::v8i16);
442 addQRTypeForNEON(MVT::v4i32);
443 addQRTypeForNEON(MVT::v2i64);
445 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446 // neither Neon nor VFP support any arithmetic operations on it.
447 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448 // supported for v4f32.
449 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452 // FIXME: Code duplication: FDIV and FREM are expanded always, see
453 // ARMTargetLowering::addTypeForNEON method for details.
454 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456 // FIXME: Create unittest.
457 // In another words, find a way when "copysign" appears in DAG with vector
459 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460 // FIXME: Code duplication: SETCC has custom operation action, see
461 // ARMTargetLowering::addTypeForNEON method for details.
462 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463 // FIXME: Create unittest for FNEG and for FABS.
464 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
484 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
500 // Mark v2f32 intrinsics.
501 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
517 // Neon does not support some operations on v1i64 and v2i64 types.
518 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519 // Custom handling for some quad-vector types to detect VMULL.
520 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523 // Custom handling for some vector types to avoid expensive expansions
524 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531 // a destination type that is wider than the source, and nor does
532 // it have a FP_TO_[SU]INT instruction with a narrower destination than
534 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
540 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
542 // NEON does not have single instruction CTPOP for vectors with element
543 // types wider than 8-bits. However, custom lowering can leverage the
544 // v8i8/v16i8 vcnt instruction.
545 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
546 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
550 // NEON does not have single instruction CTTZ for vectors.
551 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
556 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
566 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
571 // NEON only has FMA instructions as of VFP4.
572 if (!Subtarget->hasVFP4()) {
573 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
577 setTargetDAGCombine(ISD::INTRINSIC_VOID);
578 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580 setTargetDAGCombine(ISD::SHL);
581 setTargetDAGCombine(ISD::SRL);
582 setTargetDAGCombine(ISD::SRA);
583 setTargetDAGCombine(ISD::SIGN_EXTEND);
584 setTargetDAGCombine(ISD::ZERO_EXTEND);
585 setTargetDAGCombine(ISD::ANY_EXTEND);
586 setTargetDAGCombine(ISD::SELECT_CC);
587 setTargetDAGCombine(ISD::BUILD_VECTOR);
588 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
589 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
590 setTargetDAGCombine(ISD::STORE);
591 setTargetDAGCombine(ISD::FP_TO_SINT);
592 setTargetDAGCombine(ISD::FP_TO_UINT);
593 setTargetDAGCombine(ISD::FDIV);
594 setTargetDAGCombine(ISD::LOAD);
596 // It is legal to extload from v4i8 to v4i16 or v4i32.
597 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
599 for (MVT VT : MVT::integer_vector_valuetypes()) {
600 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
601 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
602 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
607 // ARM and Thumb2 support UMLAL/SMLAL.
608 if (!Subtarget->isThumb1Only())
609 setTargetDAGCombine(ISD::ADDC);
611 if (Subtarget->isFPOnlySP()) {
612 // When targeting a floating-point unit with only single-precision
613 // operations, f64 is legal for the few double-precision instructions which
614 // are present However, no double-precision operations other than moves,
615 // loads and stores are provided by the hardware.
616 setOperationAction(ISD::FADD, MVT::f64, Expand);
617 setOperationAction(ISD::FSUB, MVT::f64, Expand);
618 setOperationAction(ISD::FMUL, MVT::f64, Expand);
619 setOperationAction(ISD::FMA, MVT::f64, Expand);
620 setOperationAction(ISD::FDIV, MVT::f64, Expand);
621 setOperationAction(ISD::FREM, MVT::f64, Expand);
622 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
623 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
624 setOperationAction(ISD::FNEG, MVT::f64, Expand);
625 setOperationAction(ISD::FABS, MVT::f64, Expand);
626 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
627 setOperationAction(ISD::FSIN, MVT::f64, Expand);
628 setOperationAction(ISD::FCOS, MVT::f64, Expand);
629 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
630 setOperationAction(ISD::FPOW, MVT::f64, Expand);
631 setOperationAction(ISD::FLOG, MVT::f64, Expand);
632 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
633 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
634 setOperationAction(ISD::FEXP, MVT::f64, Expand);
635 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
636 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
637 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
638 setOperationAction(ISD::FRINT, MVT::f64, Expand);
639 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
640 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
641 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
642 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
643 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
644 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
645 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
646 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
647 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
648 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
651 computeRegisterProperties(Subtarget->getRegisterInfo());
653 // ARM does not have floating-point extending loads.
654 for (MVT VT : MVT::fp_valuetypes()) {
655 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
656 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
659 // ... or truncating stores
660 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
661 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
662 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
664 // ARM does not have i1 sign extending load.
665 for (MVT VT : MVT::integer_valuetypes())
666 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
668 // ARM supports all 4 flavors of integer indexed load / store.
669 if (!Subtarget->isThumb1Only()) {
670 for (unsigned im = (unsigned)ISD::PRE_INC;
671 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
672 setIndexedLoadAction(im, MVT::i1, Legal);
673 setIndexedLoadAction(im, MVT::i8, Legal);
674 setIndexedLoadAction(im, MVT::i16, Legal);
675 setIndexedLoadAction(im, MVT::i32, Legal);
676 setIndexedStoreAction(im, MVT::i1, Legal);
677 setIndexedStoreAction(im, MVT::i8, Legal);
678 setIndexedStoreAction(im, MVT::i16, Legal);
679 setIndexedStoreAction(im, MVT::i32, Legal);
683 setOperationAction(ISD::SADDO, MVT::i32, Custom);
684 setOperationAction(ISD::UADDO, MVT::i32, Custom);
685 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
686 setOperationAction(ISD::USUBO, MVT::i32, Custom);
688 // i64 operation support.
689 setOperationAction(ISD::MUL, MVT::i64, Expand);
690 setOperationAction(ISD::MULHU, MVT::i32, Expand);
691 if (Subtarget->isThumb1Only()) {
692 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
693 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
695 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
696 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
697 setOperationAction(ISD::MULHS, MVT::i32, Expand);
699 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
700 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
702 setOperationAction(ISD::SRL, MVT::i64, Custom);
703 setOperationAction(ISD::SRA, MVT::i64, Custom);
705 if (!Subtarget->isThumb1Only()) {
706 // FIXME: We should do this for Thumb1 as well.
707 setOperationAction(ISD::ADDC, MVT::i32, Custom);
708 setOperationAction(ISD::ADDE, MVT::i32, Custom);
709 setOperationAction(ISD::SUBC, MVT::i32, Custom);
710 setOperationAction(ISD::SUBE, MVT::i32, Custom);
713 // ARM does not have ROTL.
714 setOperationAction(ISD::ROTL, MVT::i32, Expand);
715 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
716 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
717 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
718 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
720 // These just redirect to CTTZ and CTLZ on ARM.
721 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
722 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
724 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
726 // Only ARMv6 has BSWAP.
727 if (!Subtarget->hasV6Ops())
728 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
730 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
731 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
732 // These are expanded into libcalls if the cpu doesn't have HW divider.
733 setOperationAction(ISD::SDIV, MVT::i32, Expand);
734 setOperationAction(ISD::UDIV, MVT::i32, Expand);
737 // FIXME: Also set divmod for SREM on EABI/androideabi
738 setOperationAction(ISD::SREM, MVT::i32, Expand);
739 setOperationAction(ISD::UREM, MVT::i32, Expand);
740 // Register based DivRem for AEABI (RTABI 4.2)
741 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
742 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
743 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
744 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
745 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
746 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
747 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
748 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
749 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
751 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
752 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
753 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
754 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
755 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
756 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
757 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
758 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
760 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
761 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
763 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
764 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
767 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
768 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
769 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
770 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
771 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
773 setOperationAction(ISD::TRAP, MVT::Other, Legal);
775 // Use the default implementation.
776 setOperationAction(ISD::VASTART, MVT::Other, Custom);
777 setOperationAction(ISD::VAARG, MVT::Other, Expand);
778 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
779 setOperationAction(ISD::VAEND, MVT::Other, Expand);
780 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
781 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
783 if (!Subtarget->isTargetMachO()) {
784 // Non-MachO platforms may return values in these registers via the
785 // personality function.
786 setExceptionPointerRegister(ARM::R0);
787 setExceptionSelectorRegister(ARM::R1);
790 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
791 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
793 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
795 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
796 // the default expansion. If we are targeting a single threaded system,
797 // then set them all for expand so we can lower them later into their
799 if (TM.Options.ThreadModel == ThreadModel::Single)
800 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
801 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
802 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
803 // to ldrex/strex loops already.
804 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
806 // On v8, we have particularly efficient implementations of atomic fences
807 // if they can be combined with nearby atomic loads and stores.
808 if (!Subtarget->hasV8Ops()) {
809 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
810 setInsertFencesForAtomic(true);
813 // If there's anything we can use as a barrier, go through custom lowering
815 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
816 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
818 // Set them all for expansion, which will force libcalls.
819 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
820 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
821 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
822 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
823 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
824 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
825 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
826 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
827 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
828 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
829 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
830 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
831 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
832 // Unordered/Monotonic case.
833 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
834 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
837 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
839 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
840 if (!Subtarget->hasV6Ops()) {
841 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
842 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
844 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
846 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
847 !Subtarget->isThumb1Only()) {
848 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
849 // iff target supports vfp2.
850 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
851 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
854 // We want to custom lower some of our intrinsics.
855 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
856 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
857 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
858 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
859 if (Subtarget->isTargetDarwin())
860 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
862 setOperationAction(ISD::SETCC, MVT::i32, Expand);
863 setOperationAction(ISD::SETCC, MVT::f32, Expand);
864 setOperationAction(ISD::SETCC, MVT::f64, Expand);
865 setOperationAction(ISD::SELECT, MVT::i32, Custom);
866 setOperationAction(ISD::SELECT, MVT::f32, Custom);
867 setOperationAction(ISD::SELECT, MVT::f64, Custom);
868 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
869 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
870 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
872 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
873 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
874 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
875 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
876 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
878 // We don't support sin/cos/fmod/copysign/pow
879 setOperationAction(ISD::FSIN, MVT::f64, Expand);
880 setOperationAction(ISD::FSIN, MVT::f32, Expand);
881 setOperationAction(ISD::FCOS, MVT::f32, Expand);
882 setOperationAction(ISD::FCOS, MVT::f64, Expand);
883 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
884 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
885 setOperationAction(ISD::FREM, MVT::f64, Expand);
886 setOperationAction(ISD::FREM, MVT::f32, Expand);
887 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
888 !Subtarget->isThumb1Only()) {
889 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
890 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
892 setOperationAction(ISD::FPOW, MVT::f64, Expand);
893 setOperationAction(ISD::FPOW, MVT::f32, Expand);
895 if (!Subtarget->hasVFP4()) {
896 setOperationAction(ISD::FMA, MVT::f64, Expand);
897 setOperationAction(ISD::FMA, MVT::f32, Expand);
900 // Various VFP goodness
901 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
902 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
903 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
904 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
905 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
908 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
909 if (!Subtarget->hasFP16()) {
910 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
911 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
915 // Combine sin / cos into one node or libcall if possible.
916 if (Subtarget->hasSinCos()) {
917 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
918 setLibcallName(RTLIB::SINCOS_F64, "sincos");
919 if (Subtarget->getTargetTriple().isiOS()) {
920 // For iOS, we don't want to the normal expansion of a libcall to
921 // sincos. We want to issue a libcall to __sincos_stret.
922 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
923 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
927 // FP-ARMv8 implements a lot of rounding-like FP operations.
928 if (Subtarget->hasFPARMv8()) {
929 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
930 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
931 setOperationAction(ISD::FROUND, MVT::f32, Legal);
932 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
933 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
934 setOperationAction(ISD::FRINT, MVT::f32, Legal);
935 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
936 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
937 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
938 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
939 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
940 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
942 if (!Subtarget->isFPOnlySP()) {
943 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
944 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
945 setOperationAction(ISD::FROUND, MVT::f64, Legal);
946 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
947 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
948 setOperationAction(ISD::FRINT, MVT::f64, Legal);
949 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
950 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
954 if (Subtarget->hasVFP3()) {
955 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
956 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
958 if (Subtarget->hasNEON()) {
959 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
960 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
961 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
962 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
965 // We have target-specific dag combine patterns for the following nodes:
966 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
967 setTargetDAGCombine(ISD::ADD);
968 setTargetDAGCombine(ISD::SUB);
969 setTargetDAGCombine(ISD::MUL);
970 setTargetDAGCombine(ISD::AND);
971 setTargetDAGCombine(ISD::OR);
972 setTargetDAGCombine(ISD::XOR);
974 if (Subtarget->hasV6Ops())
975 setTargetDAGCombine(ISD::SRL);
977 setStackPointerRegisterToSaveRestore(ARM::SP);
979 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
980 !Subtarget->hasVFP2())
981 setSchedulingPreference(Sched::RegPressure);
983 setSchedulingPreference(Sched::Hybrid);
985 //// temporary - rewrite interface to use type
986 MaxStoresPerMemset = 8;
987 MaxStoresPerMemsetOptSize = 4;
988 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
989 MaxStoresPerMemcpyOptSize = 2;
990 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
991 MaxStoresPerMemmoveOptSize = 2;
993 // On ARM arguments smaller than 4 bytes are extended, so all arguments
994 // are at least 4 bytes aligned.
995 setMinStackArgumentAlignment(4);
997 // Prefer likely predicted branches to selects on out-of-order cores.
998 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1000 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1003 bool ARMTargetLowering::useSoftFloat() const {
1004 return Subtarget->useSoftFloat();
1007 // FIXME: It might make sense to define the representative register class as the
1008 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1009 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1010 // SPR's representative would be DPR_VFP2. This should work well if register
1011 // pressure tracking were modified such that a register use would increment the
1012 // pressure of the register class's representative and all of it's super
1013 // classes' representatives transitively. We have not implemented this because
1014 // of the difficulty prior to coalescing of modeling operand register classes
1015 // due to the common occurrence of cross class copies and subregister insertions
1017 std::pair<const TargetRegisterClass *, uint8_t>
1018 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1020 const TargetRegisterClass *RRC = nullptr;
1022 switch (VT.SimpleTy) {
1024 return TargetLowering::findRepresentativeClass(TRI, VT);
1025 // Use DPR as representative register class for all floating point
1026 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1027 // the cost is 1 for both f32 and f64.
1028 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1029 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1030 RRC = &ARM::DPRRegClass;
1031 // When NEON is used for SP, only half of the register file is available
1032 // because operations that define both SP and DP results will be constrained
1033 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1034 // coalescing by double-counting the SP regs. See the FIXME above.
1035 if (Subtarget->useNEONForSinglePrecisionFP())
1038 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1039 case MVT::v4f32: case MVT::v2f64:
1040 RRC = &ARM::DPRRegClass;
1044 RRC = &ARM::DPRRegClass;
1048 RRC = &ARM::DPRRegClass;
1052 return std::make_pair(RRC, Cost);
1055 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1056 switch ((ARMISD::NodeType)Opcode) {
1057 case ARMISD::FIRST_NUMBER: break;
1058 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1059 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1060 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1061 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1062 case ARMISD::CALL: return "ARMISD::CALL";
1063 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1064 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1065 case ARMISD::tCALL: return "ARMISD::tCALL";
1066 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1067 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1068 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1069 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1070 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1071 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1072 case ARMISD::CMP: return "ARMISD::CMP";
1073 case ARMISD::CMN: return "ARMISD::CMN";
1074 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1075 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1076 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1077 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1078 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1080 case ARMISD::CMOV: return "ARMISD::CMOV";
1082 case ARMISD::RBIT: return "ARMISD::RBIT";
1084 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1085 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1086 case ARMISD::RRX: return "ARMISD::RRX";
1088 case ARMISD::ADDC: return "ARMISD::ADDC";
1089 case ARMISD::ADDE: return "ARMISD::ADDE";
1090 case ARMISD::SUBC: return "ARMISD::SUBC";
1091 case ARMISD::SUBE: return "ARMISD::SUBE";
1093 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1094 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1096 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1097 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1098 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1100 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1102 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1104 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1106 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1108 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1110 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1112 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1113 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1114 case ARMISD::VCGE: return "ARMISD::VCGE";
1115 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1116 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1117 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1118 case ARMISD::VCGT: return "ARMISD::VCGT";
1119 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1120 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1121 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1122 case ARMISD::VTST: return "ARMISD::VTST";
1124 case ARMISD::VSHL: return "ARMISD::VSHL";
1125 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1126 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1127 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1128 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1129 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1130 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1131 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1132 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1133 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1134 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1135 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1136 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1137 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1138 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1139 case ARMISD::VSLI: return "ARMISD::VSLI";
1140 case ARMISD::VSRI: return "ARMISD::VSRI";
1141 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1142 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1143 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1144 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1145 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1146 case ARMISD::VDUP: return "ARMISD::VDUP";
1147 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1148 case ARMISD::VEXT: return "ARMISD::VEXT";
1149 case ARMISD::VREV64: return "ARMISD::VREV64";
1150 case ARMISD::VREV32: return "ARMISD::VREV32";
1151 case ARMISD::VREV16: return "ARMISD::VREV16";
1152 case ARMISD::VZIP: return "ARMISD::VZIP";
1153 case ARMISD::VUZP: return "ARMISD::VUZP";
1154 case ARMISD::VTRN: return "ARMISD::VTRN";
1155 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1156 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1157 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1158 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1159 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1160 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1161 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1162 case ARMISD::BFI: return "ARMISD::BFI";
1163 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1164 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1165 case ARMISD::VBSL: return "ARMISD::VBSL";
1166 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1167 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1168 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1169 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1170 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1171 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1172 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1173 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1174 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1175 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1176 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1177 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1178 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1179 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1180 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1181 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1182 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1183 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1184 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1185 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1190 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1193 return getPointerTy(DL);
1194 return VT.changeVectorElementTypeToInteger();
1197 /// getRegClassFor - Return the register class that should be used for the
1198 /// specified value type.
1199 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1200 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1201 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1202 // load / store 4 to 8 consecutive D registers.
1203 if (Subtarget->hasNEON()) {
1204 if (VT == MVT::v4i64)
1205 return &ARM::QQPRRegClass;
1206 if (VT == MVT::v8i64)
1207 return &ARM::QQQQPRRegClass;
1209 return TargetLowering::getRegClassFor(VT);
1212 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1213 // source/dest is aligned and the copy size is large enough. We therefore want
1214 // to align such objects passed to memory intrinsics.
1215 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1216 unsigned &PrefAlign) const {
1217 if (!isa<MemIntrinsic>(CI))
1220 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1221 // cycle faster than 4-byte aligned LDM.
1222 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1226 // Create a fast isel object.
1228 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1229 const TargetLibraryInfo *libInfo) const {
1230 return ARM::createFastISel(funcInfo, libInfo);
1233 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1234 unsigned NumVals = N->getNumValues();
1236 return Sched::RegPressure;
1238 for (unsigned i = 0; i != NumVals; ++i) {
1239 EVT VT = N->getValueType(i);
1240 if (VT == MVT::Glue || VT == MVT::Other)
1242 if (VT.isFloatingPoint() || VT.isVector())
1246 if (!N->isMachineOpcode())
1247 return Sched::RegPressure;
1249 // Load are scheduled for latency even if there instruction itinerary
1250 // is not available.
1251 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1252 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1254 if (MCID.getNumDefs() == 0)
1255 return Sched::RegPressure;
1256 if (!Itins->isEmpty() &&
1257 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1260 return Sched::RegPressure;
1263 //===----------------------------------------------------------------------===//
1265 //===----------------------------------------------------------------------===//
1267 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1268 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1270 default: llvm_unreachable("Unknown condition code!");
1271 case ISD::SETNE: return ARMCC::NE;
1272 case ISD::SETEQ: return ARMCC::EQ;
1273 case ISD::SETGT: return ARMCC::GT;
1274 case ISD::SETGE: return ARMCC::GE;
1275 case ISD::SETLT: return ARMCC::LT;
1276 case ISD::SETLE: return ARMCC::LE;
1277 case ISD::SETUGT: return ARMCC::HI;
1278 case ISD::SETUGE: return ARMCC::HS;
1279 case ISD::SETULT: return ARMCC::LO;
1280 case ISD::SETULE: return ARMCC::LS;
1284 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1285 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1286 ARMCC::CondCodes &CondCode2) {
1287 CondCode2 = ARMCC::AL;
1289 default: llvm_unreachable("Unknown FP condition!");
1291 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1293 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1295 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1296 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1297 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1298 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1299 case ISD::SETO: CondCode = ARMCC::VC; break;
1300 case ISD::SETUO: CondCode = ARMCC::VS; break;
1301 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1302 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1303 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1305 case ISD::SETULT: CondCode = ARMCC::LT; break;
1307 case ISD::SETULE: CondCode = ARMCC::LE; break;
1309 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1313 //===----------------------------------------------------------------------===//
1314 // Calling Convention Implementation
1315 //===----------------------------------------------------------------------===//
1317 #include "ARMGenCallingConv.inc"
1319 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1320 /// account presence of floating point hardware and calling convention
1321 /// limitations, such as support for variadic functions.
1323 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1324 bool isVarArg) const {
1327 llvm_unreachable("Unsupported calling convention");
1328 case CallingConv::ARM_AAPCS:
1329 case CallingConv::ARM_APCS:
1330 case CallingConv::GHC:
1332 case CallingConv::ARM_AAPCS_VFP:
1333 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1334 case CallingConv::C:
1335 if (!Subtarget->isAAPCS_ABI())
1336 return CallingConv::ARM_APCS;
1337 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1338 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1340 return CallingConv::ARM_AAPCS_VFP;
1342 return CallingConv::ARM_AAPCS;
1343 case CallingConv::Fast:
1344 if (!Subtarget->isAAPCS_ABI()) {
1345 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1346 return CallingConv::Fast;
1347 return CallingConv::ARM_APCS;
1348 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1349 return CallingConv::ARM_AAPCS_VFP;
1351 return CallingConv::ARM_AAPCS;
1355 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1356 /// CallingConvention.
1357 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1359 bool isVarArg) const {
1360 switch (getEffectiveCallingConv(CC, isVarArg)) {
1362 llvm_unreachable("Unsupported calling convention");
1363 case CallingConv::ARM_APCS:
1364 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1365 case CallingConv::ARM_AAPCS:
1366 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1367 case CallingConv::ARM_AAPCS_VFP:
1368 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1369 case CallingConv::Fast:
1370 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1371 case CallingConv::GHC:
1372 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1376 /// LowerCallResult - Lower the result values of a call into the
1377 /// appropriate copies out of appropriate physical registers.
1379 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1380 CallingConv::ID CallConv, bool isVarArg,
1381 const SmallVectorImpl<ISD::InputArg> &Ins,
1382 SDLoc dl, SelectionDAG &DAG,
1383 SmallVectorImpl<SDValue> &InVals,
1384 bool isThisReturn, SDValue ThisVal) const {
1386 // Assign locations to each value returned by this call.
1387 SmallVector<CCValAssign, 16> RVLocs;
1388 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1389 *DAG.getContext(), Call);
1390 CCInfo.AnalyzeCallResult(Ins,
1391 CCAssignFnForNode(CallConv, /* Return*/ true,
1394 // Copy all of the result registers out of their specified physreg.
1395 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1396 CCValAssign VA = RVLocs[i];
1398 // Pass 'this' value directly from the argument to return value, to avoid
1399 // reg unit interference
1400 if (i == 0 && isThisReturn) {
1401 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1402 "unexpected return calling convention register assignment");
1403 InVals.push_back(ThisVal);
1408 if (VA.needsCustom()) {
1409 // Handle f64 or half of a v2f64.
1410 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1412 Chain = Lo.getValue(1);
1413 InFlag = Lo.getValue(2);
1414 VA = RVLocs[++i]; // skip ahead to next loc
1415 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1417 Chain = Hi.getValue(1);
1418 InFlag = Hi.getValue(2);
1419 if (!Subtarget->isLittle())
1421 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1423 if (VA.getLocVT() == MVT::v2f64) {
1424 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1425 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1426 DAG.getConstant(0, dl, MVT::i32));
1428 VA = RVLocs[++i]; // skip ahead to next loc
1429 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1430 Chain = Lo.getValue(1);
1431 InFlag = Lo.getValue(2);
1432 VA = RVLocs[++i]; // skip ahead to next loc
1433 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1434 Chain = Hi.getValue(1);
1435 InFlag = Hi.getValue(2);
1436 if (!Subtarget->isLittle())
1438 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1439 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1440 DAG.getConstant(1, dl, MVT::i32));
1443 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1445 Chain = Val.getValue(1);
1446 InFlag = Val.getValue(2);
1449 switch (VA.getLocInfo()) {
1450 default: llvm_unreachable("Unknown loc info!");
1451 case CCValAssign::Full: break;
1452 case CCValAssign::BCvt:
1453 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1457 InVals.push_back(Val);
1463 /// LowerMemOpCallTo - Store the argument to the stack.
1465 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1466 SDValue StackPtr, SDValue Arg,
1467 SDLoc dl, SelectionDAG &DAG,
1468 const CCValAssign &VA,
1469 ISD::ArgFlagsTy Flags) const {
1470 unsigned LocMemOffset = VA.getLocMemOffset();
1471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1474 return DAG.getStore(
1475 Chain, dl, Arg, PtrOff,
1476 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1480 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1481 SDValue Chain, SDValue &Arg,
1482 RegsToPassVector &RegsToPass,
1483 CCValAssign &VA, CCValAssign &NextVA,
1485 SmallVectorImpl<SDValue> &MemOpChains,
1486 ISD::ArgFlagsTy Flags) const {
1488 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1489 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1490 unsigned id = Subtarget->isLittle() ? 0 : 1;
1491 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1493 if (NextVA.isRegLoc())
1494 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1496 assert(NextVA.isMemLoc());
1497 if (!StackPtr.getNode())
1498 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1499 getPointerTy(DAG.getDataLayout()));
1501 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1507 /// LowerCall - Lowering a call into a callseq_start <-
1508 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1511 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1512 SmallVectorImpl<SDValue> &InVals) const {
1513 SelectionDAG &DAG = CLI.DAG;
1515 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1516 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1517 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1518 SDValue Chain = CLI.Chain;
1519 SDValue Callee = CLI.Callee;
1520 bool &isTailCall = CLI.IsTailCall;
1521 CallingConv::ID CallConv = CLI.CallConv;
1522 bool doesNotRet = CLI.DoesNotReturn;
1523 bool isVarArg = CLI.IsVarArg;
1525 MachineFunction &MF = DAG.getMachineFunction();
1526 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1527 bool isThisReturn = false;
1528 bool isSibCall = false;
1529 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1531 // Disable tail calls if they're not supported.
1532 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1536 // Check if it's really possible to do a tail call.
1537 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1538 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1539 Outs, OutVals, Ins, DAG);
1540 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1541 report_fatal_error("failed to perform tail call elimination on a call "
1542 "site marked musttail");
1543 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1544 // detected sibcalls.
1551 // Analyze operands of the call, assigning locations to each operand.
1552 SmallVector<CCValAssign, 16> ArgLocs;
1553 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1554 *DAG.getContext(), Call);
1555 CCInfo.AnalyzeCallOperands(Outs,
1556 CCAssignFnForNode(CallConv, /* Return*/ false,
1559 // Get a count of how many bytes are to be pushed on the stack.
1560 unsigned NumBytes = CCInfo.getNextStackOffset();
1562 // For tail calls, memory operands are available in our caller's stack.
1566 // Adjust the stack pointer for the new arguments...
1567 // These operations are automatically eliminated by the prolog/epilog pass
1569 Chain = DAG.getCALLSEQ_START(Chain,
1570 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1573 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1575 RegsToPassVector RegsToPass;
1576 SmallVector<SDValue, 8> MemOpChains;
1578 // Walk the register/memloc assignments, inserting copies/loads. In the case
1579 // of tail call optimization, arguments are handled later.
1580 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1582 ++i, ++realArgIdx) {
1583 CCValAssign &VA = ArgLocs[i];
1584 SDValue Arg = OutVals[realArgIdx];
1585 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1586 bool isByVal = Flags.isByVal();
1588 // Promote the value if needed.
1589 switch (VA.getLocInfo()) {
1590 default: llvm_unreachable("Unknown loc info!");
1591 case CCValAssign::Full: break;
1592 case CCValAssign::SExt:
1593 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1595 case CCValAssign::ZExt:
1596 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1598 case CCValAssign::AExt:
1599 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1601 case CCValAssign::BCvt:
1602 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1606 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1607 if (VA.needsCustom()) {
1608 if (VA.getLocVT() == MVT::v2f64) {
1609 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1610 DAG.getConstant(0, dl, MVT::i32));
1611 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1612 DAG.getConstant(1, dl, MVT::i32));
1614 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1615 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1617 VA = ArgLocs[++i]; // skip ahead to next loc
1618 if (VA.isRegLoc()) {
1619 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1620 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1622 assert(VA.isMemLoc());
1624 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1625 dl, DAG, VA, Flags));
1628 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1629 StackPtr, MemOpChains, Flags);
1631 } else if (VA.isRegLoc()) {
1632 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1633 assert(VA.getLocVT() == MVT::i32 &&
1634 "unexpected calling convention register assignment");
1635 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1636 "unexpected use of 'returned'");
1637 isThisReturn = true;
1639 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1640 } else if (isByVal) {
1641 assert(VA.isMemLoc());
1642 unsigned offset = 0;
1644 // True if this byval aggregate will be split between registers
1646 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1647 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1649 if (CurByValIdx < ByValArgsCount) {
1651 unsigned RegBegin, RegEnd;
1652 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1655 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1657 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1658 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1659 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1660 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1661 MachinePointerInfo(),
1662 false, false, false,
1663 DAG.InferPtrAlignment(AddArg));
1664 MemOpChains.push_back(Load.getValue(1));
1665 RegsToPass.push_back(std::make_pair(j, Load));
1668 // If parameter size outsides register area, "offset" value
1669 // helps us to calculate stack slot for remained part properly.
1670 offset = RegEnd - RegBegin;
1672 CCInfo.nextInRegsParam();
1675 if (Flags.getByValSize() > 4*offset) {
1676 auto PtrVT = getPointerTy(DAG.getDataLayout());
1677 unsigned LocMemOffset = VA.getLocMemOffset();
1678 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1679 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1680 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1681 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1682 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1684 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1687 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1688 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1689 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1692 } else if (!isSibCall) {
1693 assert(VA.isMemLoc());
1695 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1696 dl, DAG, VA, Flags));
1700 if (!MemOpChains.empty())
1701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1703 // Build a sequence of copy-to-reg nodes chained together with token chain
1704 // and flag operands which copy the outgoing args into the appropriate regs.
1706 // Tail call byval lowering might overwrite argument registers so in case of
1707 // tail call optimization the copies to registers are lowered later.
1709 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1710 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1711 RegsToPass[i].second, InFlag);
1712 InFlag = Chain.getValue(1);
1715 // For tail calls lower the arguments to the 'real' stack slot.
1717 // Force all the incoming stack arguments to be loaded from the stack
1718 // before any new outgoing arguments are stored to the stack, because the
1719 // outgoing stack slots may alias the incoming argument stack slots, and
1720 // the alias isn't otherwise explicit. This is slightly more conservative
1721 // than necessary, because it means that each store effectively depends
1722 // on every argument instead of just those arguments it would clobber.
1724 // Do not flag preceding copytoreg stuff together with the following stuff.
1726 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1727 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1728 RegsToPass[i].second, InFlag);
1729 InFlag = Chain.getValue(1);
1734 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1735 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1736 // node so that legalize doesn't hack it.
1737 bool isDirect = false;
1738 bool isARMFunc = false;
1739 bool isLocalARMFunc = false;
1740 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1741 auto PtrVt = getPointerTy(DAG.getDataLayout());
1743 if (Subtarget->genLongCalls()) {
1744 assert((Subtarget->isTargetWindows() ||
1745 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1746 "long-calls with non-static relocation model!");
1747 // Handle a global address or an external symbol. If it's not one of
1748 // those, the target's already in a register, so we don't need to do
1750 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1751 const GlobalValue *GV = G->getGlobal();
1752 // Create a constant pool entry for the callee address
1753 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1754 ARMConstantPoolValue *CPV =
1755 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1757 // Get the address of the callee into a register
1758 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1759 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1760 Callee = DAG.getLoad(
1761 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1762 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1764 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1765 const char *Sym = S->getSymbol();
1767 // Create a constant pool entry for the callee address
1768 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1769 ARMConstantPoolValue *CPV =
1770 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1771 ARMPCLabelIndex, 0);
1772 // Get the address of the callee into a register
1773 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1774 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775 Callee = DAG.getLoad(
1776 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1777 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1780 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1781 const GlobalValue *GV = G->getGlobal();
1783 bool isDef = GV->isStrongDefinitionForLinker();
1784 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1785 getTargetMachine().getRelocationModel() != Reloc::Static;
1786 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1787 // ARM call to a local ARM function is predicable.
1788 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1789 // tBX takes a register source operand.
1790 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1791 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1792 Callee = DAG.getNode(
1793 ARMISD::WrapperPIC, dl, PtrVt,
1794 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1795 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1796 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1797 false, false, true, 0);
1798 } else if (Subtarget->isTargetCOFF()) {
1799 assert(Subtarget->isTargetWindows() &&
1800 "Windows is the only supported COFF target");
1801 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1802 ? ARMII::MO_DLLIMPORT
1803 : ARMII::MO_NO_FLAG;
1805 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1806 if (GV->hasDLLImportStorageClass())
1808 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1809 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1810 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1811 false, false, false, 0);
1813 // On ELF targets for PIC code, direct calls should go through the PLT
1814 unsigned OpFlags = 0;
1815 if (Subtarget->isTargetELF() &&
1816 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1817 OpFlags = ARMII::MO_PLT;
1818 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1820 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1822 bool isStub = Subtarget->isTargetMachO() &&
1823 getTargetMachine().getRelocationModel() != Reloc::Static;
1824 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1825 // tBX takes a register source operand.
1826 const char *Sym = S->getSymbol();
1827 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1828 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1829 ARMConstantPoolValue *CPV =
1830 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1831 ARMPCLabelIndex, 4);
1832 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1833 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1834 Callee = DAG.getLoad(
1835 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1836 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1838 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1839 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1841 unsigned OpFlags = 0;
1842 // On ELF targets for PIC code, direct calls should go through the PLT
1843 if (Subtarget->isTargetELF() &&
1844 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1845 OpFlags = ARMII::MO_PLT;
1846 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1850 // FIXME: handle tail calls differently.
1852 if (Subtarget->isThumb()) {
1853 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1854 CallOpc = ARMISD::CALL_NOLINK;
1856 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1858 if (!isDirect && !Subtarget->hasV5TOps())
1859 CallOpc = ARMISD::CALL_NOLINK;
1860 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1861 // Emit regular call when code size is the priority
1862 !MF.getFunction()->optForMinSize())
1863 // "mov lr, pc; b _foo" to avoid confusing the RSP
1864 CallOpc = ARMISD::CALL_NOLINK;
1866 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1869 std::vector<SDValue> Ops;
1870 Ops.push_back(Chain);
1871 Ops.push_back(Callee);
1873 // Add argument registers to the end of the list so that they are known live
1875 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1876 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1877 RegsToPass[i].second.getValueType()));
1879 // Add a register mask operand representing the call-preserved registers.
1881 const uint32_t *Mask;
1882 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1884 // For 'this' returns, use the R0-preserving mask if applicable
1885 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1887 // Set isThisReturn to false if the calling convention is not one that
1888 // allows 'returned' to be modeled in this way, so LowerCallResult does
1889 // not try to pass 'this' straight through
1890 isThisReturn = false;
1891 Mask = ARI->getCallPreservedMask(MF, CallConv);
1894 Mask = ARI->getCallPreservedMask(MF, CallConv);
1896 assert(Mask && "Missing call preserved mask for calling convention");
1897 Ops.push_back(DAG.getRegisterMask(Mask));
1900 if (InFlag.getNode())
1901 Ops.push_back(InFlag);
1903 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1905 MF.getFrameInfo()->setHasTailCall();
1906 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1909 // Returns a chain and a flag for retval copy to use.
1910 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1911 InFlag = Chain.getValue(1);
1913 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1914 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1916 InFlag = Chain.getValue(1);
1918 // Handle result values, copying them out of physregs into vregs that we
1920 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1921 InVals, isThisReturn,
1922 isThisReturn ? OutVals[0] : SDValue());
1925 /// HandleByVal - Every parameter *after* a byval parameter is passed
1926 /// on the stack. Remember the next parameter register to allocate,
1927 /// and then confiscate the rest of the parameter registers to insure
1929 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1930 unsigned Align) const {
1931 assert((State->getCallOrPrologue() == Prologue ||
1932 State->getCallOrPrologue() == Call) &&
1933 "unhandled ParmContext");
1935 // Byval (as with any stack) slots are always at least 4 byte aligned.
1936 Align = std::max(Align, 4U);
1938 unsigned Reg = State->AllocateReg(GPRArgRegs);
1942 unsigned AlignInRegs = Align / 4;
1943 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1944 for (unsigned i = 0; i < Waste; ++i)
1945 Reg = State->AllocateReg(GPRArgRegs);
1950 unsigned Excess = 4 * (ARM::R4 - Reg);
1952 // Special case when NSAA != SP and parameter size greater than size of
1953 // all remained GPR regs. In that case we can't split parameter, we must
1954 // send it to stack. We also must set NCRN to R4, so waste all
1955 // remained registers.
1956 const unsigned NSAAOffset = State->getNextStackOffset();
1957 if (NSAAOffset != 0 && Size > Excess) {
1958 while (State->AllocateReg(GPRArgRegs))
1963 // First register for byval parameter is the first register that wasn't
1964 // allocated before this method call, so it would be "reg".
1965 // If parameter is small enough to be saved in range [reg, r4), then
1966 // the end (first after last) register would be reg + param-size-in-regs,
1967 // else parameter would be splitted between registers and stack,
1968 // end register would be r4 in this case.
1969 unsigned ByValRegBegin = Reg;
1970 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1971 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1972 // Note, first register is allocated in the beginning of function already,
1973 // allocate remained amount of registers we need.
1974 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1975 State->AllocateReg(GPRArgRegs);
1976 // A byval parameter that is split between registers and memory needs its
1977 // size truncated here.
1978 // In the case where the entire structure fits in registers, we set the
1979 // size in memory to zero.
1980 Size = std::max<int>(Size - Excess, 0);
1983 /// MatchingStackOffset - Return true if the given stack call argument is
1984 /// already available in the same position (relatively) of the caller's
1985 /// incoming argument stack.
1987 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1988 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1989 const TargetInstrInfo *TII) {
1990 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1992 if (Arg.getOpcode() == ISD::CopyFromReg) {
1993 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1994 if (!TargetRegisterInfo::isVirtualRegister(VR))
1996 MachineInstr *Def = MRI->getVRegDef(VR);
1999 if (!Flags.isByVal()) {
2000 if (!TII->isLoadFromStackSlot(Def, FI))
2005 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2006 if (Flags.isByVal())
2007 // ByVal argument is passed in as a pointer but it's now being
2008 // dereferenced. e.g.
2009 // define @foo(%struct.X* %A) {
2010 // tail call @bar(%struct.X* byval %A)
2013 SDValue Ptr = Ld->getBasePtr();
2014 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2017 FI = FINode->getIndex();
2021 assert(FI != INT_MAX);
2022 if (!MFI->isFixedObjectIndex(FI))
2024 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2027 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2028 /// for tail call optimization. Targets which want to do tail call
2029 /// optimization should implement this function.
2031 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2032 CallingConv::ID CalleeCC,
2034 bool isCalleeStructRet,
2035 bool isCallerStructRet,
2036 const SmallVectorImpl<ISD::OutputArg> &Outs,
2037 const SmallVectorImpl<SDValue> &OutVals,
2038 const SmallVectorImpl<ISD::InputArg> &Ins,
2039 SelectionDAG& DAG) const {
2040 const Function *CallerF = DAG.getMachineFunction().getFunction();
2041 CallingConv::ID CallerCC = CallerF->getCallingConv();
2042 bool CCMatch = CallerCC == CalleeCC;
2044 // Look for obvious safe cases to perform tail call optimization that do not
2045 // require ABI changes. This is what gcc calls sibcall.
2047 // Do not sibcall optimize vararg calls unless the call site is not passing
2049 if (isVarArg && !Outs.empty())
2052 // Exception-handling functions need a special set of instructions to indicate
2053 // a return to the hardware. Tail-calling another function would probably
2055 if (CallerF->hasFnAttribute("interrupt"))
2058 // Also avoid sibcall optimization if either caller or callee uses struct
2059 // return semantics.
2060 if (isCalleeStructRet || isCallerStructRet)
2063 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2064 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2065 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2066 // support in the assembler and linker to be used. This would need to be
2067 // fixed to fully support tail calls in Thumb1.
2069 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2070 // LR. This means if we need to reload LR, it takes an extra instructions,
2071 // which outweighs the value of the tail call; but here we don't know yet
2072 // whether LR is going to be used. Probably the right approach is to
2073 // generate the tail call here and turn it back into CALL/RET in
2074 // emitEpilogue if LR is used.
2076 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2077 // but we need to make sure there are enough registers; the only valid
2078 // registers are the 4 used for parameters. We don't currently do this
2080 if (Subtarget->isThumb1Only())
2083 // Externally-defined functions with weak linkage should not be
2084 // tail-called on ARM when the OS does not support dynamic
2085 // pre-emption of symbols, as the AAELF spec requires normal calls
2086 // to undefined weak functions to be replaced with a NOP or jump to the
2087 // next instruction. The behaviour of branch instructions in this
2088 // situation (as used for tail calls) is implementation-defined, so we
2089 // cannot rely on the linker replacing the tail call with a return.
2090 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2091 const GlobalValue *GV = G->getGlobal();
2092 const Triple &TT = getTargetMachine().getTargetTriple();
2093 if (GV->hasExternalWeakLinkage() &&
2094 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2098 // If the calling conventions do not match, then we'd better make sure the
2099 // results are returned in the same way as what the caller expects.
2101 SmallVector<CCValAssign, 16> RVLocs1;
2102 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2103 *DAG.getContext(), Call);
2104 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2106 SmallVector<CCValAssign, 16> RVLocs2;
2107 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2108 *DAG.getContext(), Call);
2109 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2111 if (RVLocs1.size() != RVLocs2.size())
2113 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2114 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2116 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2118 if (RVLocs1[i].isRegLoc()) {
2119 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2122 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2128 // If Caller's vararg or byval argument has been split between registers and
2129 // stack, do not perform tail call, since part of the argument is in caller's
2131 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2132 getInfo<ARMFunctionInfo>();
2133 if (AFI_Caller->getArgRegsSaveSize())
2136 // If the callee takes no arguments then go on to check the results of the
2138 if (!Outs.empty()) {
2139 // Check if stack adjustment is needed. For now, do not do this if any
2140 // argument is passed on the stack.
2141 SmallVector<CCValAssign, 16> ArgLocs;
2142 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2143 *DAG.getContext(), Call);
2144 CCInfo.AnalyzeCallOperands(Outs,
2145 CCAssignFnForNode(CalleeCC, false, isVarArg));
2146 if (CCInfo.getNextStackOffset()) {
2147 MachineFunction &MF = DAG.getMachineFunction();
2149 // Check if the arguments are already laid out in the right way as
2150 // the caller's fixed stack objects.
2151 MachineFrameInfo *MFI = MF.getFrameInfo();
2152 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2153 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2154 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2156 ++i, ++realArgIdx) {
2157 CCValAssign &VA = ArgLocs[i];
2158 EVT RegVT = VA.getLocVT();
2159 SDValue Arg = OutVals[realArgIdx];
2160 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2161 if (VA.getLocInfo() == CCValAssign::Indirect)
2163 if (VA.needsCustom()) {
2164 // f64 and vector types are split into multiple registers or
2165 // register/stack-slot combinations. The types will not match
2166 // the registers; give up on memory f64 refs until we figure
2167 // out what to do about this.
2170 if (!ArgLocs[++i].isRegLoc())
2172 if (RegVT == MVT::v2f64) {
2173 if (!ArgLocs[++i].isRegLoc())
2175 if (!ArgLocs[++i].isRegLoc())
2178 } else if (!VA.isRegLoc()) {
2179 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2191 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2192 MachineFunction &MF, bool isVarArg,
2193 const SmallVectorImpl<ISD::OutputArg> &Outs,
2194 LLVMContext &Context) const {
2195 SmallVector<CCValAssign, 16> RVLocs;
2196 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2197 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2201 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2202 SDLoc DL, SelectionDAG &DAG) {
2203 const MachineFunction &MF = DAG.getMachineFunction();
2204 const Function *F = MF.getFunction();
2206 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2208 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2209 // version of the "preferred return address". These offsets affect the return
2210 // instruction if this is a return from PL1 without hypervisor extensions.
2211 // IRQ/FIQ: +4 "subs pc, lr, #4"
2212 // SWI: 0 "subs pc, lr, #0"
2213 // ABORT: +4 "subs pc, lr, #4"
2214 // UNDEF: +4/+2 "subs pc, lr, #0"
2215 // UNDEF varies depending on where the exception came from ARM or Thumb
2216 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2219 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2222 else if (IntKind == "SWI" || IntKind == "UNDEF")
2225 report_fatal_error("Unsupported interrupt attribute. If present, value "
2226 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2228 RetOps.insert(RetOps.begin() + 1,
2229 DAG.getConstant(LROffset, DL, MVT::i32, false));
2231 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2235 ARMTargetLowering::LowerReturn(SDValue Chain,
2236 CallingConv::ID CallConv, bool isVarArg,
2237 const SmallVectorImpl<ISD::OutputArg> &Outs,
2238 const SmallVectorImpl<SDValue> &OutVals,
2239 SDLoc dl, SelectionDAG &DAG) const {
2241 // CCValAssign - represent the assignment of the return value to a location.
2242 SmallVector<CCValAssign, 16> RVLocs;
2244 // CCState - Info about the registers and stack slots.
2245 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2246 *DAG.getContext(), Call);
2248 // Analyze outgoing return values.
2249 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2253 SmallVector<SDValue, 4> RetOps;
2254 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2255 bool isLittleEndian = Subtarget->isLittle();
2257 MachineFunction &MF = DAG.getMachineFunction();
2258 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2259 AFI->setReturnRegsCount(RVLocs.size());
2261 // Copy the result values into the output registers.
2262 for (unsigned i = 0, realRVLocIdx = 0;
2264 ++i, ++realRVLocIdx) {
2265 CCValAssign &VA = RVLocs[i];
2266 assert(VA.isRegLoc() && "Can only return in registers!");
2268 SDValue Arg = OutVals[realRVLocIdx];
2270 switch (VA.getLocInfo()) {
2271 default: llvm_unreachable("Unknown loc info!");
2272 case CCValAssign::Full: break;
2273 case CCValAssign::BCvt:
2274 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2278 if (VA.needsCustom()) {
2279 if (VA.getLocVT() == MVT::v2f64) {
2280 // Extract the first half and return it in two registers.
2281 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2282 DAG.getConstant(0, dl, MVT::i32));
2283 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2284 DAG.getVTList(MVT::i32, MVT::i32), Half);
2286 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2287 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2289 Flag = Chain.getValue(1);
2290 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2291 VA = RVLocs[++i]; // skip ahead to next loc
2292 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2293 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2295 Flag = Chain.getValue(1);
2296 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2297 VA = RVLocs[++i]; // skip ahead to next loc
2299 // Extract the 2nd half and fall through to handle it as an f64 value.
2300 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2301 DAG.getConstant(1, dl, MVT::i32));
2303 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2305 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2306 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2307 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2308 fmrrd.getValue(isLittleEndian ? 0 : 1),
2310 Flag = Chain.getValue(1);
2311 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2312 VA = RVLocs[++i]; // skip ahead to next loc
2313 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2314 fmrrd.getValue(isLittleEndian ? 1 : 0),
2317 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2319 // Guarantee that all emitted copies are
2320 // stuck together, avoiding something bad.
2321 Flag = Chain.getValue(1);
2322 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2325 // Update chain and glue.
2328 RetOps.push_back(Flag);
2330 // CPUs which aren't M-class use a special sequence to return from
2331 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2332 // though we use "subs pc, lr, #N").
2334 // M-class CPUs actually use a normal return sequence with a special
2335 // (hardware-provided) value in LR, so the normal code path works.
2336 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2337 !Subtarget->isMClass()) {
2338 if (Subtarget->isThumb1Only())
2339 report_fatal_error("interrupt attribute is not supported in Thumb1");
2340 return LowerInterruptReturn(RetOps, dl, DAG);
2343 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2346 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2347 if (N->getNumValues() != 1)
2349 if (!N->hasNUsesOfValue(1, 0))
2352 SDValue TCChain = Chain;
2353 SDNode *Copy = *N->use_begin();
2354 if (Copy->getOpcode() == ISD::CopyToReg) {
2355 // If the copy has a glue operand, we conservatively assume it isn't safe to
2356 // perform a tail call.
2357 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2359 TCChain = Copy->getOperand(0);
2360 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2361 SDNode *VMov = Copy;
2362 // f64 returned in a pair of GPRs.
2363 SmallPtrSet<SDNode*, 2> Copies;
2364 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2366 if (UI->getOpcode() != ISD::CopyToReg)
2370 if (Copies.size() > 2)
2373 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2375 SDValue UseChain = UI->getOperand(0);
2376 if (Copies.count(UseChain.getNode()))
2380 // We are at the top of this chain.
2381 // If the copy has a glue operand, we conservatively assume it
2382 // isn't safe to perform a tail call.
2383 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2389 } else if (Copy->getOpcode() == ISD::BITCAST) {
2390 // f32 returned in a single GPR.
2391 if (!Copy->hasOneUse())
2393 Copy = *Copy->use_begin();
2394 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2396 // If the copy has a glue operand, we conservatively assume it isn't safe to
2397 // perform a tail call.
2398 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2400 TCChain = Copy->getOperand(0);
2405 bool HasRet = false;
2406 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2408 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2409 UI->getOpcode() != ARMISD::INTRET_FLAG)
2421 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2422 if (!Subtarget->supportsTailCall())
2426 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2427 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2430 return !Subtarget->isThumb1Only();
2433 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2434 // and pass the lower and high parts through.
2435 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2437 SDValue WriteValue = Op->getOperand(2);
2439 // This function is only supposed to be called for i64 type argument.
2440 assert(WriteValue.getValueType() == MVT::i64
2441 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2443 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2444 DAG.getConstant(0, DL, MVT::i32));
2445 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2446 DAG.getConstant(1, DL, MVT::i32));
2447 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2448 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2451 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2452 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2453 // one of the above mentioned nodes. It has to be wrapped because otherwise
2454 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2455 // be used to form addressing mode. These wrapped nodes will be selected
2457 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2458 EVT PtrVT = Op.getValueType();
2459 // FIXME there is no actual debug info here
2461 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2463 if (CP->isMachineConstantPoolEntry())
2464 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2465 CP->getAlignment());
2467 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2468 CP->getAlignment());
2469 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2472 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2473 return MachineJumpTableInfo::EK_Inline;
2476 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2477 SelectionDAG &DAG) const {
2478 MachineFunction &MF = DAG.getMachineFunction();
2479 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2480 unsigned ARMPCLabelIndex = 0;
2482 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2483 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2484 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2486 if (RelocM == Reloc::Static) {
2487 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2489 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2490 ARMPCLabelIndex = AFI->createPICLabelUId();
2491 ARMConstantPoolValue *CPV =
2492 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2493 ARMCP::CPBlockAddress, PCAdj);
2494 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2496 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2498 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2499 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2500 false, false, false, 0);
2501 if (RelocM == Reloc::Static)
2503 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2504 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2509 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2510 SelectionDAG &DAG) const {
2512 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2513 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2514 MachineFunction &MF = DAG.getMachineFunction();
2515 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2516 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2517 ARMConstantPoolValue *CPV =
2518 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2519 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2520 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2521 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2523 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2524 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2525 false, false, false, 0);
2526 SDValue Chain = Argument.getValue(1);
2528 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2529 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2531 // call __tls_get_addr.
2534 Entry.Node = Argument;
2535 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2536 Args.push_back(Entry);
2538 // FIXME: is there useful debug info available here?
2539 TargetLowering::CallLoweringInfo CLI(DAG);
2540 CLI.setDebugLoc(dl).setChain(Chain)
2541 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2542 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2545 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2546 return CallResult.first;
2549 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2550 // "local exec" model.
2552 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2554 TLSModel::Model model) const {
2555 const GlobalValue *GV = GA->getGlobal();
2558 SDValue Chain = DAG.getEntryNode();
2559 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2560 // Get the Thread Pointer
2561 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2563 if (model == TLSModel::InitialExec) {
2564 MachineFunction &MF = DAG.getMachineFunction();
2565 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2566 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2567 // Initial exec model.
2568 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2569 ARMConstantPoolValue *CPV =
2570 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2571 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2573 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2574 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2575 Offset = DAG.getLoad(
2576 PtrVT, dl, Chain, Offset,
2577 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2579 Chain = Offset.getValue(1);
2581 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2582 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2584 Offset = DAG.getLoad(
2585 PtrVT, dl, Chain, Offset,
2586 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2590 assert(model == TLSModel::LocalExec);
2591 ARMConstantPoolValue *CPV =
2592 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2593 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2594 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2595 Offset = DAG.getLoad(
2596 PtrVT, dl, Chain, Offset,
2597 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2601 // The address of the thread local variable is the add of the thread
2602 // pointer with the offset of the variable.
2603 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2607 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2608 // TODO: implement the "local dynamic" model
2609 assert(Subtarget->isTargetELF() &&
2610 "TLS not implemented for non-ELF targets");
2611 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2612 if (DAG.getTarget().Options.EmulatedTLS)
2613 return LowerToTLSEmulatedModel(GA, DAG);
2615 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2618 case TLSModel::GeneralDynamic:
2619 case TLSModel::LocalDynamic:
2620 return LowerToTLSGeneralDynamicModel(GA, DAG);
2621 case TLSModel::InitialExec:
2622 case TLSModel::LocalExec:
2623 return LowerToTLSExecModels(GA, DAG, model);
2625 llvm_unreachable("bogus TLS model");
2628 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2629 SelectionDAG &DAG) const {
2630 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2632 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2633 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2634 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2635 ARMConstantPoolValue *CPV =
2636 ARMConstantPoolConstant::Create(GV,
2637 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2638 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2639 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2640 SDValue Result = DAG.getLoad(
2641 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2642 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2644 SDValue Chain = Result.getValue(1);
2645 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2646 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2648 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2649 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2650 false, false, false, 0);
2654 // If we have T2 ops, we can materialize the address directly via movt/movw
2655 // pair. This is always cheaper.
2656 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2658 // FIXME: Once remat is capable of dealing with instructions with register
2659 // operands, expand this into two nodes.
2660 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2661 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2663 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2664 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2666 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2667 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2672 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2673 SelectionDAG &DAG) const {
2674 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2676 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2677 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2679 if (Subtarget->useMovt(DAG.getMachineFunction()))
2682 // FIXME: Once remat is capable of dealing with instructions with register
2683 // operands, expand this into multiple nodes
2685 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2687 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2688 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2690 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2691 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2692 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2693 false, false, false, 0);
2697 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2698 SelectionDAG &DAG) const {
2699 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2700 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2701 "Windows on ARM expects to use movw/movt");
2703 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2704 const ARMII::TOF TargetFlags =
2705 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2706 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2712 // FIXME: Once remat is capable of dealing with instructions with register
2713 // operands, expand this into two nodes.
2714 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2715 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2717 if (GV->hasDLLImportStorageClass())
2718 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2719 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2720 false, false, false, 0);
2724 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2725 SelectionDAG &DAG) const {
2726 assert(Subtarget->isTargetELF() &&
2727 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2728 MachineFunction &MF = DAG.getMachineFunction();
2729 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2730 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2731 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2733 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2734 ARMConstantPoolValue *CPV =
2735 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2736 ARMPCLabelIndex, PCAdj);
2737 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2738 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2740 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2741 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2742 false, false, false, 0);
2743 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2744 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2748 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2750 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2751 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2752 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2753 Op.getOperand(1), Val);
2757 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2759 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2760 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2763 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2764 SelectionDAG &DAG) const {
2766 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2771 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2772 const ARMSubtarget *Subtarget) const {
2773 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2776 default: return SDValue(); // Don't custom lower most intrinsics.
2777 case Intrinsic::arm_rbit: {
2778 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2779 "RBIT intrinsic must have i32 type!");
2780 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2782 case Intrinsic::arm_thread_pointer: {
2783 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2784 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2786 case Intrinsic::eh_sjlj_lsda: {
2787 MachineFunction &MF = DAG.getMachineFunction();
2788 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2789 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2790 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2791 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2793 unsigned PCAdj = (RelocM != Reloc::PIC_)
2794 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2795 ARMConstantPoolValue *CPV =
2796 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2797 ARMCP::CPLSDA, PCAdj);
2798 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2799 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2800 SDValue Result = DAG.getLoad(
2801 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2802 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2805 if (RelocM == Reloc::PIC_) {
2806 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2807 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2811 case Intrinsic::arm_neon_vmulls:
2812 case Intrinsic::arm_neon_vmullu: {
2813 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2814 ? ARMISD::VMULLs : ARMISD::VMULLu;
2815 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2816 Op.getOperand(1), Op.getOperand(2));
2818 case Intrinsic::arm_neon_vminnm:
2819 case Intrinsic::arm_neon_vmaxnm: {
2820 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2821 ? ISD::FMINNUM : ISD::FMAXNUM;
2822 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2823 Op.getOperand(1), Op.getOperand(2));
2825 case Intrinsic::arm_neon_vmins:
2826 case Intrinsic::arm_neon_vmaxs: {
2827 // v{min,max}s is overloaded between signed integers and floats.
2828 if (!Op.getValueType().isFloatingPoint())
2830 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2831 ? ISD::FMINNAN : ISD::FMAXNAN;
2832 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2833 Op.getOperand(1), Op.getOperand(2));
2838 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2839 const ARMSubtarget *Subtarget) {
2840 // FIXME: handle "fence singlethread" more efficiently.
2842 if (!Subtarget->hasDataBarrier()) {
2843 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2844 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2846 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2847 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2848 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2849 DAG.getConstant(0, dl, MVT::i32));
2852 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2853 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2854 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2855 if (Subtarget->isMClass()) {
2856 // Only a full system barrier exists in the M-class architectures.
2857 Domain = ARM_MB::SY;
2858 } else if (Subtarget->isSwift() && Ord == Release) {
2859 // Swift happens to implement ISHST barriers in a way that's compatible with
2860 // Release semantics but weaker than ISH so we'd be fools not to use
2861 // it. Beware: other processors probably don't!
2862 Domain = ARM_MB::ISHST;
2865 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2866 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2867 DAG.getConstant(Domain, dl, MVT::i32));
2870 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2871 const ARMSubtarget *Subtarget) {
2872 // ARM pre v5TE and Thumb1 does not have preload instructions.
2873 if (!(Subtarget->isThumb2() ||
2874 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2875 // Just preserve the chain.
2876 return Op.getOperand(0);
2879 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2881 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2882 // ARMv7 with MP extension has PLDW.
2883 return Op.getOperand(0);
2885 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2886 if (Subtarget->isThumb()) {
2888 isRead = ~isRead & 1;
2889 isData = ~isData & 1;
2892 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2893 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2894 DAG.getConstant(isData, dl, MVT::i32));
2897 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2898 MachineFunction &MF = DAG.getMachineFunction();
2899 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2901 // vastart just stores the address of the VarArgsFrameIndex slot into the
2902 // memory location argument.
2904 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2905 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2906 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2907 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2908 MachinePointerInfo(SV), false, false, 0);
2912 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2913 SDValue &Root, SelectionDAG &DAG,
2915 MachineFunction &MF = DAG.getMachineFunction();
2916 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2918 const TargetRegisterClass *RC;
2919 if (AFI->isThumb1OnlyFunction())
2920 RC = &ARM::tGPRRegClass;
2922 RC = &ARM::GPRRegClass;
2924 // Transform the arguments stored in physical registers into virtual ones.
2925 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2926 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2929 if (NextVA.isMemLoc()) {
2930 MachineFrameInfo *MFI = MF.getFrameInfo();
2931 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2933 // Create load node to retrieve arguments from the stack.
2934 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2935 ArgValue2 = DAG.getLoad(
2936 MVT::i32, dl, Root, FIN,
2937 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2940 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2941 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2943 if (!Subtarget->isLittle())
2944 std::swap (ArgValue, ArgValue2);
2945 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2948 // The remaining GPRs hold either the beginning of variable-argument
2949 // data, or the beginning of an aggregate passed by value (usually
2950 // byval). Either way, we allocate stack slots adjacent to the data
2951 // provided by our caller, and store the unallocated registers there.
2952 // If this is a variadic function, the va_list pointer will begin with
2953 // these values; otherwise, this reassembles a (byval) structure that
2954 // was split between registers and memory.
2955 // Return: The frame index registers were stored into.
2957 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2958 SDLoc dl, SDValue &Chain,
2959 const Value *OrigArg,
2960 unsigned InRegsParamRecordIdx,
2962 unsigned ArgSize) const {
2963 // Currently, two use-cases possible:
2964 // Case #1. Non-var-args function, and we meet first byval parameter.
2965 // Setup first unallocated register as first byval register;
2966 // eat all remained registers
2967 // (these two actions are performed by HandleByVal method).
2968 // Then, here, we initialize stack frame with
2969 // "store-reg" instructions.
2970 // Case #2. Var-args function, that doesn't contain byval parameters.
2971 // The same: eat all remained unallocated registers,
2972 // initialize stack frame.
2974 MachineFunction &MF = DAG.getMachineFunction();
2975 MachineFrameInfo *MFI = MF.getFrameInfo();
2976 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2977 unsigned RBegin, REnd;
2978 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2979 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2981 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2982 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2987 ArgOffset = -4 * (ARM::R4 - RBegin);
2989 auto PtrVT = getPointerTy(DAG.getDataLayout());
2990 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2991 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2993 SmallVector<SDValue, 4> MemOps;
2994 const TargetRegisterClass *RC =
2995 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2997 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2998 unsigned VReg = MF.addLiveIn(Reg, RC);
2999 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3001 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3002 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3003 MemOps.push_back(Store);
3004 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3007 if (!MemOps.empty())
3008 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3012 // Setup stack frame, the va_list pointer will start from.
3014 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3015 SDLoc dl, SDValue &Chain,
3017 unsigned TotalArgRegsSaveSize,
3018 bool ForceMutable) const {
3019 MachineFunction &MF = DAG.getMachineFunction();
3020 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3022 // Try to store any remaining integer argument regs
3023 // to their spots on the stack so that they may be loaded by deferencing
3024 // the result of va_next.
3025 // If there is no regs to be stored, just point address after last
3026 // argument passed via stack.
3027 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3028 CCInfo.getInRegsParamsCount(),
3029 CCInfo.getNextStackOffset(), 4);
3030 AFI->setVarArgsFrameIndex(FrameIndex);
3034 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3035 CallingConv::ID CallConv, bool isVarArg,
3036 const SmallVectorImpl<ISD::InputArg>
3038 SDLoc dl, SelectionDAG &DAG,
3039 SmallVectorImpl<SDValue> &InVals)
3041 MachineFunction &MF = DAG.getMachineFunction();
3042 MachineFrameInfo *MFI = MF.getFrameInfo();
3044 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3046 // Assign locations to all of the incoming arguments.
3047 SmallVector<CCValAssign, 16> ArgLocs;
3048 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3049 *DAG.getContext(), Prologue);
3050 CCInfo.AnalyzeFormalArguments(Ins,
3051 CCAssignFnForNode(CallConv, /* Return*/ false,
3054 SmallVector<SDValue, 16> ArgValues;
3056 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3057 unsigned CurArgIdx = 0;
3059 // Initially ArgRegsSaveSize is zero.
3060 // Then we increase this value each time we meet byval parameter.
3061 // We also increase this value in case of varargs function.
3062 AFI->setArgRegsSaveSize(0);
3064 // Calculate the amount of stack space that we need to allocate to store
3065 // byval and variadic arguments that are passed in registers.
3066 // We need to know this before we allocate the first byval or variadic
3067 // argument, as they will be allocated a stack slot below the CFA (Canonical
3068 // Frame Address, the stack pointer at entry to the function).
3069 unsigned ArgRegBegin = ARM::R4;
3070 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3071 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3074 CCValAssign &VA = ArgLocs[i];
3075 unsigned Index = VA.getValNo();
3076 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3077 if (!Flags.isByVal())
3080 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3081 unsigned RBegin, REnd;
3082 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3083 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3085 CCInfo.nextInRegsParam();
3087 CCInfo.rewindByValRegsInfo();
3089 int lastInsIndex = -1;
3090 if (isVarArg && MFI->hasVAStart()) {
3091 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3092 if (RegIdx != array_lengthof(GPRArgRegs))
3093 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3096 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3097 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3098 auto PtrVT = getPointerTy(DAG.getDataLayout());
3100 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3101 CCValAssign &VA = ArgLocs[i];
3102 if (Ins[VA.getValNo()].isOrigArg()) {
3103 std::advance(CurOrigArg,
3104 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3105 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3107 // Arguments stored in registers.
3108 if (VA.isRegLoc()) {
3109 EVT RegVT = VA.getLocVT();
3111 if (VA.needsCustom()) {
3112 // f64 and vector types are split up into multiple registers or
3113 // combinations of registers and stack slots.
3114 if (VA.getLocVT() == MVT::v2f64) {
3115 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3117 VA = ArgLocs[++i]; // skip ahead to next loc
3119 if (VA.isMemLoc()) {
3120 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3121 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3122 ArgValue2 = DAG.getLoad(
3123 MVT::f64, dl, Chain, FIN,
3124 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3125 false, false, false, 0);
3127 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3130 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3131 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3132 ArgValue, ArgValue1,
3133 DAG.getIntPtrConstant(0, dl));
3134 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3135 ArgValue, ArgValue2,
3136 DAG.getIntPtrConstant(1, dl));
3138 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3141 const TargetRegisterClass *RC;
3143 if (RegVT == MVT::f32)
3144 RC = &ARM::SPRRegClass;
3145 else if (RegVT == MVT::f64)
3146 RC = &ARM::DPRRegClass;
3147 else if (RegVT == MVT::v2f64)
3148 RC = &ARM::QPRRegClass;
3149 else if (RegVT == MVT::i32)
3150 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3151 : &ARM::GPRRegClass;
3153 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3155 // Transform the arguments in physical registers into virtual ones.
3156 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3157 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3160 // If this is an 8 or 16-bit value, it is really passed promoted
3161 // to 32 bits. Insert an assert[sz]ext to capture this, then
3162 // truncate to the right size.
3163 switch (VA.getLocInfo()) {
3164 default: llvm_unreachable("Unknown loc info!");
3165 case CCValAssign::Full: break;
3166 case CCValAssign::BCvt:
3167 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3169 case CCValAssign::SExt:
3170 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3171 DAG.getValueType(VA.getValVT()));
3172 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3174 case CCValAssign::ZExt:
3175 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3176 DAG.getValueType(VA.getValVT()));
3177 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3181 InVals.push_back(ArgValue);
3183 } else { // VA.isRegLoc()
3186 assert(VA.isMemLoc());
3187 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3189 int index = VA.getValNo();
3191 // Some Ins[] entries become multiple ArgLoc[] entries.
3192 // Process them only once.
3193 if (index != lastInsIndex)
3195 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3196 // FIXME: For now, all byval parameter objects are marked mutable.
3197 // This can be changed with more analysis.
3198 // In case of tail call optimization mark all arguments mutable.
3199 // Since they could be overwritten by lowering of arguments in case of
3201 if (Flags.isByVal()) {
3202 assert(Ins[index].isOrigArg() &&
3203 "Byval arguments cannot be implicit");
3204 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3206 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3207 CurByValIndex, VA.getLocMemOffset(),
3208 Flags.getByValSize());
3209 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3210 CCInfo.nextInRegsParam();
3212 unsigned FIOffset = VA.getLocMemOffset();
3213 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3216 // Create load nodes to retrieve arguments from the stack.
3217 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3218 InVals.push_back(DAG.getLoad(
3219 VA.getValVT(), dl, Chain, FIN,
3220 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3221 false, false, false, 0));
3223 lastInsIndex = index;
3229 if (isVarArg && MFI->hasVAStart())
3230 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3231 CCInfo.getNextStackOffset(),
3232 TotalArgRegsSaveSize);
3234 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3239 /// isFloatingPointZero - Return true if this is +0.0.
3240 static bool isFloatingPointZero(SDValue Op) {
3241 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3242 return CFP->getValueAPF().isPosZero();
3243 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3244 // Maybe this has already been legalized into the constant pool?
3245 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3246 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3247 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3248 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3249 return CFP->getValueAPF().isPosZero();
3251 } else if (Op->getOpcode() == ISD::BITCAST &&
3252 Op->getValueType(0) == MVT::f64) {
3253 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3254 // created by LowerConstantFP().
3255 SDValue BitcastOp = Op->getOperand(0);
3256 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3257 SDValue MoveOp = BitcastOp->getOperand(0);
3258 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3259 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3267 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3268 /// the given operands.
3270 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3271 SDValue &ARMcc, SelectionDAG &DAG,
3273 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3274 unsigned C = RHSC->getZExtValue();
3275 if (!isLegalICmpImmediate(C)) {
3276 // Constant does not fit, try adjusting it by one?
3281 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3282 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3283 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3288 if (C != 0 && isLegalICmpImmediate(C-1)) {
3289 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3290 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3295 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3296 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3297 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3302 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3303 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3304 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3311 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3312 ARMISD::NodeType CompareType;
3315 CompareType = ARMISD::CMP;
3320 CompareType = ARMISD::CMPZ;
3323 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3324 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3327 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3329 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3331 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3333 if (!isFloatingPointZero(RHS))
3334 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3336 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3337 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3340 /// duplicateCmp - Glue values can have only one use, so this function
3341 /// duplicates a comparison node.
3343 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3344 unsigned Opc = Cmp.getOpcode();
3346 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3347 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3349 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3350 Cmp = Cmp.getOperand(0);
3351 Opc = Cmp.getOpcode();
3352 if (Opc == ARMISD::CMPFP)
3353 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3355 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3356 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3358 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3361 std::pair<SDValue, SDValue>
3362 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3363 SDValue &ARMcc) const {
3364 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3366 SDValue Value, OverflowCmp;
3367 SDValue LHS = Op.getOperand(0);
3368 SDValue RHS = Op.getOperand(1);
3371 // FIXME: We are currently always generating CMPs because we don't support
3372 // generating CMN through the backend. This is not as good as the natural
3373 // CMP case because it causes a register dependency and cannot be folded
3376 switch (Op.getOpcode()) {
3378 llvm_unreachable("Unknown overflow instruction!");
3380 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3381 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3382 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3385 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3386 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3387 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3390 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3391 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3392 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3395 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3396 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3397 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3401 return std::make_pair(Value, OverflowCmp);
3406 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3407 // Let legalize expand this if it isn't a legal type yet.
3408 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3411 SDValue Value, OverflowCmp;
3413 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3414 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3416 // We use 0 and 1 as false and true values.
3417 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3418 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3419 EVT VT = Op.getValueType();
3421 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3422 ARMcc, CCR, OverflowCmp);
3424 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3425 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3429 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3430 SDValue Cond = Op.getOperand(0);
3431 SDValue SelectTrue = Op.getOperand(1);
3432 SDValue SelectFalse = Op.getOperand(2);
3434 unsigned Opc = Cond.getOpcode();
3436 if (Cond.getResNo() == 1 &&
3437 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3438 Opc == ISD::USUBO)) {
3439 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3442 SDValue Value, OverflowCmp;
3444 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3445 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3446 EVT VT = Op.getValueType();
3448 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3454 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3455 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3457 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3458 const ConstantSDNode *CMOVTrue =
3459 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3460 const ConstantSDNode *CMOVFalse =
3461 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3463 if (CMOVTrue && CMOVFalse) {
3464 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3465 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3469 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3471 False = SelectFalse;
3472 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3477 if (True.getNode() && False.getNode()) {
3478 EVT VT = Op.getValueType();
3479 SDValue ARMcc = Cond.getOperand(2);
3480 SDValue CCR = Cond.getOperand(3);
3481 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3482 assert(True.getValueType() == VT);
3483 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3488 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3489 // undefined bits before doing a full-word comparison with zero.
3490 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3491 DAG.getConstant(1, dl, Cond.getValueType()));
3493 return DAG.getSelectCC(dl, Cond,
3494 DAG.getConstant(0, dl, Cond.getValueType()),
3495 SelectTrue, SelectFalse, ISD::SETNE);
3498 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3499 bool &swpCmpOps, bool &swpVselOps) {
3500 // Start by selecting the GE condition code for opcodes that return true for
3502 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3504 CondCode = ARMCC::GE;
3506 // and GT for opcodes that return false for 'equality'.
3507 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3509 CondCode = ARMCC::GT;
3511 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3512 // to swap the compare operands.
3513 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3517 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3518 // If we have an unordered opcode, we need to swap the operands to the VSEL
3519 // instruction (effectively negating the condition).
3521 // This also has the effect of swapping which one of 'less' or 'greater'
3522 // returns true, so we also swap the compare operands. It also switches
3523 // whether we return true for 'equality', so we compensate by picking the
3524 // opposite condition code to our original choice.
3525 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3526 CC == ISD::SETUGT) {
3527 swpCmpOps = !swpCmpOps;
3528 swpVselOps = !swpVselOps;
3529 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3532 // 'ordered' is 'anything but unordered', so use the VS condition code and
3533 // swap the VSEL operands.
3534 if (CC == ISD::SETO) {
3535 CondCode = ARMCC::VS;
3539 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3540 // code and swap the VSEL operands.
3541 if (CC == ISD::SETUNE) {
3542 CondCode = ARMCC::EQ;
3547 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3548 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3549 SDValue Cmp, SelectionDAG &DAG) const {
3550 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3551 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3552 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3553 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3554 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3556 SDValue TrueLow = TrueVal.getValue(0);
3557 SDValue TrueHigh = TrueVal.getValue(1);
3558 SDValue FalseLow = FalseVal.getValue(0);
3559 SDValue FalseHigh = FalseVal.getValue(1);
3561 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3563 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3564 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3566 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3568 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3573 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3574 EVT VT = Op.getValueType();
3575 SDValue LHS = Op.getOperand(0);
3576 SDValue RHS = Op.getOperand(1);
3577 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3578 SDValue TrueVal = Op.getOperand(2);
3579 SDValue FalseVal = Op.getOperand(3);
3582 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3583 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3586 // If softenSetCCOperands only returned one value, we should compare it to
3588 if (!RHS.getNode()) {
3589 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3594 if (LHS.getValueType() == MVT::i32) {
3595 // Try to generate VSEL on ARMv8.
3596 // The VSEL instruction can't use all the usual ARM condition
3597 // codes: it only has two bits to select the condition code, so it's
3598 // constrained to use only GE, GT, VS and EQ.
3600 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3601 // swap the operands of the previous compare instruction (effectively
3602 // inverting the compare condition, swapping 'less' and 'greater') and
3603 // sometimes need to swap the operands to the VSEL (which inverts the
3604 // condition in the sense of firing whenever the previous condition didn't)
3605 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3606 TrueVal.getValueType() == MVT::f64)) {
3607 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3608 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3609 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3610 CC = ISD::getSetCCInverse(CC, true);
3611 std::swap(TrueVal, FalseVal);
3616 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3617 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3618 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3621 ARMCC::CondCodes CondCode, CondCode2;
3622 FPCCToARMCC(CC, CondCode, CondCode2);
3624 // Try to generate VMAXNM/VMINNM on ARMv8.
3625 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3626 TrueVal.getValueType() == MVT::f64)) {
3627 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3628 // same operands, as follows:
3629 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3631 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3632 bool swapSides = false;
3633 if (!getTargetMachine().Options.NoNaNsFPMath) {
3634 // transformability may depend on which way around we compare
3642 // the non-NaN should be RHS
3643 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3649 // the non-NaN should be LHS
3650 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3654 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3656 CC = ISD::getSetCCSwappedOperands(CC);
3657 std::swap(LHS, RHS);
3659 if (LHS == TrueVal && RHS == FalseVal) {
3660 bool canTransform = true;
3661 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3662 if (!getTargetMachine().Options.UnsafeFPMath &&
3663 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3664 const ConstantFPSDNode *Zero;
3671 // RHS must not be -0
3672 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3673 !Zero->isNegative();
3678 // LHS must not be -0
3679 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3680 !Zero->isNegative();
3685 // RHS must not be +0
3686 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3692 // LHS must not be +0
3693 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3699 // Note: If one of the elements in a pair is a number and the other
3700 // element is NaN, the corresponding result element is the number.
3701 // This is consistent with the IEEE 754-2008 standard.
3702 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3708 if (!DAG.isKnownNeverNaN(RHS))
3710 return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3713 if (!DAG.isKnownNeverNaN(LHS))
3717 return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3720 if (!DAG.isKnownNeverNaN(RHS))
3722 return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3725 if (!DAG.isKnownNeverNaN(LHS))
3729 return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3734 bool swpCmpOps = false;
3735 bool swpVselOps = false;
3736 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3738 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3739 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3741 std::swap(LHS, RHS);
3743 std::swap(TrueVal, FalseVal);
3747 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3748 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3749 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3750 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3751 if (CondCode2 != ARMCC::AL) {
3752 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3753 // FIXME: Needs another CMP because flag can have but one use.
3754 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3755 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3760 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3761 /// to morph to an integer compare sequence.
3762 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3763 const ARMSubtarget *Subtarget) {
3764 SDNode *N = Op.getNode();
3765 if (!N->hasOneUse())
3766 // Otherwise it requires moving the value from fp to integer registers.
3768 if (!N->getNumValues())
3770 EVT VT = Op.getValueType();
3771 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3772 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3773 // vmrs are very slow, e.g. cortex-a8.
3776 if (isFloatingPointZero(Op)) {
3780 return ISD::isNormalLoad(N);
3783 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3784 if (isFloatingPointZero(Op))
3785 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3787 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3788 return DAG.getLoad(MVT::i32, SDLoc(Op),
3789 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3790 Ld->isVolatile(), Ld->isNonTemporal(),
3791 Ld->isInvariant(), Ld->getAlignment());
3793 llvm_unreachable("Unknown VFP cmp argument!");
3796 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3797 SDValue &RetVal1, SDValue &RetVal2) {
3800 if (isFloatingPointZero(Op)) {
3801 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3802 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3806 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3807 SDValue Ptr = Ld->getBasePtr();
3808 RetVal1 = DAG.getLoad(MVT::i32, dl,
3809 Ld->getChain(), Ptr,
3810 Ld->getPointerInfo(),
3811 Ld->isVolatile(), Ld->isNonTemporal(),
3812 Ld->isInvariant(), Ld->getAlignment());
3814 EVT PtrType = Ptr.getValueType();
3815 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3816 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3817 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3818 RetVal2 = DAG.getLoad(MVT::i32, dl,
3819 Ld->getChain(), NewPtr,
3820 Ld->getPointerInfo().getWithOffset(4),
3821 Ld->isVolatile(), Ld->isNonTemporal(),
3822 Ld->isInvariant(), NewAlign);
3826 llvm_unreachable("Unknown VFP cmp argument!");
3829 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3830 /// f32 and even f64 comparisons to integer ones.
3832 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3833 SDValue Chain = Op.getOperand(0);
3834 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3835 SDValue LHS = Op.getOperand(2);
3836 SDValue RHS = Op.getOperand(3);
3837 SDValue Dest = Op.getOperand(4);
3840 bool LHSSeenZero = false;
3841 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3842 bool RHSSeenZero = false;
3843 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3844 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3845 // If unsafe fp math optimization is enabled and there are no other uses of
3846 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3847 // to an integer comparison.
3848 if (CC == ISD::SETOEQ)
3850 else if (CC == ISD::SETUNE)
3853 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3855 if (LHS.getValueType() == MVT::f32) {
3856 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3857 bitcastf32Toi32(LHS, DAG), Mask);
3858 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3859 bitcastf32Toi32(RHS, DAG), Mask);
3860 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3861 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3862 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3863 Chain, Dest, ARMcc, CCR, Cmp);
3868 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3869 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3870 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3871 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3872 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3873 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3874 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3875 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3876 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3882 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3883 SDValue Chain = Op.getOperand(0);
3884 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3885 SDValue LHS = Op.getOperand(2);
3886 SDValue RHS = Op.getOperand(3);
3887 SDValue Dest = Op.getOperand(4);
3890 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3891 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3894 // If softenSetCCOperands only returned one value, we should compare it to
3896 if (!RHS.getNode()) {
3897 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3902 if (LHS.getValueType() == MVT::i32) {
3904 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3905 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3906 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3907 Chain, Dest, ARMcc, CCR, Cmp);
3910 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3912 if (getTargetMachine().Options.UnsafeFPMath &&
3913 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3914 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3915 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3916 if (Result.getNode())
3920 ARMCC::CondCodes CondCode, CondCode2;
3921 FPCCToARMCC(CC, CondCode, CondCode2);
3923 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3924 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3925 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3926 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3927 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3928 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3929 if (CondCode2 != ARMCC::AL) {
3930 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3931 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3932 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3937 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3938 SDValue Chain = Op.getOperand(0);
3939 SDValue Table = Op.getOperand(1);
3940 SDValue Index = Op.getOperand(2);
3943 EVT PTy = getPointerTy(DAG.getDataLayout());
3944 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3945 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3946 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3947 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3948 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3949 if (Subtarget->isThumb2()) {
3950 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3951 // which does another jump to the destination. This also makes it easier
3952 // to translate it to TBB / TBH later.
3953 // FIXME: This might not work if the function is extremely large.
3954 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3955 Addr, Op.getOperand(2), JTI);
3957 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3959 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3960 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3961 false, false, false, 0);
3962 Chain = Addr.getValue(1);
3963 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3964 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3967 DAG.getLoad(PTy, dl, Chain, Addr,
3968 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3969 false, false, false, 0);
3970 Chain = Addr.getValue(1);
3971 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3975 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3976 EVT VT = Op.getValueType();
3979 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3980 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3982 return DAG.UnrollVectorOp(Op.getNode());
3985 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3986 "Invalid type for custom lowering!");
3987 if (VT != MVT::v4i16)
3988 return DAG.UnrollVectorOp(Op.getNode());
3990 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3991 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3994 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3995 EVT VT = Op.getValueType();
3997 return LowerVectorFP_TO_INT(Op, DAG);
3998 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4000 if (Op.getOpcode() == ISD::FP_TO_SINT)
4001 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4004 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4006 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4007 /*isSigned*/ false, SDLoc(Op)).first;
4013 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4014 EVT VT = Op.getValueType();
4017 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4018 if (VT.getVectorElementType() == MVT::f32)
4020 return DAG.UnrollVectorOp(Op.getNode());
4023 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4024 "Invalid type for custom lowering!");
4025 if (VT != MVT::v4f32)
4026 return DAG.UnrollVectorOp(Op.getNode());
4030 switch (Op.getOpcode()) {
4031 default: llvm_unreachable("Invalid opcode!");
4032 case ISD::SINT_TO_FP:
4033 CastOpc = ISD::SIGN_EXTEND;
4034 Opc = ISD::SINT_TO_FP;
4036 case ISD::UINT_TO_FP:
4037 CastOpc = ISD::ZERO_EXTEND;
4038 Opc = ISD::UINT_TO_FP;
4042 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4043 return DAG.getNode(Opc, dl, VT, Op);
4046 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4047 EVT VT = Op.getValueType();
4049 return LowerVectorINT_TO_FP(Op, DAG);
4050 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4052 if (Op.getOpcode() == ISD::SINT_TO_FP)
4053 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4056 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4058 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4059 /*isSigned*/ false, SDLoc(Op)).first;
4065 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4066 // Implement fcopysign with a fabs and a conditional fneg.
4067 SDValue Tmp0 = Op.getOperand(0);
4068 SDValue Tmp1 = Op.getOperand(1);
4070 EVT VT = Op.getValueType();
4071 EVT SrcVT = Tmp1.getValueType();
4072 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4073 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4074 bool UseNEON = !InGPR && Subtarget->hasNEON();
4077 // Use VBSL to copy the sign bit.
4078 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4079 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4080 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4081 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4083 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4084 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4085 DAG.getConstant(32, dl, MVT::i32));
4086 else /*if (VT == MVT::f32)*/
4087 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4088 if (SrcVT == MVT::f32) {
4089 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4091 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4092 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4093 DAG.getConstant(32, dl, MVT::i32));
4094 } else if (VT == MVT::f32)
4095 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4096 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4097 DAG.getConstant(32, dl, MVT::i32));
4098 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4099 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4101 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4103 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4104 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4105 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4107 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4108 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4109 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4110 if (VT == MVT::f32) {
4111 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4112 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4113 DAG.getConstant(0, dl, MVT::i32));
4115 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4121 // Bitcast operand 1 to i32.
4122 if (SrcVT == MVT::f64)
4123 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4125 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4127 // Or in the signbit with integer operations.
4128 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4129 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4130 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4131 if (VT == MVT::f32) {
4132 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4133 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4134 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4135 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4138 // f64: Or the high part with signbit and then combine two parts.
4139 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4141 SDValue Lo = Tmp0.getValue(0);
4142 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4143 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4144 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4147 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4148 MachineFunction &MF = DAG.getMachineFunction();
4149 MachineFrameInfo *MFI = MF.getFrameInfo();
4150 MFI->setReturnAddressIsTaken(true);
4152 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4155 EVT VT = Op.getValueType();
4157 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4159 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4160 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4161 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4162 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4163 MachinePointerInfo(), false, false, false, 0);
4166 // Return LR, which contains the return address. Mark it an implicit live-in.
4167 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4168 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4171 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4172 const ARMBaseRegisterInfo &ARI =
4173 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4174 MachineFunction &MF = DAG.getMachineFunction();
4175 MachineFrameInfo *MFI = MF.getFrameInfo();
4176 MFI->setFrameAddressIsTaken(true);
4178 EVT VT = Op.getValueType();
4179 SDLoc dl(Op); // FIXME probably not meaningful
4180 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4181 unsigned FrameReg = ARI.getFrameRegister(MF);
4182 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4184 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4185 MachinePointerInfo(),
4186 false, false, false, 0);
4190 // FIXME? Maybe this could be a TableGen attribute on some registers and
4191 // this table could be generated automatically from RegInfo.
4192 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4193 SelectionDAG &DAG) const {
4194 unsigned Reg = StringSwitch<unsigned>(RegName)
4195 .Case("sp", ARM::SP)
4199 report_fatal_error(Twine("Invalid register name \""
4200 + StringRef(RegName) + "\"."));
4203 // Result is 64 bit value so split into two 32 bit values and return as a
4205 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4206 SelectionDAG &DAG) {
4209 // This function is only supposed to be called for i64 type destination.
4210 assert(N->getValueType(0) == MVT::i64
4211 && "ExpandREAD_REGISTER called for non-i64 type result.");
4213 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4214 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4218 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4220 Results.push_back(Read.getOperand(0));
4223 /// ExpandBITCAST - If the target supports VFP, this function is called to
4224 /// expand a bit convert where either the source or destination type is i64 to
4225 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4226 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4227 /// vectors), since the legalizer won't know what to do with that.
4228 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4229 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4231 SDValue Op = N->getOperand(0);
4233 // This function is only supposed to be called for i64 types, either as the
4234 // source or destination of the bit convert.
4235 EVT SrcVT = Op.getValueType();
4236 EVT DstVT = N->getValueType(0);
4237 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4238 "ExpandBITCAST called for non-i64 type");
4240 // Turn i64->f64 into VMOVDRR.
4241 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4242 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4243 DAG.getConstant(0, dl, MVT::i32));
4244 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4245 DAG.getConstant(1, dl, MVT::i32));
4246 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4247 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4250 // Turn f64->i64 into VMOVRRD.
4251 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4253 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4254 SrcVT.getVectorNumElements() > 1)
4255 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4256 DAG.getVTList(MVT::i32, MVT::i32),
4257 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4259 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4260 DAG.getVTList(MVT::i32, MVT::i32), Op);
4261 // Merge the pieces into a single i64 value.
4262 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4268 /// getZeroVector - Returns a vector of specified type with all zero elements.
4269 /// Zero vectors are used to represent vector negation and in those cases
4270 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4271 /// not support i64 elements, so sometimes the zero vectors will need to be
4272 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4274 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4275 assert(VT.isVector() && "Expected a vector type");
4276 // The canonical modified immediate encoding of a zero vector is....0!
4277 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4278 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4279 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4280 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4283 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4284 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4285 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4286 SelectionDAG &DAG) const {
4287 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4288 EVT VT = Op.getValueType();
4289 unsigned VTBits = VT.getSizeInBits();
4291 SDValue ShOpLo = Op.getOperand(0);
4292 SDValue ShOpHi = Op.getOperand(1);
4293 SDValue ShAmt = Op.getOperand(2);
4295 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4297 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4299 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4300 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4301 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4302 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4303 DAG.getConstant(VTBits, dl, MVT::i32));
4304 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4305 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4306 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4308 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4309 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4310 ISD::SETGE, ARMcc, DAG, dl);
4311 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4312 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4315 SDValue Ops[2] = { Lo, Hi };
4316 return DAG.getMergeValues(Ops, dl);
4319 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4320 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4321 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4322 SelectionDAG &DAG) const {
4323 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4324 EVT VT = Op.getValueType();
4325 unsigned VTBits = VT.getSizeInBits();
4327 SDValue ShOpLo = Op.getOperand(0);
4328 SDValue ShOpHi = Op.getOperand(1);
4329 SDValue ShAmt = Op.getOperand(2);
4332 assert(Op.getOpcode() == ISD::SHL_PARTS);
4333 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4334 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4335 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4336 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4337 DAG.getConstant(VTBits, dl, MVT::i32));
4338 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4339 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4341 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4342 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4343 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4344 ISD::SETGE, ARMcc, DAG, dl);
4345 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4346 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4349 SDValue Ops[2] = { Lo, Hi };
4350 return DAG.getMergeValues(Ops, dl);
4353 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4354 SelectionDAG &DAG) const {
4355 // The rounding mode is in bits 23:22 of the FPSCR.
4356 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4357 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4358 // so that the shift + and get folded into a bitfield extract.
4360 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4361 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4363 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4364 DAG.getConstant(1U << 22, dl, MVT::i32));
4365 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4366 DAG.getConstant(22, dl, MVT::i32));
4367 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4368 DAG.getConstant(3, dl, MVT::i32));
4371 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4372 const ARMSubtarget *ST) {
4374 EVT VT = N->getValueType(0);
4375 if (VT.isVector()) {
4376 assert(ST->hasNEON());
4378 // Compute the least significant set bit: LSB = X & -X
4379 SDValue X = N->getOperand(0);
4380 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4381 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4383 EVT ElemTy = VT.getVectorElementType();
4385 if (ElemTy == MVT::i8) {
4386 // Compute with: cttz(x) = ctpop(lsb - 1)
4387 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4388 DAG.getTargetConstant(1, dl, ElemTy));
4389 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4390 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4393 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4394 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4395 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4396 unsigned NumBits = ElemTy.getSizeInBits();
4397 SDValue WidthMinus1 =
4398 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4399 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4400 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4401 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4404 // Compute with: cttz(x) = ctpop(lsb - 1)
4406 // Since we can only compute the number of bits in a byte with vcnt.8, we
4407 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4412 if (ElemTy == MVT::i64) {
4413 // Load constant 0xffff'ffff'ffff'ffff to register.
4414 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4415 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4416 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4418 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4419 DAG.getTargetConstant(1, dl, ElemTy));
4420 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4423 // Count #bits with vcnt.8.
4424 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4425 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4426 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4428 // Gather the #bits with vpaddl (pairwise add.)
4429 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4430 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4431 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4433 if (ElemTy == MVT::i16)
4436 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4437 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4438 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4440 if (ElemTy == MVT::i32)
4443 assert(ElemTy == MVT::i64);
4444 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4445 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4450 if (!ST->hasV6T2Ops())
4453 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4454 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4457 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4458 /// for each 16-bit element from operand, repeated. The basic idea is to
4459 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4461 /// Trace for v4i16:
4462 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4463 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4464 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4465 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4466 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4467 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4468 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4469 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4470 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4471 EVT VT = N->getValueType(0);
4474 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4475 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4476 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4477 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4478 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4479 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4482 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4483 /// bit-count for each 16-bit element from the operand. We need slightly
4484 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4485 /// 64/128-bit registers.
4487 /// Trace for v4i16:
4488 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4489 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4490 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4491 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4492 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4493 EVT VT = N->getValueType(0);
4496 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4497 if (VT.is64BitVector()) {
4498 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4499 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4500 DAG.getIntPtrConstant(0, DL));
4502 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4503 BitCounts, DAG.getIntPtrConstant(0, DL));
4504 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4508 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4509 /// bit-count for each 32-bit element from the operand. The idea here is
4510 /// to split the vector into 16-bit elements, leverage the 16-bit count
4511 /// routine, and then combine the results.
4513 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4514 /// input = [v0 v1 ] (vi: 32-bit elements)
4515 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4516 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4517 /// vrev: N0 = [k1 k0 k3 k2 ]
4519 /// N1 =+[k1 k0 k3 k2 ]
4521 /// N2 =+[k1 k3 k0 k2 ]
4523 /// Extended =+[k1 k3 k0 k2 ]
4525 /// Extracted=+[k1 k3 ]
4527 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4528 EVT VT = N->getValueType(0);
4531 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4533 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4534 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4535 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4536 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4537 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4539 if (VT.is64BitVector()) {
4540 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4541 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4542 DAG.getIntPtrConstant(0, DL));
4544 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4545 DAG.getIntPtrConstant(0, DL));
4546 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4550 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4551 const ARMSubtarget *ST) {
4552 EVT VT = N->getValueType(0);
4554 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4555 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4556 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4557 "Unexpected type for custom ctpop lowering");
4559 if (VT.getVectorElementType() == MVT::i32)
4560 return lowerCTPOP32BitElements(N, DAG);
4562 return lowerCTPOP16BitElements(N, DAG);
4565 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4566 const ARMSubtarget *ST) {
4567 EVT VT = N->getValueType(0);
4573 // Lower vector shifts on NEON to use VSHL.
4574 assert(ST->hasNEON() && "unexpected vector shift");
4576 // Left shifts translate directly to the vshiftu intrinsic.
4577 if (N->getOpcode() == ISD::SHL)
4578 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4579 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4581 N->getOperand(0), N->getOperand(1));
4583 assert((N->getOpcode() == ISD::SRA ||
4584 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4586 // NEON uses the same intrinsics for both left and right shifts. For
4587 // right shifts, the shift amounts are negative, so negate the vector of
4589 EVT ShiftVT = N->getOperand(1).getValueType();
4590 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4591 getZeroVector(ShiftVT, DAG, dl),
4593 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4594 Intrinsic::arm_neon_vshifts :
4595 Intrinsic::arm_neon_vshiftu);
4596 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4597 DAG.getConstant(vshiftInt, dl, MVT::i32),
4598 N->getOperand(0), NegatedCount);
4601 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4602 const ARMSubtarget *ST) {
4603 EVT VT = N->getValueType(0);
4606 // We can get here for a node like i32 = ISD::SHL i32, i64
4610 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4611 "Unknown shift to lower!");
4613 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4614 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4615 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4618 // If we are in thumb mode, we don't have RRX.
4619 if (ST->isThumb1Only()) return SDValue();
4621 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4622 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4623 DAG.getConstant(0, dl, MVT::i32));
4624 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4625 DAG.getConstant(1, dl, MVT::i32));
4627 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4628 // captures the result into a carry flag.
4629 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4630 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4632 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4633 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4635 // Merge the pieces into a single i64 value.
4636 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4639 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4640 SDValue TmpOp0, TmpOp1;
4641 bool Invert = false;
4645 SDValue Op0 = Op.getOperand(0);
4646 SDValue Op1 = Op.getOperand(1);
4647 SDValue CC = Op.getOperand(2);
4648 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4649 EVT VT = Op.getValueType();
4650 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4653 if (Op1.getValueType().isFloatingPoint()) {
4654 switch (SetCCOpcode) {
4655 default: llvm_unreachable("Illegal FP comparison");
4657 case ISD::SETNE: Invert = true; // Fallthrough
4659 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4661 case ISD::SETLT: Swap = true; // Fallthrough
4663 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4665 case ISD::SETLE: Swap = true; // Fallthrough
4667 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4668 case ISD::SETUGE: Swap = true; // Fallthrough
4669 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4670 case ISD::SETUGT: Swap = true; // Fallthrough
4671 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4672 case ISD::SETUEQ: Invert = true; // Fallthrough
4674 // Expand this to (OLT | OGT).
4678 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4679 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4681 case ISD::SETUO: Invert = true; // Fallthrough
4683 // Expand this to (OLT | OGE).
4687 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4688 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4692 // Integer comparisons.
4693 switch (SetCCOpcode) {
4694 default: llvm_unreachable("Illegal integer comparison");
4695 case ISD::SETNE: Invert = true;
4696 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4697 case ISD::SETLT: Swap = true;
4698 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4699 case ISD::SETLE: Swap = true;
4700 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4701 case ISD::SETULT: Swap = true;
4702 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4703 case ISD::SETULE: Swap = true;
4704 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4707 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4708 if (Opc == ARMISD::VCEQ) {
4711 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4713 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4716 // Ignore bitconvert.
4717 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4718 AndOp = AndOp.getOperand(0);
4720 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4722 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4723 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4730 std::swap(Op0, Op1);
4732 // If one of the operands is a constant vector zero, attempt to fold the
4733 // comparison to a specialized compare-against-zero form.
4735 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4737 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4738 if (Opc == ARMISD::VCGE)
4739 Opc = ARMISD::VCLEZ;
4740 else if (Opc == ARMISD::VCGT)
4741 Opc = ARMISD::VCLTZ;
4746 if (SingleOp.getNode()) {
4749 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4751 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4753 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4755 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4757 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4759 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4762 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4765 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4768 Result = DAG.getNOT(dl, Result, VT);
4773 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4774 /// valid vector constant for a NEON instruction with a "modified immediate"
4775 /// operand (e.g., VMOV). If so, return the encoded value.
4776 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4777 unsigned SplatBitSize, SelectionDAG &DAG,
4778 SDLoc dl, EVT &VT, bool is128Bits,
4779 NEONModImmType type) {
4780 unsigned OpCmode, Imm;
4782 // SplatBitSize is set to the smallest size that splats the vector, so a
4783 // zero vector will always have SplatBitSize == 8. However, NEON modified
4784 // immediate instructions others than VMOV do not support the 8-bit encoding
4785 // of a zero vector, and the default encoding of zero is supposed to be the
4790 switch (SplatBitSize) {
4792 if (type != VMOVModImm)
4794 // Any 1-byte value is OK. Op=0, Cmode=1110.
4795 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4798 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4802 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4803 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4804 if ((SplatBits & ~0xff) == 0) {
4805 // Value = 0x00nn: Op=x, Cmode=100x.
4810 if ((SplatBits & ~0xff00) == 0) {
4811 // Value = 0xnn00: Op=x, Cmode=101x.
4813 Imm = SplatBits >> 8;
4819 // NEON's 32-bit VMOV supports splat values where:
4820 // * only one byte is nonzero, or
4821 // * the least significant byte is 0xff and the second byte is nonzero, or
4822 // * the least significant 2 bytes are 0xff and the third is nonzero.
4823 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4824 if ((SplatBits & ~0xff) == 0) {
4825 // Value = 0x000000nn: Op=x, Cmode=000x.
4830 if ((SplatBits & ~0xff00) == 0) {
4831 // Value = 0x0000nn00: Op=x, Cmode=001x.
4833 Imm = SplatBits >> 8;
4836 if ((SplatBits & ~0xff0000) == 0) {
4837 // Value = 0x00nn0000: Op=x, Cmode=010x.
4839 Imm = SplatBits >> 16;
4842 if ((SplatBits & ~0xff000000) == 0) {
4843 // Value = 0xnn000000: Op=x, Cmode=011x.
4845 Imm = SplatBits >> 24;
4849 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4850 if (type == OtherModImm) return SDValue();
4852 if ((SplatBits & ~0xffff) == 0 &&
4853 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4854 // Value = 0x0000nnff: Op=x, Cmode=1100.
4856 Imm = SplatBits >> 8;
4860 if ((SplatBits & ~0xffffff) == 0 &&
4861 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4862 // Value = 0x00nnffff: Op=x, Cmode=1101.
4864 Imm = SplatBits >> 16;
4868 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4869 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4870 // VMOV.I32. A (very) minor optimization would be to replicate the value
4871 // and fall through here to test for a valid 64-bit splat. But, then the
4872 // caller would also need to check and handle the change in size.
4876 if (type != VMOVModImm)
4878 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4879 uint64_t BitMask = 0xff;
4881 unsigned ImmMask = 1;
4883 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4884 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4887 } else if ((SplatBits & BitMask) != 0) {
4894 if (DAG.getDataLayout().isBigEndian())
4895 // swap higher and lower 32 bit word
4896 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4898 // Op=1, Cmode=1110.
4900 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4905 llvm_unreachable("unexpected size for isNEONModifiedImm");
4908 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4909 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4912 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4913 const ARMSubtarget *ST) const {
4917 bool IsDouble = Op.getValueType() == MVT::f64;
4918 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4920 // Use the default (constant pool) lowering for double constants when we have
4922 if (IsDouble && Subtarget->isFPOnlySP())
4925 // Try splatting with a VMOV.f32...
4926 APFloat FPVal = CFP->getValueAPF();
4927 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4930 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4931 // We have code in place to select a valid ConstantFP already, no need to
4936 // It's a float and we are trying to use NEON operations where
4937 // possible. Lower it to a splat followed by an extract.
4939 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4940 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4942 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4943 DAG.getConstant(0, DL, MVT::i32));
4946 // The rest of our options are NEON only, make sure that's allowed before
4948 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4952 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4954 // It wouldn't really be worth bothering for doubles except for one very
4955 // important value, which does happen to match: 0.0. So make sure we don't do
4957 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4960 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4961 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4962 VMovVT, false, VMOVModImm);
4963 if (NewVal != SDValue()) {
4965 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4968 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4970 // It's a float: cast and extract a vector element.
4971 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4973 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4974 DAG.getConstant(0, DL, MVT::i32));
4977 // Finally, try a VMVN.i32
4978 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4980 if (NewVal != SDValue()) {
4982 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4985 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4987 // It's a float: cast and extract a vector element.
4988 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4990 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4991 DAG.getConstant(0, DL, MVT::i32));
4997 // check if an VEXT instruction can handle the shuffle mask when the
4998 // vector sources of the shuffle are the same.
4999 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5000 unsigned NumElts = VT.getVectorNumElements();
5002 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5008 // If this is a VEXT shuffle, the immediate value is the index of the first
5009 // element. The other shuffle indices must be the successive elements after
5011 unsigned ExpectedElt = Imm;
5012 for (unsigned i = 1; i < NumElts; ++i) {
5013 // Increment the expected index. If it wraps around, just follow it
5014 // back to index zero and keep going.
5016 if (ExpectedElt == NumElts)
5019 if (M[i] < 0) continue; // ignore UNDEF indices
5020 if (ExpectedElt != static_cast<unsigned>(M[i]))
5028 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5029 bool &ReverseVEXT, unsigned &Imm) {
5030 unsigned NumElts = VT.getVectorNumElements();
5031 ReverseVEXT = false;
5033 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5039 // If this is a VEXT shuffle, the immediate value is the index of the first
5040 // element. The other shuffle indices must be the successive elements after
5042 unsigned ExpectedElt = Imm;
5043 for (unsigned i = 1; i < NumElts; ++i) {
5044 // Increment the expected index. If it wraps around, it may still be
5045 // a VEXT but the source vectors must be swapped.
5047 if (ExpectedElt == NumElts * 2) {
5052 if (M[i] < 0) continue; // ignore UNDEF indices
5053 if (ExpectedElt != static_cast<unsigned>(M[i]))
5057 // Adjust the index value if the source operands will be swapped.
5064 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5065 /// instruction with the specified blocksize. (The order of the elements
5066 /// within each block of the vector is reversed.)
5067 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5068 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5069 "Only possible block sizes for VREV are: 16, 32, 64");
5071 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5075 unsigned NumElts = VT.getVectorNumElements();
5076 unsigned BlockElts = M[0] + 1;
5077 // If the first shuffle index is UNDEF, be optimistic.
5079 BlockElts = BlockSize / EltSz;
5081 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5084 for (unsigned i = 0; i < NumElts; ++i) {
5085 if (M[i] < 0) continue; // ignore UNDEF indices
5086 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5093 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5094 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5095 // range, then 0 is placed into the resulting vector. So pretty much any mask
5096 // of 8 elements can work here.
5097 return VT == MVT::v8i8 && M.size() == 8;
5100 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5101 // checking that pairs of elements in the shuffle mask represent the same index
5102 // in each vector, incrementing the expected index by 2 at each step.
5103 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5104 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5106 // WhichResult gives the offset for each element in the mask based on which
5107 // of the two results it belongs to.
5109 // The transpose can be represented either as:
5110 // result1 = shufflevector v1, v2, result1_shuffle_mask
5111 // result2 = shufflevector v1, v2, result2_shuffle_mask
5112 // where v1/v2 and the shuffle masks have the same number of elements
5113 // (here WhichResult (see below) indicates which result is being checked)
5116 // results = shufflevector v1, v2, shuffle_mask
5117 // where both results are returned in one vector and the shuffle mask has twice
5118 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5119 // want to check the low half and high half of the shuffle mask as if it were
5121 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5122 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5126 unsigned NumElts = VT.getVectorNumElements();
5127 if (M.size() != NumElts && M.size() != NumElts*2)
5130 // If the mask is twice as long as the result then we need to check the upper
5131 // and lower parts of the mask
5132 for (unsigned i = 0; i < M.size(); i += NumElts) {
5133 WhichResult = M[i] == 0 ? 0 : 1;
5134 for (unsigned j = 0; j < NumElts; j += 2) {
5135 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5136 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5141 if (M.size() == NumElts*2)
5147 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5148 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5149 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5150 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5151 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5155 unsigned NumElts = VT.getVectorNumElements();
5156 if (M.size() != NumElts && M.size() != NumElts*2)
5159 for (unsigned i = 0; i < M.size(); i += NumElts) {
5160 WhichResult = M[i] == 0 ? 0 : 1;
5161 for (unsigned j = 0; j < NumElts; j += 2) {
5162 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5163 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5168 if (M.size() == NumElts*2)
5174 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5175 // that the mask elements are either all even and in steps of size 2 or all odd
5176 // and in steps of size 2.
5177 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5178 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5180 // Requires similar checks to that of isVTRNMask with
5181 // respect the how results are returned.
5182 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5183 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5187 unsigned NumElts = VT.getVectorNumElements();
5188 if (M.size() != NumElts && M.size() != NumElts*2)
5191 for (unsigned i = 0; i < M.size(); i += NumElts) {
5192 WhichResult = M[i] == 0 ? 0 : 1;
5193 for (unsigned j = 0; j < NumElts; ++j) {
5194 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5199 if (M.size() == NumElts*2)
5202 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5203 if (VT.is64BitVector() && EltSz == 32)
5209 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5210 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5211 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5212 static bool isVUZP_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 unsigned Half = NumElts / 2;
5222 for (unsigned i = 0; i < M.size(); i += NumElts) {
5223 WhichResult = M[i] == 0 ? 0 : 1;
5224 for (unsigned j = 0; j < NumElts; j += Half) {
5225 unsigned Idx = WhichResult;
5226 for (unsigned k = 0; k < Half; ++k) {
5227 int MIdx = M[i + j + k];
5228 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5235 if (M.size() == NumElts*2)
5238 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5239 if (VT.is64BitVector() && EltSz == 32)
5245 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5246 // that pairs of elements of the shufflemask represent the same index in each
5247 // vector incrementing sequentially through the vectors.
5248 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5249 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5251 // Requires similar checks to that of isVTRNMask with respect the how results
5253 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5254 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5258 unsigned NumElts = VT.getVectorNumElements();
5259 if (M.size() != NumElts && M.size() != NumElts*2)
5262 for (unsigned i = 0; i < M.size(); i += NumElts) {
5263 WhichResult = M[i] == 0 ? 0 : 1;
5264 unsigned Idx = WhichResult * NumElts / 2;
5265 for (unsigned j = 0; j < NumElts; j += 2) {
5266 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5267 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5273 if (M.size() == NumElts*2)
5276 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5277 if (VT.is64BitVector() && EltSz == 32)
5283 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5284 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5285 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5286 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5287 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5291 unsigned NumElts = VT.getVectorNumElements();
5292 if (M.size() != NumElts && M.size() != NumElts*2)
5295 for (unsigned i = 0; i < M.size(); i += NumElts) {
5296 WhichResult = M[i] == 0 ? 0 : 1;
5297 unsigned Idx = WhichResult * NumElts / 2;
5298 for (unsigned j = 0; j < NumElts; j += 2) {
5299 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5300 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5306 if (M.size() == NumElts*2)
5309 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5310 if (VT.is64BitVector() && EltSz == 32)
5316 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5317 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5318 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5319 unsigned &WhichResult,
5322 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5323 return ARMISD::VTRN;
5324 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5325 return ARMISD::VUZP;
5326 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5327 return ARMISD::VZIP;
5330 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5331 return ARMISD::VTRN;
5332 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5333 return ARMISD::VUZP;
5334 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5335 return ARMISD::VZIP;
5340 /// \return true if this is a reverse operation on an vector.
5341 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5342 unsigned NumElts = VT.getVectorNumElements();
5343 // Make sure the mask has the right size.
5344 if (NumElts != M.size())
5347 // Look for <15, ..., 3, -1, 1, 0>.
5348 for (unsigned i = 0; i != NumElts; ++i)
5349 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5355 // If N is an integer constant that can be moved into a register in one
5356 // instruction, return an SDValue of such a constant (will become a MOV
5357 // instruction). Otherwise return null.
5358 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5359 const ARMSubtarget *ST, SDLoc dl) {
5361 if (!isa<ConstantSDNode>(N))
5363 Val = cast<ConstantSDNode>(N)->getZExtValue();
5365 if (ST->isThumb1Only()) {
5366 if (Val <= 255 || ~Val <= 255)
5367 return DAG.getConstant(Val, dl, MVT::i32);
5369 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5370 return DAG.getConstant(Val, dl, MVT::i32);
5375 // If this is a case we can't handle, return null and let the default
5376 // expansion code take care of it.
5377 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5378 const ARMSubtarget *ST) const {
5379 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5381 EVT VT = Op.getValueType();
5383 APInt SplatBits, SplatUndef;
5384 unsigned SplatBitSize;
5386 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5387 if (SplatBitSize <= 64) {
5388 // Check if an immediate VMOV works.
5390 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5391 SplatUndef.getZExtValue(), SplatBitSize,
5392 DAG, dl, VmovVT, VT.is128BitVector(),
5394 if (Val.getNode()) {
5395 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5396 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5399 // Try an immediate VMVN.
5400 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5401 Val = isNEONModifiedImm(NegatedImm,
5402 SplatUndef.getZExtValue(), SplatBitSize,
5403 DAG, dl, VmovVT, VT.is128BitVector(),
5405 if (Val.getNode()) {
5406 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5407 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5410 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5411 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5412 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5414 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5415 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5421 // Scan through the operands to see if only one value is used.
5423 // As an optimisation, even if more than one value is used it may be more
5424 // profitable to splat with one value then change some lanes.
5426 // Heuristically we decide to do this if the vector has a "dominant" value,
5427 // defined as splatted to more than half of the lanes.
5428 unsigned NumElts = VT.getVectorNumElements();
5429 bool isOnlyLowElement = true;
5430 bool usesOnlyOneValue = true;
5431 bool hasDominantValue = false;
5432 bool isConstant = true;
5434 // Map of the number of times a particular SDValue appears in the
5436 DenseMap<SDValue, unsigned> ValueCounts;
5438 for (unsigned i = 0; i < NumElts; ++i) {
5439 SDValue V = Op.getOperand(i);
5440 if (V.getOpcode() == ISD::UNDEF)
5443 isOnlyLowElement = false;
5444 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5447 ValueCounts.insert(std::make_pair(V, 0));
5448 unsigned &Count = ValueCounts[V];
5450 // Is this value dominant? (takes up more than half of the lanes)
5451 if (++Count > (NumElts / 2)) {
5452 hasDominantValue = true;
5456 if (ValueCounts.size() != 1)
5457 usesOnlyOneValue = false;
5458 if (!Value.getNode() && ValueCounts.size() > 0)
5459 Value = ValueCounts.begin()->first;
5461 if (ValueCounts.size() == 0)
5462 return DAG.getUNDEF(VT);
5464 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5465 // Keep going if we are hitting this case.
5466 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5467 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5469 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5471 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5472 // i32 and try again.
5473 if (hasDominantValue && EltSize <= 32) {
5477 // If we are VDUPing a value that comes directly from a vector, that will
5478 // cause an unnecessary move to and from a GPR, where instead we could
5479 // just use VDUPLANE. We can only do this if the lane being extracted
5480 // is at a constant index, as the VDUP from lane instructions only have
5481 // constant-index forms.
5482 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5483 isa<ConstantSDNode>(Value->getOperand(1))) {
5484 // We need to create a new undef vector to use for the VDUPLANE if the
5485 // size of the vector from which we get the value is different than the
5486 // size of the vector that we need to create. We will insert the element
5487 // such that the register coalescer will remove unnecessary copies.
5488 if (VT != Value->getOperand(0).getValueType()) {
5489 ConstantSDNode *constIndex;
5490 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5491 assert(constIndex && "The index is not a constant!");
5492 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5493 VT.getVectorNumElements();
5494 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5495 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5496 Value, DAG.getConstant(index, dl, MVT::i32)),
5497 DAG.getConstant(index, dl, MVT::i32));
5499 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5500 Value->getOperand(0), Value->getOperand(1));
5502 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5504 if (!usesOnlyOneValue) {
5505 // The dominant value was splatted as 'N', but we now have to insert
5506 // all differing elements.
5507 for (unsigned I = 0; I < NumElts; ++I) {
5508 if (Op.getOperand(I) == Value)
5510 SmallVector<SDValue, 3> Ops;
5512 Ops.push_back(Op.getOperand(I));
5513 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5514 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5519 if (VT.getVectorElementType().isFloatingPoint()) {
5520 SmallVector<SDValue, 8> Ops;
5521 for (unsigned i = 0; i < NumElts; ++i)
5522 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5524 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5525 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5526 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5528 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5530 if (usesOnlyOneValue) {
5531 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5532 if (isConstant && Val.getNode())
5533 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5537 // If all elements are constants and the case above didn't get hit, fall back
5538 // to the default expansion, which will generate a load from the constant
5543 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5545 SDValue shuffle = ReconstructShuffle(Op, DAG);
5546 if (shuffle != SDValue())
5550 // Vectors with 32- or 64-bit elements can be built by directly assigning
5551 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5552 // will be legalized.
5553 if (EltSize >= 32) {
5554 // Do the expansion with floating-point types, since that is what the VFP
5555 // registers are defined to use, and since i64 is not legal.
5556 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5557 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5558 SmallVector<SDValue, 8> Ops;
5559 for (unsigned i = 0; i < NumElts; ++i)
5560 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5561 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5562 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5565 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5566 // know the default expansion would otherwise fall back on something even
5567 // worse. For a vector with one or two non-undef values, that's
5568 // scalar_to_vector for the elements followed by a shuffle (provided the
5569 // shuffle is valid for the target) and materialization element by element
5570 // on the stack followed by a load for everything else.
5571 if (!isConstant && !usesOnlyOneValue) {
5572 SDValue Vec = DAG.getUNDEF(VT);
5573 for (unsigned i = 0 ; i < NumElts; ++i) {
5574 SDValue V = Op.getOperand(i);
5575 if (V.getOpcode() == ISD::UNDEF)
5577 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5578 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5586 /// getExtFactor - Determine the adjustment factor for the position when
5587 /// generating an "extract from vector registers" instruction.
5588 static unsigned getExtFactor(SDValue &V) {
5589 EVT EltType = V.getValueType().getVectorElementType();
5590 return EltType.getSizeInBits() / 8;
5593 // Gather data to see if the operation can be modelled as a
5594 // shuffle in combination with VEXTs.
5595 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5596 SelectionDAG &DAG) const {
5597 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5599 EVT VT = Op.getValueType();
5600 unsigned NumElts = VT.getVectorNumElements();
5602 struct ShuffleSourceInfo {
5607 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5608 // be compatible with the shuffle we intend to construct. As a result
5609 // ShuffleVec will be some sliding window into the original Vec.
5612 // Code should guarantee that element i in Vec starts at element "WindowBase
5613 // + i * WindowScale in ShuffleVec".
5617 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5618 ShuffleSourceInfo(SDValue Vec)
5619 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5623 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5625 SmallVector<ShuffleSourceInfo, 2> Sources;
5626 for (unsigned i = 0; i < NumElts; ++i) {
5627 SDValue V = Op.getOperand(i);
5628 if (V.getOpcode() == ISD::UNDEF)
5630 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5631 // A shuffle can only come from building a vector from various
5632 // elements of other vectors.
5636 // Add this element source to the list if it's not already there.
5637 SDValue SourceVec = V.getOperand(0);
5638 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5639 if (Source == Sources.end())
5640 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5642 // Update the minimum and maximum lane number seen.
5643 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5644 Source->MinElt = std::min(Source->MinElt, EltNo);
5645 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5648 // Currently only do something sane when at most two source vectors
5650 if (Sources.size() > 2)
5653 // Find out the smallest element size among result and two sources, and use
5654 // it as element size to build the shuffle_vector.
5655 EVT SmallestEltTy = VT.getVectorElementType();
5656 for (auto &Source : Sources) {
5657 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5658 if (SrcEltTy.bitsLT(SmallestEltTy))
5659 SmallestEltTy = SrcEltTy;
5661 unsigned ResMultiplier =
5662 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5663 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5664 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5666 // If the source vector is too wide or too narrow, we may nevertheless be able
5667 // to construct a compatible shuffle either by concatenating it with UNDEF or
5668 // extracting a suitable range of elements.
5669 for (auto &Src : Sources) {
5670 EVT SrcVT = Src.ShuffleVec.getValueType();
5672 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5675 // This stage of the search produces a source with the same element type as
5676 // the original, but with a total width matching the BUILD_VECTOR output.
5677 EVT EltVT = SrcVT.getVectorElementType();
5678 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5679 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5681 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5682 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5684 // We can pad out the smaller vector for free, so if it's part of a
5687 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5688 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5692 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5695 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5696 // Span too large for a VEXT to cope
5700 if (Src.MinElt >= NumSrcElts) {
5701 // The extraction can just take the second half
5703 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5704 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5705 Src.WindowBase = -NumSrcElts;
5706 } else if (Src.MaxElt < NumSrcElts) {
5707 // The extraction can just take the first half
5709 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5710 DAG.getConstant(0, dl, MVT::i32));
5712 // An actual VEXT is needed
5714 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5715 DAG.getConstant(0, dl, MVT::i32));
5717 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5718 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5719 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5721 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5723 DAG.getConstant(Imm, dl, MVT::i32));
5724 Src.WindowBase = -Src.MinElt;
5728 // Another possible incompatibility occurs from the vector element types. We
5729 // can fix this by bitcasting the source vectors to the same type we intend
5731 for (auto &Src : Sources) {
5732 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5733 if (SrcEltTy == SmallestEltTy)
5735 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5736 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5737 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5738 Src.WindowBase *= Src.WindowScale;
5741 // Final sanity check before we try to actually produce a shuffle.
5743 for (auto Src : Sources)
5744 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5747 // The stars all align, our next step is to produce the mask for the shuffle.
5748 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5749 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5750 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5751 SDValue Entry = Op.getOperand(i);
5752 if (Entry.getOpcode() == ISD::UNDEF)
5755 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5756 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5758 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5759 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5761 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5762 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5763 VT.getVectorElementType().getSizeInBits());
5764 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5766 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5767 // starting at the appropriate offset.
5768 int *LaneMask = &Mask[i * ResMultiplier];
5770 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5771 ExtractBase += NumElts * (Src - Sources.begin());
5772 for (int j = 0; j < LanesDefined; ++j)
5773 LaneMask[j] = ExtractBase + j;
5776 // Final check before we try to produce nonsense...
5777 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5780 // We can't handle more than two sources. This should have already
5781 // been checked before this point.
5782 assert(Sources.size() <= 2 && "Too many sources!");
5784 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5785 for (unsigned i = 0; i < Sources.size(); ++i)
5786 ShuffleOps[i] = Sources[i].ShuffleVec;
5788 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5789 ShuffleOps[1], &Mask[0]);
5790 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5793 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5794 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5795 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5796 /// are assumed to be legal.
5798 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5800 if (VT.getVectorNumElements() == 4 &&
5801 (VT.is128BitVector() || VT.is64BitVector())) {
5802 unsigned PFIndexes[4];
5803 for (unsigned i = 0; i != 4; ++i) {
5807 PFIndexes[i] = M[i];
5810 // Compute the index in the perfect shuffle table.
5811 unsigned PFTableIndex =
5812 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5813 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5814 unsigned Cost = (PFEntry >> 30);
5820 bool ReverseVEXT, isV_UNDEF;
5821 unsigned Imm, WhichResult;
5823 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5824 return (EltSize >= 32 ||
5825 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5826 isVREVMask(M, VT, 64) ||
5827 isVREVMask(M, VT, 32) ||
5828 isVREVMask(M, VT, 16) ||
5829 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5830 isVTBLMask(M, VT) ||
5831 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5832 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5835 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5836 /// the specified operations to build the shuffle.
5837 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5838 SDValue RHS, SelectionDAG &DAG,
5840 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5841 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5842 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5845 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5854 OP_VUZPL, // VUZP, left result
5855 OP_VUZPR, // VUZP, right result
5856 OP_VZIPL, // VZIP, left result
5857 OP_VZIPR, // VZIP, right result
5858 OP_VTRNL, // VTRN, left result
5859 OP_VTRNR // VTRN, right result
5862 if (OpNum == OP_COPY) {
5863 if (LHSID == (1*9+2)*9+3) return LHS;
5864 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5868 SDValue OpLHS, OpRHS;
5869 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5870 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5871 EVT VT = OpLHS.getValueType();
5874 default: llvm_unreachable("Unknown shuffle opcode!");
5876 // VREV divides the vector in half and swaps within the half.
5877 if (VT.getVectorElementType() == MVT::i32 ||
5878 VT.getVectorElementType() == MVT::f32)
5879 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5880 // vrev <4 x i16> -> VREV32
5881 if (VT.getVectorElementType() == MVT::i16)
5882 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5883 // vrev <4 x i8> -> VREV16
5884 assert(VT.getVectorElementType() == MVT::i8);
5885 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5890 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5891 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5895 return DAG.getNode(ARMISD::VEXT, dl, VT,
5897 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5900 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5901 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5904 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5905 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5908 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5909 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5913 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5914 ArrayRef<int> ShuffleMask,
5915 SelectionDAG &DAG) {
5916 // Check to see if we can use the VTBL instruction.
5917 SDValue V1 = Op.getOperand(0);
5918 SDValue V2 = Op.getOperand(1);
5921 SmallVector<SDValue, 8> VTBLMask;
5922 for (ArrayRef<int>::iterator
5923 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5924 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5926 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5927 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5928 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5930 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5931 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5934 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5935 SelectionDAG &DAG) {
5937 SDValue OpLHS = Op.getOperand(0);
5938 EVT VT = OpLHS.getValueType();
5940 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5941 "Expect an v8i16/v16i8 type");
5942 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5943 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5944 // extract the first 8 bytes into the top double word and the last 8 bytes
5945 // into the bottom double word. The v8i16 case is similar.
5946 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5947 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5948 DAG.getConstant(ExtractNum, DL, MVT::i32));
5951 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5952 SDValue V1 = Op.getOperand(0);
5953 SDValue V2 = Op.getOperand(1);
5955 EVT VT = Op.getValueType();
5956 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5958 // Convert shuffles that are directly supported on NEON to target-specific
5959 // DAG nodes, instead of keeping them as shuffles and matching them again
5960 // during code selection. This is more efficient and avoids the possibility
5961 // of inconsistencies between legalization and selection.
5962 // FIXME: floating-point vectors should be canonicalized to integer vectors
5963 // of the same time so that they get CSEd properly.
5964 ArrayRef<int> ShuffleMask = SVN->getMask();
5966 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5967 if (EltSize <= 32) {
5968 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5969 int Lane = SVN->getSplatIndex();
5970 // If this is undef splat, generate it via "just" vdup, if possible.
5971 if (Lane == -1) Lane = 0;
5973 // Test if V1 is a SCALAR_TO_VECTOR.
5974 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5975 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5977 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5978 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5980 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5981 !isa<ConstantSDNode>(V1.getOperand(0))) {
5982 bool IsScalarToVector = true;
5983 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5984 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5985 IsScalarToVector = false;
5988 if (IsScalarToVector)
5989 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5991 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5992 DAG.getConstant(Lane, dl, MVT::i32));
5997 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6000 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6001 DAG.getConstant(Imm, dl, MVT::i32));
6004 if (isVREVMask(ShuffleMask, VT, 64))
6005 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6006 if (isVREVMask(ShuffleMask, VT, 32))
6007 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6008 if (isVREVMask(ShuffleMask, VT, 16))
6009 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6011 if (V2->getOpcode() == ISD::UNDEF &&
6012 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6013 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6014 DAG.getConstant(Imm, dl, MVT::i32));
6017 // Check for Neon shuffles that modify both input vectors in place.
6018 // If both results are used, i.e., if there are two shuffles with the same
6019 // source operands and with masks corresponding to both results of one of
6020 // these operations, DAG memoization will ensure that a single node is
6021 // used for both shuffles.
6022 unsigned WhichResult;
6024 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6025 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6028 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6029 .getValue(WhichResult);
6032 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6033 // shuffles that produce a result larger than their operands with:
6034 // shuffle(concat(v1, undef), concat(v2, undef))
6036 // shuffle(concat(v1, v2), undef)
6037 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6039 // This is useful in the general case, but there are special cases where
6040 // native shuffles produce larger results: the two-result ops.
6042 // Look through the concat when lowering them:
6043 // shuffle(concat(v1, v2), undef)
6045 // concat(VZIP(v1, v2):0, :1)
6047 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6048 V2->getOpcode() == ISD::UNDEF) {
6049 SDValue SubV1 = V1->getOperand(0);
6050 SDValue SubV2 = V1->getOperand(1);
6051 EVT SubVT = SubV1.getValueType();
6053 // We expect these to have been canonicalized to -1.
6054 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6055 return i < (int)VT.getVectorNumElements();
6056 }) && "Unexpected shuffle index into UNDEF operand!");
6058 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6059 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6062 assert((WhichResult == 0) &&
6063 "In-place shuffle of concat can only have one result!");
6064 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6066 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6072 // If the shuffle is not directly supported and it has 4 elements, use
6073 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6074 unsigned NumElts = VT.getVectorNumElements();
6076 unsigned PFIndexes[4];
6077 for (unsigned i = 0; i != 4; ++i) {
6078 if (ShuffleMask[i] < 0)
6081 PFIndexes[i] = ShuffleMask[i];
6084 // Compute the index in the perfect shuffle table.
6085 unsigned PFTableIndex =
6086 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6087 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6088 unsigned Cost = (PFEntry >> 30);
6091 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6094 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6095 if (EltSize >= 32) {
6096 // Do the expansion with floating-point types, since that is what the VFP
6097 // registers are defined to use, and since i64 is not legal.
6098 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6099 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6100 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6101 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6102 SmallVector<SDValue, 8> Ops;
6103 for (unsigned i = 0; i < NumElts; ++i) {
6104 if (ShuffleMask[i] < 0)
6105 Ops.push_back(DAG.getUNDEF(EltVT));
6107 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6108 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6109 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6112 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6113 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6116 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6117 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6119 if (VT == MVT::v8i8) {
6120 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6121 if (NewOp.getNode())
6128 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6129 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6130 SDValue Lane = Op.getOperand(2);
6131 if (!isa<ConstantSDNode>(Lane))
6137 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6138 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6139 SDValue Lane = Op.getOperand(1);
6140 if (!isa<ConstantSDNode>(Lane))
6143 SDValue Vec = Op.getOperand(0);
6144 if (Op.getValueType() == MVT::i32 &&
6145 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6147 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6153 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6154 // The only time a CONCAT_VECTORS operation can have legal types is when
6155 // two 64-bit vectors are concatenated to a 128-bit vector.
6156 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6157 "unexpected CONCAT_VECTORS");
6159 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6160 SDValue Op0 = Op.getOperand(0);
6161 SDValue Op1 = Op.getOperand(1);
6162 if (Op0.getOpcode() != ISD::UNDEF)
6163 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6164 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6165 DAG.getIntPtrConstant(0, dl));
6166 if (Op1.getOpcode() != ISD::UNDEF)
6167 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6168 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6169 DAG.getIntPtrConstant(1, dl));
6170 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6173 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6174 /// element has been zero/sign-extended, depending on the isSigned parameter,
6175 /// from an integer type half its size.
6176 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6178 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6179 EVT VT = N->getValueType(0);
6180 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6181 SDNode *BVN = N->getOperand(0).getNode();
6182 if (BVN->getValueType(0) != MVT::v4i32 ||
6183 BVN->getOpcode() != ISD::BUILD_VECTOR)
6185 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6186 unsigned HiElt = 1 - LoElt;
6187 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6188 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6189 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6190 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6191 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6194 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6195 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6198 if (Hi0->isNullValue() && Hi1->isNullValue())
6204 if (N->getOpcode() != ISD::BUILD_VECTOR)
6207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6208 SDNode *Elt = N->getOperand(i).getNode();
6209 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6210 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6211 unsigned HalfSize = EltSize / 2;
6213 if (!isIntN(HalfSize, C->getSExtValue()))
6216 if (!isUIntN(HalfSize, C->getZExtValue()))
6227 /// isSignExtended - Check if a node is a vector value that is sign-extended
6228 /// or a constant BUILD_VECTOR with sign-extended elements.
6229 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6230 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6232 if (isExtendedBUILD_VECTOR(N, DAG, true))
6237 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6238 /// or a constant BUILD_VECTOR with zero-extended elements.
6239 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6240 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6242 if (isExtendedBUILD_VECTOR(N, DAG, false))
6247 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6248 if (OrigVT.getSizeInBits() >= 64)
6251 assert(OrigVT.isSimple() && "Expecting a simple value type");
6253 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6254 switch (OrigSimpleTy) {
6255 default: llvm_unreachable("Unexpected Vector Type");
6264 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6265 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6266 /// We insert the required extension here to get the vector to fill a D register.
6267 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6270 unsigned ExtOpcode) {
6271 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6272 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6273 // 64-bits we need to insert a new extension so that it will be 64-bits.
6274 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6275 if (OrigTy.getSizeInBits() >= 64)
6278 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6279 EVT NewVT = getExtensionTo64Bits(OrigTy);
6281 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6284 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6285 /// does not do any sign/zero extension. If the original vector is less
6286 /// than 64 bits, an appropriate extension will be added after the load to
6287 /// reach a total size of 64 bits. We have to add the extension separately
6288 /// because ARM does not have a sign/zero extending load for vectors.
6289 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6290 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6292 // The load already has the right type.
6293 if (ExtendedTy == LD->getMemoryVT())
6294 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6295 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6296 LD->isNonTemporal(), LD->isInvariant(),
6297 LD->getAlignment());
6299 // We need to create a zextload/sextload. We cannot just create a load
6300 // followed by a zext/zext node because LowerMUL is also run during normal
6301 // operation legalization where we can't create illegal types.
6302 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6303 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6304 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6305 LD->isNonTemporal(), LD->getAlignment());
6308 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6309 /// extending load, or BUILD_VECTOR with extended elements, return the
6310 /// unextended value. The unextended vector should be 64 bits so that it can
6311 /// be used as an operand to a VMULL instruction. If the original vector size
6312 /// before extension is less than 64 bits we add a an extension to resize
6313 /// the vector to 64 bits.
6314 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6315 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6316 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6317 N->getOperand(0)->getValueType(0),
6321 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6322 return SkipLoadExtensionForVMULL(LD, DAG);
6324 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6325 // have been legalized as a BITCAST from v4i32.
6326 if (N->getOpcode() == ISD::BITCAST) {
6327 SDNode *BVN = N->getOperand(0).getNode();
6328 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6329 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6330 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6331 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6332 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6334 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6335 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6336 EVT VT = N->getValueType(0);
6337 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6338 unsigned NumElts = VT.getVectorNumElements();
6339 MVT TruncVT = MVT::getIntegerVT(EltSize);
6340 SmallVector<SDValue, 8> Ops;
6342 for (unsigned i = 0; i != NumElts; ++i) {
6343 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6344 const APInt &CInt = C->getAPIntValue();
6345 // Element types smaller than 32 bits are not legal, so use i32 elements.
6346 // The values are implicitly truncated so sext vs. zext doesn't matter.
6347 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6349 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6350 MVT::getVectorVT(TruncVT, NumElts), Ops);
6353 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6354 unsigned Opcode = N->getOpcode();
6355 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6356 SDNode *N0 = N->getOperand(0).getNode();
6357 SDNode *N1 = N->getOperand(1).getNode();
6358 return N0->hasOneUse() && N1->hasOneUse() &&
6359 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6364 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6365 unsigned Opcode = N->getOpcode();
6366 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6367 SDNode *N0 = N->getOperand(0).getNode();
6368 SDNode *N1 = N->getOperand(1).getNode();
6369 return N0->hasOneUse() && N1->hasOneUse() &&
6370 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6375 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6376 // Multiplications are only custom-lowered for 128-bit vectors so that
6377 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6378 EVT VT = Op.getValueType();
6379 assert(VT.is128BitVector() && VT.isInteger() &&
6380 "unexpected type for custom-lowering ISD::MUL");
6381 SDNode *N0 = Op.getOperand(0).getNode();
6382 SDNode *N1 = Op.getOperand(1).getNode();
6383 unsigned NewOpc = 0;
6385 bool isN0SExt = isSignExtended(N0, DAG);
6386 bool isN1SExt = isSignExtended(N1, DAG);
6387 if (isN0SExt && isN1SExt)
6388 NewOpc = ARMISD::VMULLs;
6390 bool isN0ZExt = isZeroExtended(N0, DAG);
6391 bool isN1ZExt = isZeroExtended(N1, DAG);
6392 if (isN0ZExt && isN1ZExt)
6393 NewOpc = ARMISD::VMULLu;
6394 else if (isN1SExt || isN1ZExt) {
6395 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6396 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6397 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6398 NewOpc = ARMISD::VMULLs;
6400 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6401 NewOpc = ARMISD::VMULLu;
6403 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6405 NewOpc = ARMISD::VMULLu;
6411 if (VT == MVT::v2i64)
6412 // Fall through to expand this. It is not legal.
6415 // Other vector multiplications are legal.
6420 // Legalize to a VMULL instruction.
6423 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6425 Op0 = SkipExtensionForVMULL(N0, DAG);
6426 assert(Op0.getValueType().is64BitVector() &&
6427 Op1.getValueType().is64BitVector() &&
6428 "unexpected types for extended operands to VMULL");
6429 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6432 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6433 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6440 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6441 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6442 EVT Op1VT = Op1.getValueType();
6443 return DAG.getNode(N0->getOpcode(), DL, VT,
6444 DAG.getNode(NewOpc, DL, VT,
6445 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6446 DAG.getNode(NewOpc, DL, VT,
6447 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6451 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6453 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6454 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6455 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6456 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6457 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6458 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6459 // Get reciprocal estimate.
6460 // float4 recip = vrecpeq_f32(yf);
6461 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6462 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6464 // Because char has a smaller range than uchar, we can actually get away
6465 // without any newton steps. This requires that we use a weird bias
6466 // of 0xb000, however (again, this has been exhaustively tested).
6467 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6468 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6469 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6470 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6471 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6472 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6473 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6474 // Convert back to short.
6475 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6476 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6481 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6483 // Convert to float.
6484 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6485 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6486 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6487 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6488 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6489 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6491 // Use reciprocal estimate and one refinement step.
6492 // float4 recip = vrecpeq_f32(yf);
6493 // recip *= vrecpsq_f32(yf, recip);
6494 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6495 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6497 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6498 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6500 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6501 // Because short has a smaller range than ushort, we can actually get away
6502 // with only a single newton step. This requires that we use a weird bias
6503 // of 89, however (again, this has been exhaustively tested).
6504 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6505 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6506 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6507 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6508 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6509 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6510 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6511 // Convert back to integer and return.
6512 // return vmovn_s32(vcvt_s32_f32(result));
6513 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6514 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6518 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6519 EVT VT = Op.getValueType();
6520 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6521 "unexpected type for custom-lowering ISD::SDIV");
6524 SDValue N0 = Op.getOperand(0);
6525 SDValue N1 = Op.getOperand(1);
6528 if (VT == MVT::v8i8) {
6529 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6530 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6532 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6533 DAG.getIntPtrConstant(4, dl));
6534 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6535 DAG.getIntPtrConstant(4, dl));
6536 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6537 DAG.getIntPtrConstant(0, dl));
6538 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6539 DAG.getIntPtrConstant(0, dl));
6541 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6542 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6544 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6545 N0 = LowerCONCAT_VECTORS(N0, DAG);
6547 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6550 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6553 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6554 EVT VT = Op.getValueType();
6555 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6556 "unexpected type for custom-lowering ISD::UDIV");
6559 SDValue N0 = Op.getOperand(0);
6560 SDValue N1 = Op.getOperand(1);
6563 if (VT == MVT::v8i8) {
6564 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6565 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6567 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6568 DAG.getIntPtrConstant(4, dl));
6569 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6570 DAG.getIntPtrConstant(4, dl));
6571 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6572 DAG.getIntPtrConstant(0, dl));
6573 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6574 DAG.getIntPtrConstant(0, dl));
6576 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6577 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6579 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6580 N0 = LowerCONCAT_VECTORS(N0, DAG);
6582 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6583 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6589 // v4i16 sdiv ... Convert to float.
6590 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6591 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6592 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6593 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6594 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6595 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6597 // Use reciprocal estimate and two refinement steps.
6598 // float4 recip = vrecpeq_f32(yf);
6599 // recip *= vrecpsq_f32(yf, recip);
6600 // recip *= vrecpsq_f32(yf, recip);
6601 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6602 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6604 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6605 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6607 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6608 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6609 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6611 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6612 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6613 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6614 // and that it will never cause us to return an answer too large).
6615 // float4 result = as_float4(as_int4(xf*recip) + 2);
6616 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6617 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6618 N1 = DAG.getConstant(2, dl, MVT::i32);
6619 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6620 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6621 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6622 // Convert back to integer and return.
6623 // return vmovn_u32(vcvt_s32_f32(result));
6624 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6625 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6629 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6630 EVT VT = Op.getNode()->getValueType(0);
6631 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6634 bool ExtraOp = false;
6635 switch (Op.getOpcode()) {
6636 default: llvm_unreachable("Invalid code");
6637 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6638 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6639 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6640 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6644 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6646 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6647 Op.getOperand(1), Op.getOperand(2));
6650 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6651 assert(Subtarget->isTargetDarwin());
6653 // For iOS, we want to call an alternative entry point: __sincos_stret,
6654 // return values are passed via sret.
6656 SDValue Arg = Op.getOperand(0);
6657 EVT ArgVT = Arg.getValueType();
6658 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6659 auto PtrVT = getPointerTy(DAG.getDataLayout());
6661 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6663 // Pair of floats / doubles used to pass the result.
6664 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6666 // Create stack object for sret.
6667 auto &DL = DAG.getDataLayout();
6668 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6669 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6670 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6671 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6677 Entry.Ty = RetTy->getPointerTo();
6678 Entry.isSExt = false;
6679 Entry.isZExt = false;
6680 Entry.isSRet = true;
6681 Args.push_back(Entry);
6685 Entry.isSExt = false;
6686 Entry.isZExt = false;
6687 Args.push_back(Entry);
6689 const char *LibcallName = (ArgVT == MVT::f64)
6690 ? "__sincos_stret" : "__sincosf_stret";
6691 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6693 TargetLowering::CallLoweringInfo CLI(DAG);
6694 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6695 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6697 .setDiscardResult();
6699 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6701 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6702 MachinePointerInfo(), false, false, false, 0);
6704 // Address of cos field.
6705 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6706 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6707 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6708 MachinePointerInfo(), false, false, false, 0);
6710 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6711 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6712 LoadSin.getValue(0), LoadCos.getValue(0));
6715 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6716 // Monotonic load/store is legal for all targets
6717 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6720 // Acquire/Release load/store is not legal for targets without a
6721 // dmb or equivalent available.
6725 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6726 SmallVectorImpl<SDValue> &Results,
6728 const ARMSubtarget *Subtarget) {
6730 SDValue Cycles32, OutChain;
6732 if (Subtarget->hasPerfMon()) {
6733 // Under Power Management extensions, the cycle-count is:
6734 // mrc p15, #0, <Rt>, c9, c13, #0
6735 SDValue Ops[] = { N->getOperand(0), // Chain
6736 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6737 DAG.getConstant(15, DL, MVT::i32),
6738 DAG.getConstant(0, DL, MVT::i32),
6739 DAG.getConstant(9, DL, MVT::i32),
6740 DAG.getConstant(13, DL, MVT::i32),
6741 DAG.getConstant(0, DL, MVT::i32)
6744 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6745 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6746 OutChain = Cycles32.getValue(1);
6748 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6749 // there are older ARM CPUs that have implementation-specific ways of
6750 // obtaining this information (FIXME!).
6751 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6752 OutChain = DAG.getEntryNode();
6756 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6757 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6758 Results.push_back(Cycles64);
6759 Results.push_back(OutChain);
6762 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6763 switch (Op.getOpcode()) {
6764 default: llvm_unreachable("Don't know how to custom lower this!");
6765 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6766 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6767 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6768 case ISD::GlobalAddress:
6769 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6770 default: llvm_unreachable("unknown object format");
6772 return LowerGlobalAddressWindows(Op, DAG);
6774 return LowerGlobalAddressELF(Op, DAG);
6776 return LowerGlobalAddressDarwin(Op, DAG);
6778 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6779 case ISD::SELECT: return LowerSELECT(Op, DAG);
6780 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6781 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6782 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6783 case ISD::VASTART: return LowerVASTART(Op, DAG);
6784 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6785 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6786 case ISD::SINT_TO_FP:
6787 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6788 case ISD::FP_TO_SINT:
6789 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6790 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6791 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6792 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6793 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6794 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6795 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6796 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6797 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6799 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6802 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6803 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6804 case ISD::SRL_PARTS:
6805 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6807 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6808 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6809 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6810 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6811 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6812 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6813 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6814 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6815 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6816 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6817 case ISD::MUL: return LowerMUL(Op, DAG);
6818 case ISD::SDIV: return LowerSDIV(Op, DAG);
6819 case ISD::UDIV: return LowerUDIV(Op, DAG);
6823 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6828 return LowerXALUO(Op, DAG);
6829 case ISD::ATOMIC_LOAD:
6830 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6831 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6833 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6834 case ISD::DYNAMIC_STACKALLOC:
6835 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6836 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6837 llvm_unreachable("Don't know how to custom lower this!");
6838 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6839 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6843 /// ReplaceNodeResults - Replace the results of node with an illegal result
6844 /// type with new values built out of custom code.
6845 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6846 SmallVectorImpl<SDValue>&Results,
6847 SelectionDAG &DAG) const {
6849 switch (N->getOpcode()) {
6851 llvm_unreachable("Don't know how to custom expand this!");
6852 case ISD::READ_REGISTER:
6853 ExpandREAD_REGISTER(N, Results, DAG);
6856 Res = ExpandBITCAST(N, DAG);
6860 Res = Expand64BitShift(N, DAG, Subtarget);
6862 case ISD::READCYCLECOUNTER:
6863 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6867 Results.push_back(Res);
6870 //===----------------------------------------------------------------------===//
6871 // ARM Scheduler Hooks
6872 //===----------------------------------------------------------------------===//
6874 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6875 /// registers the function context.
6876 void ARMTargetLowering::
6877 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6878 MachineBasicBlock *DispatchBB, int FI) const {
6879 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6880 DebugLoc dl = MI->getDebugLoc();
6881 MachineFunction *MF = MBB->getParent();
6882 MachineRegisterInfo *MRI = &MF->getRegInfo();
6883 MachineConstantPool *MCP = MF->getConstantPool();
6884 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6885 const Function *F = MF->getFunction();
6887 bool isThumb = Subtarget->isThumb();
6888 bool isThumb2 = Subtarget->isThumb2();
6890 unsigned PCLabelId = AFI->createPICLabelUId();
6891 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6892 ARMConstantPoolValue *CPV =
6893 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6894 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6896 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6897 : &ARM::GPRRegClass;
6899 // Grab constant pool and fixed stack memory operands.
6900 MachineMemOperand *CPMMO =
6901 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6902 MachineMemOperand::MOLoad, 4, 4);
6904 MachineMemOperand *FIMMOSt =
6905 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6906 MachineMemOperand::MOStore, 4, 4);
6908 // Load the address of the dispatch MBB into the jump buffer.
6910 // Incoming value: jbuf
6911 // ldr.n r5, LCPI1_1
6914 // str r5, [$jbuf, #+4] ; &jbuf[1]
6915 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6916 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6917 .addConstantPoolIndex(CPI)
6918 .addMemOperand(CPMMO));
6919 // Set the low bit because of thumb mode.
6920 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6922 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6923 .addReg(NewVReg1, RegState::Kill)
6925 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6926 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6927 .addReg(NewVReg2, RegState::Kill)
6929 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6930 .addReg(NewVReg3, RegState::Kill)
6932 .addImm(36) // &jbuf[1] :: pc
6933 .addMemOperand(FIMMOSt));
6934 } else if (isThumb) {
6935 // Incoming value: jbuf
6936 // ldr.n r1, LCPI1_4
6940 // add r2, $jbuf, #+4 ; &jbuf[1]
6942 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6943 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6944 .addConstantPoolIndex(CPI)
6945 .addMemOperand(CPMMO));
6946 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6947 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6948 .addReg(NewVReg1, RegState::Kill)
6950 // Set the low bit because of thumb mode.
6951 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6952 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6953 .addReg(ARM::CPSR, RegState::Define)
6955 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6956 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6957 .addReg(ARM::CPSR, RegState::Define)
6958 .addReg(NewVReg2, RegState::Kill)
6959 .addReg(NewVReg3, RegState::Kill));
6960 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6961 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6963 .addImm(36); // &jbuf[1] :: pc
6964 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6965 .addReg(NewVReg4, RegState::Kill)
6966 .addReg(NewVReg5, RegState::Kill)
6968 .addMemOperand(FIMMOSt));
6970 // Incoming value: jbuf
6973 // str r1, [$jbuf, #+4] ; &jbuf[1]
6974 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6975 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6976 .addConstantPoolIndex(CPI)
6978 .addMemOperand(CPMMO));
6979 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6980 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6981 .addReg(NewVReg1, RegState::Kill)
6982 .addImm(PCLabelId));
6983 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6984 .addReg(NewVReg2, RegState::Kill)
6986 .addImm(36) // &jbuf[1] :: pc
6987 .addMemOperand(FIMMOSt));
6991 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6992 MachineBasicBlock *MBB) const {
6993 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6994 DebugLoc dl = MI->getDebugLoc();
6995 MachineFunction *MF = MBB->getParent();
6996 MachineRegisterInfo *MRI = &MF->getRegInfo();
6997 MachineFrameInfo *MFI = MF->getFrameInfo();
6998 int FI = MFI->getFunctionContextIndex();
7000 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7001 : &ARM::GPRnopcRegClass;
7003 // Get a mapping of the call site numbers to all of the landing pads they're
7005 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7006 unsigned MaxCSNum = 0;
7007 MachineModuleInfo &MMI = MF->getMMI();
7008 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7010 if (!BB->isLandingPad()) continue;
7012 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7014 for (MachineBasicBlock::iterator
7015 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7016 if (!II->isEHLabel()) continue;
7018 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7019 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7021 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7022 for (SmallVectorImpl<unsigned>::iterator
7023 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7024 CSI != CSE; ++CSI) {
7025 CallSiteNumToLPad[*CSI].push_back(BB);
7026 MaxCSNum = std::max(MaxCSNum, *CSI);
7032 // Get an ordered list of the machine basic blocks for the jump table.
7033 std::vector<MachineBasicBlock*> LPadList;
7034 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7035 LPadList.reserve(CallSiteNumToLPad.size());
7036 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7037 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7038 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7039 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7040 LPadList.push_back(*II);
7041 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7045 assert(!LPadList.empty() &&
7046 "No landing pad destinations for the dispatch jump table!");
7048 // Create the jump table and associated information.
7049 MachineJumpTableInfo *JTI =
7050 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7051 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7052 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7054 // Create the MBBs for the dispatch code.
7056 // Shove the dispatch's address into the return slot in the function context.
7057 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7058 DispatchBB->setIsLandingPad();
7060 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7061 unsigned trap_opcode;
7062 if (Subtarget->isThumb())
7063 trap_opcode = ARM::tTRAP;
7065 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7067 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7068 DispatchBB->addSuccessor(TrapBB);
7070 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7071 DispatchBB->addSuccessor(DispContBB);
7074 MF->insert(MF->end(), DispatchBB);
7075 MF->insert(MF->end(), DispContBB);
7076 MF->insert(MF->end(), TrapBB);
7078 // Insert code into the entry block that creates and registers the function
7080 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7082 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7083 MachinePointerInfo::getFixedStack(*MF, FI),
7084 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7086 MachineInstrBuilder MIB;
7087 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7089 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7090 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7092 // Add a register mask with no preserved registers. This results in all
7093 // registers being marked as clobbered.
7094 MIB.addRegMask(RI.getNoPreservedMask());
7096 unsigned NumLPads = LPadList.size();
7097 if (Subtarget->isThumb2()) {
7098 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7099 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7102 .addMemOperand(FIMMOLd));
7104 if (NumLPads < 256) {
7105 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7107 .addImm(LPadList.size()));
7109 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7110 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7111 .addImm(NumLPads & 0xFFFF));
7113 unsigned VReg2 = VReg1;
7114 if ((NumLPads & 0xFFFF0000) != 0) {
7115 VReg2 = MRI->createVirtualRegister(TRC);
7116 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7118 .addImm(NumLPads >> 16));
7121 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7126 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7131 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7132 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7133 .addJumpTableIndex(MJTI));
7135 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7138 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7139 .addReg(NewVReg3, RegState::Kill)
7141 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7143 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7144 .addReg(NewVReg4, RegState::Kill)
7146 .addJumpTableIndex(MJTI);
7147 } else if (Subtarget->isThumb()) {
7148 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7149 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7152 .addMemOperand(FIMMOLd));
7154 if (NumLPads < 256) {
7155 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7159 MachineConstantPool *ConstantPool = MF->getConstantPool();
7160 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7161 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7163 // MachineConstantPool wants an explicit alignment.
7164 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7166 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7167 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7169 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7170 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7171 .addReg(VReg1, RegState::Define)
7172 .addConstantPoolIndex(Idx));
7173 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7178 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7183 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7184 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7185 .addReg(ARM::CPSR, RegState::Define)
7189 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7190 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7191 .addJumpTableIndex(MJTI));
7193 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7194 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7195 .addReg(ARM::CPSR, RegState::Define)
7196 .addReg(NewVReg2, RegState::Kill)
7199 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7200 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7202 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7203 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7204 .addReg(NewVReg4, RegState::Kill)
7206 .addMemOperand(JTMMOLd));
7208 unsigned NewVReg6 = NewVReg5;
7209 if (RelocM == Reloc::PIC_) {
7210 NewVReg6 = MRI->createVirtualRegister(TRC);
7211 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7212 .addReg(ARM::CPSR, RegState::Define)
7213 .addReg(NewVReg5, RegState::Kill)
7217 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7218 .addReg(NewVReg6, RegState::Kill)
7219 .addJumpTableIndex(MJTI);
7221 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7222 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7225 .addMemOperand(FIMMOLd));
7227 if (NumLPads < 256) {
7228 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7231 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7232 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7233 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7234 .addImm(NumLPads & 0xFFFF));
7236 unsigned VReg2 = VReg1;
7237 if ((NumLPads & 0xFFFF0000) != 0) {
7238 VReg2 = MRI->createVirtualRegister(TRC);
7239 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7241 .addImm(NumLPads >> 16));
7244 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7248 MachineConstantPool *ConstantPool = MF->getConstantPool();
7249 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7250 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7252 // MachineConstantPool wants an explicit alignment.
7253 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7255 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7256 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7258 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7259 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7260 .addReg(VReg1, RegState::Define)
7261 .addConstantPoolIndex(Idx)
7263 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7265 .addReg(VReg1, RegState::Kill));
7268 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7273 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7275 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7277 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7278 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7279 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7280 .addJumpTableIndex(MJTI));
7282 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7283 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7284 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7286 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7287 .addReg(NewVReg3, RegState::Kill)
7290 .addMemOperand(JTMMOLd));
7292 if (RelocM == Reloc::PIC_) {
7293 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7294 .addReg(NewVReg5, RegState::Kill)
7296 .addJumpTableIndex(MJTI);
7298 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7299 .addReg(NewVReg5, RegState::Kill)
7300 .addJumpTableIndex(MJTI);
7304 // Add the jump table entries as successors to the MBB.
7305 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7306 for (std::vector<MachineBasicBlock*>::iterator
7307 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7308 MachineBasicBlock *CurMBB = *I;
7309 if (SeenMBBs.insert(CurMBB).second)
7310 DispContBB->addSuccessor(CurMBB);
7313 // N.B. the order the invoke BBs are processed in doesn't matter here.
7314 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7315 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7316 for (MachineBasicBlock *BB : InvokeBBs) {
7318 // Remove the landing pad successor from the invoke block and replace it
7319 // with the new dispatch block.
7320 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7322 while (!Successors.empty()) {
7323 MachineBasicBlock *SMBB = Successors.pop_back_val();
7324 if (SMBB->isLandingPad()) {
7325 BB->removeSuccessor(SMBB);
7326 MBBLPads.push_back(SMBB);
7330 BB->addSuccessor(DispatchBB);
7332 // Find the invoke call and mark all of the callee-saved registers as
7333 // 'implicit defined' so that they're spilled. This prevents code from
7334 // moving instructions to before the EH block, where they will never be
7336 for (MachineBasicBlock::reverse_iterator
7337 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7338 if (!II->isCall()) continue;
7340 DenseMap<unsigned, bool> DefRegs;
7341 for (MachineInstr::mop_iterator
7342 OI = II->operands_begin(), OE = II->operands_end();
7344 if (!OI->isReg()) continue;
7345 DefRegs[OI->getReg()] = true;
7348 MachineInstrBuilder MIB(*MF, &*II);
7350 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7351 unsigned Reg = SavedRegs[i];
7352 if (Subtarget->isThumb2() &&
7353 !ARM::tGPRRegClass.contains(Reg) &&
7354 !ARM::hGPRRegClass.contains(Reg))
7356 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7358 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7361 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7368 // Mark all former landing pads as non-landing pads. The dispatch is the only
7370 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7371 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7372 (*I)->setIsLandingPad(false);
7374 // The instruction is gone now.
7375 MI->eraseFromParent();
7379 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7380 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7381 E = MBB->succ_end(); I != E; ++I)
7384 llvm_unreachable("Expecting a BB with two successors!");
7387 /// Return the load opcode for a given load size. If load size >= 8,
7388 /// neon opcode will be returned.
7389 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7391 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7392 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7394 return LdSize == 4 ? ARM::tLDRi
7395 : LdSize == 2 ? ARM::tLDRHi
7396 : LdSize == 1 ? ARM::tLDRBi : 0;
7398 return LdSize == 4 ? ARM::t2LDR_POST
7399 : LdSize == 2 ? ARM::t2LDRH_POST
7400 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7401 return LdSize == 4 ? ARM::LDR_POST_IMM
7402 : LdSize == 2 ? ARM::LDRH_POST
7403 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7406 /// Return the store opcode for a given store size. If store size >= 8,
7407 /// neon opcode will be returned.
7408 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7410 return StSize == 16 ? ARM::VST1q32wb_fixed
7411 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7413 return StSize == 4 ? ARM::tSTRi
7414 : StSize == 2 ? ARM::tSTRHi
7415 : StSize == 1 ? ARM::tSTRBi : 0;
7417 return StSize == 4 ? ARM::t2STR_POST
7418 : StSize == 2 ? ARM::t2STRH_POST
7419 : StSize == 1 ? ARM::t2STRB_POST : 0;
7420 return StSize == 4 ? ARM::STR_POST_IMM
7421 : StSize == 2 ? ARM::STRH_POST
7422 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7425 /// Emit a post-increment load operation with given size. The instructions
7426 /// will be added to BB at Pos.
7427 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7428 const TargetInstrInfo *TII, DebugLoc dl,
7429 unsigned LdSize, unsigned Data, unsigned AddrIn,
7430 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7431 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7432 assert(LdOpc != 0 && "Should have a load opcode");
7434 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7435 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7437 } else if (IsThumb1) {
7438 // load + update AddrIn
7439 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7440 .addReg(AddrIn).addImm(0));
7441 MachineInstrBuilder MIB =
7442 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7443 MIB = AddDefaultT1CC(MIB);
7444 MIB.addReg(AddrIn).addImm(LdSize);
7445 AddDefaultPred(MIB);
7446 } else if (IsThumb2) {
7447 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7448 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7451 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7452 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7453 .addReg(0).addImm(LdSize));
7457 /// Emit a post-increment store operation with given size. The instructions
7458 /// will be added to BB at Pos.
7459 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7460 const TargetInstrInfo *TII, DebugLoc dl,
7461 unsigned StSize, unsigned Data, unsigned AddrIn,
7462 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7463 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7464 assert(StOpc != 0 && "Should have a store opcode");
7466 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7467 .addReg(AddrIn).addImm(0).addReg(Data));
7468 } else if (IsThumb1) {
7469 // store + update AddrIn
7470 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7471 .addReg(AddrIn).addImm(0));
7472 MachineInstrBuilder MIB =
7473 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7474 MIB = AddDefaultT1CC(MIB);
7475 MIB.addReg(AddrIn).addImm(StSize);
7476 AddDefaultPred(MIB);
7477 } else if (IsThumb2) {
7478 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7479 .addReg(Data).addReg(AddrIn).addImm(StSize));
7481 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7482 .addReg(Data).addReg(AddrIn).addReg(0)
7488 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7489 MachineBasicBlock *BB) const {
7490 // This pseudo instruction has 3 operands: dst, src, size
7491 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7492 // Otherwise, we will generate unrolled scalar copies.
7493 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7494 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7495 MachineFunction::iterator It = BB;
7498 unsigned dest = MI->getOperand(0).getReg();
7499 unsigned src = MI->getOperand(1).getReg();
7500 unsigned SizeVal = MI->getOperand(2).getImm();
7501 unsigned Align = MI->getOperand(3).getImm();
7502 DebugLoc dl = MI->getDebugLoc();
7504 MachineFunction *MF = BB->getParent();
7505 MachineRegisterInfo &MRI = MF->getRegInfo();
7506 unsigned UnitSize = 0;
7507 const TargetRegisterClass *TRC = nullptr;
7508 const TargetRegisterClass *VecTRC = nullptr;
7510 bool IsThumb1 = Subtarget->isThumb1Only();
7511 bool IsThumb2 = Subtarget->isThumb2();
7515 } else if (Align & 2) {
7518 // Check whether we can use NEON instructions.
7519 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7520 Subtarget->hasNEON()) {
7521 if ((Align % 16 == 0) && SizeVal >= 16)
7523 else if ((Align % 8 == 0) && SizeVal >= 8)
7526 // Can't use NEON instructions.
7531 // Select the correct opcode and register class for unit size load/store
7532 bool IsNeon = UnitSize >= 8;
7533 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7535 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7536 : UnitSize == 8 ? &ARM::DPRRegClass
7539 unsigned BytesLeft = SizeVal % UnitSize;
7540 unsigned LoopSize = SizeVal - BytesLeft;
7542 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7543 // Use LDR and STR to copy.
7544 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7545 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7546 unsigned srcIn = src;
7547 unsigned destIn = dest;
7548 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7549 unsigned srcOut = MRI.createVirtualRegister(TRC);
7550 unsigned destOut = MRI.createVirtualRegister(TRC);
7551 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7552 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7553 IsThumb1, IsThumb2);
7554 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7555 IsThumb1, IsThumb2);
7560 // Handle the leftover bytes with LDRB and STRB.
7561 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7562 // [destOut] = STRB_POST(scratch, destIn, 1)
7563 for (unsigned i = 0; i < BytesLeft; i++) {
7564 unsigned srcOut = MRI.createVirtualRegister(TRC);
7565 unsigned destOut = MRI.createVirtualRegister(TRC);
7566 unsigned scratch = MRI.createVirtualRegister(TRC);
7567 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7568 IsThumb1, IsThumb2);
7569 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7570 IsThumb1, IsThumb2);
7574 MI->eraseFromParent(); // The instruction is gone now.
7578 // Expand the pseudo op to a loop.
7581 // movw varEnd, # --> with thumb2
7583 // ldrcp varEnd, idx --> without thumb2
7584 // fallthrough --> loopMBB
7586 // PHI varPhi, varEnd, varLoop
7587 // PHI srcPhi, src, srcLoop
7588 // PHI destPhi, dst, destLoop
7589 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7590 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7591 // subs varLoop, varPhi, #UnitSize
7593 // fallthrough --> exitMBB
7595 // epilogue to handle left-over bytes
7596 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7597 // [destOut] = STRB_POST(scratch, destLoop, 1)
7598 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7599 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7600 MF->insert(It, loopMBB);
7601 MF->insert(It, exitMBB);
7603 // Transfer the remainder of BB and its successor edges to exitMBB.
7604 exitMBB->splice(exitMBB->begin(), BB,
7605 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7606 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7608 // Load an immediate to varEnd.
7609 unsigned varEnd = MRI.createVirtualRegister(TRC);
7610 if (Subtarget->useMovt(*MF)) {
7611 unsigned Vtmp = varEnd;
7612 if ((LoopSize & 0xFFFF0000) != 0)
7613 Vtmp = MRI.createVirtualRegister(TRC);
7614 AddDefaultPred(BuildMI(BB, dl,
7615 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7616 Vtmp).addImm(LoopSize & 0xFFFF));
7618 if ((LoopSize & 0xFFFF0000) != 0)
7619 AddDefaultPred(BuildMI(BB, dl,
7620 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7623 .addImm(LoopSize >> 16));
7625 MachineConstantPool *ConstantPool = MF->getConstantPool();
7626 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7627 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7629 // MachineConstantPool wants an explicit alignment.
7630 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7632 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7633 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7636 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7637 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7639 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7640 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7642 BB->addSuccessor(loopMBB);
7644 // Generate the loop body:
7645 // varPhi = PHI(varLoop, varEnd)
7646 // srcPhi = PHI(srcLoop, src)
7647 // destPhi = PHI(destLoop, dst)
7648 MachineBasicBlock *entryBB = BB;
7650 unsigned varLoop = MRI.createVirtualRegister(TRC);
7651 unsigned varPhi = MRI.createVirtualRegister(TRC);
7652 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7653 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7654 unsigned destLoop = MRI.createVirtualRegister(TRC);
7655 unsigned destPhi = MRI.createVirtualRegister(TRC);
7657 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7658 .addReg(varLoop).addMBB(loopMBB)
7659 .addReg(varEnd).addMBB(entryBB);
7660 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7661 .addReg(srcLoop).addMBB(loopMBB)
7662 .addReg(src).addMBB(entryBB);
7663 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7664 .addReg(destLoop).addMBB(loopMBB)
7665 .addReg(dest).addMBB(entryBB);
7667 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7668 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7669 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7670 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7671 IsThumb1, IsThumb2);
7672 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7673 IsThumb1, IsThumb2);
7675 // Decrement loop variable by UnitSize.
7677 MachineInstrBuilder MIB =
7678 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7679 MIB = AddDefaultT1CC(MIB);
7680 MIB.addReg(varPhi).addImm(UnitSize);
7681 AddDefaultPred(MIB);
7683 MachineInstrBuilder MIB =
7684 BuildMI(*BB, BB->end(), dl,
7685 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7686 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7687 MIB->getOperand(5).setReg(ARM::CPSR);
7688 MIB->getOperand(5).setIsDef(true);
7690 BuildMI(*BB, BB->end(), dl,
7691 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7692 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7694 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7695 BB->addSuccessor(loopMBB);
7696 BB->addSuccessor(exitMBB);
7698 // Add epilogue to handle BytesLeft.
7700 MachineInstr *StartOfExit = exitMBB->begin();
7702 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7703 // [destOut] = STRB_POST(scratch, destLoop, 1)
7704 unsigned srcIn = srcLoop;
7705 unsigned destIn = destLoop;
7706 for (unsigned i = 0; i < BytesLeft; i++) {
7707 unsigned srcOut = MRI.createVirtualRegister(TRC);
7708 unsigned destOut = MRI.createVirtualRegister(TRC);
7709 unsigned scratch = MRI.createVirtualRegister(TRC);
7710 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7711 IsThumb1, IsThumb2);
7712 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7713 IsThumb1, IsThumb2);
7718 MI->eraseFromParent(); // The instruction is gone now.
7723 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7724 MachineBasicBlock *MBB) const {
7725 const TargetMachine &TM = getTargetMachine();
7726 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7727 DebugLoc DL = MI->getDebugLoc();
7729 assert(Subtarget->isTargetWindows() &&
7730 "__chkstk is only supported on Windows");
7731 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7733 // __chkstk takes the number of words to allocate on the stack in R4, and
7734 // returns the stack adjustment in number of bytes in R4. This will not
7735 // clober any other registers (other than the obvious lr).
7737 // Although, technically, IP should be considered a register which may be
7738 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7739 // thumb-2 environment, so there is no interworking required. As a result, we
7740 // do not expect a veneer to be emitted by the linker, clobbering IP.
7742 // Each module receives its own copy of __chkstk, so no import thunk is
7743 // required, again, ensuring that IP is not clobbered.
7745 // Finally, although some linkers may theoretically provide a trampoline for
7746 // out of range calls (which is quite common due to a 32M range limitation of
7747 // branches for Thumb), we can generate the long-call version via
7748 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7751 switch (TM.getCodeModel()) {
7752 case CodeModel::Small:
7753 case CodeModel::Medium:
7754 case CodeModel::Default:
7755 case CodeModel::Kernel:
7756 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7757 .addImm((unsigned)ARMCC::AL).addReg(0)
7758 .addExternalSymbol("__chkstk")
7759 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7760 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7761 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7763 case CodeModel::Large:
7764 case CodeModel::JITDefault: {
7765 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7766 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7768 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7769 .addExternalSymbol("__chkstk");
7770 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7771 .addImm((unsigned)ARMCC::AL).addReg(0)
7772 .addReg(Reg, RegState::Kill)
7773 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7774 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7775 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7780 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7782 .addReg(ARM::SP).addReg(ARM::R4)));
7784 MI->eraseFromParent();
7789 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7790 MachineBasicBlock *BB) const {
7791 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7792 DebugLoc dl = MI->getDebugLoc();
7793 bool isThumb2 = Subtarget->isThumb2();
7794 switch (MI->getOpcode()) {
7797 llvm_unreachable("Unexpected instr type to insert");
7799 // The Thumb2 pre-indexed stores have the same MI operands, they just
7800 // define them differently in the .td files from the isel patterns, so
7801 // they need pseudos.
7802 case ARM::t2STR_preidx:
7803 MI->setDesc(TII->get(ARM::t2STR_PRE));
7805 case ARM::t2STRB_preidx:
7806 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7808 case ARM::t2STRH_preidx:
7809 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7812 case ARM::STRi_preidx:
7813 case ARM::STRBi_preidx: {
7814 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7815 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7816 // Decode the offset.
7817 unsigned Offset = MI->getOperand(4).getImm();
7818 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7819 Offset = ARM_AM::getAM2Offset(Offset);
7823 MachineMemOperand *MMO = *MI->memoperands_begin();
7824 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7825 .addOperand(MI->getOperand(0)) // Rn_wb
7826 .addOperand(MI->getOperand(1)) // Rt
7827 .addOperand(MI->getOperand(2)) // Rn
7828 .addImm(Offset) // offset (skip GPR==zero_reg)
7829 .addOperand(MI->getOperand(5)) // pred
7830 .addOperand(MI->getOperand(6))
7831 .addMemOperand(MMO);
7832 MI->eraseFromParent();
7835 case ARM::STRr_preidx:
7836 case ARM::STRBr_preidx:
7837 case ARM::STRH_preidx: {
7839 switch (MI->getOpcode()) {
7840 default: llvm_unreachable("unexpected opcode!");
7841 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7842 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7843 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7845 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7846 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7847 MIB.addOperand(MI->getOperand(i));
7848 MI->eraseFromParent();
7852 case ARM::tMOVCCr_pseudo: {
7853 // To "insert" a SELECT_CC instruction, we actually have to insert the
7854 // diamond control-flow pattern. The incoming instruction knows the
7855 // destination vreg to set, the condition code register to branch on, the
7856 // true/false values to select between, and a branch opcode to use.
7857 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7858 MachineFunction::iterator It = BB;
7864 // cmpTY ccX, r1, r2
7866 // fallthrough --> copy0MBB
7867 MachineBasicBlock *thisMBB = BB;
7868 MachineFunction *F = BB->getParent();
7869 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7870 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7871 F->insert(It, copy0MBB);
7872 F->insert(It, sinkMBB);
7874 // Transfer the remainder of BB and its successor edges to sinkMBB.
7875 sinkMBB->splice(sinkMBB->begin(), BB,
7876 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7877 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7879 BB->addSuccessor(copy0MBB);
7880 BB->addSuccessor(sinkMBB);
7882 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7883 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7886 // %FalseValue = ...
7887 // # fallthrough to sinkMBB
7890 // Update machine-CFG edges
7891 BB->addSuccessor(sinkMBB);
7894 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7897 BuildMI(*BB, BB->begin(), dl,
7898 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7899 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7900 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7902 MI->eraseFromParent(); // The pseudo instruction is gone now.
7907 case ARM::BCCZi64: {
7908 // If there is an unconditional branch to the other successor, remove it.
7909 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7911 // Compare both parts that make up the double comparison separately for
7913 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7915 unsigned LHS1 = MI->getOperand(1).getReg();
7916 unsigned LHS2 = MI->getOperand(2).getReg();
7918 AddDefaultPred(BuildMI(BB, dl,
7919 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7920 .addReg(LHS1).addImm(0));
7921 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7922 .addReg(LHS2).addImm(0)
7923 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7925 unsigned RHS1 = MI->getOperand(3).getReg();
7926 unsigned RHS2 = MI->getOperand(4).getReg();
7927 AddDefaultPred(BuildMI(BB, dl,
7928 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7929 .addReg(LHS1).addReg(RHS1));
7930 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7931 .addReg(LHS2).addReg(RHS2)
7932 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7935 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7936 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7937 if (MI->getOperand(0).getImm() == ARMCC::NE)
7938 std::swap(destMBB, exitMBB);
7940 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7941 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7943 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7945 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7947 MI->eraseFromParent(); // The pseudo instruction is gone now.
7951 case ARM::Int_eh_sjlj_setjmp:
7952 case ARM::Int_eh_sjlj_setjmp_nofp:
7953 case ARM::tInt_eh_sjlj_setjmp:
7954 case ARM::t2Int_eh_sjlj_setjmp:
7955 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7958 case ARM::Int_eh_sjlj_setup_dispatch:
7959 EmitSjLjDispatchBlock(MI, BB);
7964 // To insert an ABS instruction, we have to insert the
7965 // diamond control-flow pattern. The incoming instruction knows the
7966 // source vreg to test against 0, the destination vreg to set,
7967 // the condition code register to branch on, the
7968 // true/false values to select between, and a branch opcode to use.
7973 // BCC (branch to SinkBB if V0 >= 0)
7974 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7975 // SinkBB: V1 = PHI(V2, V3)
7976 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7977 MachineFunction::iterator BBI = BB;
7979 MachineFunction *Fn = BB->getParent();
7980 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7981 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7982 Fn->insert(BBI, RSBBB);
7983 Fn->insert(BBI, SinkBB);
7985 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7986 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7987 bool ABSSrcKIll = MI->getOperand(1).isKill();
7988 bool isThumb2 = Subtarget->isThumb2();
7989 MachineRegisterInfo &MRI = Fn->getRegInfo();
7990 // In Thumb mode S must not be specified if source register is the SP or
7991 // PC and if destination register is the SP, so restrict register class
7992 unsigned NewRsbDstReg =
7993 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7995 // Transfer the remainder of BB and its successor edges to sinkMBB.
7996 SinkBB->splice(SinkBB->begin(), BB,
7997 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7998 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8000 BB->addSuccessor(RSBBB);
8001 BB->addSuccessor(SinkBB);
8003 // fall through to SinkMBB
8004 RSBBB->addSuccessor(SinkBB);
8006 // insert a cmp at the end of BB
8007 AddDefaultPred(BuildMI(BB, dl,
8008 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8009 .addReg(ABSSrcReg).addImm(0));
8011 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8013 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8014 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8016 // insert rsbri in RSBBB
8017 // Note: BCC and rsbri will be converted into predicated rsbmi
8018 // by if-conversion pass
8019 BuildMI(*RSBBB, RSBBB->begin(), dl,
8020 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8021 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8022 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8024 // insert PHI in SinkBB,
8025 // reuse ABSDstReg to not change uses of ABS instruction
8026 BuildMI(*SinkBB, SinkBB->begin(), dl,
8027 TII->get(ARM::PHI), ABSDstReg)
8028 .addReg(NewRsbDstReg).addMBB(RSBBB)
8029 .addReg(ABSSrcReg).addMBB(BB);
8031 // remove ABS instruction
8032 MI->eraseFromParent();
8034 // return last added BB
8037 case ARM::COPY_STRUCT_BYVAL_I32:
8039 return EmitStructByval(MI, BB);
8040 case ARM::WIN__CHKSTK:
8041 return EmitLowered__chkstk(MI, BB);
8045 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8046 SDNode *Node) const {
8047 const MCInstrDesc *MCID = &MI->getDesc();
8048 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8049 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8050 // operand is still set to noreg. If needed, set the optional operand's
8051 // register to CPSR, and remove the redundant implicit def.
8053 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8055 // Rename pseudo opcodes.
8056 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8058 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8059 MCID = &TII->get(NewOpc);
8061 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8062 "converted opcode should be the same except for cc_out");
8066 // Add the optional cc_out operand
8067 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8069 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8071 // Any ARM instruction that sets the 's' bit should specify an optional
8072 // "cc_out" operand in the last operand position.
8073 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8074 assert(!NewOpc && "Optional cc_out operand required");
8077 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8078 // since we already have an optional CPSR def.
8079 bool definesCPSR = false;
8080 bool deadCPSR = false;
8081 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8083 const MachineOperand &MO = MI->getOperand(i);
8084 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8088 MI->RemoveOperand(i);
8093 assert(!NewOpc && "Optional cc_out operand required");
8096 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8098 assert(!MI->getOperand(ccOutIdx).getReg() &&
8099 "expect uninitialized optional cc_out operand");
8103 // If this instruction was defined with an optional CPSR def and its dag node
8104 // had a live implicit CPSR def, then activate the optional CPSR def.
8105 MachineOperand &MO = MI->getOperand(ccOutIdx);
8106 MO.setReg(ARM::CPSR);
8110 //===----------------------------------------------------------------------===//
8111 // ARM Optimization Hooks
8112 //===----------------------------------------------------------------------===//
8114 // Helper function that checks if N is a null or all ones constant.
8115 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8116 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8119 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8122 // Return true if N is conditionally 0 or all ones.
8123 // Detects these expressions where cc is an i1 value:
8125 // (select cc 0, y) [AllOnes=0]
8126 // (select cc y, 0) [AllOnes=0]
8127 // (zext cc) [AllOnes=0]
8128 // (sext cc) [AllOnes=0/1]
8129 // (select cc -1, y) [AllOnes=1]
8130 // (select cc y, -1) [AllOnes=1]
8132 // Invert is set when N is the null/all ones constant when CC is false.
8133 // OtherOp is set to the alternative value of N.
8134 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8135 SDValue &CC, bool &Invert,
8137 SelectionDAG &DAG) {
8138 switch (N->getOpcode()) {
8139 default: return false;
8141 CC = N->getOperand(0);
8142 SDValue N1 = N->getOperand(1);
8143 SDValue N2 = N->getOperand(2);
8144 if (isZeroOrAllOnes(N1, AllOnes)) {
8149 if (isZeroOrAllOnes(N2, AllOnes)) {
8156 case ISD::ZERO_EXTEND:
8157 // (zext cc) can never be the all ones value.
8161 case ISD::SIGN_EXTEND: {
8163 EVT VT = N->getValueType(0);
8164 CC = N->getOperand(0);
8165 if (CC.getValueType() != MVT::i1)
8169 // When looking for an AllOnes constant, N is an sext, and the 'other'
8171 OtherOp = DAG.getConstant(0, dl, VT);
8172 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8173 // When looking for a 0 constant, N can be zext or sext.
8174 OtherOp = DAG.getConstant(1, dl, VT);
8176 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8183 // Combine a constant select operand into its use:
8185 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8186 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8187 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8188 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8189 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8191 // The transform is rejected if the select doesn't have a constant operand that
8192 // is null, or all ones when AllOnes is set.
8194 // Also recognize sext/zext from i1:
8196 // (add (zext cc), x) -> (select cc (add x, 1), x)
8197 // (add (sext cc), x) -> (select cc (add x, -1), x)
8199 // These transformations eventually create predicated instructions.
8201 // @param N The node to transform.
8202 // @param Slct The N operand that is a select.
8203 // @param OtherOp The other N operand (x above).
8204 // @param DCI Context.
8205 // @param AllOnes Require the select constant to be all ones instead of null.
8206 // @returns The new node, or SDValue() on failure.
8208 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8209 TargetLowering::DAGCombinerInfo &DCI,
8210 bool AllOnes = false) {
8211 SelectionDAG &DAG = DCI.DAG;
8212 EVT VT = N->getValueType(0);
8213 SDValue NonConstantVal;
8216 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8217 NonConstantVal, DAG))
8220 // Slct is now know to be the desired identity constant when CC is true.
8221 SDValue TrueVal = OtherOp;
8222 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8223 OtherOp, NonConstantVal);
8224 // Unless SwapSelectOps says CC should be false.
8226 std::swap(TrueVal, FalseVal);
8228 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8229 CCOp, TrueVal, FalseVal);
8232 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8234 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8235 TargetLowering::DAGCombinerInfo &DCI) {
8236 SDValue N0 = N->getOperand(0);
8237 SDValue N1 = N->getOperand(1);
8238 if (N0.getNode()->hasOneUse()) {
8239 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8240 if (Result.getNode())
8243 if (N1.getNode()->hasOneUse()) {
8244 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8245 if (Result.getNode())
8251 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8252 // (only after legalization).
8253 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8254 TargetLowering::DAGCombinerInfo &DCI,
8255 const ARMSubtarget *Subtarget) {
8257 // Only perform optimization if after legalize, and if NEON is available. We
8258 // also expected both operands to be BUILD_VECTORs.
8259 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8260 || N0.getOpcode() != ISD::BUILD_VECTOR
8261 || N1.getOpcode() != ISD::BUILD_VECTOR)
8264 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8265 EVT VT = N->getValueType(0);
8266 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8269 // Check that the vector operands are of the right form.
8270 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8271 // operands, where N is the size of the formed vector.
8272 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8273 // index such that we have a pair wise add pattern.
8275 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8276 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8278 SDValue Vec = N0->getOperand(0)->getOperand(0);
8279 SDNode *V = Vec.getNode();
8280 unsigned nextIndex = 0;
8282 // For each operands to the ADD which are BUILD_VECTORs,
8283 // check to see if each of their operands are an EXTRACT_VECTOR with
8284 // the same vector and appropriate index.
8285 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8286 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8287 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8289 SDValue ExtVec0 = N0->getOperand(i);
8290 SDValue ExtVec1 = N1->getOperand(i);
8292 // First operand is the vector, verify its the same.
8293 if (V != ExtVec0->getOperand(0).getNode() ||
8294 V != ExtVec1->getOperand(0).getNode())
8297 // Second is the constant, verify its correct.
8298 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8299 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8301 // For the constant, we want to see all the even or all the odd.
8302 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8303 || C1->getZExtValue() != nextIndex+1)
8312 // Create VPADDL node.
8313 SelectionDAG &DAG = DCI.DAG;
8314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8318 // Build operand list.
8319 SmallVector<SDValue, 8> Ops;
8320 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8321 TLI.getPointerTy(DAG.getDataLayout())));
8323 // Input is the vector.
8326 // Get widened type and narrowed type.
8328 unsigned numElem = VT.getVectorNumElements();
8330 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8331 switch (inputLaneType.getSimpleVT().SimpleTy) {
8332 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8333 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8334 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8336 llvm_unreachable("Invalid vector element type for padd optimization.");
8339 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8340 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8341 return DAG.getNode(ExtOp, dl, VT, tmp);
8344 static SDValue findMUL_LOHI(SDValue V) {
8345 if (V->getOpcode() == ISD::UMUL_LOHI ||
8346 V->getOpcode() == ISD::SMUL_LOHI)
8351 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8352 TargetLowering::DAGCombinerInfo &DCI,
8353 const ARMSubtarget *Subtarget) {
8355 if (Subtarget->isThumb1Only()) return SDValue();
8357 // Only perform the checks after legalize when the pattern is available.
8358 if (DCI.isBeforeLegalize()) return SDValue();
8360 // Look for multiply add opportunities.
8361 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8362 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8363 // a glue link from the first add to the second add.
8364 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8365 // a S/UMLAL instruction.
8368 // / \ [no multiline comment]
8374 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8375 SDValue AddcOp0 = AddcNode->getOperand(0);
8376 SDValue AddcOp1 = AddcNode->getOperand(1);
8378 // Check if the two operands are from the same mul_lohi node.
8379 if (AddcOp0.getNode() == AddcOp1.getNode())
8382 assert(AddcNode->getNumValues() == 2 &&
8383 AddcNode->getValueType(0) == MVT::i32 &&
8384 "Expect ADDC with two result values. First: i32");
8386 // Check that we have a glued ADDC node.
8387 if (AddcNode->getValueType(1) != MVT::Glue)
8390 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8391 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8392 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8393 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8394 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8397 // Look for the glued ADDE.
8398 SDNode* AddeNode = AddcNode->getGluedUser();
8402 // Make sure it is really an ADDE.
8403 if (AddeNode->getOpcode() != ISD::ADDE)
8406 assert(AddeNode->getNumOperands() == 3 &&
8407 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8408 "ADDE node has the wrong inputs");
8410 // Check for the triangle shape.
8411 SDValue AddeOp0 = AddeNode->getOperand(0);
8412 SDValue AddeOp1 = AddeNode->getOperand(1);
8414 // Make sure that the ADDE operands are not coming from the same node.
8415 if (AddeOp0.getNode() == AddeOp1.getNode())
8418 // Find the MUL_LOHI node walking up ADDE's operands.
8419 bool IsLeftOperandMUL = false;
8420 SDValue MULOp = findMUL_LOHI(AddeOp0);
8421 if (MULOp == SDValue())
8422 MULOp = findMUL_LOHI(AddeOp1);
8424 IsLeftOperandMUL = true;
8425 if (MULOp == SDValue())
8428 // Figure out the right opcode.
8429 unsigned Opc = MULOp->getOpcode();
8430 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8432 // Figure out the high and low input values to the MLAL node.
8433 SDValue* HiAdd = nullptr;
8434 SDValue* LoMul = nullptr;
8435 SDValue* LowAdd = nullptr;
8437 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8438 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8441 if (IsLeftOperandMUL)
8447 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8448 // whose low result is fed to the ADDC we are checking.
8450 if (AddcOp0 == MULOp.getValue(0)) {
8454 if (AddcOp1 == MULOp.getValue(0)) {
8462 // Create the merged node.
8463 SelectionDAG &DAG = DCI.DAG;
8465 // Build operand list.
8466 SmallVector<SDValue, 8> Ops;
8467 Ops.push_back(LoMul->getOperand(0));
8468 Ops.push_back(LoMul->getOperand(1));
8469 Ops.push_back(*LowAdd);
8470 Ops.push_back(*HiAdd);
8472 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8473 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8475 // Replace the ADDs' nodes uses by the MLA node's values.
8476 SDValue HiMLALResult(MLALNode.getNode(), 1);
8477 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8479 SDValue LoMLALResult(MLALNode.getNode(), 0);
8480 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8482 // Return original node to notify the driver to stop replacing.
8483 SDValue resNode(AddcNode, 0);
8487 /// PerformADDCCombine - Target-specific dag combine transform from
8488 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8489 static SDValue PerformADDCCombine(SDNode *N,
8490 TargetLowering::DAGCombinerInfo &DCI,
8491 const ARMSubtarget *Subtarget) {
8493 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8497 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8498 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8499 /// called with the default operands, and if that fails, with commuted
8501 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8502 TargetLowering::DAGCombinerInfo &DCI,
8503 const ARMSubtarget *Subtarget){
8505 // Attempt to create vpaddl for this add.
8506 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8507 if (Result.getNode())
8510 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8511 if (N0.getNode()->hasOneUse()) {
8512 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8513 if (Result.getNode()) return Result;
8518 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8520 static SDValue PerformADDCombine(SDNode *N,
8521 TargetLowering::DAGCombinerInfo &DCI,
8522 const ARMSubtarget *Subtarget) {
8523 SDValue N0 = N->getOperand(0);
8524 SDValue N1 = N->getOperand(1);
8526 // First try with the default operand order.
8527 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8528 if (Result.getNode())
8531 // If that didn't work, try again with the operands commuted.
8532 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8535 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8537 static SDValue PerformSUBCombine(SDNode *N,
8538 TargetLowering::DAGCombinerInfo &DCI) {
8539 SDValue N0 = N->getOperand(0);
8540 SDValue N1 = N->getOperand(1);
8542 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8543 if (N1.getNode()->hasOneUse()) {
8544 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8545 if (Result.getNode()) return Result;
8551 /// PerformVMULCombine
8552 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8553 /// special multiplier accumulator forwarding.
8559 // However, for (A + B) * (A + B),
8566 static SDValue PerformVMULCombine(SDNode *N,
8567 TargetLowering::DAGCombinerInfo &DCI,
8568 const ARMSubtarget *Subtarget) {
8569 if (!Subtarget->hasVMLxForwarding())
8572 SelectionDAG &DAG = DCI.DAG;
8573 SDValue N0 = N->getOperand(0);
8574 SDValue N1 = N->getOperand(1);
8575 unsigned Opcode = N0.getOpcode();
8576 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8577 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8578 Opcode = N1.getOpcode();
8579 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8580 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8588 EVT VT = N->getValueType(0);
8590 SDValue N00 = N0->getOperand(0);
8591 SDValue N01 = N0->getOperand(1);
8592 return DAG.getNode(Opcode, DL, VT,
8593 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8594 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8597 static SDValue PerformMULCombine(SDNode *N,
8598 TargetLowering::DAGCombinerInfo &DCI,
8599 const ARMSubtarget *Subtarget) {
8600 SelectionDAG &DAG = DCI.DAG;
8602 if (Subtarget->isThumb1Only())
8605 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8608 EVT VT = N->getValueType(0);
8609 if (VT.is64BitVector() || VT.is128BitVector())
8610 return PerformVMULCombine(N, DCI, Subtarget);
8614 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8618 int64_t MulAmt = C->getSExtValue();
8619 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8621 ShiftAmt = ShiftAmt & (32 - 1);
8622 SDValue V = N->getOperand(0);
8626 MulAmt >>= ShiftAmt;
8629 if (isPowerOf2_32(MulAmt - 1)) {
8630 // (mul x, 2^N + 1) => (add (shl x, N), x)
8631 Res = DAG.getNode(ISD::ADD, DL, VT,
8633 DAG.getNode(ISD::SHL, DL, VT,
8635 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8637 } else if (isPowerOf2_32(MulAmt + 1)) {
8638 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8639 Res = DAG.getNode(ISD::SUB, DL, VT,
8640 DAG.getNode(ISD::SHL, DL, VT,
8642 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8648 uint64_t MulAmtAbs = -MulAmt;
8649 if (isPowerOf2_32(MulAmtAbs + 1)) {
8650 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8651 Res = DAG.getNode(ISD::SUB, DL, VT,
8653 DAG.getNode(ISD::SHL, DL, VT,
8655 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8657 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8658 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8659 Res = DAG.getNode(ISD::ADD, DL, VT,
8661 DAG.getNode(ISD::SHL, DL, VT,
8663 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8665 Res = DAG.getNode(ISD::SUB, DL, VT,
8666 DAG.getConstant(0, DL, MVT::i32), Res);
8673 Res = DAG.getNode(ISD::SHL, DL, VT,
8674 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8676 // Do not add new nodes to DAG combiner worklist.
8677 DCI.CombineTo(N, Res, false);
8681 static SDValue PerformANDCombine(SDNode *N,
8682 TargetLowering::DAGCombinerInfo &DCI,
8683 const ARMSubtarget *Subtarget) {
8685 // Attempt to use immediate-form VBIC
8686 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8688 EVT VT = N->getValueType(0);
8689 SelectionDAG &DAG = DCI.DAG;
8691 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8694 APInt SplatBits, SplatUndef;
8695 unsigned SplatBitSize;
8698 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8699 if (SplatBitSize <= 64) {
8701 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8702 SplatUndef.getZExtValue(), SplatBitSize,
8703 DAG, dl, VbicVT, VT.is128BitVector(),
8705 if (Val.getNode()) {
8707 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8708 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8709 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8714 if (!Subtarget->isThumb1Only()) {
8715 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8716 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8717 if (Result.getNode())
8724 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8725 static SDValue PerformORCombine(SDNode *N,
8726 TargetLowering::DAGCombinerInfo &DCI,
8727 const ARMSubtarget *Subtarget) {
8728 // Attempt to use immediate-form VORR
8729 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8731 EVT VT = N->getValueType(0);
8732 SelectionDAG &DAG = DCI.DAG;
8734 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8737 APInt SplatBits, SplatUndef;
8738 unsigned SplatBitSize;
8740 if (BVN && Subtarget->hasNEON() &&
8741 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8742 if (SplatBitSize <= 64) {
8744 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8745 SplatUndef.getZExtValue(), SplatBitSize,
8746 DAG, dl, VorrVT, VT.is128BitVector(),
8748 if (Val.getNode()) {
8750 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8751 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8752 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8757 if (!Subtarget->isThumb1Only()) {
8758 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8759 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8760 if (Result.getNode())
8764 // The code below optimizes (or (and X, Y), Z).
8765 // The AND operand needs to have a single user to make these optimizations
8767 SDValue N0 = N->getOperand(0);
8768 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8770 SDValue N1 = N->getOperand(1);
8772 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8773 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8774 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8776 unsigned SplatBitSize;
8779 APInt SplatBits0, SplatBits1;
8780 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8781 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8782 // Ensure that the second operand of both ands are constants
8783 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8784 HasAnyUndefs) && !HasAnyUndefs) {
8785 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8786 HasAnyUndefs) && !HasAnyUndefs) {
8787 // Ensure that the bit width of the constants are the same and that
8788 // the splat arguments are logical inverses as per the pattern we
8789 // are trying to simplify.
8790 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8791 SplatBits0 == ~SplatBits1) {
8792 // Canonicalize the vector type to make instruction selection
8794 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8795 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8799 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8805 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8808 // BFI is only available on V6T2+
8809 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8813 // 1) or (and A, mask), val => ARMbfi A, val, mask
8814 // iff (val & mask) == val
8816 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8817 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8818 // && mask == ~mask2
8819 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8820 // && ~mask == mask2
8821 // (i.e., copy a bitfield value into another bitfield of the same width)
8826 SDValue N00 = N0.getOperand(0);
8828 // The value and the mask need to be constants so we can verify this is
8829 // actually a bitfield set. If the mask is 0xffff, we can do better
8830 // via a movt instruction, so don't use BFI in that case.
8831 SDValue MaskOp = N0.getOperand(1);
8832 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8835 unsigned Mask = MaskC->getZExtValue();
8839 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8842 unsigned Val = N1C->getZExtValue();
8843 if ((Val & ~Mask) != Val)
8846 if (ARM::isBitFieldInvertedMask(Mask)) {
8847 Val >>= countTrailingZeros(~Mask);
8849 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8850 DAG.getConstant(Val, DL, MVT::i32),
8851 DAG.getConstant(Mask, DL, MVT::i32));
8853 // Do not add new nodes to DAG combiner worklist.
8854 DCI.CombineTo(N, Res, false);
8857 } else if (N1.getOpcode() == ISD::AND) {
8858 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8859 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8862 unsigned Mask2 = N11C->getZExtValue();
8864 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8866 if (ARM::isBitFieldInvertedMask(Mask) &&
8868 // The pack halfword instruction works better for masks that fit it,
8869 // so use that when it's available.
8870 if (Subtarget->hasT2ExtractPack() &&
8871 (Mask == 0xffff || Mask == 0xffff0000))
8874 unsigned amt = countTrailingZeros(Mask2);
8875 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8876 DAG.getConstant(amt, DL, MVT::i32));
8877 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8878 DAG.getConstant(Mask, DL, MVT::i32));
8879 // Do not add new nodes to DAG combiner worklist.
8880 DCI.CombineTo(N, Res, false);
8882 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8884 // The pack halfword instruction works better for masks that fit it,
8885 // so use that when it's available.
8886 if (Subtarget->hasT2ExtractPack() &&
8887 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8890 unsigned lsb = countTrailingZeros(Mask);
8891 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8892 DAG.getConstant(lsb, DL, MVT::i32));
8893 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8894 DAG.getConstant(Mask2, DL, MVT::i32));
8895 // Do not add new nodes to DAG combiner worklist.
8896 DCI.CombineTo(N, Res, false);
8901 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8902 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8903 ARM::isBitFieldInvertedMask(~Mask)) {
8904 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8905 // where lsb(mask) == #shamt and masked bits of B are known zero.
8906 SDValue ShAmt = N00.getOperand(1);
8907 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8908 unsigned LSB = countTrailingZeros(Mask);
8912 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8913 DAG.getConstant(~Mask, DL, MVT::i32));
8915 // Do not add new nodes to DAG combiner worklist.
8916 DCI.CombineTo(N, Res, false);
8922 static SDValue PerformXORCombine(SDNode *N,
8923 TargetLowering::DAGCombinerInfo &DCI,
8924 const ARMSubtarget *Subtarget) {
8925 EVT VT = N->getValueType(0);
8926 SelectionDAG &DAG = DCI.DAG;
8928 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8931 if (!Subtarget->isThumb1Only()) {
8932 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8933 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8934 if (Result.getNode())
8941 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8942 /// the bits being cleared by the AND are not demanded by the BFI.
8943 static SDValue PerformBFICombine(SDNode *N,
8944 TargetLowering::DAGCombinerInfo &DCI) {
8945 SDValue N1 = N->getOperand(1);
8946 if (N1.getOpcode() == ISD::AND) {
8947 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8950 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8951 unsigned LSB = countTrailingZeros(~InvMask);
8952 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8954 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8955 "undefined behavior");
8956 unsigned Mask = (1u << Width) - 1;
8957 unsigned Mask2 = N11C->getZExtValue();
8958 if ((Mask & (~Mask2)) == 0)
8959 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8960 N->getOperand(0), N1.getOperand(0),
8966 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8967 /// ARMISD::VMOVRRD.
8968 static SDValue PerformVMOVRRDCombine(SDNode *N,
8969 TargetLowering::DAGCombinerInfo &DCI,
8970 const ARMSubtarget *Subtarget) {
8971 // vmovrrd(vmovdrr x, y) -> x,y
8972 SDValue InDouble = N->getOperand(0);
8973 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8974 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8976 // vmovrrd(load f64) -> (load i32), (load i32)
8977 SDNode *InNode = InDouble.getNode();
8978 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8979 InNode->getValueType(0) == MVT::f64 &&
8980 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8981 !cast<LoadSDNode>(InNode)->isVolatile()) {
8982 // TODO: Should this be done for non-FrameIndex operands?
8983 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8985 SelectionDAG &DAG = DCI.DAG;
8987 SDValue BasePtr = LD->getBasePtr();
8988 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8989 LD->getPointerInfo(), LD->isVolatile(),
8990 LD->isNonTemporal(), LD->isInvariant(),
8991 LD->getAlignment());
8993 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8994 DAG.getConstant(4, DL, MVT::i32));
8995 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8996 LD->getPointerInfo(), LD->isVolatile(),
8997 LD->isNonTemporal(), LD->isInvariant(),
8998 std::min(4U, LD->getAlignment() / 2));
9000 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9001 if (DCI.DAG.getDataLayout().isBigEndian())
9002 std::swap (NewLD1, NewLD2);
9003 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9010 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9011 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9012 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9013 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9014 SDValue Op0 = N->getOperand(0);
9015 SDValue Op1 = N->getOperand(1);
9016 if (Op0.getOpcode() == ISD::BITCAST)
9017 Op0 = Op0.getOperand(0);
9018 if (Op1.getOpcode() == ISD::BITCAST)
9019 Op1 = Op1.getOperand(0);
9020 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9021 Op0.getNode() == Op1.getNode() &&
9022 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9023 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9024 N->getValueType(0), Op0.getOperand(0));
9028 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9029 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9030 /// i64 vector to have f64 elements, since the value can then be loaded
9031 /// directly into a VFP register.
9032 static bool hasNormalLoadOperand(SDNode *N) {
9033 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9034 for (unsigned i = 0; i < NumElts; ++i) {
9035 SDNode *Elt = N->getOperand(i).getNode();
9036 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9042 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9043 /// ISD::BUILD_VECTOR.
9044 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9045 TargetLowering::DAGCombinerInfo &DCI,
9046 const ARMSubtarget *Subtarget) {
9047 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9048 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9049 // into a pair of GPRs, which is fine when the value is used as a scalar,
9050 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9051 SelectionDAG &DAG = DCI.DAG;
9052 if (N->getNumOperands() == 2) {
9053 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9058 // Load i64 elements as f64 values so that type legalization does not split
9059 // them up into i32 values.
9060 EVT VT = N->getValueType(0);
9061 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9064 SmallVector<SDValue, 8> Ops;
9065 unsigned NumElts = VT.getVectorNumElements();
9066 for (unsigned i = 0; i < NumElts; ++i) {
9067 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9069 // Make the DAGCombiner fold the bitcast.
9070 DCI.AddToWorklist(V.getNode());
9072 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9073 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9074 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9077 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9079 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9080 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9081 // At that time, we may have inserted bitcasts from integer to float.
9082 // If these bitcasts have survived DAGCombine, change the lowering of this
9083 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9084 // force to use floating point types.
9086 // Make sure we can change the type of the vector.
9087 // This is possible iff:
9088 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9089 // 1.1. Vector is used only once.
9090 // 1.2. Use is a bit convert to an integer type.
9091 // 2. The size of its operands are 32-bits (64-bits are not legal).
9092 EVT VT = N->getValueType(0);
9093 EVT EltVT = VT.getVectorElementType();
9095 // Check 1.1. and 2.
9096 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9099 // By construction, the input type must be float.
9100 assert(EltVT == MVT::f32 && "Unexpected type!");
9103 SDNode *Use = *N->use_begin();
9104 if (Use->getOpcode() != ISD::BITCAST ||
9105 Use->getValueType(0).isFloatingPoint())
9108 // Check profitability.
9109 // Model is, if more than half of the relevant operands are bitcast from
9110 // i32, turn the build_vector into a sequence of insert_vector_elt.
9111 // Relevant operands are everything that is not statically
9112 // (i.e., at compile time) bitcasted.
9113 unsigned NumOfBitCastedElts = 0;
9114 unsigned NumElts = VT.getVectorNumElements();
9115 unsigned NumOfRelevantElts = NumElts;
9116 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9117 SDValue Elt = N->getOperand(Idx);
9118 if (Elt->getOpcode() == ISD::BITCAST) {
9119 // Assume only bit cast to i32 will go away.
9120 if (Elt->getOperand(0).getValueType() == MVT::i32)
9121 ++NumOfBitCastedElts;
9122 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9123 // Constants are statically casted, thus do not count them as
9124 // relevant operands.
9125 --NumOfRelevantElts;
9128 // Check if more than half of the elements require a non-free bitcast.
9129 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9132 SelectionDAG &DAG = DCI.DAG;
9133 // Create the new vector type.
9134 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9135 // Check if the type is legal.
9136 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9137 if (!TLI.isTypeLegal(VecVT))
9141 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9142 // => BITCAST INSERT_VECTOR_ELT
9143 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9145 SDValue Vec = DAG.getUNDEF(VecVT);
9147 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9148 SDValue V = N->getOperand(Idx);
9149 if (V.getOpcode() == ISD::UNDEF)
9151 if (V.getOpcode() == ISD::BITCAST &&
9152 V->getOperand(0).getValueType() == MVT::i32)
9153 // Fold obvious case.
9154 V = V.getOperand(0);
9156 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9157 // Make the DAGCombiner fold the bitcasts.
9158 DCI.AddToWorklist(V.getNode());
9160 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9161 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9163 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9164 // Make the DAGCombiner fold the bitcasts.
9165 DCI.AddToWorklist(Vec.getNode());
9169 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9170 /// ISD::INSERT_VECTOR_ELT.
9171 static SDValue PerformInsertEltCombine(SDNode *N,
9172 TargetLowering::DAGCombinerInfo &DCI) {
9173 // Bitcast an i64 load inserted into a vector to f64.
9174 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9175 EVT VT = N->getValueType(0);
9176 SDNode *Elt = N->getOperand(1).getNode();
9177 if (VT.getVectorElementType() != MVT::i64 ||
9178 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9181 SelectionDAG &DAG = DCI.DAG;
9183 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9184 VT.getVectorNumElements());
9185 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9186 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9187 // Make the DAGCombiner fold the bitcasts.
9188 DCI.AddToWorklist(Vec.getNode());
9189 DCI.AddToWorklist(V.getNode());
9190 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9191 Vec, V, N->getOperand(2));
9192 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9195 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9196 /// ISD::VECTOR_SHUFFLE.
9197 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9198 // The LLVM shufflevector instruction does not require the shuffle mask
9199 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9200 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9201 // operands do not match the mask length, they are extended by concatenating
9202 // them with undef vectors. That is probably the right thing for other
9203 // targets, but for NEON it is better to concatenate two double-register
9204 // size vector operands into a single quad-register size vector. Do that
9205 // transformation here:
9206 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9207 // shuffle(concat(v1, v2), undef)
9208 SDValue Op0 = N->getOperand(0);
9209 SDValue Op1 = N->getOperand(1);
9210 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9211 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9212 Op0.getNumOperands() != 2 ||
9213 Op1.getNumOperands() != 2)
9215 SDValue Concat0Op1 = Op0.getOperand(1);
9216 SDValue Concat1Op1 = Op1.getOperand(1);
9217 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9218 Concat1Op1.getOpcode() != ISD::UNDEF)
9220 // Skip the transformation if any of the types are illegal.
9221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9222 EVT VT = N->getValueType(0);
9223 if (!TLI.isTypeLegal(VT) ||
9224 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9225 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9228 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9229 Op0.getOperand(0), Op1.getOperand(0));
9230 // Translate the shuffle mask.
9231 SmallVector<int, 16> NewMask;
9232 unsigned NumElts = VT.getVectorNumElements();
9233 unsigned HalfElts = NumElts/2;
9234 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9235 for (unsigned n = 0; n < NumElts; ++n) {
9236 int MaskElt = SVN->getMaskElt(n);
9238 if (MaskElt < (int)HalfElts)
9240 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9241 NewElt = HalfElts + MaskElt - NumElts;
9242 NewMask.push_back(NewElt);
9244 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9245 DAG.getUNDEF(VT), NewMask.data());
9248 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9249 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9250 /// base address updates.
9251 /// For generic load/stores, the memory type is assumed to be a vector.
9252 /// The caller is assumed to have checked legality.
9253 static SDValue CombineBaseUpdate(SDNode *N,
9254 TargetLowering::DAGCombinerInfo &DCI) {
9255 SelectionDAG &DAG = DCI.DAG;
9256 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9257 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9258 const bool isStore = N->getOpcode() == ISD::STORE;
9259 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9260 SDValue Addr = N->getOperand(AddrOpIdx);
9261 MemSDNode *MemN = cast<MemSDNode>(N);
9264 // Search for a use of the address operand that is an increment.
9265 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9266 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9268 if (User->getOpcode() != ISD::ADD ||
9269 UI.getUse().getResNo() != Addr.getResNo())
9272 // Check that the add is independent of the load/store. Otherwise, folding
9273 // it would create a cycle.
9274 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9277 // Find the new opcode for the updating load/store.
9278 bool isLoadOp = true;
9279 bool isLaneOp = false;
9280 unsigned NewOpc = 0;
9281 unsigned NumVecs = 0;
9283 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9285 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9286 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9288 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9290 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9292 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9294 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9295 NumVecs = 2; isLaneOp = true; break;
9296 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9297 NumVecs = 3; isLaneOp = true; break;
9298 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9299 NumVecs = 4; isLaneOp = true; break;
9300 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9301 NumVecs = 1; isLoadOp = false; break;
9302 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9303 NumVecs = 2; isLoadOp = false; break;
9304 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9305 NumVecs = 3; isLoadOp = false; break;
9306 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9307 NumVecs = 4; isLoadOp = false; break;
9308 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9309 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9310 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9311 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9312 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9313 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9317 switch (N->getOpcode()) {
9318 default: llvm_unreachable("unexpected opcode for Neon base update");
9319 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9320 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9321 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9322 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9323 NumVecs = 1; isLaneOp = false; break;
9324 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9325 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9329 // Find the size of memory referenced by the load/store.
9332 VecTy = N->getValueType(0);
9333 } else if (isIntrinsic) {
9334 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9336 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9337 VecTy = N->getOperand(1).getValueType();
9340 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9342 NumBytes /= VecTy.getVectorNumElements();
9344 // If the increment is a constant, it must match the memory ref size.
9345 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9346 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9347 uint64_t IncVal = CInc->getZExtValue();
9348 if (IncVal != NumBytes)
9350 } else if (NumBytes >= 3 * 16) {
9351 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9352 // separate instructions that make it harder to use a non-constant update.
9356 // OK, we found an ADD we can fold into the base update.
9357 // Now, create a _UPD node, taking care of not breaking alignment.
9359 EVT AlignedVecTy = VecTy;
9360 unsigned Alignment = MemN->getAlignment();
9362 // If this is a less-than-standard-aligned load/store, change the type to
9363 // match the standard alignment.
9364 // The alignment is overlooked when selecting _UPD variants; and it's
9365 // easier to introduce bitcasts here than fix that.
9366 // There are 3 ways to get to this base-update combine:
9367 // - intrinsics: they are assumed to be properly aligned (to the standard
9368 // alignment of the memory type), so we don't need to do anything.
9369 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9370 // intrinsics, so, likewise, there's nothing to do.
9371 // - generic load/store instructions: the alignment is specified as an
9372 // explicit operand, rather than implicitly as the standard alignment
9373 // of the memory type (like the intrisics). We need to change the
9374 // memory type to match the explicit alignment. That way, we don't
9375 // generate non-standard-aligned ARMISD::VLDx nodes.
9376 if (isa<LSBaseSDNode>(N)) {
9379 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9380 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9381 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9382 assert(!isLaneOp && "Unexpected generic load/store lane.");
9383 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9384 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9386 // Don't set an explicit alignment on regular load/stores that we want
9387 // to transform to VLD/VST 1_UPD nodes.
9388 // This matches the behavior of regular load/stores, which only get an
9389 // explicit alignment if the MMO alignment is larger than the standard
9390 // alignment of the memory type.
9391 // Intrinsics, however, always get an explicit alignment, set to the
9392 // alignment of the MMO.
9396 // Create the new updating load/store node.
9397 // First, create an SDVTList for the new updating node's results.
9399 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9401 for (n = 0; n < NumResultVecs; ++n)
9402 Tys[n] = AlignedVecTy;
9403 Tys[n++] = MVT::i32;
9404 Tys[n] = MVT::Other;
9405 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9407 // Then, gather the new node's operands.
9408 SmallVector<SDValue, 8> Ops;
9409 Ops.push_back(N->getOperand(0)); // incoming chain
9410 Ops.push_back(N->getOperand(AddrOpIdx));
9413 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9414 // Try to match the intrinsic's signature
9415 Ops.push_back(StN->getValue());
9417 // Loads (and of course intrinsics) match the intrinsics' signature,
9418 // so just add all but the alignment operand.
9419 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9420 Ops.push_back(N->getOperand(i));
9423 // For all node types, the alignment operand is always the last one.
9424 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9426 // If this is a non-standard-aligned STORE, the penultimate operand is the
9427 // stored value. Bitcast it to the aligned type.
9428 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9429 SDValue &StVal = Ops[Ops.size()-2];
9430 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9433 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9435 MemN->getMemOperand());
9438 SmallVector<SDValue, 5> NewResults;
9439 for (unsigned i = 0; i < NumResultVecs; ++i)
9440 NewResults.push_back(SDValue(UpdN.getNode(), i));
9442 // If this is an non-standard-aligned LOAD, the first result is the loaded
9443 // value. Bitcast it to the expected result type.
9444 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9445 SDValue &LdVal = NewResults[0];
9446 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9449 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9450 DCI.CombineTo(N, NewResults);
9451 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9458 static SDValue PerformVLDCombine(SDNode *N,
9459 TargetLowering::DAGCombinerInfo &DCI) {
9460 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9463 return CombineBaseUpdate(N, DCI);
9466 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9467 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9468 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9470 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9471 SelectionDAG &DAG = DCI.DAG;
9472 EVT VT = N->getValueType(0);
9473 // vldN-dup instructions only support 64-bit vectors for N > 1.
9474 if (!VT.is64BitVector())
9477 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9478 SDNode *VLD = N->getOperand(0).getNode();
9479 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9481 unsigned NumVecs = 0;
9482 unsigned NewOpc = 0;
9483 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9484 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9486 NewOpc = ARMISD::VLD2DUP;
9487 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9489 NewOpc = ARMISD::VLD3DUP;
9490 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9492 NewOpc = ARMISD::VLD4DUP;
9497 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9498 // numbers match the load.
9499 unsigned VLDLaneNo =
9500 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9501 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9503 // Ignore uses of the chain result.
9504 if (UI.getUse().getResNo() == NumVecs)
9507 if (User->getOpcode() != ARMISD::VDUPLANE ||
9508 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9512 // Create the vldN-dup node.
9515 for (n = 0; n < NumVecs; ++n)
9517 Tys[n] = MVT::Other;
9518 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9519 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9520 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9521 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9522 Ops, VLDMemInt->getMemoryVT(),
9523 VLDMemInt->getMemOperand());
9526 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9528 unsigned ResNo = UI.getUse().getResNo();
9529 // Ignore uses of the chain result.
9530 if (ResNo == NumVecs)
9533 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9536 // Now the vldN-lane intrinsic is dead except for its chain result.
9537 // Update uses of the chain.
9538 std::vector<SDValue> VLDDupResults;
9539 for (unsigned n = 0; n < NumVecs; ++n)
9540 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9541 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9542 DCI.CombineTo(VLD, VLDDupResults);
9547 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9548 /// ARMISD::VDUPLANE.
9549 static SDValue PerformVDUPLANECombine(SDNode *N,
9550 TargetLowering::DAGCombinerInfo &DCI) {
9551 SDValue Op = N->getOperand(0);
9553 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9554 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9555 if (CombineVLDDUP(N, DCI))
9556 return SDValue(N, 0);
9558 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9559 // redundant. Ignore bit_converts for now; element sizes are checked below.
9560 while (Op.getOpcode() == ISD::BITCAST)
9561 Op = Op.getOperand(0);
9562 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9565 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9566 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9567 // The canonical VMOV for a zero vector uses a 32-bit element size.
9568 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9570 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9572 EVT VT = N->getValueType(0);
9573 if (EltSize > VT.getVectorElementType().getSizeInBits())
9576 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9579 static SDValue PerformLOADCombine(SDNode *N,
9580 TargetLowering::DAGCombinerInfo &DCI) {
9581 EVT VT = N->getValueType(0);
9583 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9584 if (ISD::isNormalLoad(N) && VT.isVector() &&
9585 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9586 return CombineBaseUpdate(N, DCI);
9591 /// PerformSTORECombine - Target-specific dag combine xforms for
9593 static SDValue PerformSTORECombine(SDNode *N,
9594 TargetLowering::DAGCombinerInfo &DCI) {
9595 StoreSDNode *St = cast<StoreSDNode>(N);
9596 if (St->isVolatile())
9599 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9600 // pack all of the elements in one place. Next, store to memory in fewer
9602 SDValue StVal = St->getValue();
9603 EVT VT = StVal.getValueType();
9604 if (St->isTruncatingStore() && VT.isVector()) {
9605 SelectionDAG &DAG = DCI.DAG;
9606 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9607 EVT StVT = St->getMemoryVT();
9608 unsigned NumElems = VT.getVectorNumElements();
9609 assert(StVT != VT && "Cannot truncate to the same type");
9610 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9611 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9613 // From, To sizes and ElemCount must be pow of two
9614 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9616 // We are going to use the original vector elt for storing.
9617 // Accumulated smaller vector elements must be a multiple of the store size.
9618 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9620 unsigned SizeRatio = FromEltSz / ToEltSz;
9621 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9623 // Create a type on which we perform the shuffle.
9624 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9625 NumElems*SizeRatio);
9626 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9629 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9630 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9631 for (unsigned i = 0; i < NumElems; ++i)
9632 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9633 ? (i + 1) * SizeRatio - 1
9636 // Can't shuffle using an illegal type.
9637 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9639 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9640 DAG.getUNDEF(WideVec.getValueType()),
9642 // At this point all of the data is stored at the bottom of the
9643 // register. We now need to save it to mem.
9645 // Find the largest store unit
9646 MVT StoreType = MVT::i8;
9647 for (MVT Tp : MVT::integer_valuetypes()) {
9648 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9651 // Didn't find a legal store type.
9652 if (!TLI.isTypeLegal(StoreType))
9655 // Bitcast the original vector into a vector of store-size units
9656 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9657 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9658 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9659 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9660 SmallVector<SDValue, 8> Chains;
9661 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9662 TLI.getPointerTy(DAG.getDataLayout()));
9663 SDValue BasePtr = St->getBasePtr();
9665 // Perform one or more big stores into memory.
9666 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9667 for (unsigned I = 0; I < E; I++) {
9668 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9669 StoreType, ShuffWide,
9670 DAG.getIntPtrConstant(I, DL));
9671 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9672 St->getPointerInfo(), St->isVolatile(),
9673 St->isNonTemporal(), St->getAlignment());
9674 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9676 Chains.push_back(Ch);
9678 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9681 if (!ISD::isNormalStore(St))
9684 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9685 // ARM stores of arguments in the same cache line.
9686 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9687 StVal.getNode()->hasOneUse()) {
9688 SelectionDAG &DAG = DCI.DAG;
9689 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9691 SDValue BasePtr = St->getBasePtr();
9692 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9693 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9694 BasePtr, St->getPointerInfo(), St->isVolatile(),
9695 St->isNonTemporal(), St->getAlignment());
9697 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9698 DAG.getConstant(4, DL, MVT::i32));
9699 return DAG.getStore(NewST1.getValue(0), DL,
9700 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9701 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9702 St->isNonTemporal(),
9703 std::min(4U, St->getAlignment() / 2));
9706 if (StVal.getValueType() == MVT::i64 &&
9707 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9709 // Bitcast an i64 store extracted from a vector to f64.
9710 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9711 SelectionDAG &DAG = DCI.DAG;
9713 SDValue IntVec = StVal.getOperand(0);
9714 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9715 IntVec.getValueType().getVectorNumElements());
9716 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9717 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9718 Vec, StVal.getOperand(1));
9720 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9721 // Make the DAGCombiner fold the bitcasts.
9722 DCI.AddToWorklist(Vec.getNode());
9723 DCI.AddToWorklist(ExtElt.getNode());
9724 DCI.AddToWorklist(V.getNode());
9725 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9726 St->getPointerInfo(), St->isVolatile(),
9727 St->isNonTemporal(), St->getAlignment(),
9731 // If this is a legal vector store, try to combine it into a VST1_UPD.
9732 if (ISD::isNormalStore(N) && VT.isVector() &&
9733 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9734 return CombineBaseUpdate(N, DCI);
9739 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9740 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9741 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9745 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9747 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9752 APFloat APF = C->getValueAPF();
9753 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9754 != APFloat::opOK || !isExact)
9757 c0 = (I == 0) ? cN : c0;
9758 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9765 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9766 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9767 /// when the VMUL has a constant operand that is a power of 2.
9769 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9770 /// vmul.f32 d16, d17, d16
9771 /// vcvt.s32.f32 d16, d16
9773 /// vcvt.s32.f32 d16, d16, #3
9774 static SDValue PerformVCVTCombine(SDNode *N,
9775 TargetLowering::DAGCombinerInfo &DCI,
9776 const ARMSubtarget *Subtarget) {
9777 SelectionDAG &DAG = DCI.DAG;
9778 SDValue Op = N->getOperand(0);
9780 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9781 Op.getOpcode() != ISD::FMUL)
9785 SDValue N0 = Op->getOperand(0);
9786 SDValue ConstVec = Op->getOperand(1);
9787 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9789 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9790 !isConstVecPow2(ConstVec, isSigned, C))
9793 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9794 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9795 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9796 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9798 // These instructions only exist converting from f32 to i32. We can handle
9799 // smaller integers by generating an extra truncate, but larger ones would
9800 // be lossy. We also can't handle more then 4 lanes, since these intructions
9801 // only support v2i32/v4i32 types.
9806 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9807 Intrinsic::arm_neon_vcvtfp2fxu;
9808 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9809 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9810 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9812 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9814 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9815 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9820 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9821 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9822 /// when the VDIV has a constant operand that is a power of 2.
9824 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9825 /// vcvt.f32.s32 d16, d16
9826 /// vdiv.f32 d16, d17, d16
9828 /// vcvt.f32.s32 d16, d16, #3
9829 static SDValue PerformVDIVCombine(SDNode *N,
9830 TargetLowering::DAGCombinerInfo &DCI,
9831 const ARMSubtarget *Subtarget) {
9832 SelectionDAG &DAG = DCI.DAG;
9833 SDValue Op = N->getOperand(0);
9834 unsigned OpOpcode = Op.getNode()->getOpcode();
9836 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9837 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9841 SDValue ConstVec = N->getOperand(1);
9842 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9844 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9845 !isConstVecPow2(ConstVec, isSigned, C))
9848 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9849 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9850 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9851 // These instructions only exist converting from i32 to f32. We can handle
9852 // smaller integers by generating an extra extend, but larger ones would
9858 SDValue ConvInput = Op.getOperand(0);
9859 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9860 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9861 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9862 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9865 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9866 Intrinsic::arm_neon_vcvtfxu2fp;
9867 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9869 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9870 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9873 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9874 /// operand of a vector shift operation, where all the elements of the
9875 /// build_vector must have the same constant integer value.
9876 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9877 // Ignore bit_converts.
9878 while (Op.getOpcode() == ISD::BITCAST)
9879 Op = Op.getOperand(0);
9880 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9881 APInt SplatBits, SplatUndef;
9882 unsigned SplatBitSize;
9884 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9885 HasAnyUndefs, ElementBits) ||
9886 SplatBitSize > ElementBits)
9888 Cnt = SplatBits.getSExtValue();
9892 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9893 /// operand of a vector shift left operation. That value must be in the range:
9894 /// 0 <= Value < ElementBits for a left shift; or
9895 /// 0 <= Value <= ElementBits for a long left shift.
9896 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9897 assert(VT.isVector() && "vector shift count is not a vector type");
9898 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9899 if (! getVShiftImm(Op, ElementBits, Cnt))
9901 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9904 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9905 /// operand of a vector shift right operation. For a shift opcode, the value
9906 /// is positive, but for an intrinsic the value count must be negative. The
9907 /// absolute value must be in the range:
9908 /// 1 <= |Value| <= ElementBits for a right shift; or
9909 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9910 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9912 assert(VT.isVector() && "vector shift count is not a vector type");
9913 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9914 if (! getVShiftImm(Op, ElementBits, Cnt))
9917 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9918 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9925 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9926 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9927 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9930 // Don't do anything for most intrinsics.
9933 case Intrinsic::arm_neon_vabds:
9934 if (!N->getValueType(0).isInteger())
9936 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9937 N->getOperand(1), N->getOperand(2));
9938 case Intrinsic::arm_neon_vabdu:
9939 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9940 N->getOperand(1), N->getOperand(2));
9942 // Vector shifts: check for immediate versions and lower them.
9943 // Note: This is done during DAG combining instead of DAG legalizing because
9944 // the build_vectors for 64-bit vector element shift counts are generally
9945 // not legal, and it is hard to see their values after they get legalized to
9946 // loads from a constant pool.
9947 case Intrinsic::arm_neon_vshifts:
9948 case Intrinsic::arm_neon_vshiftu:
9949 case Intrinsic::arm_neon_vrshifts:
9950 case Intrinsic::arm_neon_vrshiftu:
9951 case Intrinsic::arm_neon_vrshiftn:
9952 case Intrinsic::arm_neon_vqshifts:
9953 case Intrinsic::arm_neon_vqshiftu:
9954 case Intrinsic::arm_neon_vqshiftsu:
9955 case Intrinsic::arm_neon_vqshiftns:
9956 case Intrinsic::arm_neon_vqshiftnu:
9957 case Intrinsic::arm_neon_vqshiftnsu:
9958 case Intrinsic::arm_neon_vqrshiftns:
9959 case Intrinsic::arm_neon_vqrshiftnu:
9960 case Intrinsic::arm_neon_vqrshiftnsu: {
9961 EVT VT = N->getOperand(1).getValueType();
9963 unsigned VShiftOpc = 0;
9966 case Intrinsic::arm_neon_vshifts:
9967 case Intrinsic::arm_neon_vshiftu:
9968 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9969 VShiftOpc = ARMISD::VSHL;
9972 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9973 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9974 ARMISD::VSHRs : ARMISD::VSHRu);
9979 case Intrinsic::arm_neon_vrshifts:
9980 case Intrinsic::arm_neon_vrshiftu:
9981 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9985 case Intrinsic::arm_neon_vqshifts:
9986 case Intrinsic::arm_neon_vqshiftu:
9987 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9991 case Intrinsic::arm_neon_vqshiftsu:
9992 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9994 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9996 case Intrinsic::arm_neon_vrshiftn:
9997 case Intrinsic::arm_neon_vqshiftns:
9998 case Intrinsic::arm_neon_vqshiftnu:
9999 case Intrinsic::arm_neon_vqshiftnsu:
10000 case Intrinsic::arm_neon_vqrshiftns:
10001 case Intrinsic::arm_neon_vqrshiftnu:
10002 case Intrinsic::arm_neon_vqrshiftnsu:
10003 // Narrowing shifts require an immediate right shift.
10004 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10006 llvm_unreachable("invalid shift count for narrowing vector shift "
10010 llvm_unreachable("unhandled vector shift");
10014 case Intrinsic::arm_neon_vshifts:
10015 case Intrinsic::arm_neon_vshiftu:
10016 // Opcode already set above.
10018 case Intrinsic::arm_neon_vrshifts:
10019 VShiftOpc = ARMISD::VRSHRs; break;
10020 case Intrinsic::arm_neon_vrshiftu:
10021 VShiftOpc = ARMISD::VRSHRu; break;
10022 case Intrinsic::arm_neon_vrshiftn:
10023 VShiftOpc = ARMISD::VRSHRN; break;
10024 case Intrinsic::arm_neon_vqshifts:
10025 VShiftOpc = ARMISD::VQSHLs; break;
10026 case Intrinsic::arm_neon_vqshiftu:
10027 VShiftOpc = ARMISD::VQSHLu; break;
10028 case Intrinsic::arm_neon_vqshiftsu:
10029 VShiftOpc = ARMISD::VQSHLsu; break;
10030 case Intrinsic::arm_neon_vqshiftns:
10031 VShiftOpc = ARMISD::VQSHRNs; break;
10032 case Intrinsic::arm_neon_vqshiftnu:
10033 VShiftOpc = ARMISD::VQSHRNu; break;
10034 case Intrinsic::arm_neon_vqshiftnsu:
10035 VShiftOpc = ARMISD::VQSHRNsu; break;
10036 case Intrinsic::arm_neon_vqrshiftns:
10037 VShiftOpc = ARMISD::VQRSHRNs; break;
10038 case Intrinsic::arm_neon_vqrshiftnu:
10039 VShiftOpc = ARMISD::VQRSHRNu; break;
10040 case Intrinsic::arm_neon_vqrshiftnsu:
10041 VShiftOpc = ARMISD::VQRSHRNsu; break;
10045 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10046 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10049 case Intrinsic::arm_neon_vshiftins: {
10050 EVT VT = N->getOperand(1).getValueType();
10052 unsigned VShiftOpc = 0;
10054 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10055 VShiftOpc = ARMISD::VSLI;
10056 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10057 VShiftOpc = ARMISD::VSRI;
10059 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10063 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10064 N->getOperand(1), N->getOperand(2),
10065 DAG.getConstant(Cnt, dl, MVT::i32));
10068 case Intrinsic::arm_neon_vqrshifts:
10069 case Intrinsic::arm_neon_vqrshiftu:
10070 // No immediate versions of these to check for.
10077 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10078 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10079 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10080 /// vector element shift counts are generally not legal, and it is hard to see
10081 /// their values after they get legalized to loads from a constant pool.
10082 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10083 const ARMSubtarget *ST) {
10084 EVT VT = N->getValueType(0);
10085 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10086 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10087 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10088 SDValue N1 = N->getOperand(1);
10089 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10090 SDValue N0 = N->getOperand(0);
10091 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10092 DAG.MaskedValueIsZero(N0.getOperand(0),
10093 APInt::getHighBitsSet(32, 16)))
10094 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10098 // Nothing to be done for scalar shifts.
10099 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10100 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10103 assert(ST->hasNEON() && "unexpected vector shift");
10106 switch (N->getOpcode()) {
10107 default: llvm_unreachable("unexpected shift opcode");
10110 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10112 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10113 DAG.getConstant(Cnt, dl, MVT::i32));
10119 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10120 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10121 ARMISD::VSHRs : ARMISD::VSHRu);
10123 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10124 DAG.getConstant(Cnt, dl, MVT::i32));
10130 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10131 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10132 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10133 const ARMSubtarget *ST) {
10134 SDValue N0 = N->getOperand(0);
10136 // Check for sign- and zero-extensions of vector extract operations of 8-
10137 // and 16-bit vector elements. NEON supports these directly. They are
10138 // handled during DAG combining because type legalization will promote them
10139 // to 32-bit types and it is messy to recognize the operations after that.
10140 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10141 SDValue Vec = N0.getOperand(0);
10142 SDValue Lane = N0.getOperand(1);
10143 EVT VT = N->getValueType(0);
10144 EVT EltVT = N0.getValueType();
10145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10147 if (VT == MVT::i32 &&
10148 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10149 TLI.isTypeLegal(Vec.getValueType()) &&
10150 isa<ConstantSDNode>(Lane)) {
10153 switch (N->getOpcode()) {
10154 default: llvm_unreachable("unexpected opcode");
10155 case ISD::SIGN_EXTEND:
10156 Opc = ARMISD::VGETLANEs;
10158 case ISD::ZERO_EXTEND:
10159 case ISD::ANY_EXTEND:
10160 Opc = ARMISD::VGETLANEu;
10163 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10170 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10171 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10172 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10173 const ARMSubtarget *ST) {
10174 // If the target supports NEON, try to use vmax/vmin instructions for f32
10175 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
10176 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
10177 // a NaN; only do the transformation when it matches that behavior.
10179 // For now only do this when using NEON for FP operations; if using VFP, it
10180 // is not obvious that the benefit outweighs the cost of switching to the
10182 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10183 N->getValueType(0) != MVT::f32)
10186 SDValue CondLHS = N->getOperand(0);
10187 SDValue CondRHS = N->getOperand(1);
10188 SDValue LHS = N->getOperand(2);
10189 SDValue RHS = N->getOperand(3);
10190 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10192 unsigned Opcode = 0;
10194 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10195 IsReversed = false; // x CC y ? x : y
10196 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10197 IsReversed = true ; // x CC y ? y : x
10211 // If LHS is NaN, an ordered comparison will be false and the result will
10212 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10213 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10214 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10215 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10217 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10218 // will return -0, so vmin can only be used for unsafe math or if one of
10219 // the operands is known to be nonzero.
10220 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10221 !DAG.getTarget().Options.UnsafeFPMath &&
10222 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10224 Opcode = IsReversed ? ISD::FMAXNAN : ISD::FMINNAN;
10233 // If LHS is NaN, an ordered comparison will be false and the result will
10234 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10235 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10236 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10237 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10239 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10240 // will return +0, so vmax can only be used for unsafe math or if one of
10241 // the operands is known to be nonzero.
10242 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10243 !DAG.getTarget().Options.UnsafeFPMath &&
10244 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10246 Opcode = IsReversed ? ISD::FMINNAN : ISD::FMAXNAN;
10252 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10255 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10257 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10258 SDValue Cmp = N->getOperand(4);
10259 if (Cmp.getOpcode() != ARMISD::CMPZ)
10260 // Only looking at EQ and NE cases.
10263 EVT VT = N->getValueType(0);
10265 SDValue LHS = Cmp.getOperand(0);
10266 SDValue RHS = Cmp.getOperand(1);
10267 SDValue FalseVal = N->getOperand(0);
10268 SDValue TrueVal = N->getOperand(1);
10269 SDValue ARMcc = N->getOperand(2);
10270 ARMCC::CondCodes CC =
10271 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10289 /// FIXME: Turn this into a target neutral optimization?
10291 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10292 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10293 N->getOperand(3), Cmp);
10294 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10296 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10297 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10298 N->getOperand(3), NewCmp);
10301 if (Res.getNode()) {
10302 APInt KnownZero, KnownOne;
10303 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10304 // Capture demanded bits information that would be otherwise lost.
10305 if (KnownZero == 0xfffffffe)
10306 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10307 DAG.getValueType(MVT::i1));
10308 else if (KnownZero == 0xffffff00)
10309 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10310 DAG.getValueType(MVT::i8));
10311 else if (KnownZero == 0xffff0000)
10312 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10313 DAG.getValueType(MVT::i16));
10319 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10320 DAGCombinerInfo &DCI) const {
10321 switch (N->getOpcode()) {
10323 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10324 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10325 case ISD::SUB: return PerformSUBCombine(N, DCI);
10326 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10327 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10328 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10329 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10330 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10331 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10332 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10333 case ISD::STORE: return PerformSTORECombine(N, DCI);
10334 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10335 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10336 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10337 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10338 case ISD::FP_TO_SINT:
10339 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10340 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10341 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10344 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10345 case ISD::SIGN_EXTEND:
10346 case ISD::ZERO_EXTEND:
10347 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10348 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10349 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10350 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10351 case ARMISD::VLD2DUP:
10352 case ARMISD::VLD3DUP:
10353 case ARMISD::VLD4DUP:
10354 return PerformVLDCombine(N, DCI);
10355 case ARMISD::BUILD_VECTOR:
10356 return PerformARMBUILD_VECTORCombine(N, DCI);
10357 case ISD::INTRINSIC_VOID:
10358 case ISD::INTRINSIC_W_CHAIN:
10359 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10360 case Intrinsic::arm_neon_vld1:
10361 case Intrinsic::arm_neon_vld2:
10362 case Intrinsic::arm_neon_vld3:
10363 case Intrinsic::arm_neon_vld4:
10364 case Intrinsic::arm_neon_vld2lane:
10365 case Intrinsic::arm_neon_vld3lane:
10366 case Intrinsic::arm_neon_vld4lane:
10367 case Intrinsic::arm_neon_vst1:
10368 case Intrinsic::arm_neon_vst2:
10369 case Intrinsic::arm_neon_vst3:
10370 case Intrinsic::arm_neon_vst4:
10371 case Intrinsic::arm_neon_vst2lane:
10372 case Intrinsic::arm_neon_vst3lane:
10373 case Intrinsic::arm_neon_vst4lane:
10374 return PerformVLDCombine(N, DCI);
10382 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10384 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10387 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10390 bool *Fast) const {
10391 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10392 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10394 switch (VT.getSimpleVT().SimpleTy) {
10400 // Unaligned access can use (for example) LRDB, LRDH, LDR
10401 if (AllowsUnaligned) {
10403 *Fast = Subtarget->hasV7Ops();
10410 // For any little-endian targets with neon, we can support unaligned ld/st
10411 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10412 // A big-endian target may also explicitly support unaligned accesses
10413 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10423 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10424 unsigned AlignCheck) {
10425 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10426 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10429 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10430 unsigned DstAlign, unsigned SrcAlign,
10431 bool IsMemset, bool ZeroMemset,
10433 MachineFunction &MF) const {
10434 const Function *F = MF.getFunction();
10436 // See if we can use NEON instructions for this...
10437 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10438 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10441 (memOpAlign(SrcAlign, DstAlign, 16) ||
10442 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10444 } else if (Size >= 8 &&
10445 (memOpAlign(SrcAlign, DstAlign, 8) ||
10446 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10452 // Lowering to i32/i16 if the size permits.
10455 else if (Size >= 2)
10458 // Let the target-independent logic figure it out.
10462 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10463 if (Val.getOpcode() != ISD::LOAD)
10466 EVT VT1 = Val.getValueType();
10467 if (!VT1.isSimple() || !VT1.isInteger() ||
10468 !VT2.isSimple() || !VT2.isInteger())
10471 switch (VT1.getSimpleVT().SimpleTy) {
10476 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10483 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10484 EVT VT = ExtVal.getValueType();
10486 if (!isTypeLegal(VT))
10489 // Don't create a loadext if we can fold the extension into a wide/long
10491 // If there's more than one user instruction, the loadext is desirable no
10492 // matter what. There can be two uses by the same instruction.
10493 if (ExtVal->use_empty() ||
10494 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10497 SDNode *U = *ExtVal->use_begin();
10498 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10499 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10505 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10506 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10509 if (!isTypeLegal(EVT::getEVT(Ty1)))
10512 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10514 // Assuming the caller doesn't have a zeroext or signext return parameter,
10515 // truncation all the way down to i1 is valid.
10520 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10524 unsigned Scale = 1;
10525 switch (VT.getSimpleVT().SimpleTy) {
10526 default: return false;
10541 if ((V & (Scale - 1)) != 0)
10544 return V == (V & ((1LL << 5) - 1));
10547 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10548 const ARMSubtarget *Subtarget) {
10549 bool isNeg = false;
10555 switch (VT.getSimpleVT().SimpleTy) {
10556 default: return false;
10561 // + imm12 or - imm8
10563 return V == (V & ((1LL << 8) - 1));
10564 return V == (V & ((1LL << 12) - 1));
10567 // Same as ARM mode. FIXME: NEON?
10568 if (!Subtarget->hasVFP2())
10573 return V == (V & ((1LL << 8) - 1));
10577 /// isLegalAddressImmediate - Return true if the integer value can be used
10578 /// as the offset of the target addressing mode for load / store of the
10580 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10581 const ARMSubtarget *Subtarget) {
10585 if (!VT.isSimple())
10588 if (Subtarget->isThumb1Only())
10589 return isLegalT1AddressImmediate(V, VT);
10590 else if (Subtarget->isThumb2())
10591 return isLegalT2AddressImmediate(V, VT, Subtarget);
10596 switch (VT.getSimpleVT().SimpleTy) {
10597 default: return false;
10602 return V == (V & ((1LL << 12) - 1));
10605 return V == (V & ((1LL << 8) - 1));
10608 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10613 return V == (V & ((1LL << 8) - 1));
10617 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10619 int Scale = AM.Scale;
10623 switch (VT.getSimpleVT().SimpleTy) {
10624 default: return false;
10632 Scale = Scale & ~1;
10633 return Scale == 2 || Scale == 4 || Scale == 8;
10636 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10640 // Note, we allow "void" uses (basically, uses that aren't loads or
10641 // stores), because arm allows folding a scale into many arithmetic
10642 // operations. This should be made more precise and revisited later.
10644 // Allow r << imm, but the imm has to be a multiple of two.
10645 if (Scale & 1) return false;
10646 return isPowerOf2_32(Scale);
10650 /// isLegalAddressingMode - Return true if the addressing mode represented
10651 /// by AM is legal for this target, for a load/store of the specified type.
10652 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10653 const AddrMode &AM, Type *Ty,
10654 unsigned AS) const {
10655 EVT VT = getValueType(DL, Ty, true);
10656 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10659 // Can never fold addr of global into load/store.
10663 switch (AM.Scale) {
10664 case 0: // no scale reg, must be "r+i" or "r", or "i".
10667 if (Subtarget->isThumb1Only())
10671 // ARM doesn't support any R+R*scale+imm addr modes.
10675 if (!VT.isSimple())
10678 if (Subtarget->isThumb2())
10679 return isLegalT2ScaledAddressingMode(AM, VT);
10681 int Scale = AM.Scale;
10682 switch (VT.getSimpleVT().SimpleTy) {
10683 default: return false;
10687 if (Scale < 0) Scale = -Scale;
10691 return isPowerOf2_32(Scale & ~1);
10695 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10700 // Note, we allow "void" uses (basically, uses that aren't loads or
10701 // stores), because arm allows folding a scale into many arithmetic
10702 // operations. This should be made more precise and revisited later.
10704 // Allow r << imm, but the imm has to be a multiple of two.
10705 if (Scale & 1) return false;
10706 return isPowerOf2_32(Scale);
10712 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10713 /// icmp immediate, that is the target has icmp instructions which can compare
10714 /// a register against the immediate without having to materialize the
10715 /// immediate into a register.
10716 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10717 // Thumb2 and ARM modes can use cmn for negative immediates.
10718 if (!Subtarget->isThumb())
10719 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10720 if (Subtarget->isThumb2())
10721 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10722 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10723 return Imm >= 0 && Imm <= 255;
10726 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10727 /// *or sub* immediate, that is the target has add or sub instructions which can
10728 /// add a register with the immediate without having to materialize the
10729 /// immediate into a register.
10730 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10731 // Same encoding for add/sub, just flip the sign.
10732 int64_t AbsImm = std::abs(Imm);
10733 if (!Subtarget->isThumb())
10734 return ARM_AM::getSOImmVal(AbsImm) != -1;
10735 if (Subtarget->isThumb2())
10736 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10737 // Thumb1 only has 8-bit unsigned immediate.
10738 return AbsImm >= 0 && AbsImm <= 255;
10741 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10742 bool isSEXTLoad, SDValue &Base,
10743 SDValue &Offset, bool &isInc,
10744 SelectionDAG &DAG) {
10745 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10748 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10749 // AddressingMode 3
10750 Base = Ptr->getOperand(0);
10751 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10752 int RHSC = (int)RHS->getZExtValue();
10753 if (RHSC < 0 && RHSC > -256) {
10754 assert(Ptr->getOpcode() == ISD::ADD);
10756 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10760 isInc = (Ptr->getOpcode() == ISD::ADD);
10761 Offset = Ptr->getOperand(1);
10763 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10764 // AddressingMode 2
10765 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10766 int RHSC = (int)RHS->getZExtValue();
10767 if (RHSC < 0 && RHSC > -0x1000) {
10768 assert(Ptr->getOpcode() == ISD::ADD);
10770 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10771 Base = Ptr->getOperand(0);
10776 if (Ptr->getOpcode() == ISD::ADD) {
10778 ARM_AM::ShiftOpc ShOpcVal=
10779 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10780 if (ShOpcVal != ARM_AM::no_shift) {
10781 Base = Ptr->getOperand(1);
10782 Offset = Ptr->getOperand(0);
10784 Base = Ptr->getOperand(0);
10785 Offset = Ptr->getOperand(1);
10790 isInc = (Ptr->getOpcode() == ISD::ADD);
10791 Base = Ptr->getOperand(0);
10792 Offset = Ptr->getOperand(1);
10796 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10800 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10801 bool isSEXTLoad, SDValue &Base,
10802 SDValue &Offset, bool &isInc,
10803 SelectionDAG &DAG) {
10804 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10807 Base = Ptr->getOperand(0);
10808 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10809 int RHSC = (int)RHS->getZExtValue();
10810 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10811 assert(Ptr->getOpcode() == ISD::ADD);
10813 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10815 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10816 isInc = Ptr->getOpcode() == ISD::ADD;
10817 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10825 /// getPreIndexedAddressParts - returns true by value, base pointer and
10826 /// offset pointer and addressing mode by reference if the node's address
10827 /// can be legally represented as pre-indexed load / store address.
10829 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10831 ISD::MemIndexedMode &AM,
10832 SelectionDAG &DAG) const {
10833 if (Subtarget->isThumb1Only())
10838 bool isSEXTLoad = false;
10839 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10840 Ptr = LD->getBasePtr();
10841 VT = LD->getMemoryVT();
10842 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10843 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10844 Ptr = ST->getBasePtr();
10845 VT = ST->getMemoryVT();
10850 bool isLegal = false;
10851 if (Subtarget->isThumb2())
10852 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10853 Offset, isInc, DAG);
10855 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10856 Offset, isInc, DAG);
10860 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10864 /// getPostIndexedAddressParts - returns true by value, base pointer and
10865 /// offset pointer and addressing mode by reference if this node can be
10866 /// combined with a load / store to form a post-indexed load / store.
10867 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10870 ISD::MemIndexedMode &AM,
10871 SelectionDAG &DAG) const {
10872 if (Subtarget->isThumb1Only())
10877 bool isSEXTLoad = false;
10878 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10879 VT = LD->getMemoryVT();
10880 Ptr = LD->getBasePtr();
10881 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10882 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10883 VT = ST->getMemoryVT();
10884 Ptr = ST->getBasePtr();
10889 bool isLegal = false;
10890 if (Subtarget->isThumb2())
10891 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10894 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10900 // Swap base ptr and offset to catch more post-index load / store when
10901 // it's legal. In Thumb2 mode, offset must be an immediate.
10902 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10903 !Subtarget->isThumb2())
10904 std::swap(Base, Offset);
10906 // Post-indexed load / store update the base pointer.
10911 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10915 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10918 const SelectionDAG &DAG,
10919 unsigned Depth) const {
10920 unsigned BitWidth = KnownOne.getBitWidth();
10921 KnownZero = KnownOne = APInt(BitWidth, 0);
10922 switch (Op.getOpcode()) {
10928 // These nodes' second result is a boolean
10929 if (Op.getResNo() == 0)
10931 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10933 case ARMISD::CMOV: {
10934 // Bits are known zero/one if known on the LHS and RHS.
10935 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10936 if (KnownZero == 0 && KnownOne == 0) return;
10938 APInt KnownZeroRHS, KnownOneRHS;
10939 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10940 KnownZero &= KnownZeroRHS;
10941 KnownOne &= KnownOneRHS;
10944 case ISD::INTRINSIC_W_CHAIN: {
10945 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10946 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10949 case Intrinsic::arm_ldaex:
10950 case Intrinsic::arm_ldrex: {
10951 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10952 unsigned MemBits = VT.getScalarType().getSizeInBits();
10953 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10961 //===----------------------------------------------------------------------===//
10962 // ARM Inline Assembly Support
10963 //===----------------------------------------------------------------------===//
10965 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10966 // Looking for "rev" which is V6+.
10967 if (!Subtarget->hasV6Ops())
10970 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10971 std::string AsmStr = IA->getAsmString();
10972 SmallVector<StringRef, 4> AsmPieces;
10973 SplitString(AsmStr, AsmPieces, ";\n");
10975 switch (AsmPieces.size()) {
10976 default: return false;
10978 AsmStr = AsmPieces[0];
10980 SplitString(AsmStr, AsmPieces, " \t,");
10983 if (AsmPieces.size() == 3 &&
10984 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10985 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10986 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10987 if (Ty && Ty->getBitWidth() == 32)
10988 return IntrinsicLowering::LowerToByteSwap(CI);
10996 /// getConstraintType - Given a constraint letter, return the type of
10997 /// constraint it is for this target.
10998 ARMTargetLowering::ConstraintType
10999 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11000 if (Constraint.size() == 1) {
11001 switch (Constraint[0]) {
11003 case 'l': return C_RegisterClass;
11004 case 'w': return C_RegisterClass;
11005 case 'h': return C_RegisterClass;
11006 case 'x': return C_RegisterClass;
11007 case 't': return C_RegisterClass;
11008 case 'j': return C_Other; // Constant for movw.
11009 // An address with a single base register. Due to the way we
11010 // currently handle addresses it is the same as an 'r' memory constraint.
11011 case 'Q': return C_Memory;
11013 } else if (Constraint.size() == 2) {
11014 switch (Constraint[0]) {
11016 // All 'U+' constraints are addresses.
11017 case 'U': return C_Memory;
11020 return TargetLowering::getConstraintType(Constraint);
11023 /// Examine constraint type and operand type and determine a weight value.
11024 /// This object must already have been set up with the operand type
11025 /// and the current alternative constraint selected.
11026 TargetLowering::ConstraintWeight
11027 ARMTargetLowering::getSingleConstraintMatchWeight(
11028 AsmOperandInfo &info, const char *constraint) const {
11029 ConstraintWeight weight = CW_Invalid;
11030 Value *CallOperandVal = info.CallOperandVal;
11031 // If we don't have a value, we can't do a match,
11032 // but allow it at the lowest weight.
11033 if (!CallOperandVal)
11035 Type *type = CallOperandVal->getType();
11036 // Look at the constraint type.
11037 switch (*constraint) {
11039 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11042 if (type->isIntegerTy()) {
11043 if (Subtarget->isThumb())
11044 weight = CW_SpecificReg;
11046 weight = CW_Register;
11050 if (type->isFloatingPointTy())
11051 weight = CW_Register;
11057 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11058 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11059 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11060 if (Constraint.size() == 1) {
11061 // GCC ARM Constraint Letters
11062 switch (Constraint[0]) {
11063 case 'l': // Low regs or general regs.
11064 if (Subtarget->isThumb())
11065 return RCPair(0U, &ARM::tGPRRegClass);
11066 return RCPair(0U, &ARM::GPRRegClass);
11067 case 'h': // High regs or no regs.
11068 if (Subtarget->isThumb())
11069 return RCPair(0U, &ARM::hGPRRegClass);
11072 if (Subtarget->isThumb1Only())
11073 return RCPair(0U, &ARM::tGPRRegClass);
11074 return RCPair(0U, &ARM::GPRRegClass);
11076 if (VT == MVT::Other)
11078 if (VT == MVT::f32)
11079 return RCPair(0U, &ARM::SPRRegClass);
11080 if (VT.getSizeInBits() == 64)
11081 return RCPair(0U, &ARM::DPRRegClass);
11082 if (VT.getSizeInBits() == 128)
11083 return RCPair(0U, &ARM::QPRRegClass);
11086 if (VT == MVT::Other)
11088 if (VT == MVT::f32)
11089 return RCPair(0U, &ARM::SPR_8RegClass);
11090 if (VT.getSizeInBits() == 64)
11091 return RCPair(0U, &ARM::DPR_8RegClass);
11092 if (VT.getSizeInBits() == 128)
11093 return RCPair(0U, &ARM::QPR_8RegClass);
11096 if (VT == MVT::f32)
11097 return RCPair(0U, &ARM::SPRRegClass);
11101 if (StringRef("{cc}").equals_lower(Constraint))
11102 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11104 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11107 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11108 /// vector. If it is invalid, don't add anything to Ops.
11109 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11110 std::string &Constraint,
11111 std::vector<SDValue>&Ops,
11112 SelectionDAG &DAG) const {
11115 // Currently only support length 1 constraints.
11116 if (Constraint.length() != 1) return;
11118 char ConstraintLetter = Constraint[0];
11119 switch (ConstraintLetter) {
11122 case 'I': case 'J': case 'K': case 'L':
11123 case 'M': case 'N': case 'O':
11124 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11128 int64_t CVal64 = C->getSExtValue();
11129 int CVal = (int) CVal64;
11130 // None of these constraints allow values larger than 32 bits. Check
11131 // that the value fits in an int.
11132 if (CVal != CVal64)
11135 switch (ConstraintLetter) {
11137 // Constant suitable for movw, must be between 0 and
11139 if (Subtarget->hasV6T2Ops())
11140 if (CVal >= 0 && CVal <= 65535)
11144 if (Subtarget->isThumb1Only()) {
11145 // This must be a constant between 0 and 255, for ADD
11147 if (CVal >= 0 && CVal <= 255)
11149 } else if (Subtarget->isThumb2()) {
11150 // A constant that can be used as an immediate value in a
11151 // data-processing instruction.
11152 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11155 // A constant that can be used as an immediate value in a
11156 // data-processing instruction.
11157 if (ARM_AM::getSOImmVal(CVal) != -1)
11163 if (Subtarget->isThumb()) { // FIXME thumb2
11164 // This must be a constant between -255 and -1, for negated ADD
11165 // immediates. This can be used in GCC with an "n" modifier that
11166 // prints the negated value, for use with SUB instructions. It is
11167 // not useful otherwise but is implemented for compatibility.
11168 if (CVal >= -255 && CVal <= -1)
11171 // This must be a constant between -4095 and 4095. It is not clear
11172 // what this constraint is intended for. Implemented for
11173 // compatibility with GCC.
11174 if (CVal >= -4095 && CVal <= 4095)
11180 if (Subtarget->isThumb1Only()) {
11181 // A 32-bit value where only one byte has a nonzero value. Exclude
11182 // zero to match GCC. This constraint is used by GCC internally for
11183 // constants that can be loaded with a move/shift combination.
11184 // It is not useful otherwise but is implemented for compatibility.
11185 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11187 } else if (Subtarget->isThumb2()) {
11188 // A constant whose bitwise inverse can be used as an immediate
11189 // value in a data-processing instruction. This can be used in GCC
11190 // with a "B" modifier that prints the inverted value, for use with
11191 // BIC and MVN instructions. It is not useful otherwise but is
11192 // implemented for compatibility.
11193 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11196 // A constant whose bitwise inverse can be used as an immediate
11197 // value in a data-processing instruction. This can be used in GCC
11198 // with a "B" modifier that prints the inverted value, for use with
11199 // BIC and MVN instructions. It is not useful otherwise but is
11200 // implemented for compatibility.
11201 if (ARM_AM::getSOImmVal(~CVal) != -1)
11207 if (Subtarget->isThumb1Only()) {
11208 // This must be a constant between -7 and 7,
11209 // for 3-operand ADD/SUB immediate instructions.
11210 if (CVal >= -7 && CVal < 7)
11212 } else if (Subtarget->isThumb2()) {
11213 // A constant whose negation can be used as an immediate value in a
11214 // data-processing instruction. This can be used in GCC with an "n"
11215 // modifier that prints the negated value, for use with SUB
11216 // instructions. It is not useful otherwise but is implemented for
11218 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11221 // A constant whose negation can be used as an immediate value in a
11222 // data-processing instruction. This can be used in GCC with an "n"
11223 // modifier that prints the negated value, for use with SUB
11224 // instructions. It is not useful otherwise but is implemented for
11226 if (ARM_AM::getSOImmVal(-CVal) != -1)
11232 if (Subtarget->isThumb()) { // FIXME thumb2
11233 // This must be a multiple of 4 between 0 and 1020, for
11234 // ADD sp + immediate.
11235 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11238 // A power of two or a constant between 0 and 32. This is used in
11239 // GCC for the shift amount on shifted register operands, but it is
11240 // useful in general for any shift amounts.
11241 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11247 if (Subtarget->isThumb()) { // FIXME thumb2
11248 // This must be a constant between 0 and 31, for shift amounts.
11249 if (CVal >= 0 && CVal <= 31)
11255 if (Subtarget->isThumb()) { // FIXME thumb2
11256 // This must be a multiple of 4 between -508 and 508, for
11257 // ADD/SUB sp = sp + immediate.
11258 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11263 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11267 if (Result.getNode()) {
11268 Ops.push_back(Result);
11271 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11274 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11275 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11276 "Register-based DivRem lowering only");
11277 unsigned Opcode = Op->getOpcode();
11278 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11279 "Invalid opcode for Div/Rem lowering");
11280 bool isSigned = (Opcode == ISD::SDIVREM);
11281 EVT VT = Op->getValueType(0);
11282 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11285 switch (VT.getSimpleVT().SimpleTy) {
11286 default: llvm_unreachable("Unexpected request for libcall!");
11287 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11288 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11289 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11290 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11293 SDValue InChain = DAG.getEntryNode();
11295 TargetLowering::ArgListTy Args;
11296 TargetLowering::ArgListEntry Entry;
11297 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11298 EVT ArgVT = Op->getOperand(i).getValueType();
11299 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11300 Entry.Node = Op->getOperand(i);
11302 Entry.isSExt = isSigned;
11303 Entry.isZExt = !isSigned;
11304 Args.push_back(Entry);
11307 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11308 getPointerTy(DAG.getDataLayout()));
11310 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11313 TargetLowering::CallLoweringInfo CLI(DAG);
11314 CLI.setDebugLoc(dl).setChain(InChain)
11315 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11316 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11318 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11319 return CallInfo.first;
11323 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11324 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11328 SDValue Chain = Op.getOperand(0);
11329 SDValue Size = Op.getOperand(1);
11331 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11332 DAG.getConstant(2, DL, MVT::i32));
11335 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11336 Flag = Chain.getValue(1);
11338 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11339 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11341 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11342 Chain = NewSP.getValue(1);
11344 SDValue Ops[2] = { NewSP, Chain };
11345 return DAG.getMergeValues(Ops, DL);
11348 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11349 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11350 "Unexpected type for custom-lowering FP_EXTEND");
11353 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11355 SDValue SrcVal = Op.getOperand(0);
11356 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11357 /*isSigned*/ false, SDLoc(Op)).first;
11360 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11361 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11362 Subtarget->isFPOnlySP() &&
11363 "Unexpected type for custom-lowering FP_ROUND");
11366 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11368 SDValue SrcVal = Op.getOperand(0);
11369 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11370 /*isSigned*/ false, SDLoc(Op)).first;
11374 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11375 // The ARM target isn't yet aware of offsets.
11379 bool ARM::isBitFieldInvertedMask(unsigned v) {
11380 if (v == 0xffffffff)
11383 // there can be 1's on either or both "outsides", all the "inside"
11384 // bits must be 0's
11385 return isShiftedMask_32(~v);
11388 /// isFPImmLegal - Returns true if the target can instruction select the
11389 /// specified FP immediate natively. If false, the legalizer will
11390 /// materialize the FP immediate as a load from a constant pool.
11391 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11392 if (!Subtarget->hasVFP3())
11394 if (VT == MVT::f32)
11395 return ARM_AM::getFP32Imm(Imm) != -1;
11396 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11397 return ARM_AM::getFP64Imm(Imm) != -1;
11401 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11402 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11403 /// specified in the intrinsic calls.
11404 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11406 unsigned Intrinsic) const {
11407 switch (Intrinsic) {
11408 case Intrinsic::arm_neon_vld1:
11409 case Intrinsic::arm_neon_vld2:
11410 case Intrinsic::arm_neon_vld3:
11411 case Intrinsic::arm_neon_vld4:
11412 case Intrinsic::arm_neon_vld2lane:
11413 case Intrinsic::arm_neon_vld3lane:
11414 case Intrinsic::arm_neon_vld4lane: {
11415 Info.opc = ISD::INTRINSIC_W_CHAIN;
11416 // Conservatively set memVT to the entire set of vectors loaded.
11417 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11418 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11419 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11420 Info.ptrVal = I.getArgOperand(0);
11422 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11423 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11424 Info.vol = false; // volatile loads with NEON intrinsics not supported
11425 Info.readMem = true;
11426 Info.writeMem = false;
11429 case Intrinsic::arm_neon_vst1:
11430 case Intrinsic::arm_neon_vst2:
11431 case Intrinsic::arm_neon_vst3:
11432 case Intrinsic::arm_neon_vst4:
11433 case Intrinsic::arm_neon_vst2lane:
11434 case Intrinsic::arm_neon_vst3lane:
11435 case Intrinsic::arm_neon_vst4lane: {
11436 Info.opc = ISD::INTRINSIC_VOID;
11437 // Conservatively set memVT to the entire set of vectors stored.
11438 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11439 unsigned NumElts = 0;
11440 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11441 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11442 if (!ArgTy->isVectorTy())
11444 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11446 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11447 Info.ptrVal = I.getArgOperand(0);
11449 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11450 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11451 Info.vol = false; // volatile stores with NEON intrinsics not supported
11452 Info.readMem = false;
11453 Info.writeMem = true;
11456 case Intrinsic::arm_ldaex:
11457 case Intrinsic::arm_ldrex: {
11458 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11459 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11460 Info.opc = ISD::INTRINSIC_W_CHAIN;
11461 Info.memVT = MVT::getVT(PtrTy->getElementType());
11462 Info.ptrVal = I.getArgOperand(0);
11464 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11466 Info.readMem = true;
11467 Info.writeMem = false;
11470 case Intrinsic::arm_stlex:
11471 case Intrinsic::arm_strex: {
11472 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11473 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11474 Info.opc = ISD::INTRINSIC_W_CHAIN;
11475 Info.memVT = MVT::getVT(PtrTy->getElementType());
11476 Info.ptrVal = I.getArgOperand(1);
11478 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11480 Info.readMem = false;
11481 Info.writeMem = true;
11484 case Intrinsic::arm_stlexd:
11485 case Intrinsic::arm_strexd: {
11486 Info.opc = ISD::INTRINSIC_W_CHAIN;
11487 Info.memVT = MVT::i64;
11488 Info.ptrVal = I.getArgOperand(2);
11492 Info.readMem = false;
11493 Info.writeMem = true;
11496 case Intrinsic::arm_ldaexd:
11497 case Intrinsic::arm_ldrexd: {
11498 Info.opc = ISD::INTRINSIC_W_CHAIN;
11499 Info.memVT = MVT::i64;
11500 Info.ptrVal = I.getArgOperand(0);
11504 Info.readMem = true;
11505 Info.writeMem = false;
11515 /// \brief Returns true if it is beneficial to convert a load of a constant
11516 /// to just the constant itself.
11517 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11519 assert(Ty->isIntegerTy());
11521 unsigned Bits = Ty->getPrimitiveSizeInBits();
11522 if (Bits == 0 || Bits > 32)
11527 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11529 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11530 ARM_MB::MemBOpt Domain) const {
11531 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11533 // First, if the target has no DMB, see what fallback we can use.
11534 if (!Subtarget->hasDataBarrier()) {
11535 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11536 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11538 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11539 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11540 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11541 Builder.getInt32(0), Builder.getInt32(7),
11542 Builder.getInt32(10), Builder.getInt32(5)};
11543 return Builder.CreateCall(MCR, args);
11545 // Instead of using barriers, atomic accesses on these subtargets use
11547 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11550 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11551 // Only a full system barrier exists in the M-class architectures.
11552 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11553 Constant *CDomain = Builder.getInt32(Domain);
11554 return Builder.CreateCall(DMB, CDomain);
11558 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11559 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11560 AtomicOrdering Ord, bool IsStore,
11561 bool IsLoad) const {
11562 if (!getInsertFencesForAtomic())
11568 llvm_unreachable("Invalid fence: unordered/non-atomic");
11571 return nullptr; // Nothing to do
11572 case SequentiallyConsistent:
11574 return nullptr; // Nothing to do
11577 case AcquireRelease:
11578 if (Subtarget->isSwift())
11579 return makeDMB(Builder, ARM_MB::ISHST);
11580 // FIXME: add a comment with a link to documentation justifying this.
11582 return makeDMB(Builder, ARM_MB::ISH);
11584 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11587 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11588 AtomicOrdering Ord, bool IsStore,
11589 bool IsLoad) const {
11590 if (!getInsertFencesForAtomic())
11596 llvm_unreachable("Invalid fence: unordered/not-atomic");
11599 return nullptr; // Nothing to do
11601 case AcquireRelease:
11602 case SequentiallyConsistent:
11603 return makeDMB(Builder, ARM_MB::ISH);
11605 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11608 // Loads and stores less than 64-bits are already atomic; ones above that
11609 // are doomed anyway, so defer to the default libcall and blame the OS when
11610 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11611 // anything for those.
11612 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11613 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11614 return (Size == 64) && !Subtarget->isMClass();
11617 // Loads and stores less than 64-bits are already atomic; ones above that
11618 // are doomed anyway, so defer to the default libcall and blame the OS when
11619 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11620 // anything for those.
11621 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11622 // guarantee, see DDI0406C ARM architecture reference manual,
11623 // sections A8.8.72-74 LDRD)
11624 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11625 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11626 return (Size == 64) && !Subtarget->isMClass();
11629 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11630 // and up to 64 bits on the non-M profiles
11631 TargetLoweringBase::AtomicRMWExpansionKind
11632 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11633 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11634 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11635 ? AtomicRMWExpansionKind::LLSC
11636 : AtomicRMWExpansionKind::None;
11639 // This has so far only been implemented for MachO.
11640 bool ARMTargetLowering::useLoadStackGuardNode() const {
11641 return Subtarget->isTargetMachO();
11644 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11645 unsigned &Cost) const {
11646 // If we do not have NEON, vector types are not natively supported.
11647 if (!Subtarget->hasNEON())
11650 // Floating point values and vector values map to the same register file.
11651 // Therefore, although we could do a store extract of a vector type, this is
11652 // better to leave at float as we have more freedom in the addressing mode for
11654 if (VectorTy->isFPOrFPVectorTy())
11657 // If the index is unknown at compile time, this is very expensive to lower
11658 // and it is not possible to combine the store with the extract.
11659 if (!isa<ConstantInt>(Idx))
11662 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11663 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11664 // We can do a store + vector extract on any vector that fits perfectly in a D
11666 if (BitWidth == 64 || BitWidth == 128) {
11673 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11674 AtomicOrdering Ord) const {
11675 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11676 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11677 bool IsAcquire = isAtLeastAcquire(Ord);
11679 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11680 // intrinsic must return {i32, i32} and we have to recombine them into a
11681 // single i64 here.
11682 if (ValTy->getPrimitiveSizeInBits() == 64) {
11683 Intrinsic::ID Int =
11684 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11685 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11687 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11688 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11690 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11691 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11692 if (!Subtarget->isLittle())
11693 std::swap (Lo, Hi);
11694 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11695 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11696 return Builder.CreateOr(
11697 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11700 Type *Tys[] = { Addr->getType() };
11701 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11702 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11704 return Builder.CreateTruncOrBitCast(
11705 Builder.CreateCall(Ldrex, Addr),
11706 cast<PointerType>(Addr->getType())->getElementType());
11709 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11711 AtomicOrdering Ord) const {
11712 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11713 bool IsRelease = isAtLeastRelease(Ord);
11715 // Since the intrinsics must have legal type, the i64 intrinsics take two
11716 // parameters: "i32, i32". We must marshal Val into the appropriate form
11717 // before the call.
11718 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11719 Intrinsic::ID Int =
11720 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11721 Function *Strex = Intrinsic::getDeclaration(M, Int);
11722 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11724 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11725 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11726 if (!Subtarget->isLittle())
11727 std::swap (Lo, Hi);
11728 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11729 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11732 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11733 Type *Tys[] = { Addr->getType() };
11734 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11736 return Builder.CreateCall(
11737 Strex, {Builder.CreateZExtOrBitCast(
11738 Val, Strex->getFunctionType()->getParamType(0)),
11742 /// \brief Lower an interleaved load into a vldN intrinsic.
11744 /// E.g. Lower an interleaved load (Factor = 2):
11745 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11746 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11747 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11750 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11751 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11752 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11753 bool ARMTargetLowering::lowerInterleavedLoad(
11754 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11755 ArrayRef<unsigned> Indices, unsigned Factor) const {
11756 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11757 "Invalid interleave factor");
11758 assert(!Shuffles.empty() && "Empty shufflevector input");
11759 assert(Shuffles.size() == Indices.size() &&
11760 "Unmatched number of shufflevectors and indices");
11762 VectorType *VecTy = Shuffles[0]->getType();
11763 Type *EltTy = VecTy->getVectorElementType();
11765 const DataLayout &DL = LI->getModule()->getDataLayout();
11766 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11767 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11769 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11770 // support i64/f64 element).
11771 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11774 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11775 // load integer vectors first and then convert to pointer vectors.
11776 if (EltTy->isPointerTy())
11778 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11780 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11781 Intrinsic::arm_neon_vld3,
11782 Intrinsic::arm_neon_vld4};
11784 Function *VldnFunc =
11785 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11787 IRBuilder<> Builder(LI);
11788 SmallVector<Value *, 2> Ops;
11790 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11791 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11792 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11794 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11796 // Replace uses of each shufflevector with the corresponding vector loaded
11798 for (unsigned i = 0; i < Shuffles.size(); i++) {
11799 ShuffleVectorInst *SV = Shuffles[i];
11800 unsigned Index = Indices[i];
11802 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11804 // Convert the integer vector to pointer vector if the element is pointer.
11805 if (EltTy->isPointerTy())
11806 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11808 SV->replaceAllUsesWith(SubVec);
11814 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11816 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11817 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11818 unsigned NumElts) {
11819 SmallVector<Constant *, 16> Mask;
11820 for (unsigned i = 0; i < NumElts; i++)
11821 Mask.push_back(Builder.getInt32(Start + i));
11823 return ConstantVector::get(Mask);
11826 /// \brief Lower an interleaved store into a vstN intrinsic.
11828 /// E.g. Lower an interleaved store (Factor = 3):
11829 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11830 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11831 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11834 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11835 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11836 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11837 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11839 /// Note that the new shufflevectors will be removed and we'll only generate one
11840 /// vst3 instruction in CodeGen.
11841 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11842 ShuffleVectorInst *SVI,
11843 unsigned Factor) const {
11844 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11845 "Invalid interleave factor");
11847 VectorType *VecTy = SVI->getType();
11848 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11849 "Invalid interleaved store");
11851 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11852 Type *EltTy = VecTy->getVectorElementType();
11853 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11855 const DataLayout &DL = SI->getModule()->getDataLayout();
11856 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11857 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11859 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11860 // doesn't support i64/f64 element).
11861 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11864 Value *Op0 = SVI->getOperand(0);
11865 Value *Op1 = SVI->getOperand(1);
11866 IRBuilder<> Builder(SI);
11868 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11869 // vectors to integer vectors.
11870 if (EltTy->isPointerTy()) {
11871 Type *IntTy = DL.getIntPtrType(EltTy);
11873 // Convert to the corresponding integer vector.
11875 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11876 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11877 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11879 SubVecTy = VectorType::get(IntTy, NumSubElts);
11882 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11883 Intrinsic::arm_neon_vst3,
11884 Intrinsic::arm_neon_vst4};
11885 Function *VstNFunc = Intrinsic::getDeclaration(
11886 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11888 SmallVector<Value *, 6> Ops;
11890 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11891 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11893 // Split the shufflevector operands into sub vectors for the new vstN call.
11894 for (unsigned i = 0; i < Factor; i++)
11895 Ops.push_back(Builder.CreateShuffleVector(
11896 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11898 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11899 Builder.CreateCall(VstNFunc, Ops);
11911 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11912 uint64_t &Members) {
11913 if (auto *ST = dyn_cast<StructType>(Ty)) {
11914 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11915 uint64_t SubMembers = 0;
11916 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11918 Members += SubMembers;
11920 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11921 uint64_t SubMembers = 0;
11922 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11924 Members += SubMembers * AT->getNumElements();
11925 } else if (Ty->isFloatTy()) {
11926 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11930 } else if (Ty->isDoubleTy()) {
11931 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11935 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11942 return VT->getBitWidth() == 64;
11944 return VT->getBitWidth() == 128;
11946 switch (VT->getBitWidth()) {
11959 return (Members > 0 && Members <= 4);
11962 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11963 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11964 /// passing according to AAPCS rules.
11965 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11966 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11967 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11968 CallingConv::ARM_AAPCS_VFP)
11971 HABaseType Base = HA_UNKNOWN;
11972 uint64_t Members = 0;
11973 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11974 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11976 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11977 return IsHA || IsIntArray;